the-stack-inspection / data /key_detections_fn.json
loubnabnl's picture
loubnabnl HF staff
Duplicate from bigcode/pii-test
461c45d
raw
history blame
90.6 kB
["/*\n * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.hazelcast.client.impl.protocol.codec;\n\nimport com.hazelcast.client.impl.protocol.ClientMessage;\nimport com.hazelcast.client.impl.protocol.Generated;\nimport com.hazelcast.client.impl.protocol.codec.builtin.*;\nimport com.hazelcast.client.impl.protocol.codec.custom.*;\n\nimport javax.annotation.Nullable;\n\nimport static com.hazelcast.client.impl.protocol.ClientMessage.*;\nimport static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*;\n\n/*\n * This file is auto-generated by the Hazelcast Client Protocol Code Generator.\n * To change this file, edit the templates or the protocol\n * definitions on the https://github.com/hazelcast/hazelcast-client-protocol\n * and regenerate it.\n */\n\n/**\n * Checks the lock for the specified key.If the lock is acquired then returns true, else returns false.\n */\n@Generated(\"PI:FN:306071f9db7b2ab1e92edc63a77973c7END_PI\")\npublic final class MapIsLockedCodec {\n //hex: 0x011200\n public static final int REQUEST_MESSAGE_TYPE = 70144;\n //hex: 0x011201\n public static final int RESPONSE_MESSAGE_TYPE = 70145;\n private static final int REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES;\n private static final int RESPONSE_RESPONSE_FIELD_OFFSET = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES;\n private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_RESPONSE_FIELD_OFFSET + BOOLEAN_SIZE_IN_BYTES;\n\n private MapIsLockedCodec() {\n }\n\n @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({\"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD\"})\n public static class RequestParameters {\n\n /**\n * name of map\n */\n public java.lang.String name;\n\n /**\n * Key for the map entry to check if it is locked.\n */\n public com.hazelcast.internal.serialization.Data key;\n }\n\n public static ClientMessage encodeRequest(java.lang.String name, com.hazelcast.internal.serialization.Data key) {\n ClientMessage clientMessage = ClientMessage.createForEncode();\n clientMessage.setRetryable(true);\n clientMessage.setOperationName(\"Map.IsLocked\");\n ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);\n encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE);\n encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1);\n clientMessage.add(initialFrame);\n StringCodec.encode(clientMessage, name);\n DataCodec.encode(clientMessage, key);\n return clientMessage;\n }\n\n public static MapIsLockedCodec.RequestParameters decodeRequest(ClientMessage clientMessage) {\n ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();\n RequestParameters request = new RequestParameters();\n //empty initial frame\n iterator.next();\n request.name = StringCodec.decode(iterator);\n request.key = DataCodec.decode(iterator);\n return request;\n }\n\n @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({\"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD\"})\n public static class ResponseParameters {\n\n /**\n * Returns true if the entry is locked, otherwise returns false\n */\n public boolean response;\n }\n\n public static ClientMessage encodeResponse(boolean response) {\n ClientMessage clientMessage = ClientMessage.createForEncode();\n ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);\n encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE);\n encodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET, response);\n clientMessage.add(initialFrame);\n\n return clientMessage;\n }\n\n public static MapIsLockedCodec.ResponseParameters decodeResponse(ClientMessage clientMessage) {\n ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();\n ResponseParameters response = new ResponseParameters();\n ClientMessage.Frame initialFrame = iterator.next();\n response.response = decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET);\n return response;\n }\n\n}\n", "/* eslint-disable camelcase */\nimport test from \"ava\";\nimport nock from \"nock\";\nimport { setGlobalDispatcher } from \"undici\";\nimport { websiteAgent } from \"@indiekit-test/mock-agent\";\nimport { twitter } from \"../../lib/twitter.js\";\n\nsetGlobalDispatcher(websiteAgent());\n\ntest.beforeEach((t) => {\n t.context = {\n apiResponse: {\n id_str: \"1234567890987654321\",\n user: { screen_name: \"username\" },\n },\n media: (filename) => ({\n url: `https://website.example/${filename}`,\n alt: \"Example image\",\n }),\n tweetUrl: \"https://twitter.com/username/status/1234567890987654321\",\n statusId: \"1234567890987654321\",\n options: {\n apiKey: \"PI:FN:0123456789abcdefghijklmnoEND_PI\",\n apiKeySecret: \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0123456789\",\n accessTokenKey: \"ABCDEFGHIJKLMNabcdefghijklmnopqrstuvwxyz0123456789\",\n accessTokenSecret: \"PI:FN:0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNEND_PI\",\n user: \"username\",\n },\n publication: {\n me: \"https://website.example\",\n },\n };\n});\n\ntest(\"Posts a like\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/favorites/create.json\")\n .reply(200, t.context.apiResponse);\n\n const result = await twitter(t.context.options).postLike(t.context.tweetUrl);\n\n t.is(result, \"https://twitter.com/username/status/1234567890987654321\");\n});\n\ntest(\"Throws error posting a like\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/favorites/create.json\")\n .replyWithError(\"Not found\");\n\n await t.throwsAsync(twitter(t.context.options).postLike(t.context.tweetUrl), {\n message: /Not found/,\n });\n});\n\ntest(\"Throws API error posting a like\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/favorites/create.json\")\n .reply(404, {\n errors: [{ message: \"Not found\" }],\n });\n\n await t.throwsAsync(twitter(t.context.options).postLike(t.context.tweetUrl), {\n message: /Not found/,\n });\n});\n\ntest(\"Posts a retweet\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(`/1.1/statuses/retweet/${t.context.statusId}.json`)\n .reply(200, t.context.apiResponse);\n\n const result = await twitter(t.context.options).postRetweet(\n t.context.tweetUrl\n );\n\n t.is(result, \"https://twitter.com/username/status/1234567890987654321\");\n});\n\ntest(\"Throws error posting a retweet\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(`/1.1/statuses/retweet/${t.context.statusId}.json`)\n .replyWithError(\"Not found\");\n\n await t.throwsAsync(\n twitter(t.context.options).postRetweet(t.context.tweetUrl),\n {\n message: /Not found/,\n }\n );\n});\n\ntest(\"Throws API error posting a retweet\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(`/1.1/statuses/retweet/${t.context.statusId}.json`)\n .reply(404, {\n errors: [{ message: \"Not found\" }],\n });\n\n await t.throwsAsync(\n twitter(t.context.options).postRetweet(t.context.tweetUrl),\n {\n message: /Not found/,\n }\n );\n});\n\ntest(\"Posts a status\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/statuses/update.json\")\n .reply(200, t.context.apiResponse);\n\n const result = await twitter(t.context.options).postStatus(t.context.status);\n\n t.is(result, \"https://twitter.com/username/status/1234567890987654321\");\n});\n\ntest(\"Throws error posting a status\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/statuses/update.json\")\n .replyWithError(\"Not found\");\n\n await t.throwsAsync(twitter(t.context.options).postStatus(t.context.status), {\n message: /Not found/,\n });\n});\n\ntest(\"Throws API error posting a status\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/statuses/update.json\")\n .reply(404, {\n errors: [{ message: \"Not found\" }],\n });\n\n await t.throwsAsync(twitter(t.context.options).postStatus(t.context.status), {\n message: /Not found/,\n });\n});\n\ntest(\"Throws error fetching media to upload\", async (t) => {\n await t.throwsAsync(\n twitter(t.context.options).uploadMedia(\n t.context.media(\"image.jpg\"),\n t.context.publication\n ),\n {\n message: \"Not Found\",\n }\n );\n});\n\ntest(\"Uploads media and returns a media id\", async (t) => {\n nock(\"https://upload.twitter.com\").post(\"/1.1/media/upload.json\").reply(200, {\n media_id_string: \"1234567890987654321\",\n });\n nock(\"https://upload.twitter.com\")\n .post(\"/1.1/media/metadata/create.json\")\n .reply(200, {});\n\n const result = await twitter(t.context.options).uploadMedia(\n t.context.media(\"photo1.jpg\"),\n t.context.publication\n );\n\n t.is(result, \"1234567890987654321\");\n});\n\ntest(\"Throws error uploading media\", async (t) => {\n nock(\"https://upload.twitter.com\")\n .post(\"/1.1/media/upload.json\")\n .reply(404, {\n errors: [{ message: \"Not found\" }],\n });\n\n await t.throwsAsync(\n twitter(t.context.options).uploadMedia(\n t.context.media(\"photo2.jpg\"),\n t.context.publication\n ),\n {\n message: /Not found/,\n }\n );\n});\n\ntest(\"Returns false passing an object to media upload function\", async (t) => {\n const result = await twitter(t.context.options).uploadMedia(\n { foo: \"bar\" },\n t.context.publication\n );\n\n t.falsy(result);\n});\n\ntest(\"Posts a like of a tweet to Twitter\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/favorites/create.json\")\n .reply(200, t.context.apiResponse);\n\n const result = await twitter(t.context.options).post(\n {\n \"like-of\": t.context.tweetUrl,\n },\n t.context.publication\n );\n\n t.is(result, \"https://twitter.com/username/status/1234567890987654321\");\n});\n\ntest(\"Doesn\u2019t post a like of a URL to Twitter\", async (t) => {\n const result = await twitter(t.context.options).post(\n {\n \"like-of\": \"https://foo.bar/lunchtime\",\n },\n t.context.publication\n );\n\n t.falsy(result);\n});\n\ntest(\"Posts a repost of a tweet to Twitter\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(`/1.1/statuses/retweet/${t.context.statusId}.json`)\n .reply(200, t.context.apiResponse);\n\n const result = await twitter(t.context.options).post(\n {\n \"repost-of\": t.context.tweetUrl,\n },\n t.context.publication\n );\n\n t.is(result, \"https://twitter.com/username/status/1234567890987654321\");\n});\n\ntest(\"Doesn\u2019t post a repost of a URL to Twitter\", async (t) => {\n const result = await twitter(t.context.options).post(\n {\n \"repost-of\": \"https://foo.bar/lunchtime\",\n },\n t.context.publication\n );\n\n t.falsy(result);\n});\n\ntest(\"Posts a quote status to Twitter\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/statuses/update.json\")\n .reply(200, t.context.apiResponse);\n\n const result = await twitter(t.context.options).post(\n {\n content: {\n html: \"<p>Someone else who likes cheese sandwiches.</p>\",\n },\n \"repost-of\": t.context.tweetUrl,\n \"post-type\": \"repost\",\n },\n t.context.publication\n );\n\n t.is(result, \"https://twitter.com/username/status/1234567890987654321\");\n});\n\ntest(\"Posts a status to Twitter\", async (t) => {\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/statuses/update.json\")\n .reply(200, t.context.apiResponse);\n\n const result = await twitter(t.context.options).post(\n {\n content: {\n html: \"<p>I ate a <em>cheese</em> sandwich, which was nice.</p>\",\n text: \"I ate a cheese sandwich, which was nice.\",\n },\n url: \"https://foo.bar/lunchtime\",\n },\n t.context.publication\n );\n\n t.is(result, \"https://twitter.com/username/status/1234567890987654321\");\n});\n\ntest(\"Posts a status to Twitter with 4 out of 5 photos\", async (t) => {\n nock(\"https://upload.twitter.com\")\n .post(\"/1.1/media/upload.json\")\n .reply(200, { media_id_string: \"1\" });\n nock(\"https://upload.twitter.com\")\n .post(\"/1.1/media/upload.json\")\n .reply(200, { media_id_string: \"2\" });\n nock(\"https://upload.twitter.com\")\n .post(\"/1.1/media/upload.json\")\n .reply(200, { media_id_string: \"3\" });\n nock(\"https://upload.twitter.com\")\n .post(\"/1.1/media/upload.json\")\n .reply(200, { media_id_string: \"4\" });\n nock(\"https://api.twitter.com\")\n .post(\"/1.1/statuses/update.json\")\n .reply(200, t.context.apiResponse);\n\n const result = await twitter(t.context.options).post(\n {\n content: {\n html: \"<p>Here\u2019s the cheese sandwiches I ate.</p>\",\n },\n photo: [\n { url: `${t.context.publication.me}/photo3.jpg` },\n { url: `${t.context.publication.me}/photo4.jpg` },\n { url: `${t.context.publication.me}/photo5.jpg` },\n { url: `${t.context.publication.me}/photo6.jpg` },\n { url: `${t.context.publication.me}/photo7.jpg` },\n ],\n },\n t.context.publication\n );\n\n t.is(result, \"https://twitter.com/username/status/1234567890987654321\");\n});\n", "# IMPORTATION STANDARD\n\n# IMPORTATION THIRDPARTY\nimport pytest\n\n# IMPORTATION INTERNAL\nfrom openbb_terminal.cryptocurrency.defi import terraengineer_model\n\n\n@pytest.mark.vcr\n@pytest.mark.parametrize(\n \"asset,address\",\n [(\"ust\", \"PI:FN:terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8END_PI\")],\n)\ndef test_get_history_asset_from_terra_address(asset, address, recorder):\n df = terraengineer_model.get_history_asset_from_terra_address(\n asset=asset,\n address=address,\n )\n recorder.capture(df)\n", "<?php\nnamespace app\\common\\model;\n\nuse think\\Db;\nuse think\\Model;\n\nclass Api extends Model\n{\n /*\n * \u83b7\u53d6\u5730\u533a\n */\n public function getRegion()\n {\n $parent_id = I('get.parent_id/d');\n $selected = I('get.selected', 0);\n $data = M('region')->where(\"parent_id\", $parent_id)->select();\n $html = '';\n if ($data) {\n foreach ($data as $h) {\n if ($h['id'] == $selected) {\n $html .= \"<option value='{$h['id']}' selected>{$h['name']}</option>\";\n }\n $html .= \"<option value='{$h['id']}'>{$h['name']}</option>\";\n }\n }\n echo $html;\n }\n\n\n public function getTwon()\n {\n $parent_id = I('get.parent_id/d');\n $data = M('region')->where(\"parent_id\", $parent_id)->select();\n $html = '';\n if ($data) {\n foreach ($data as $h) {\n $html .= \"<option value='{$h['id']}'>{$h['name']}</option>\";\n }\n }\n if (empty($html)) {\n echo '0';\n } else {\n echo $html;\n }\n }\n\n /**\n * \u83b7\u53d6\u7701\n */\n public function getProvince()\n {\n $province = Db::name('region')->field('id,name')->where(array('level' => 1))->cache(true)->select();\n $res = array('status' => 1, 'msg' => '\u83b7\u53d6\u6210\u529f', 'result' => $province);\n exit(json_encode($res));\n }\n\n public function area()\n {\n $province_id = input('province_id/d');\n $city_id = input('city_id/d');\n $district_id = input('district_id/d');\n $province_list = Db::name('region')->field('id,name')->where('level', 1)->cache(true)->select();\n $city_list = Db::name('region')->field('id,name')->where('parent_id', $province_id)->cache(true)->select();\n $district_list = Db::name('region')->field('id,name')->where('parent_id', $city_id)->cache(true)->select();\n $town_list = Db::name('region')->field('id,name')->where('parent_id', $district_id)->cache(true)->select();\n $this->ajaxReturn(['status' => 1, 'msg' => '\u83b7\u53d6\u6210\u529f',\n 'result' => ['province_list' => $province_list, 'city_list' => $city_list, 'district_list' => $district_list, 'town_list' => $town_list]]);\n }\n\n /**\n * \u83b7\u53d6\u5e02\u6216\u8005\u533a\n */\n public function getRegionByParentId()\n {\n $parent_id = input('parent_id');\n $res = array('status' => 0, 'msg' => '\u83b7\u53d6\u5931\u8d25\uff0c\u53c2\u6570\u9519\u8bef', 'result' => '');\n if ($parent_id) {\n $region_list = Db::name('region')->field('id,name')->where(['parent_id' => $parent_id])->select();\n $res = array('status' => 1, 'msg' => '\u83b7\u53d6\u6210\u529f', 'result' => $region_list);\n }\n exit(json_encode($res));\n }\n\n /*\n * \u83b7\u53d6\u4e0b\u7ea7\u5206\u7c7b\n */\n public function get_category()\n {\n $parent_id = I('get.parent_id/d'); // \u5546\u54c1\u5206\u7c7b \u7236id\n $list = M('goods_category')->where(\"parent_id\", $parent_id)->select();\n if ($list) {\n $this->ajaxReturn(['status' => 1, 'msg' => '\u83b7\u53d6\u6210\u529f\uff01', 'result' => $list]);\n }\n $this->ajaxReturn(['status' => -1, 'msg' => '\u83b7\u53d6\u5931\u8d25\uff01', 'result' =>[]]);\n }\n\n\n /**\n * \u524d\u7aef\u53d1\u9001\u77ed\u4fe1\u65b9\u6cd5: /WAP/PC \u5171\u7528\u53d1\u9001\u65b9\u6cd5\n */\n public function send_validate_code()\n {\n\t\t$res = $this->private_send_validate_code();\n\t\tajaxReturn($res);\n }\n\n /**\n * \u524d\u7aef\u53d1\u9001\u77ed\u4fe1\u65b9\u6cd5: APP/WAP/PC \u5171\u7528\u53d1\u9001\u65b9\u6cd5\n */\n public function app_send_validate_code()\n {\n\t\t$res = $this->private_send_validate_code('app');\n\t\tif($res['status'] == 1){\n\t\t\t$this->ajaxReturn(['status' => 0 , 'msg'=>$res['msg'],'data'=>null]);\n\t\t}else\n\t\t\t$this->ajaxReturn(['status' => $res['status'] , 'msg'=>$res['msg'],'data'=>null]);\n }\n\n /**\n * \u9a8c\u8bc1\u77ed\u4fe1\u9a8c\u8bc1\u7801: APP/WAP/PC \u5171\u7528\u53d1\u9001\u65b9\u6cd5\n */\n public function check_validate_code()\n {\n\n $code = I('post.code');\n $mobile = I('mobile');\n $send = I('send');\n $sender = empty($mobile) ? $send : $mobile;\n $type = I('type');\n $session_id = I('unique_id', session_id());\n $scene = I('scene', -1);\n\n $logic = new UsersLogic();\n $res = $logic->check_validate_code($code, $sender, $type, $session_id, $scene);\n ajaxReturn($res);\n }\n\n /**\n * \u68c0\u6d4b\u624b\u673a\u53f7\u662f\u5426\u5df2\u7ecf\u5b58\u5728\n */\n public function issetMobile()\n {\n $mobile = I(\"get.mobile\");\n $users = M('users')->where('mobile', $mobile)->find();\n if ($users)\n exit ('1');\n else\n exit ('0');\n }\n\n public function issetMobileOrEmail()\n {\n $mobile = I(\"mobile\", '0');\n $users = M('users')->where(\"email\", $mobile)->whereOr('mobile', $mobile)->find();\n if ($users)\n exit ('1');\n else\n exit ('0');\n }\n\n /**\n * \u67e5\u8be2\u7269\u6d41\n */\n public function queryExpress($shipping_code, $invoice_no)\n {\n \n// $shipping_code = I('shipping_code');\n// $invoice_no = I('invoice_no');\n\n //\u5224\u65ad\u53d8\u91cf\u662f\u5426\u4e3a\u7a7a\n if((!$shipping_code) or (!$invoice_no)){\n return ['status' => -1, 'message' => '\u53c2\u6570\u6709\u8bef', 'result' => ''];\n }\n\n //\u5feb\u9012\u516c\u53f8\u8f6c\u6362\n switch ($shipping_code) {\n case 'YD':\n $shipping_code = 'YUNDA';\n break;\n \n case 'shunfeng':\n $shipping_code = 'SFEXPRESS';\n break;\n\t\t\t\n\t\t\tcase 'YZPY':\n $shipping_code = 'CHINAPOST';\n break;\n\t\t\t\n\t\t\tcase 'YTO':\n $shipping_code = 'YTO';\n break;\n\n\t\t\tcase 'ZTO':\n $shipping_code = 'ZTO';\n break;\n\n default:\n $shipping_code = '';\n break;\n }\n\n $condition = array(\n 'shipping_code' => $shipping_code,\n 'invoice_no' => $invoice_no,\n );\n $is_exists = Db::name('delivery_express')->where($condition)->find();\n\n //\u5224\u65ad\u7269\u6d41\u8bb0\u5f55\u8868\u662f\u5426\u5df2\u6709\u8bb0\u5f55,\u6ca1\u6709\u5219\u53bb\u8bf7\u6c42\u65b0\u6570\u636e\n if($is_exists){\n $result = unserialize($is_exists['result']);\n\n //1\u4e3a\u8ba2\u5355\u7b7e\u6536\u72b6\u6001,\u8ba21\u5355\u5df2\u7ecf\u7b7e\u6536,\u5df2\u7b7e\u6536\u5219\u4e0d\u53bb\u8bf7\u6c42\u65b0\u6570\u636e\n if($is_exists['issign'] == 1){\n return $result;\n }\n\n $pre_time = time();\n $flag_time = (int)$is_exists['update_time'];\n $space_time = $pre_time - $flag_time;\n //\u8bf7\u6c42\u72b6\u6001\u6b63\u5e38\u7684\u6570\u636e\u8bf7\u6c42\u65f6\u95f4\u95f4\u9694\u5c0f\u4e8e\u4e24\u5c0f\u65f6\u5219\u4e0d\u8bf7\u6c42\u65b0\u6570\u636e\n //\u5176\u4ed6\u6570\u636e\u8bf7\u6c42\u65f6\u95f4\u95f4\u9694\u5c0f\u4e8e\u534a\u5c0f\u65f6\u5219\u4e0d\u8bf7\u6c42\u65b0\u6570\u636e\n if($result['status'] == 0){\n if($space_time < 7200){\n return $result;\n }\n }else{\n if($space_time < 1800){\n return $result;\n }\n }\n \n $result = $this->getDelivery($shipping_code, $invoice_no);\n print_r($result);die;\n $result = json_decode($result, true);\n //\u66f4\u65b0\u8868\u6570\u636e\n $flag = $this->updateData($result, $is_exists['id']);\n return $result;\n \n }else{\n $result = $this->getDelivery($shipping_code, $invoice_no);\n\n $result = json_decode($result, true);\n\n $flag = $this->insertData($result, $shipping_code, $invoice_no);\n return $result;\n }\n // $express_switch = tpCache('express.express_switch');\n // $express_switch_input = input('express_switch/d');\n // $express_switch = is_null($express_switch_input) ? $express_switch : $express_switch_input;\n // if ($express_switch == 1) {\n // require_once(PLUGIN_PATH . 'kdniao/kdniao.php');\n // $kdniao = new \\kdniao();\n // $data['OrderCode'] = empty(I('order_sn')) ? date('YmdHis') : I('order_sn');\n // $data['ShipperCode'] = I('shipping_code');\n // $data['LogisticCode'] = I('invoice_no');\n // $res = $kdniao->getOrderTracesByJson(json_encode($data));\n // $res = json_decode($res, true);\n // if ($res['State'] == 3) {\n // foreach ($res['Traces'] as $val) {\n // $tmp['context'] = $val['AcceptStation'];\n // $tmp['time'] = $val['AcceptTime'];\n // $res['data'][] = $tmp;\n // }\n // $res['status'] = \"200\";\n // } else {\n // $res['message'] = $res['Reason'];\n // }\n // return json($res);\n // } else {\n // $shipping_code = input('shipping_code');\n // $invoice_no = input('invoice_no');\n // if (empty($shipping_code) || empty($invoice_no)) {\n // return json(['status' => 0, 'message' => '\u53c2\u6570\u6709\u8bef', 'result' => '']);\n // }\n // return json(queryExpress($shipping_code, $invoice_no));\n // }\n\n\n }\n\n //\u7269\u6d41\u63d2\u8868\n public function insertData($result, $shipping_code, $invoice_no)\n {\n $data = array(\n 'shipping_code' => $shipping_code,\n 'invoice_no' => $invoice_no,\n 'result' => serialize($result),\n // 'issign' => $result['result']['issign'],\n 'update_time' => time(),\n );\n if(isset($result['result']['issign'])){\n $data['issign'] = $result['result']['issign'];\n }\n \n return Db::name('delivery_express')->strict(false)->insert($data);\n }\n\n //\u7269\u6d41\u8868\u66f4\u65b0\n public function updateData($result, $id)\n {\n $data = array(\n 'result' => serialize($result),\n // 'issign' => $result['result']['issign'],\n 'update_time' => time(),\n );\n if(isset($result['result']['issign'])){\n $data['issign'] = $result['result']['issign'];\n }\n \n return Db::name('delivery_express')->where('id', $id)->strict(false)->update($data);\n }\n\n /**\n *\u7269\u6d41\u63a5\u53e3\n */\n private function getDelivery($shipping_code, $invoice_no)\n {\n $host = \"https://wuliu.market.alicloudapi.com\";//api\u8bbf\u95ee\u94fe\u63a5\n $path = \"/kdi\";//API\u8bbf\u95ee\u540e\u7f00\n $method = \"GET\";\n //\u7269\u6d41\n $appcode = 'c5ccb196109848fe8ea5e1668410132a';//\u66ff\u6362\u6210\u81ea\u5df1\u7684\u963f\u91cc\u4e91appcode\n $headers = array();\n array_push($headers, \"Authorization:APPCODE \" . $appcode);\n $querys = \"no=\".$invoice_no.\"&type=\".$shipping_code; //\u53c2\u6570\u5199\u5728\u8fd9\u91cc\n $bodys = \"\";\n $url = $host . $path . \"?\" . $querys;//url\u62fc\u63a5\n $curl = curl_init();\n curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);\n curl_setopt($curl, CURLOPT_URL, $url);\n curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);\n curl_setopt($curl, CURLOPT_FAILONERROR, false);\n curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($curl, CURLOPT_HEADER, false);\n\n //curl_setopt($curl, CURLOPT_HEADER, true); \u5982\u4e0d\u8f93\u51fajson, \u8bf7\u6253\u5f00\u8fd9\u884c\u4ee3\u7801\uff0c\u6253\u5370\u8c03\u8bd5\u5934\u90e8\u72b6\u6001\u7801\u3002\n //\u72b6\u6001\u7801: 200 \u6b63\u5e38\uff1b400 URL\u65e0\u6548\uff1b401 appCode\u9519\u8bef\uff1b 403 \u6b21\u6570\u7528\u5b8c\uff1b 500 API\u7f51\u7ba1\u9519\u8bef\n if (1 == strpos(\"$\".$host, \"https://\"))\n {\n curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);\n curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);\n }\n\n return curl_exec($curl);\n }\n\n /**\n * \u68c0\u67e5\u8ba2\u5355\u72b6\u6001\n */\n public function check_order_pay_status()\n {\n $order_id = I('order_id/d');\n if (empty($order_id)) {\n $res = ['message' => '\u53c2\u6570\u9519\u8bef', 'status' => -1, 'result' => ''];\n $this->AjaxReturn($res);\n }\n $recharge = I('recharge/d');\n if ($recharge == 1) {\n // \u5145\u503c\u67e5\u8be2\n $order = M('recharge')->field('pay_status')->where(['order_id' => $order_id])->find();\n if ($order['pay_status'] == 1) {\n $res = ['message' => '\u5df2\u652f\u4ed8', 'status' => 1, 'result' => $order];\n } else {\n $res = ['message' => '\u672a\u652f\u4ed8', 'status' => 0, 'result' => $order];\n }\n }else{\n $order = M('order')->field('pay_status')->where(['order_id' => $order_id])->find();\n if ($order['pay_status'] != 0) {\n $res = ['message' => '\u5df2\u652f\u4ed8', 'status' => 1, 'result' => $order];\n } else {\n $res = ['message' => '\u672a\u652f\u4ed8', 'status' => 0, 'result' => $order];\n }\n }\n $this->AjaxReturn($res);\n }\n\n /**\n * \u5e7f\u544a\u4f4djs\n */\n public function ad_show()\n {\n $pid = I('pid/d', 1);\n $where = array(\n 'pid' => $pid,\n 'enable' => 1,\n 'start_time' => array('lt', strtotime(date('Y-m-d H:00:00'))),\n 'end_time' => array('gt', strtotime(date('Y-m-d H:00:00'))),\n );\n $ad = D(\"ad\")->where($where)->order(\"orderby desc\")->cache(true, TPSHOP_CACHE_TIME)->find();\n $this->assign('ad', $ad);\n return $this->fetch();\n }\n\n /**\n * \u641c\u7d22\u5173\u952e\u5b57\n * @return array\n */\n public function searchKey()\n {\n $searchKey = input('key');\n $searchKeyList = Db::name('search_word')\n ->where('keywords', 'like', $searchKey . '%')\n ->whereOr('pinyin_full', 'like', $searchKey . '%')\n ->whereOr('pinyin_simple', 'like', $searchKey . '%')\n ->limit(10)\n ->select();\n if ($searchKeyList) {\n return json(['status' => 1, 'msg' => '\u641c\u7d22\u6210\u529f', 'result' => $searchKeyList]);\n } else {\n return json(['status' => 0, 'msg' => '\u6ca1\u8bb0\u5f55', 'result' => $searchKeyList]);\n }\n }\n\n /**\n * \u6839\u636eip\u8bbe\u7f6e\u83b7\u53d6\u7684\u5730\u533a\u6765\u8bbe\u7f6e\u5730\u533a\u7f13\u5b58\n */\n public function doCookieArea()\n {\n// $ip = '183.147.30.238';//\u6d4b\u8bd5ip\n $address = input('address/a', []);\n if (empty($address) || empty($address['province'])) {\n $this->setCookieArea();\n return;\n }\n $province_id = Db::name('region')->where(['level' => 1, 'name' => ['like', '%' . $address['province'] . '%']])->limit('1')->value('id');\n if (empty($province_id)) {\n $this->setCookieArea();\n return;\n }\n if (empty($address['city'])) {\n $city_id = Db::name('region')->where(['level' => 2, 'parent_id' => $province_id])->limit('1')->order('id')->value('id');\n } else {\n $city_id = Db::name('region')->where(['level' => 2, 'parent_id' => $province_id, 'name' => ['like', '%' . $address['city'] . '%']])->limit('1')->value('id');\n }\n if (empty($address['district'])) {\n $district_id = Db::name('region')->where(['level' => 3, 'parent_id' => $city_id])->limit('1')->order('id')->value('id');\n } else {\n $district_id = Db::name('region')->where(['level' => 3, 'parent_id' => $city_id, 'name' => ['like', '%' . $address['district'] . '%']])->limit('1')->value('id');\n }\n $this->setCookieArea($province_id, $city_id, $district_id);\n }\n\n /**\n * \u8bbe\u7f6e\u5730\u533a\u7f13\u5b58\n * @param $province_id\n * @param $city_id\n * @param $district_id\n */\n private function setCookieArea($province_id = 1, $city_id = 2, $district_id = 3)\n {\n Cookie::set('province_id', $province_id);\n Cookie::set('city_id', $city_id);\n Cookie::set('district_id', $district_id);\n }\n\n public function shop()\n {\n $province_id = input('province_id/d', 0);\n $city_id = input('city_id/d', 0);\n $district_id = input('district_id/d', 0);\n $shop_address = input('shop_address/s', '');\n $longitude = input('longitude/s', 0);\n $latitude = input('latitude/s', 0);\n if (empty($province_id) && empty($province_id) && empty($district_id)) {\n $this->ajaxReturn([]);\n }\n $where = ['deleted' => 0, 'shop_status' => 1, 'province_id' => $province_id, 'city_id' => $city_id, 'district_id' => $district_id];\n $field = '*';\n $order = 'shop_id desc';\n if ($longitude) {\n $field .= ',round(SQRT((POW(((' . $longitude . ' - longitude)* 111),2))+ (POW(((' . $latitude . ' - latitude)* 111),2))),2) AS distance';\n $order = 'distance ASC';\n }\n if($shop_address){\n $where['shop_name|shop_address'] = ['like', '%'.$shop_address.'%'];\n }\n $Shop = new Shop();\n $shop_list = $Shop->field($field)->where($where)->order($order)->select();\n $origins = $destinations = [];\n if ($shop_list) {\n $shop_list = collection($shop_list)->append(['phone','area_list','work_time','work_day'])->toArray();\n $shop_list_length = count($shop_list);\n for ($shop_cursor = 0; $shop_cursor < $shop_list_length; $shop_cursor++) {\n $origin = $latitude . ',' . $longitude;\n array_push($origins, $origin);\n $destination = $shop_list[$shop_cursor]['latitude'] . ',' . $shop_list[$shop_cursor]['longitude'];\n array_push($destinations, $destination);\n }\n $url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=' . implode('|', $origins) . '&destinations=' . implode('|', $destinations) . '&ak=PI:FN:Sgg73Hgc2HizzMiL74TUj42o0j3vM5ALEND_PI';\n $result = httpRequest($url, \"get\");\n $data = json_decode($result, true);\n if (!empty($data['result'])) {\n for ($shop_cursor = 0; $shop_cursor < $shop_list_length; $shop_cursor++) {\n $shop_list[$shop_cursor]['distance_text'] = $data['result'][$shop_cursor]['distance']['text'];\n }\n }else{\n for ($shop_cursor = 0; $shop_cursor < $shop_list_length; $shop_cursor++) {\n $shop_list[$shop_cursor]['distance_text'] = $data['message'];\n }\n }\n }\n $this->ajaxReturn($shop_list);\n }\n\n /**\n * \u68c0\u67e5\u7ed1\u5b9a\u8d26\u53f7\u7684\u5408\u6cd5\u6027\n */\n public function checkBindMobile()\n {\n $mobile = input('mobile/s');\n if(empty($mobile)){\n $this->ajaxReturn(['status' => 0, 'msg' => '\u53c2\u6570\u9519\u8bef', 'result' => '']);\n }\n if(!check_mobile($mobile)){\n $this->ajaxReturn(['status' => 0, 'msg' => '\u624b\u673a\u683c\u5f0f\u9519\u8bef', 'result' => '']);\n }\n //1.\u68c0\u67e5\u8d26\u53f7\u5bc6\u7801\u662f\u5426\u6b63\u786e\n $users = Users::get(['mobile'=>$mobile]);\n if (empty($users)) {\n $this->ajaxReturn(['status' => 0, 'msg' => '\u8d26\u53f7\u4e0d\u5b58\u5728', 'result' => '']);\n }\n $user = new User();\n try{\n $user->setUser($users);\n $user->checkOauthBind();\n $this->ajaxReturn(['status' => 1, 'msg' => '\u8be5\u624b\u673a\u53ef\u7ed1\u5b9a', 'result' => '']);\n }catch (TpshopException $t){\n $error = $t->getErrorArr();\n $this->ajaxReturn($error);\n }\n }\n /**\n * \u68c0\u67e5\u6ce8\u518c\u8d26\u53f7\u7684\u5408\u6cd5\u6027\n */\n public function checkRegMobile()\n {\n $mobile = input('mobile/s');\n if(empty($mobile)){\n $this->ajaxReturn(['status' => 0, 'msg' => '\u53c2\u6570\u9519\u8bef', 'result' => '']);\n }\n if(!check_mobile($mobile)){\n $this->ajaxReturn(['status' => 0, 'msg' => '\u624b\u673a\u683c\u5f0f\u9519\u8bef', 'result' => '']);\n }\n //1.\u68c0\u67e5\u8d26\u53f7\u5bc6\u7801\u662f\u5426\u6b63\u786e\n $users = Db::name('users')->where(\"mobile\", $mobile)->find();\n if ($users) {\n $this->ajaxReturn(['status' => 0, 'msg' => '\u8be5\u624b\u673a\u53f7\u5df2\u88ab\u6ce8\u518c', 'result' => '']);\n }\n $this->ajaxReturn(['status' => 1, 'msg' => '\u8be5\u624b\u673a\u53ef\u6ce8\u518c', 'result' => '']);\n }\n\n\t//------------------------------------------------------------------------------------------\n private function private_send_validate_code($bool=false)\n {\n $this->send_scene = C('SEND_SCENE');\n\n $type = I('type'); //email|\u5176\u4ed6\n $scene = I('scene',0); //\u53d1\u9001\u77ed\u4fe1\u9a8c\u8bc1\u7801\u4f7f\u7528\u573a\u666f\uff0c1\uff1a\u6ce8\u518c\uff0c2\uff1a\u627e\u56de\u5bc6\u7801\uff0c3\uff1a\u5ba2\u6237\u4e0b\u5355\uff0c4\uff1a\u5ba2\u6237\u652f\u4ed8\uff0c5\uff1a\u5546\u5bb6\u53d1\u8d27\uff0c6\uff1a\u8eab\u4efd\u9a8c\u8bc1\uff0c7\uff1a\u8d2d\u4e70\u865a\u62df\u5546\u54c1\u901a\u77e5\n $mobile = I('mobile'); //\u624b\u673a\u53f7\u7801\n $sender = I('send');\n $verify_code = I('verify_code'); //\u56fe\u50cf\u9a8c\u8bc1\u7801\n $mobile = !empty($mobile) ? $mobile : $sender;\n $session_id = I('unique_id', session_id());\n if($bool)session(\"scene\", $scene);\n\n\t\tif($scene == 1){\n\t\t\t$userinfo = M('users')->where(['mobile'=>$mobile])->count();\n\t\t\tif($userinfo)return array('status' => -1, 'msg' => '\u8be5\u624b\u673a\u53f7\u7801\u5df2\u5b58\u5728');\n\t\t}\n\n //\u6ce8\u518c\n if ($scene == 1 && !empty($verify_code)) {\n $verify = new Verify();\n if (!$verify->check($verify_code, 'user_reg')) {\n return array('status' => -1, 'msg' => '\u56fe\u50cf\u9a8c\u8bc1\u7801\u9519\u8bef');\n }\n }\n if ($type == 'email') {\n //\u53d1\u9001\u90ae\u4ef6\u9a8c\u8bc1\u7801\n $logic = new UsersLogic();\n $res = $logic->send_email_code($sender);\n return $res;\n } else {\n //\u53d1\u9001\u77ed\u4fe1\u9a8c\u8bc1\u7801\n $res = checkEnableSendSms($scene);\n if ($res['status'] != 1) {\n return $res;\n }\n //\u5224\u65ad\u662f\u5426\u5b58\u5728\u9a8c\u8bc1\u7801\n $data = M('sms_log')->where(array('mobile' => $mobile, 'session_id' => $session_id, 'status' => 1))->order('id DESC')->find();\n //\u83b7\u53d6\u65f6\u95f4\u914d\u7f6e\n $sms_time_out = tpCache('sms.sms_time_out');\n $sms_time_out = $sms_time_out ? $sms_time_out : 120;\n //120\u79d2\u4ee5\u5185\u4e0d\u53ef\u91cd\u590d\u53d1\u9001\n if ($data && (time() - $data['add_time']) < $sms_time_out) {\n $return_arr = array('status' => -1, 'msg' => $sms_time_out . '\u79d2\u5185\u4e0d\u5141\u8bb8\u91cd\u590d\u53d1\u9001');\n return $return_arr;\n }\n //\u968f\u673a\u4e00\u4e2a\u9a8c\u8bc1\u7801\n $code = rand(1000, 9999);\n $params['code'] = $code;\n\n //\u53d1\u9001\u77ed\u4fe1\n $resp = sendSms($scene, $mobile, $params, $session_id);\n\n if ($resp['status'] == 1) {\n //\u53d1\u9001\u6210\u529f, \u4fee\u6539\u53d1\u9001\u72b6\u6001\u4f4d\u6210\u529f\n M('sms_log')->where(array('mobile' => $mobile, 'code' => $code, 'session_id' => $session_id, 'status' => 0))->save(array('status' => 1, 'add_time'=>time()));\n $return_arr = array('status' => 1, 'msg' => '\u53d1\u9001\u6210\u529f,\u8bf7\u6ce8\u610f\u67e5\u6536');\n } else {\n $return_arr = array('status' => -1, 'msg' => '\u53d1\u9001\u5931\u8d25' . $resp['msg']);\n }\n return $return_arr;\n }\n }\n}", "# Get twilio-ruby from twilio.com/docs/ruby/install\nrequire 'twilio-ruby'\n\n# Get your Account Sid and Auth Token from twilio.com/user/account\naccount_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'\nauth_token = 'your_auth_token'\nclient = Twilio::REST::Client.new(account_sid, auth_token)\n\n# Get an object from its sid. If you do not have a sid,\n# check out the list resource examples on this page\nparticipant = client.account\n .conferences.get('PI:FN:CFbbe4632a3c49700934481addd5ce1659END_PI')\n .participants.get('CA386025c9bf5d6052a1d1ea42b4d16662')\n .update(muted: 'True')\nputs participant.muted\n", "#\n# Copyright 2014 Google Inc. All rights reserved.\n#\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n#\n\n\n\"\"\"Tests for client module.\"\"\"\n\nimport responses\nimport time\n\nimport googlemaps\nfrom googlemaps import client as _client\nimport test as _test\nimport requests\n\nclass ClientTest(_test.TestCase):\n\n def test_no_api_key(self):\n with self.assertRaises(Exception):\n client = googlemaps.Client()\n client.directions(\"Sydney\", \"Melbourne\")\n\n def test_invalid_api_key(self):\n with self.assertRaises(Exception):\n client = googlemaps.Client(key=\"Invalid key.\")\n client.directions(\"Sydney\", \"Melbourne\")\n\n def test_urlencode(self):\n # See GH #72.\n encoded_params = _client.urlencode_params([(\"address\", \"=Sydney ~\")])\n self.assertEqual(\"address=%3DSydney+~\", encoded_params)\n\n @responses.activate\n def test_queries_per_second(self):\n # This test assumes that the time to run a mocked query is\n # relatively small, eg a few milliseconds. We define a rate of\n # 3 queries per second, and run double that, which should take at\n # least 1 second but no more than 2.\n queries_per_second = 3\n query_range = range(queries_per_second * 2)\n for _ in query_range:\n responses.add(responses.GET,\n \"https://maps.googleapis.com/maps/api/geocode/json\",\n body='{\"status\":\"OK\",\"results\":[]}',\n status=200,\n content_type=\"application/json\")\n client = googlemaps.Client(key=\"AIzaasdf\",\n queries_per_second=queries_per_second)\n start = time.time()\n for _ in query_range:\n client.geocode(\"Sesame St.\")\n end = time.time()\n self.assertTrue(start + 1 < end < start + 2)\n\n @responses.activate\n def test_key_sent(self):\n responses.add(responses.GET,\n \"https://maps.googleapis.com/maps/api/geocode/json\",\n body='{\"status\":\"OK\",\"results\":[]}',\n status=200,\n content_type=\"application/json\")\n\n client = googlemaps.Client(key=\"AIzaasdf\")\n client.geocode(\"Sesame St.\")\n\n self.assertEqual(1, len(responses.calls))\n self.assertURLEqual(\"https://maps.googleapis.com/maps/api/geocode/json?\"\n \"key=AIzaasdf&address=Sesame+St.\",\n responses.calls[0].request.url)\n\n @responses.activate\n def test_extra_params(self):\n responses.add(responses.GET,\n \"https://maps.googleapis.com/maps/api/geocode/json\",\n body='{\"status\":\"OK\",\"results\":[]}',\n status=200,\n content_type=\"application/json\")\n\n client = googlemaps.Client(key=\"AIzaasdf\")\n client.geocode(\"Sesame St.\", extra_params={\"foo\": \"bar\"})\n\n self.assertEqual(1, len(responses.calls))\n self.assertURLEqual(\"https://maps.googleapis.com/maps/api/geocode/json?\"\n \"key=AIzaasdf&address=Sesame+St.&foo=bar\",\n responses.calls[0].request.url)\n\n def test_hmac(self):\n \"\"\"\n From http://en.wikipedia.org/wiki/Hash-based_message_authentication_code\n\n HMAC_SHA1(\"key\", \"The quick brown fox jumps over the lazy dog\")\n = 0xde7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9\n \"\"\"\n\n message = \"The quick brown fox jumps over the lazy dog\"\n key = \"a2V5\" # \"key\" -> base64\n signature = \"3nybhbi3iqa8ino29wqQcBydtNk=\"\n\n self.assertEqual(signature, _client.sign_hmac(key, message))\n\n @responses.activate\n def test_url_signed(self):\n responses.add(responses.GET,\n \"https://maps.googleapis.com/maps/api/geocode/json\",\n body='{\"status\":\"OK\",\"results\":[]}',\n status=200,\n content_type=\"application/json\")\n\n client = googlemaps.Client(client_id=\"foo\", client_secret=\"a2V5\")\n client.geocode(\"Sesame St.\")\n\n self.assertEqual(1, len(responses.calls))\n\n # Check ordering of parameters.\n self.assertIn(\"address=Sesame+St.&client=foo&signature\",\n responses.calls[0].request.url)\n self.assertURLEqual(\"https://maps.googleapis.com/maps/api/geocode/json?\"\n \"address=Sesame+St.&client=foo&\"\n \"signature=PI:FN:fxbWUIcNPZSekVOhp2ul9LW5TpY=END_PI\",\n responses.calls[0].request.url)\n\n @responses.activate\n def test_ua_sent(self):\n responses.add(responses.GET,\n \"https://maps.googleapis.com/maps/api/geocode/json\",\n body='{\"status\":\"OK\",\"results\":[]}',\n status=200,\n content_type=\"application/json\")\n\n client = googlemaps.Client(key=\"AIzaasdf\")\n client.geocode(\"Sesame St.\")\n\n self.assertEqual(1, len(responses.calls))\n user_agent = responses.calls[0].request.headers[\"User-Agent\"]\n self.assertTrue(user_agent.startswith(\"GoogleGeoApiClientPython\"))\n\n @responses.activate\n def test_retry(self):\n class request_callback:\n def __init__(self):\n self.first_req = True\n\n def __call__(self, req):\n if self.first_req:\n self.first_req = False\n return (200, {}, '{\"status\":\"OVER_QUERY_LIMIT\"}')\n return (200, {}, '{\"status\":\"OK\",\"results\":[]}')\n\n responses.add_callback(responses.GET,\n \"https://maps.googleapis.com/maps/api/geocode/json\",\n content_type='application/json',\n callback=request_callback())\n\n client = googlemaps.Client(key=\"AIzaasdf\")\n client.geocode(\"Sesame St.\")\n\n self.assertEqual(2, len(responses.calls))\n self.assertEqual(responses.calls[0].request.url, responses.calls[1].request.url)\n\n @responses.activate\n def test_transport_error(self):\n responses.add(responses.GET,\n \"https://maps.googleapis.com/maps/api/geocode/json\",\n status=404,\n content_type='application/json')\n\n client = googlemaps.Client(key=\"AIzaasdf\")\n with self.assertRaises(googlemaps.exceptions.HTTPError) as e:\n client.geocode(\"Foo\")\n\n self.assertEqual(e.exception.status_code, 404)\n\n @responses.activate\n def test_host_override(self):\n responses.add(responses.GET,\n \"https://foo.com/bar\",\n body='{\"status\":\"OK\",\"results\":[]}',\n status=200,\n content_type=\"application/json\")\n\n client = googlemaps.Client(key=\"AIzaasdf\")\n client._get(\"/bar\", {}, base_url=\"https://foo.com\")\n\n self.assertEqual(1, len(responses.calls))\n\n @responses.activate\n def test_custom_extract(self):\n def custom_extract(resp):\n return resp.json()\n\n responses.add(responses.GET,\n \"https://maps.googleapis.com/bar\",\n body='{\"error\":\"errormessage\"}',\n status=403,\n content_type=\"application/json\")\n\n client = googlemaps.Client(key=\"AIzaasdf\")\n b = client._get(\"/bar\", {}, extract_body=custom_extract)\n self.assertEqual(1, len(responses.calls))\n self.assertEqual(\"errormessage\", b[\"error\"])\n\n @responses.activate\n def test_retry_intermittent(self):\n class request_callback:\n def __init__(self):\n self.first_req = True\n\n def __call__(self, req):\n if self.first_req:\n self.first_req = False\n return (500, {}, 'Internal Server Error.')\n return (200, {}, '{\"status\":\"OK\",\"results\":[]}')\n\n responses.add_callback(responses.GET,\n \"https://maps.googleapis.com/maps/api/geocode/json\",\n content_type=\"application/json\",\n callback=request_callback())\n\n client = googlemaps.Client(key=\"AIzaasdf\")\n client.geocode(\"Sesame St.\")\n\n self.assertEqual(2, len(responses.calls))\n\n def test_channel_without_client_id(self):\n with self.assertRaises(ValueError):\n client = googlemaps.Client(key=\"AIzaasdf\", channel=\"mychannel\")\n\n def test_invalid_channel(self):\n # Cf. limitations here:\n # https://developers.google.com/maps/premium/reports\n # /usage-reports#channels\n with self.assertRaises(ValueError):\n client = googlemaps.Client(client_id=\"foo\", client_secret=\"a2V5\",\n channel=\"auieauie$? \")\n\n def test_auth_url_with_channel(self):\n client = googlemaps.Client(key=\"AIzaasdf\",\n client_id=\"foo\",\n client_secret=\"a2V5\",\n channel=\"MyChannel_1\")\n\n # Check ordering of parameters + signature.\n auth_url = client._generate_auth_url(\"/test\",\n {\"param\": \"param\"},\n accepts_clientid=True)\n self.assertEqual(auth_url, \"/test?param=param\"\n \"&channel=MyChannel_1\"\n \"&client=foo\"\n \"&signature=PI:FN:OH18GuQto_mEpxj99UimKskvo4k=END_PI\")\n\n # Check if added to requests to API with accepts_clientid=False\n auth_url = client._generate_auth_url(\"/test\",\n {\"param\": \"param\"},\n accepts_clientid=False)\n self.assertEqual(auth_url, \"/test?param=param&key=AIzaasdf\")\n\n def test_requests_version(self):\n client_args_timeout = {\n \"key\": \"AIzaasdf\",\n \"client_id\": \"foo\",\n \"client_secret\": \"a2V5\",\n \"channel\": \"MyChannel_1\",\n \"connect_timeout\": 5,\n \"read_timeout\": 5\n }\n client_args = client_args_timeout.copy()\n del client_args[\"connect_timeout\"]\n del client_args[\"read_timeout\"]\n\n requests.__version__ = '2.3.0'\n with self.assertRaises(NotImplementedError):\n googlemaps.Client(**client_args_timeout)\n googlemaps.Client(**client_args)\n\n requests.__version__ = '2.4.0'\n googlemaps.Client(**client_args_timeout)\n googlemaps.Client(**client_args)\n\n @responses.activate\n def test_no_retry_over_query_limit(self):\n responses.add(responses.GET,\n \"https://maps.googleapis.com/foo\",\n body='{\"status\":\"OVER_QUERY_LIMIT\"}',\n status=200,\n content_type=\"application/json\")\n\n client = googlemaps.Client(key=\"AIzaasdf\",\n retry_over_query_limit=False)\n\n with self.assertRaises(googlemaps.exceptions.ApiError):\n client._request(\"/foo\", {})\n\n self.assertEqual(1, len(responses.calls))\n", "<?php\n\nreturn [\n /*\n * Debug \u6a21\u5f0f\uff0cbool \u503c\uff1atrue/false\n *\n * \u5f53\u503c\u4e3a false \u65f6\uff0c\u6240\u6709\u7684\u65e5\u5fd7\u90fd\u4e0d\u4f1a\u8bb0\u5f55\n */\n 'debug' => true,\n\n /*\n * \u4f7f\u7528 Laravel \u7684\u7f13\u5b58\u7cfb\u7edf\n */\n 'use_laravel_cache' => true,\n\n /*\n * \u8d26\u53f7\u57fa\u672c\u4fe1\u606f\uff0c\u8bf7\u4ece\u5fae\u4fe1\u516c\u4f17\u5e73\u53f0/\u5f00\u653e\u5e73\u53f0\u83b7\u53d6\n */\n 'app_id' => env('WECHAT_APPID', 'PI:FN:wx85a771d5dac6c0d0END_PI'), // AppID\n 'secret' => env('WECHAT_SECRET', '05dc14834a17fab400da0b532fc8657f'), // AppSecret\n 'token' => env('WECHAT_TOKEN', '3Eowbj5dA4zkbprvK3nnp3NDz/pj6TSVdyVO+b/AX90='), // Token\n 'aes_key' => env('WECHAT_AES_KEY', ''), // EncodingAESKey\n\n /*\n * \u65e5\u5fd7\u914d\u7f6e\n *\n * level: \u65e5\u5fd7\u7ea7\u522b\uff0c\u53ef\u9009\u4e3a\uff1a\n * debug/info/notice/warning/error/critical/alert/emergency\n * file\uff1a\u65e5\u5fd7\u6587\u4ef6\u4f4d\u7f6e(\u7edd\u5bf9\u8def\u5f84!!!)\uff0c\u8981\u6c42\u53ef\u5199\u6743\u9650\n */\n 'log' => [\n 'level' => env('WECHAT_LOG_LEVEL', 'error'),\n 'file' => env('WECHAT_LOG_FILE', storage_path('logs/wechat.log')),\n ],\n /*\n * \u5c0f\u7a0b\u5e8f\u914d\u7f6e\n * */\n \"mini\"=>[\n 'app_id' => '',\n 'secret' => '',\n // \u6307\u5b9a API \u8c03\u7528\u8fd4\u56de\u7ed3\u679c\u7684\u7c7b\u578b\uff1aarray(default)/collection/object/raw/\u81ea\u5b9a\u4e49\u7c7b\u540d\n 'response_type' => 'array',\n\t\t//\u5546\u6237\u53f7\u3001api\u79d8\u94a5\n 'mch_id' =>'',\n 'key' =>'',\n\t\t'cert_path'=> './apiclient_cert.pem', \n\t\t'key_path' => './apiclient_key.pem', \n //\u56de\u8c03\u5730\u5740\n 'notify_url'=>'https://domain/api/notify',\n 'log' => [\n 'level' => 'error',\n 'file' => storage_path('logs/mini.log'),\n ]\n ],\n\n /*\n * OAuth \u914d\u7f6e\n *\n * scopes\uff1a\u516c\u4f17\u5e73\u53f0\uff08snsapi_userinfo / snsapi_base\uff09\uff0c\u5f00\u653e\u5e73\u53f0\uff1asnsapi_login\n * callback\uff1aOAuth\u6388\u6743\u5b8c\u6210\u540e\u7684\u56de\u8c03\u9875\u5730\u5740(\u5982\u679c\u4f7f\u7528\u4e2d\u95f4\u4ef6\uff0c\u5219\u968f\u4fbf\u586b\u5199\u3002\u3002\u3002)\n */\n // 'oauth' => [\n // 'scopes' => array_map('trim', explode(',', env('WECHAT_OAUTH_SCOPES', 'snsapi_userinfo'))),\n // 'callback' => env('WECHAT_OAUTH_CALLBACK', '/examples/oauth_callback.php'),\n // ],\n\n /*\n * \u5fae\u4fe1\u652f\u4ed8\n */\n // 'payment' => [\n // 'merchant_id' => env('WECHAT_PAYMENT_MERCHANT_ID', 'your-mch-id'),\n // 'key' => env('WECHAT_PAYMENT_KEY', 'key-for-signature'),\n // 'cert_path' => env('WECHAT_PAYMENT_CERT_PATH', 'path/to/your/cert.pem'), // XXX: \u7edd\u5bf9\u8def\u5f84\uff01\uff01\uff01\uff01\n // 'key_path' => env('WECHAT_PAYMENT_KEY_PATH', 'path/to/your/key'), // XXX: \u7edd\u5bf9\u8def\u5f84\uff01\uff01\uff01\uff01\n // // 'device_info' => env('WECHAT_PAYMENT_DEVICE_INFO', ''),\n // // 'sub_app_id' => env('WECHAT_PAYMENT_SUB_APP_ID', ''),\n // // 'sub_merchant_id' => env('WECHAT_PAYMENT_SUB_MERCHANT_ID', ''),\n // // ...\n // ],\n\n /*\n * \u5f00\u53d1\u6a21\u5f0f\u4e0b\u7684\u514d\u6388\u6743\u6a21\u62df\u6388\u6743\u7528\u6237\u8d44\u6599\n *\n * \u5f53 enable_mock \u4e3a true \u5219\u4f1a\u542f\u7528\u6a21\u62df\u5fae\u4fe1\u6388\u6743\uff0c\u7528\u4e8e\u5f00\u53d1\u65f6\u4f7f\u7528\uff0c\u5f00\u53d1\u5b8c\u6210\u8bf7\u5220\u9664\u6216\u8005\u6539\u4e3a false \u5373\u53ef\n */\n // 'enable_mock' => env('WECHAT_ENABLE_MOCK', true),\n // 'mock_user' => [\n // \"openid\" =>\"odh7zsgI75iT8FRh0fGlSojc9PWM\",\n // // \u4ee5\u4e0b\u5b57\u6bb5\u4e3a scope \u4e3a snsapi_userinfo \u65f6\u9700\u8981\n // \"nickname\" => \"overtrue\",\n // \"sex\" =>\"1\",\n // \"province\" =>\"\u5317\u4eac\",\n // \"city\" =>\"\u5317\u4eac\",\n // \"country\" =>\"\u4e2d\u56fd\",\n // \"headimgurl\" => \"http://wx.qlogo.cn/mmopen/C2rEUskXQiblFYMUl9O0G05Q6pKibg7V1WpHX6CIQaic824apriabJw4r6EWxziaSt5BATrlbx1GVzwW2qjUCqtYpDvIJLjKgP1ug/0\",\n // ],\n];\n", "\"\"\"\nDjango settings for backend project.\n\nGenerated by 'django-admin startproject' using Django 3.1.3.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/3.1/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/3.1/ref/settings/\n\"\"\"\n\nfrom pathlib import Path\nfrom datetime import timedelta\nimport os\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'PI:FN:2(iwreobf4b(-=h_p=^!obgxdgn3_*s!17=_3wc4dun9_y^q+cEND_PI'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'backend.core',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'backend.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'backend.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/3.1/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': BASE_DIR / 'db.sqlite3',\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nLOGIN_URL = \"/api/v1/signin\"\nSIMPLE_JWT = {\n \"ACCESS_TOKEN_LIFETIME\": timedelta(minutes=60),\n \"REFRESH_TOKEN_LIFETIME\": timedelta(days=2),\n}\n\nCORS_ORIGIN_WHITELIST = [\"http://localhost:3000\", \"http://127.0.0.1:3000\"]\n# Internationalization\n# https://docs.djangoproject.com/en/3.1/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.1/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, \"static/\")\n\nREST_FRAMEWORK = {\n \"DEFAULT_AUTHENTICATION_CLASSES\": [\"rest_framework_simplejwt.authentication.JWTAuthentication\"],\n \"DEFAULT_RENDERER_CLASSES\": [\"rest_framework.renderers.JSONRenderer\"],\n \"TEST_REQUEST_DEFAULT_FORMAT\": \"json\",\n \"DEFAULT_PERMISSION_CLASSES\": (\"rest_framework.permissions.DjangoModelPermissions\",),\n}\n", "/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License;\n * you may not use this file except in compliance with the Elastic License.\n */\n\nimport expect from 'expect.js';\n\nimport { metadataQuery } from '../../../../plugins/infra/public/containers/metadata/metadata.gql_query';\nimport { MetadataQuery } from '../../../../plugins/infra/public/graphql/types';\nimport { KbnTestProvider } from './types';\n\nconst metadataTests: KbnTestProvider = ({ getService }) => {\n const esArchiver = getService('esArchiver');\n const client = getService('infraOpsGraphQLClient');\n\n describe('metadata', () => {\n describe('docker', () => {\n before(() => esArchiver.load('infra/6.6.0/docker'));\n after(() => esArchiver.unload('infra/6.6.0/docker'));\n\n it('supports the metadata container query', () => {\n return client\n .query<MetadataQuery.Query>({\n query: metadataQuery,\n variables: {\n sourceId: 'default',\n nodeId: 'PI:FN:242fddb9d376bbf0e38025d81764847ee5ec0308adfa095918fd3266f9d06c6aEND_PI',\n nodeType: 'container',\n },\n })\n .then(resp => {\n const metadata = resp.data.source.metadataByNode;\n if (metadata) {\n expect(metadata.features.length).to.be(8);\n expect(metadata.name).to.equal('docker-autodiscovery_nginx_1');\n } else {\n throw new Error('Metadata should never be empty');\n }\n });\n });\n });\n\n describe('hosts', () => {\n before(() => esArchiver.load('infra/metrics_and_logs'));\n after(() => esArchiver.unload('infra/metrics_and_logs'));\n\n it('supports the metadata container query', () => {\n return client\n .query<MetadataQuery.Query>({\n query: metadataQuery,\n variables: {\n sourceId: 'default',\n nodeId: 'demo-stack-nginx-01',\n nodeType: 'host',\n },\n })\n .then(resp => {\n const metadata = resp.data.source.metadataByNode;\n if (metadata) {\n expect(metadata.features.length).to.be(14);\n expect(metadata.name).to.equal('demo-stack-nginx-01');\n } else {\n throw new Error('Metadata should never be empty');\n }\n });\n });\n });\n });\n};\n\n// tslint:disable-next-line no-default-export\nexport default metadataTests;\n", "require 'spec_helper'\n\nRSpec.describe Airbrake::AirbrakeLogger do\n let(:project_id) { 113743 }\n let(:project_key) { 'PI:FN:fd04e13d806a90f96614ad8e529b2822END_PI' }\n\n let(:endpoint) do\n \"https://airbrake.io/api/v3/projects/#{project_id}/notices?key=#{project_key}\"\n end\n\n let(:airbrake) do\n Airbrake::Notifier.new(project_id: project_id, project_key: project_key)\n end\n\n let(:logger) { Logger.new('/dev/null') }\n\n subject { described_class.new(logger) }\n\n def wait_for_a_request_with_body(body)\n wait_for(a_request(:post, endpoint).with(body: body)).to have_been_made.once\n end\n\n before do\n stub_request(:post, endpoint).to_return(status: 201, body: '{}')\n end\n\n describe \"#airbrake_notifier\" do\n it \"has the default notifier installed by default\" do\n expect(subject.airbrake_notifier).to be_an(Airbrake::Notifier)\n end\n\n it \"installs Airbrake notifier\" do\n notifier_id = airbrake.object_id\n expect(subject.airbrake_notifier.object_id).not_to eq(notifier_id)\n\n subject.airbrake_notifier = airbrake\n expect(subject.airbrake_notifier.object_id).to eq(notifier_id)\n end\n\n context \"when Airbrake is installed explicitly\" do\n let(:out) { StringIO.new }\n let(:logger) { Logger.new(out) }\n\n before do\n subject.airbrake_notifier = airbrake\n end\n\n it \"both logs and notifies\" do\n msg = 'bingo'\n subject.fatal(msg)\n\n wait_for_a_request_with_body(/\"message\":\"#{msg}\"/)\n expect(out.string).to match(/FATAL -- : #{msg}/)\n end\n\n it \"sets the correct severity\" do\n subject.fatal('bango')\n wait_for_a_request_with_body(/\"context\":{.*\"severity\":\"critical\".*}/)\n end\n\n it \"sets the correct component\" do\n subject.fatal('bingo')\n wait_for_a_request_with_body(/\"component\":\"log\"/)\n end\n\n it \"strips out internal logger frames\" do\n subject.fatal('bongo')\n\n wait_for(\n a_request(:post, endpoint).\n with(body: %r{\"file\":\".+/logger.rb\"})\n ).not_to have_been_made\n wait_for(a_request(:post, endpoint)).to have_been_made.once\n end\n end\n\n context \"when Airbrake is not installed\" do\n it \"only logs, never notifies\" do\n out = StringIO.new\n l = described_class.new(Logger.new(out))\n l.airbrake_notifier = nil\n msg = 'bango'\n\n l.fatal(msg)\n\n wait_for(a_request(:post, endpoint)).not_to have_been_made\n expect(out.string).to match('FATAL -- : bango')\n end\n end\n end\n\n describe \"#airbrake_level\" do\n context \"when not set\" do\n it \"defaults to Logger::WARN\" do\n expect(subject.airbrake_level).to eq(Logger::WARN)\n end\n end\n\n context \"when set\" do\n before do\n subject.airbrake_level = Logger::FATAL\n end\n\n it \"does not notify below the specified level\" do\n subject.error('bingo')\n wait_for(a_request(:post, endpoint)).not_to have_been_made\n end\n\n it \"notifies in the current or above level\" do\n subject.fatal('bingo')\n wait_for(a_request(:post, endpoint)).to have_been_made\n end\n\n it \"raises error when below the allowed level\" do\n expect do\n subject.airbrake_level = Logger::DEBUG\n end.to raise_error(/severity level \\d is not allowed/)\n end\n end\n end\nend\n", "#!/usr/bin/env python\n\nimport common\nimport json\nimport docker_utils\n\nnginx_sites_available = '/etc/nginx/sites-available'\nCERT_DIR = '/root/certs'\n\nimport subprocess\n\ndef create_certificates(domains):\n format_args = {'cert_dir': CERT_DIR}\n\n import os.path\n if not os.path.isfile(os.path.join(CERT_DIR, 'acmeCA.key.deleteme')):\n commands = \"\"\"openssl rsa -in %(cert_dir)s/acmeCA.key -out %(cert_dir)s/acmeCA.key.deleteme\"\"\" % format_args\n for command in [cmd for cmd in commands.split(\"\\n\") if cmd]:\n subprocess.call([arg for arg in command.split(\" \") if arg])\n\n for domain in domains:\n create_certificate(domain)\n\ndef create_certificate(domain):\n format_args = {'domain': domain,\n 'cert_dir': CERT_DIR}\n import os.path\n if os.path.isfile('%(cert_dir)s/%(domain)s.key' % format_args):\n return\n \n commands = \"\"\"\n openssl genrsa -out %(cert_dir)s/%(domain)s.key 2048\n openssl req -new -key %(cert_dir)s/%(domain)s.key -out %(cert_dir)s/%(domain)s.csr -subj /C=DE/ST=Niedersachsen/L=Osnabrueck/O=OPS/CN=%(domain)s\n openssl x509 -req -in %(cert_dir)s/%(domain)s.csr -CA %(cert_dir)s/acmeCA.pem -CAkey %(cert_dir)s/acmeCA.key.deleteme -CAcreateserial -out %(cert_dir)s/%(domain)s.crt -days 500\n rm %(cert_dir)s/%(domain)s.csr\n\"\"\" % format_args\n \n for command in [cmd for cmd in commands.split(\"\\n\") if cmd]:\n print command.split(\" \")\n subprocess.call([arg for arg in command.split(\" \") if arg])\n\n# create_certificates([host.domains[0] for host in common.get_vhost_config()])\n\ndef update_vhosts_config(applications):\n jsonFile = open('/root/config/nginx_vhosts.json', \"r\")\n data = json.load(jsonFile)\n jsonFile.close()\n\n for app in applications:\n docker_container_config = docker_utils.get_config(app.docker_container_name)\n vhost_config = data[app.vhost_name]\n vhost_config['port'] = docker_container_config.port if not app.docker_container_port else app.docker_container_port\n vhost_config['ip_addr'] = docker_container_config.ip_addr\n \n jsonFile = open('/root/config/nginx_vhosts.json', \"w+\")\n jsonFile.write(json.dumps(data, indent=4, sort_keys=True))\n jsonFile.close()\n\n\ndef update_vhosts(vhosts):\n for vhost in vhosts:\n host = vhost.host\n port = vhost.port\n ip_addr = vhost.ip_addr\n domains = vhost.domains\n flags = vhost.flags\n\n location_tmpl = \"\"\"\n location %(path)s {\n proxy_pass http://upstream_%(upstream)s%(upstream_path)s;\n proxy_http_version 1.1;\n %(redirect_rule)s\n proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;\n proxy_set_header Host %(host)s;\n %(set_script_name)s\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Port $server_port;\n %(misc)s\n }\n \"\"\"\n location_tmpl_params = {\n 'redirect_rule': 'proxy_redirect off;' if flags.get('disableRedirect') else ''\n }\n\n def render_location(location_dict):\n location_dict['host'] = location_dict.get('host', '$host')\n location_dict['set_script_name'] = location_dict.get('set_script_name', '')\n location_dict['misc'] = location_dict.get('misc', '')\n location_dict['upstream_path'] = location_dict.get('upstream_path', '')\n params = dict(location_dict.items()+ location_tmpl_params.items())\n # print params\n return location_tmpl % params\n \n location_parameters = { 'upstream': domains[0], 'path': '/', 'host': flags.get('forceHost', '$host'),\n 'upstream_path': flags.get('upstream_path', '')}\n\n if 'htpasswd_file' in flags:\n location_parameters['misc'] = 'auth_basic \"Restricted\"; auth_basic_user_file %s;' % (flags['htpasswd_file'])\n\n if 'location_extra' in flags:\n location_parameters['misc'] = location_parameters['misc'] if 'misc' in location_parameters else ''\n location_parameters['misc'] += flags['location_extra']\n\n location = render_location(location_parameters)\n \n location_ssl = location\n\n upstreams = [{\n 'local_port': port,\n 'local_address': ip_addr,\n 'name': domains[0]\n }]\n\n if flags.get('sslToPort'):\n upstream_name = \"%s_ssl \" % domains[0]\n location_ssl = render_location({ 'upstream': upstream_name, 'path': '/', 'host': flags.get('forceHost', '$host')})\n upstreams.append({\n 'local_port': flags.get('sslToPort'),\n 'local_address': ip_addr,\n 'name': upstream_name\n })\n\n if flags.get('httpsToHttpPaths'):\n for path in flags.get('httpsToHttpPaths').split(','): \n location_ssl += \"\\n\" + render_location({ 'upstream': domains[0], 'path': '/%s' % path, 'host': flags.get('forceHost', '$host') })\n\n other_locations = [{ 'upstream': domains[0], 'path': '@failover', 'host': flags.get('forceHost', '$host')}]\n other_locations_https = []\n\n path_idx = 0\n for path, path_config in vhost.paths.items():\n upstream_name = \"%s_%s \" % (domains[0], path_idx)\n upstreams.append({\n 'local_port': path_config['port'],\n 'local_address': vm_map[path_config['host']]['local_address'],\n 'name': upstream_name\n })\n\n if path_config['secure']:\n other_locations_https.append({ 'upstream': upstream_name, 'path': '/%s' % path,\n 'misc': '''\n''',\n 'set_script_name': ('proxy_set_header SCRIPT_NAME /%s;' % path.rstrip('/')) if path_config.get('setScriptName') else '',\n 'host': flags.get('forceHost', '$host')})\n else:\n other_locations.append({ 'upstream': upstream_name, 'path': '/%s' % path,\n 'misc': '''\n\t error_page 500 = @failover;\n\t proxy_intercept_errors on;\n''',\n 'set_script_name': ('proxy_set_header SCRIPT_NAME /%s;' % path.rstrip('/')) if path_config.get('setScriptName') else '',\n 'host': flags.get('forceHost', '$host')})\n \n\n path_idx += 1\n\n upstream_tmpl = 'upstream upstream_%(name)s { server %(local_address)s:%(local_port)s; }'\n\n rewrites = ''\n\n extra_directives = ''\n if flags.get('block_robots'):\n extra_directives += '''\n location = /robots.txt {\n alias /var/www/robots_deny.txt;\n }\n '''\n\n if flags.get('allow_robots'):\n extra_directives += '''\n location = /robots.txt {\n alias /var/www/robots_allow.txt;\n }\n '''\n\n if 'server_config_extra' in flags:\n extra_directives += flags['server_config_extra']\n\n if flags.get('aliases'):\n aliases = flags.get('aliases').split(\"\\n\")\n for alias in aliases:\n extra_directives += '''\n location /%s {\n alias %s;\n }\n ''' % tuple(alias.strip().split('->'))\n\n \n if vhost.rewrites:\n rewrites += vhost.rewrites\n\n location_http = location if flags.get('allow_http') else 'return 301 https://$host$request_uri;'\n\n if flags.get('httpPaths'):\n for path in flags.get('httpPaths').split(','): \n location_http = \"\\n\" + render_location({ 'upstream': domains[0], 'path': '/%s' % path, 'host': flags.get('forceHost', '$host') }) + \"\\n\" + ''' location / { return 301 https://$host$request_uri; } \n '''\n\n format_args = {\n 'upstreams': \"\\n\".join([upstream_tmpl % up for up in upstreams]),\n 'public_port': port,\n 'other_locations': \"\\n\".join([render_location(location_dict) for location_dict in other_locations]),\n 'other_locations_https': \"\\n\".join([render_location(location_dict) for location_dict in other_locations_https]),\n 'extra_directives': extra_directives,\n 'domain': domains[0],\n 'server_names': ' '.join(domains) if not flags.get('rewriteDomains') else domains[0],\n 'location': location_ssl,\n 'rewrites': rewrites,\n 'upload_limit': flags.get('uploadLimit', '20M'),\n 'location_http': location_http,\n 'cert_dir': CERT_DIR}\n \n \n config = \"\"\"\n %(upstreams)s\n server {\n listen 80;\n server_name %(server_names)s;\n client_max_body_size %(upload_limit)s;\n\n %(rewrites)s\n\n %(location_http)s\n\n %(other_locations)s\n\n %(extra_directives)s\n }\n \n \"\"\" % format_args\n\n if not flags.get('noSsl'):\n config += \"\"\"\n server {\n listen 443 ssl;\n server_name %(server_names)s;\n client_max_body_size %(upload_limit)s;\n \n ssl on;\n ssl_certificate %(cert_dir)s/%(domain)s.cer;\n ssl_certificate_key %(cert_dir)s/%(domain)s.key;\n ssl_ciphers PI:FN:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-RC4-SHA:ECDHE-RSA-AES128-SHA:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH:!CAMELLIAEND_PI;\n ssl_protocols TLSv1.2 TLSv1.1 TLSv1;\n ssl_prefer_server_ciphers on;\n \n %(location)s\n\n %(other_locations_https)s\n\n %(extra_directives)s\n }\n \"\"\" % format_args\n\n\n if flags.get('rewriteDomains'):\n for domain in domains[1:]:\n config += \"\"\"\nserver {\n listen 80;\n server_name %(domain1)s;\n return 301 http://%(domain2)s$request_uri;\n}\n\"\"\" % {'domain1': domain, 'domain2': domains[0]}\n\n\n\n f = open('%s/%s' % (nginx_sites_available, domains[0]), 'w')\n f.write(config)\n f.close()\n \n '''\n proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n '''\n\nupdate_vhosts_config(common.get_applications_config())\nupdate_vhosts(common.get_vhost_config())\n", "\ufeffusing Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.AspNetCore.Identity;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\nusing IdentityServer4.Services;\nusing System.Reflection;\nusing IdentityServer4;\nusing System;\nusing Microsoft.AspNetCore.HttpOverrides;\nusing System.Security.Cryptography.X509Certificates;\nusing AspNetCoreSpa.STS.Models;\nusing AspNetCoreSpa.STS.Resources;\nusing Microsoft.IdentityModel.Tokens;\nusing AspNetCoreSpa.STS.Services.Certificate;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing Microsoft.AspNetCore.Localization;\nusing AspNetCoreSpa.STS.Services;\nusing Microsoft.Extensions.Options;\nusing Microsoft.Extensions.Hosting;\nusing System.IO;\n\nnamespace AspNetCoreSpa.STS\n{\n public class Startup\n {\n public static IConfiguration Configuration { get; set; }\n public IWebHostEnvironment Environment { get; }\n\n public Startup(IConfiguration configuration, IWebHostEnvironment environment)\n {\n Configuration = configuration;\n Environment = environment;\n }\n\n public void ConfigureServices(IServiceCollection services)\n {\n var x509Certificate2 = GetCertificate(Environment, Configuration);\n\n services.Configure<StsConfig>(Configuration.GetSection(\"StsConfig\"));\n services.Configure<EmailSettings>(Configuration.GetSection(\"EmailSettings\"));\n services.AddSingleton<LocService>();\n services.AddLocalization(options => options.ResourcesPath = \"Resources\");\n services.Configure<RequestLocalizationOptions>(\n options =>\n {\n var supportedCultures = new List<CultureInfo>\n {\n new CultureInfo(\"en-US\"),\n new CultureInfo(\"de-DE\"),\n new CultureInfo(\"de-CH\"),\n new CultureInfo(\"it-IT\"),\n new CultureInfo(\"gsw-CH\"),\n new CultureInfo(\"fr-FR\")\n };\n\n options.DefaultRequestCulture = new RequestCulture(culture: \"de-DE\", uiCulture: \"de-DE\");\n options.SupportedCultures = supportedCultures;\n options.SupportedUICultures = supportedCultures;\n\n var providerQuery = new LocalizationQueryProvider\n {\n QureyParamterName = \"ui_locales\"\n };\n\n options.RequestCultureProviders.Insert(0, providerQuery);\n });\n\n services.Configure<IISOptions>(options =>\n {\n options.AutomaticAuthentication = false;\n options.AuthenticationDisplayName = \"Windows\";\n });\n\n var connectionString = Configuration.GetConnectionString(\"DefaultConnection\");\n var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;\n\n // Add framework services.\n services.AddDbContextPool<ApplicationDbContext>(options =>\n {\n options.UseSqlite(connectionString);\n options.UseSqlite(connectionString, b => b.MigrationsAssembly(migrationsAssembly));\n });\n\n services.AddIdentity<ApplicationUser, ApplicationRole>()\n .AddEntityFrameworkStores<ApplicationDbContext>()\n .AddDefaultTokenProviders();\n\n services.AddCors(options =>\n {\n options.AddPolicy(\"CorsPolicy\", corsBuilder =>\n {\n corsBuilder.AllowAnyHeader()\n .AllowAnyMethod()\n .AllowAnyOrigin();\n });\n });\n\n services.AddTransient<ISeedData, SeedData>();\n services.AddTransient<IProfileService, CustomProfileService>();\n services.AddTransient<ApplicationDbContext>();\n\n services.AddControllersWithViews();\n services.AddRazorPages()\n .AddViewLocalization()\n .AddDataAnnotationsLocalization(options =>\n {\n options.DataAnnotationLocalizerProvider = (type, factory) =>\n {\n var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);\n return factory.Create(\"SharedResource\", assemblyName.Name);\n };\n });\n\n services.AddTransient<IProfileService, CustomProfileService>();\n\n services.AddTransient<IEmailSender, EmailSender>();\n\n var identityServer = services.AddIdentityServer(options =>\n {\n options.Events.RaiseErrorEvents = true;\n options.Events.RaiseInformationEvents = true;\n options.Events.RaiseFailureEvents = true;\n options.Events.RaiseSuccessEvents = true;\n })\n .AddSigningCredential(x509Certificate2)\n // this adds the config data from DB (clients, resources, CORS)\n .AddConfigurationStore(options =>\n {\n options.ConfigureDbContext = builder =>\n builder.UseSqlite(connectionString,\n sql => sql.MigrationsAssembly(migrationsAssembly));\n })\n\n // OR In memory config store\n //.AddInMemoryApiResources(Config.GetApiResources())\n //.AddInMemoryClients(Config.GetClients(Configuration[\"ClientUrls\"]))\n //.AddInMemoryIdentityResources(Config.GetIdentityResources())\n\n // this adds the operational data from DB (codes, tokens, consents)\n .AddOperationalStore(options =>\n {\n options.ConfigureDbContext = builder =>\n builder.UseSqlite(connectionString,\n sql => sql.MigrationsAssembly(migrationsAssembly));\n\n // this enables automatic token cleanup. this is optional.\n options.EnableTokenCleanup = true;\n // options.TokenCleanupInterval = 15; // interval in seconds. 15 seconds useful for debugging\n })\n .AddAspNetIdentity<ApplicationUser>()\n .AddProfileService<CustomProfileService>();\n\n services.AddAuthentication()\n .AddGoogle(options =>\n {\n options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;\n\n options.ClientId = \"PI:FN:476611152863-ltgqfk9jhq1vsenin5039n58ogkraltb.apps.googleusercontent.comEND_PI\";\n options.ClientSecret = \"PI:FN:rSHvhgdOQUB4KMc5JS1alzhgEND_PI\";\n })\n .AddOpenIdConnect(\"aad\", \"Login with Azure AD\", options =>\n {\n options.Authority = $\"https://login.microsoftonline.com/common\";\n options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false };\n options.ClientId = \"PI:FN:99eb0b9d-ca40-476e-b5ac-6f4c32bfb530END_PI\";\n options.CallbackPath = \"/signin-oidc\";\n options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;\n });\n }\n\n public void Configure(IApplicationBuilder app, IWebHostEnvironment env)\n {\n // https://github.com/openiddict/openiddict-core/issues/518\n // And\n // https://github.com/aspnet/Docs/issues/2384#issuecomment-297980490\n var forwarOptions = new ForwardedHeadersOptions\n {\n ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto\n };\n forwarOptions.KnownNetworks.Clear();\n forwarOptions.KnownProxies.Clear();\n\n app.UseForwardedHeaders(forwarOptions);\n\n if (env.IsDevelopment())\n {\n app.UseDeveloperExceptionPage();\n }\n else\n {\n app.UseHsts();\n app.UseExceptionHandler(\"/Home/Error\");\n }\n\n var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();\n app.UseRequestLocalization(locOptions.Value);\n\n app.UseHttpsRedirection();\n\n // app.UseMiddleware<AdminSafeListMiddleware>(\n // Configuration[\"AdminSafeList\"]);\n\n app.UseStaticFiles();\n\n app.UseRouting();\n\n app.UseCors(\"CorsPolicy\");\n\n app.UseAuthentication();\n\n app.UseIdentityServer();\n\n app.UseAuthorization();\n\n app.UseEndpoints(endpoints =>\n {\n endpoints.MapControllerRoute(\n name: \"default\",\n pattern: \"{controller=Home}/{action=Index}/{id?}\");\n endpoints.MapRazorPages();\n });\n }\n \n private static X509Certificate2 GetCertificate(IWebHostEnvironment environment, IConfiguration configuration)\n {\n var useDevCertificate = bool.Parse(configuration[\"UseDevCertificate\"]);\n\n X509Certificate2 cert = new X509Certificate2(Path.Combine(environment.ContentRootPath, \"sts_dev_cert.pfx\"), \"1234\");\n\n if (environment.IsProduction() && !useDevCertificate)\n {\n var useLocalCertStore = Convert.ToBoolean(configuration[\"UseLocalCertStore\"]);\n\n if (useLocalCertStore)\n {\n using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))\n {\n var certificateThumbprint = configuration[\"CertificateThumbprint\"];\n\n store.Open(OpenFlags.ReadOnly);\n var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);\n cert = certs[0];\n store.Close();\n }\n }\n else\n {\n // Azure deployment, will be used if deployed to Azure\n var vaultConfigSection = configuration.GetSection(\"Vault\");\n var keyVaultService = new KeyVaultCertificateService(vaultConfigSection[\"Url\"], vaultConfigSection[\"ClientId\"], vaultConfigSection[\"ClientSecret\"]);\n cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection[\"CertificateName\"]);\n }\n }\n return cert;\n }\n }\n \n}\n"]