loubnabnl HF staff commited on
Commit
461c45d
0 Parent(s):

Duplicate from bigcode/pii-test

Browse files
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Pii Test
3
+ emoji: 🏃
4
+ colorFrom: blue
5
+ colorTo: red
6
+ sdk: streamlit
7
+ sdk_version: 1.10.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ duplicated_from: bigcode/pii-test
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code was adapted from https://huggingface.co/spaces/HugoLaurencon/examples_before_after_pii/
3
+ """
4
+
5
+ import streamlit as st
6
+ import json
7
+ import pandas as pd
8
+
9
+ st.set_page_config(page_title="PII Visualization", layout="wide")
10
+ st.title("PII Visualization")
11
+
12
+ tags = ["KEY", "IP_ADDRESS", "EMAIL"]
13
+ types = ["False positives", "False negatives"]
14
+ matches = {"False negatives": "fn", "False positives": "fp"}
15
+
16
+ @st.cache()
17
+ def load_data():
18
+ with open(f"data/{chosen_tag.lower()}_detections_{matches[chosen_type]}.json", "r") as f:
19
+ samples = json.load(f)
20
+ return samples
21
+
22
+ col1, col2, col3 = st.columns([1, 1, 4])
23
+ with col1:
24
+ chosen_type = st.selectbox(
25
+ label="Select the type of detections",
26
+ options=types,
27
+ index=0)
28
+ with col2:
29
+ chosen_tag = st.selectbox(
30
+ label="Select the PII TAG",
31
+ options=tags,
32
+ index=0)
33
+
34
+ samples = load_data()
35
+ max_docs = len(samples)
36
+
37
+ col1, col2 = st.columns([2, 4])
38
+ with col1:
39
+ index_example = st.number_input(f"Index of the chosen example from the existing {max_docs}", min_value=0, max_value=max_docs-1, value=0, step=1)
40
+
41
+ st.write("Scroll down to visualize PII detections highlighted in yellow, we split the text at the start and end of the key to highlight it.")
42
+
43
+ detection = samples[index_example]
44
+ delimiter = f"PI:{matches[chosen_type].upper()}"
45
+ count = detection.count(delimiter)
46
+
47
+ st.subheader(f"{count} {chosen_type.lower()} for {chosen_tag} tag in example {index_example}:")
48
+
49
+ subparts = []
50
+ advance, found = 0, 0
51
+ last_part = detection
52
+ while found < count:
53
+ start = advance + last_part.index(delimiter)
54
+ end = advance + last_part.index("END_PI")+ 6
55
+ st.code(detection[advance:start])
56
+ st.markdown("<span style=\"background-color: #FFFF00\">"+detection[start:end]+"</span>", unsafe_allow_html=True)
57
+ last_part = detection[end:]
58
+ advance = end
59
+ found += 1
60
+ st.code(last_part)
61
+
data/email_detections_fn.json ADDED
@@ -0,0 +1 @@
 
 
1
+ ["/**\n * @author {PI:FN:benyuwan@gmail.comEND_PI}\n * @file tags\u7684model\n */\n\nimport query from '../utils/query'\nimport escape from '../utils/escape'\n\nclass Tags {\n async updateTag(id, tags) {\n return await query(escape`UPDATE ARTICLE SET tags=${tags} WHERE id=${id}`)\n }\n}\n\nexport default new Tags()\n", "<?php\n# Variables\n$page = 'contact';\n?>\n\n<!DOCTYPE html>\n<html lang=en>\n<head>\n<?php\nob_start();\ninclude( \"includes/head.php\" );\n$buffer = ob_get_contents();\nob_end_clean();\n$buffer = str_replace( \"%TITLE%\", \"Cool City Band - Contact\", $buffer );\necho $buffer;\n?>\n<meta name=\"description\" content=\"\">\n</head>\n\n<body>\n<!-- Navigation -->\n<?php include ('includes/navigation.php') ?>\n<section class=\"section1\">\n <div class=\"container\" style=\"min-height:900px\">\n <div class=\"row\">\n <div class=\"col-lg-12\">\n <h1 class=\"page-header\">Contact Us </h1>\n </div>\n </div>\n <div class=\"row section-content\">\n <div class=\"col-md-8\">\n <p class=\"lead\"> Thank You!\n \n Your message has been sent, we'll be in touch shortly. </p>\n </div>\n <div class=\"col-md-4\">\n <h3>Leader/Conductor/Pianist</h3>\n <p><strong>Roy Geesa</strong></p>\n <p><i class=\"fa fa-phone\"></i> 317-529-3640 (text/voice)</p>\n <p><i class=\"fa fa-envelope-o\"></i> <a href=\"mailto:roygeesa@gmail.com\">PI:FN:roygeesa@gmail.comEND_PI</a> </p>\n <ul class=\"list-unstyled list-inline list-social-icons\">\n <li> <a href=\"https://www.facebook.com/Cool-City-Band-149866258393477/?fref=ts\" target=\"_blank\"><i class=\"fa fa-facebook-square fa-2x\"></i></a> </li>\n </ul>\n </div>\n </div>\n <!-- /.row --> \n \n </div>\n</section>\n<?php include ('includes/stayintouch.php') ?>\n<?php include ('includes/footer.php') ?>\n\n<!-- /.container -->\n<?php include ('includes/scripts.php') ?>\n</body>\n</html>", "---\ntitle: Alter the Appearance\nseo-title: Alter the Appearance\ndescription: Modify the script\nseo-description: Modify the script\nuuid: 6930381b-74c1-4e63-9621-621dbedbc25e\ncontentOwner: User\nproducts: SG_EXPERIENCEMANAGER/6.4/COMMUNITIES\ntopic-tags: developing\ncontent-type: reference\ndiscoiquuid: da3891d3-fa07-4c88-b4ac-077926b3a674\nexl-id: 01a20578-56c3-41b3-8a0e-281104af2481\n---\n# Alter the Appearance {#alter-the-appearance}\n\n## Modify the Script {#modify-the-script}\n\nThe comment.hbs script is responsible for creating the overall HTML for each comment.\n\nTo not display the avatar next to each posted comment:\n\n1. Copy `comment.hbs`from `libs`to `apps`\n 1. Select `/libs/social/commons/components/hbs/comments/comment/comment.hbs`\n 1. Select **[!UICONTROL Copy]**\n 1. Select `/apps/social/commons/components/hbs/comments/comment`\n 1. Select **[!UICONTROL Paste]**\n1. Open the overlaid `comment.hbs`\n * Double-click on node `comment.hbs`in `/apps/social/commons/components/hbs/comments/comment folder`\n1. Find the following lines and either delete or comment them out:\n\n ```xml\n <aside class=\"scf-comment-author\">\n <img class=\"scf-comment-avatar {{#if topLevel}}withTopLevel{{/if}}\" src=\"{{author.avatarUrl}}\"></img>\n ```\n\nEither delete the lines, or surround them with '&lt;!--' and '--&gt;' to comment them out. Also, the characters 'xxx' are being added as a visual indicator of where the avatar would have been.\n\n```xml\n<!-- do not display avatar with comment\n <aside class=\"scf-comment-author\">\n <img class=\"scf-comment-avatar {{#if topLevel}}withTopLevel{{/if}}\" src=\"{{author.avatarUrl}}\"></img>\n```\n\n## Replicate the Overlay {#replicate-the-overlay}\n\nPush the overlaid comments component to the publish instance using the Replication Tool.\n\n>[!NOTE]\n>\n>A more robust form of replication would be to create a package in Package Manager and [activate](../../help/sites-administering/package-manager.md#replicating-packages) it. A package can be exported and archived.\n\nFrom the global navigation, select **[!UICONTROL Tools > Deployment > Replication]** and then **[!UICONTROL Activate Tree]**.\n\nFor the Start Path enter `/apps/social/commons` and select **[!UICONTROL Activate]**.\n\n![chlimage_1-42](assets/chlimage_1-42.png) \n\n## View Results {#view-results}\n\nIf you login to the publish instance as an administrator, e.g., http://localhost:4503/crx/de as admin/admin, you can verify the overlaid components are there.\n\nIf you logout and re-login as `PI:FN:aaron.mcdonald@mailinator.comEND_PI/password` and refresh the page, you will observe that the posted comment no longer displays with an avatar, instead a simple 'xxx' is displayed.\n\n![chlimage_1-43](assets/chlimage_1-43.png)\n", "/*\n * Copyright (c) 2018. paascloud.net All Rights Reserved.\n * \u9879\u76ee\u540d\u79f0\uff1a\u9644\u8fd1\u6709\u597d\u5403\u7684\n * \u7c7b\u540d\u79f0\uff1aPublicUtil.java\n * \u521b\u5efa\u4eba\uff1a\u5170\u9f99\u658c\n * \u8054\u7cfb\u65b9\u5f0f\uff1aPI:FN:llb7891@163.comEND_PI\n * \u5f00\u6e90\u5730\u5740: https://github.com/NewlyLan/nearbyEat.git\n *\n *\n */\n\npackage com.paascloud;\n\nimport lombok.AccessLevel;\nimport lombok.NoArgsConstructor;\n\nimport java.util.Collection;\nimport java.util.Map;\n\n/**\n * The class Public util.\n *\n * @author paascloud.net@gmail.com\n */\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class PublicUtil {\n\n\t/**\n\t * \u5224\u65ad\u5bf9\u8c61\u662f\u5426Empty(null\u6216\u5143\u7d20\u4e3a0)\n\t * \u5b9e\u7528\u4e8e\u5bf9\u5982\u4e0b\u5bf9\u8c61\u505a\u5224\u65ad:String Collection\u53ca\u5176\u5b50\u7c7b Map\u53ca\u5176\u5b50\u7c7b\n\t *\n\t * @param pObj \u5f85\u68c0\u67e5\u5bf9\u8c61\n\t *\n\t * @return boolean \u8fd4\u56de\u7684\u5e03\u5c14\u503c\n\t */\n\tpublic static boolean isEmpty(Object pObj) {\n\t\tif (pObj == null) {\n\t\t\treturn true;\n\t\t}\n\t\tif (pObj == \"\") {\n\t\t\treturn true;\n\t\t}\n\t\tif (pObj instanceof String) {\n\t\t\treturn ((String) pObj).length() == 0;\n\t\t} else if (pObj instanceof Collection) {\n\t\t\treturn ((Collection) pObj).isEmpty();\n\t\t} else if (pObj instanceof Map) {\n\t\t\treturn ((Map) pObj).size() == 0;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * \u5224\u65ad\u5bf9\u8c61\u662f\u5426\u4e3aNotEmpty(!null\u6216\u5143\u7d20\u5927\u4e8e0)\n\t * \u5b9e\u7528\u4e8e\u5bf9\u5982\u4e0b\u5bf9\u8c61\u505a\u5224\u65ad:String Collection\u53ca\u5176\u5b50\u7c7b Map\u53ca\u5176\u5b50\u7c7b\n\t *\n\t * @param pObj \u5f85\u68c0\u67e5\u5bf9\u8c61\n\t *\n\t * @return boolean \u8fd4\u56de\u7684\u5e03\u5c14\u503c\n\t */\n\tpublic static boolean isNotEmpty(Object pObj) {\n\t\tif (pObj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (pObj == \"\") {\n\t\t\treturn false;\n\t\t}\n\t\tif (pObj instanceof String) {\n\t\t\treturn ((String) pObj).length() != 0;\n\t\t} else if (pObj instanceof Collection) {\n\t\t\treturn !((Collection) pObj).isEmpty();\n\t\t} else if (pObj instanceof Map) {\n\t\t\treturn ((Map) pObj).size() != 0;\n\t\t}\n\t\treturn true;\n\t}\n\n}\n", "---\nlayout: post\ntitle: \"Vadym Bartko - Python Backend Engineer\"\nauthor: \"Vadym Bartko\"\npermalink: /my_cv/\n---\n\n\n[My CV in PDF](/assets/other/Vadym Bartko - Python Backend Engineer.pdf)\n\n\n## Contacts\n* email: [PI:FN:hudvin@gmail.comEND_PI](hudvin@gmail.com) or [PI:FN:vadym.bartko@protonmail.comEND_PI](PI:FN:vadym.bartko@protonmail.comEND_PI)\n\n* skype: hudvin\n\n\n## COMPUTER SKILLS AND COMPETENCES\n**AWS:**\nLambda, SQS, SNS, S3, Textract\n\n**Backend:**\nPython Backend Stack - Flask, Django, DRF, gunicorn, RabbitMQ, Celery,\nboto3, Tornado, Flasgger, dynaconf, MongoDB, ElasticSearch etc\n\n**Pdf Processing:**\nghostscript, fitz\n\n**AI:**\nConvolutional Neural Networks, image classification, object detection, image\ncaptioning, image segmentation(UNet), homography, keypoints detection,\nimage processing, FaceNet, classification and clusterization methods, ROS,\ndatasets preparation\n\n**AI Tools:**\nOpenCV, Scikit-learn, Scikit-image, Tensorflow, Pandas, Jupyter Notebook,\nKeras, Dlib, Pillow\n\n**Languages:**\nPython, Java\n\n**OS:**\nLinux (Debian based), Windows\n\n**Cloud and Deployment:**\nKubernetes, Docker, nvidia-docker, Helm, AWS, microservices and distributed systems\n\n**Other:**\nsome experience with LIDARs and stereocameras, R&D, basic language\nprocessing\n\n\n\n## NOTABLE PROJECTS\n### [pdf processing - fintech]\nprocessing and analysis of financial pdf documents, OCR, dealing with pdf\nformat issues, pdf/image compression and optimization, ghoscript based\nprocessing, dealing with font related issues\n\nghostscript, imagemagic, fitz, flask, AWS Lambda, AWS Te xtract\n\n### Khumbu\nimage search engine based on AI and computer vision. Performs face\nrecognition, object detection, image classification, metadata extraction, query\nprocessing.\n\nDocker, RabbitMQ, Flask, Mongo, Keras, Tensorflow, Kubernetes, React\n\ntechnical research, market research and analysis, prepare pitch deck,\ninterviewing potential customers, talk to investors, implement backend and\nfrontend parts\n\n### [bots and image processing]\nautomatically train customer specific NLP bots, deploy ML apps to cloud\nKubernetes, Helm, nvidia-docker, Flask, Celery, Airflow\n\nimplement web api for third-party ML models, build distributed training system, Kubernetes management and deployment, performance optimization\n\n### [media assets management software]\nface detection and recognition, image tagging, inappropriate content detection\n\nOpenCV, Keras, Tensorflow, Docker, dlib, pandas, scikit-image\n\nimplement image classification and nsfw content detection, build dataset for\nface recognition tasks, test various facerecog approaches, integrate with\nanother services\n\n### [autonomous robocar]\ncontrol, navigation, route planning and map building for small 4W robot\nOpenCV, ROS, LIDAR, ZED Camera\n\nhardware design, test various SLAM algorithms, setup ROS env for wheel\nrobot, experiments with LIDAR and stereocamera\n\n### [gene variations classification]\ndetect pathogenic variations in genes\npandas, scikit-learn\n\n### ITraffic\ndetect empty parking lots using webcamera\nOpencv, Caffe, digits, Python, Docker, RabbitMQ; AKAZE/ORB/BRISK,\nhomography\n\ncreate datasets, train models, implement API for models, deployment,\nimplement cv tasks\n\n### [crawling/scraping]\nlarge scale web crawling and data extraction\n\nRabbitMQ, MySQL, Python, PhantomJS, RedShift, S3, EC2, ElasticSearch,\nNLTK\n\n### Firefly\nweb manager for scientific papers\n\nGridFS, TitanDB, ElasticSearch\n\n### Nomad\ndistributed crawler\n\nTitanDB, OrientDB, gremlin\n\n### Denigma\ntools for ageing research project, server administration, knowledge extraction\n\nCloudStack, Scala, NLTK, OpenNLP, semantic tools\n\nresearch, backend implementation, some DevOps\n\n### BigPlanet\noffline map with different sources of geo data\n\nAndroid 2.x\n\n\n\n\n\n## WORK EXPERIENCE\n* 2020 \u2013 current time Zoral, Python Backend Engineer\n\n* 2018 \u2013 2019 Khumbu, founder\n\n* 2015 \u2013 2019 Lohika, Machine Learning Engineer\n\n* 2014 \u2013 2015 freelance(Python Engineer)\n\n* 2013 \u2013 2014 Codeminders, Java Engineer\n\n* 2012 \u2013 2013 Researcher, freelance\n\n* 2011 \u2013 2012 Ciklum, Java/Android Software Engineer, Team Lead\n\n* 2009 \u2013 2011 P-Product, Java/Android Software Engineer\n\n* 2008 \u2013 2009 N.S, co-founder\n\n* 2007-2008 Exadel, Java Engineer\n\n\n## EDUCATION AND TRAINING\n* University Kharkiv National University of Radio Electronics, 2008 \u2013 2014\n\n* Degree BS in Information Technology\n\n* Online course Machine Learning, Coursera\n\n* Online course Introduction to Artificial Intelligence, EdX\n\n* Certification MapR Certified Hadoop Developer, [https://accredible.com/10056013](https://accredible.com/10056013)\n\n## OTHER\n* Mother tongue(s): Russian\n\n* Other language(s): English, Ukrainian, Deutsch(beginner)\n\n* Hobbies: climbing, hiking, photography, history, art\n\n* Personal blog: [https://vadym.bartko.me/](https://vadym.bartko.me/)\n"]
data/email_detections_fp.json ADDED
@@ -0,0 +1 @@
 
 
1
+ ["/*=============================================================================\n Copyright (c) 2003 Jonathan de Halleux (PI:FP:dehalleux@pelikhan.comEND_PI)\n http://spirit.sourceforge.net/\n\n Use, modification and distribution is subject to the Boost Software\n License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n http://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n#include \"action_tests.hpp\"\n\nint\nmain()\n{\n assign_action_test();\n assign_key_action_test();\n clear_action_test();\n decrement_action_test();\n erase_action_test();\n increment_action_test();\n insert_key_action_test();\n push_front_action_test();\n push_back_action_test();\n swap_action_test();\n\n return boost::report_errors();\n}\n", "/**\n * OEML - REST API\n * This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\\\"https://postman.coinapi.io/\\\" target=\\\"_blank\\\">https://postman.coinapi.io/</a> \n *\n * The version of the OpenAPI document: v1\n * Contact: PI:FP:support@coinapi.ioEND_PI\n *\n * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1.\n * https://openapi-generator.tech\n * Do not edit the class manually.\n */\n\n#include \"ApiConfiguration.h\"\n\nnamespace org {\nnamespace openapitools {\nnamespace client {\nnamespace api {\n\nApiConfiguration::ApiConfiguration()\n{\n}\n\nApiConfiguration::~ApiConfiguration()\n{\n}\n\nconst web::http::client::http_client_config& ApiConfiguration::getHttpConfig() const\n{\n return m_HttpConfig;\n}\n\nvoid ApiConfiguration::setHttpConfig( web::http::client::http_client_config& value )\n{\n m_HttpConfig = value;\n}\n\nutility::string_t ApiConfiguration::getBaseUrl() const\n{\n return m_BaseUrl;\n}\n\nvoid ApiConfiguration::setBaseUrl( const utility::string_t value )\n{\n m_BaseUrl = value;\n}\n\nutility::string_t ApiConfiguration::getUserAgent() const\n{\n return m_UserAgent;\n}\n\nvoid ApiConfiguration::setUserAgent( const utility::string_t value )\n{\n m_UserAgent = value;\n}\n\nstd::map<utility::string_t, utility::string_t>& ApiConfiguration::getDefaultHeaders()\n{\n return m_DefaultHeaders;\n}\n\nconst std::map<utility::string_t, utility::string_t>& ApiConfiguration::getDefaultHeaders() const\n{\n return m_DefaultHeaders;\n}\n\nutility::string_t ApiConfiguration::getApiKey( const utility::string_t& prefix) const\n{\n auto result = m_ApiKeys.find(prefix);\n if( result != m_ApiKeys.end() )\n {\n return result->second;\n }\n return utility::conversions::to_string_t(\"\");\n}\n\nvoid ApiConfiguration::setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey )\n{\n m_ApiKeys[prefix] = apiKey;\n}\n\n}\n}\n}\n}\n", "from datetime import timedelta\nimport pytest\n\nfrom django.utils import timezone\nfrom electeez_auth.models import User\n\n\n@pytest.mark.django_db\ndef test_otp(client):\n user = User.objects.create(email='PI:FP:otp@example.comEND_PI')\n token = user.otp_new(redirect='valid')\n\n response = client.post(token.path)\n assert response['Location'] == 'valid'\n\n # can't use the link twice\n response = client.post(token.path)\n assert response['Location'] != 'valid'\n\n # try expired link\n token = user.otp_new()\n token.otp_expiry = timezone.now() - timedelta(minutes=1)\n token.save()\n response = client.post(token.path)\n assert response['Location'] != 'valid'\n", "@extends('layouts.main')\n@section('title','Surat | ')\n@section('css_script')\n <style>\n /*body {*/\n /* background: rgb(204, 204, 204);*/\n /*}*/\n\n page {\n background: white;\n display: block;\n margin: 0 auto;\n margin-bottom: 0.5cm;\n box-shadow: 0 0 0.3cm rgba(0, 0, 0, 0.5);\n }\n\n page[size=\"A4\"] {\n width: 21cm;\n height: 29.7cm;\n }\n\n page[size=\"A4\"][layout=\"landscape\"] {\n width: 29.7cm;\n height: 21cm;\n }\n\n page[size=\"A3\"] {\n width: 29.7cm;\n height: 42cm;\n }\n\n page[size=\"A3\"][layout=\"landscape\"] {\n width: 42cm;\n height: 29.7cm;\n }\n\n page[size=\"A5\"] {\n width: 14.8cm;\n height: 21cm;\n }\n\n page[size=\"A5\"][layout=\"landscape\"] {\n width: 21cm;\n height: 14.8cm;\n }\n\n @media print {\n body, page {\n margin: 0;\n box-shadow: 0;\n }\n }\n </style>\n@endsection\n@section('main_content')\n\n {{-- <page size=\"A4\"></page>--}}\n {{-- <page size=\"A4\"></page>--}}\n {{-- <page size=\"A4\" layout=\"landscape\"></page>--}}\n {{-- <page size=\"A5\" layout=\"landscape\"></page>--}}\n {{-- <page size=\"A3\"></page>--}}\n {{-- <page size=\"A3\" layout=\"landscape\"></page>--}}\n\n <section class=\"section feather-bg-img\"\n style=\"background-image: url({{asset('lezir/images/features-bg-img-1.png')}})\">\n <div class=\"row justify-content-center\">\n <div class=\"col-lg-6\">\n <div class=\"text-center mb-5\">\n <h3 class=\"title mb-3\">Awesome Features</h3>\n <p class=\"text-muted font-size-15\">Et harum quidem rerum facilis est et expedita distinctio nam\n libero tempore cum soluta nobis eligendi cumque.</p>\n </div>\n </div>\n </div>\n <div class=\"container\">\n <div class=\"row align-items-center\">\n <div class=\"col-lg-10\">\n <p class=\"font-weight-medium text-uppercase mb-2\"><i\n class=\"mdi mdi-chart-bubble h2 text-primary mr-1 align-middle\"></i> Surat Keluar</p>\n <div class=\"card\" style=\"box-shadow: 0 0 0.1cm rgba(0, 0, 0, 0.5); width: 21cm;\n height: 29.7cm;\">\n <div class=\"card-body\">\n <table>\n <tr>\n <td width=\"15%\">\n <div>\n <img src=\"{{asset('madiun_logo.png')}}\" alt=\"\" width=\"128\">\n </div>\n </td>\n <td align=\"center\" width=\"85%\">\n <div>\n <b style=\"font-size: 16pt\"> PEMERINTAH KOTA MADIUN</b> <br>\n <b>DINAS KOMUNIKASI DAN INFORMATIKA</b> <br>\n <div style=\"font-size: 11pt; margin: 0; padding-top: -10;\"> JJalan Perintis\n Kemerdekaan No. 32 Kota Madiun\n <br>\n No Telp / Fax : (0351) 467327 / (0351) 457331 email:\n PI:FP:kominfo.madiunkota@gmail.comEND_PI\n </div>\n </div>\n </td>\n </tr>\n <tr>\n <td colspan=\"2\">\n <hr>\n </td>\n </tr>\n </table>\n {{-- <h3 class=\"font-weight-semibold line-height-1_4 mb-4\">We do the work you <b>stay focused</b>--}}\n {{-- on <b>your customers</b>.</h3>--}}\n\n\n <!-- <h3 class=\"font-weight-semibold line-height-1_4 mb-4\">Build <b>community</b> & <b>conversion</b> with our suite of <b>social tool</b></h3> -->\n {{-- <p class=\"text-muted font-size-15 mb-4\">Temporibus autem quibusdam et aut officiis debitis--}}\n {{-- aut rerum a necessitatibus saepe eveniet ut et voluptates repudiandae sint molestiae non--}}\n {{-- recusandae itaque.</p>--}}\n {{-- <p class=\"text-muted mb-2\"><i class=\"icon-xs mr-1\" data-feather=\"server\"></i> Donec pede--}}\n {{-- justo fringilla vel nec.</p>--}}\n {{-- <p class=\"text-muted\"><i class=\"icon-xs mr-1\" data-feather=\"rss\"></i> Cras ultricies mi eu--}}\n {{-- turpis hendrerit fringilla.</p>--}}\n\n <div class=\"row align-items-center\">\n <div class=\"col-lg-12\">\n <div class=\"custom-form mb-5 mb-lg-0\">\n <div id=\"message\"></div>\n <form method=\"post\" action=\"\" name=\"contact-form\"\n id=\"surat\">\n @CSRF\n <div class=\"row\">\n <div class=\"col-md-6\">\n <div class=\"form-group\">\n <label for=\"name\">Yth.*</label>\n <input name=\"yth\" id=\"name\" type=\"text\" class=\"form-control\"\n placeholder=\"Pihak yang dituju...\"required>\n </div>\n </div>\n <div class=\"col-md-6\">\n <div class=\"form-group\">\n <label for=\"email\">Dari*</label>\n <input name=\"dari\" id=\"email\" type=\"text\" class=\"form-control\"\n placeholder=\"Pengirim ...\" required>\n </div>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-md-6\">\n <div class=\"form-group\">\n <label for=\"name\">No. Surat*</label>\n <input name=\"no_surat\" id=\"name\" type=\"text\" class=\"form-control\"\n placeholder=\"1xxxxx...\" required>\n </div>\n </div>\n <div class=\"col-md-6\">\n <div class=\"form-group\">\n <label for=\"email\">Perihal*</label>\n <input name=\"perihal\" id=\"email\" type=\"text\" class=\"form-control\"\n placeholder=\"Perihal Surat...\" required >\n </div>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-md-6\">\n <div class=\"form-group\">\n <label for=\"name\">Lampiran*</label>\n <input name=\"lampiran\" id=\"name\" type=\"text\" class=\"form-control\"\n placeholder=\"Jumlah Lampiran...\" required>\n </div>\n </div>\n <div class=\"col-md-6\">\n <div class=\"form-group\">\n <label for=\"email\">Tujuan*</label>\n <input name=\"tujuan\" id=\"email\" type=\"text\" class=\"form-control\"\n placeholder=\"Your email...\" required>\n </div>\n </div>\n </div>\n\n <div class=\"row\">\n <div class=\"col-lg-12\">\n <div class=\"form-group\">\n <label for=\"comments\">Isi Surat *</label>\n <textarea name=\"pesan\" id=\"summernote\" rows=\"4\"\n class=\"form-control\"\n placeholder=\"Your message...\"></textarea>\n </div>\n </div>\n </div>\n\n </form>\n </div>\n </div>\n\n </div>\n </div>\n </div>\n\n <div class=\"mt-5\">\n <button type=\"submit\" class=\"btn btn-primary mr-2\" onclick=\"submit_form('{{route('surat.save')}}')\"> Simpan & Kirim <i class=\"mdi mdi-send\"></i></button>\n {{-- <a href=\"#\" class=\"btn btn-soft-primary\">Simpan Draft </a>--}}\n </div>\n </div>\n\n {{-- <div class=\"col-lg-6 offset-lg-1\">--}}\n {{-- <div class=\"mt-4 mt-lg-0\">--}}\n {{-- <img src=\"images/features-img-1.png\" alt=\"\" class=\"img-fluid d-block mx-auto\">--}}\n {{-- </div>--}}\n {{-- </div>--}}\n </div>\n </div>\n </section>\n@endsection\n@push('script')\n\n <script>\n function submit_form(link) {\n $('#surat').attr('action',link).submit();\n console.log(\"hello\");\n\n }\n </script>\n@endpush\n", "<?php\ninclude_once(\"php_includes/check_login_status.php\");\ninclude_once(\"classes/develop_php_library.php\");\nsession_start();\n// If user is logged in, header them away\nif(isset($_SESSION[\"username\"])){\n\theader(\"location: user.php?u=\".$_SESSION[\"username\"]);\n exit();\n}\n?><?php\n// AJAX CALLS THIS LOGIN CODE TO EXECUTE\nif(isset($_POST[\"e\"])){\n\t// CONNECT TO THE DATABASE\n\t// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE\n\t$e = mysqli_real_escape_string($db_conx, $_POST['e']);\n\t$p = md5($_POST['p']);\n\t// GET USER IP ADDRESS\n $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));\n\t// FORM DATA ERROR HANDLING\n\tif($e == \"\" || $p == \"\"){\n\t\techo \"login_failed\";\n exit();\n\t} else {\n\t// END FORM DATA ERROR HANDLING\n\t\tsleep(3);\n\t\t$sql = \"SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1\";\n $query = mysqli_query($db_conx, $sql);\n $row = mysqli_fetch_row($query);\n\t\t$db_id = $row[0];\n\t\t$db_username = $row[1];\n $db_pass_str = $row[2];\n\t\tif($p != $db_pass_str){\n\t\t\techo \"login_failed\";\n exit();\n\t\t} else {\n\t\t\t// CREATE THEIR SESSIONS AND COOKIES\n\t\t\t$_SESSION['userid'] = $db_id;\n\t\t\t$_SESSION['username'] = $db_username;\n\t\t\t$_SESSION['password'] = $db_pass_str;\n\t\t\tsetcookie(\"id\", $db_id, strtotime( '+30 days' ), \"/\", \"\", \"\", TRUE);\n\t\t\tsetcookie(\"user\", $db_username, strtotime( '+30 days' ), \"/\", \"\", \"\", TRUE);\n \t\tsetcookie(\"pass\", $db_pass_str, strtotime( '+30 days' ), \"/\", \"\", \"\", TRUE); \n\t\t\t// UPDATE THEIR \"IP\" AND \"LASTLOGIN\" FIELDS\n\t\t\t$sql = \"UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1\";\n $query = mysqli_query($db_conx, $sql);\n\t\t\techo $db_username;\n\t\t exit();\n\t\t}\n\t}\n \n\texit();\n}\n?>\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Easy Fundraising Ideas</title>\n <meta name=\"description\" content=\"Sign up. Make a post for the things you want. Tell your friends about it. Receive donations.\">\n <meta name=\"viewport\" content=\"initial-scale=1.0,width=device-width\" />\n <meta name=\"msvalidate.01\" content=\"25A9DC1385D08C4DF90A1DCE8F58723A\" />\n <meta http-equiv=\"content-language\" content=\"en-gb\">\n <link rel=\"stylesheet\" href=\"style/style.css\" />\n <link rel=\"stylesheet\" media=\"only screen and (max-width: 4000px)\" href=\"style/pageTop1.css\" />\n <link rel=\"stylesheet\" href=\"style/pageTop3.css\" media=\"only screen and (max-width: 700px)\" />\n <link rel=\"stylesheet\" media=\"only screen and (max-width: 4000px)\" href=\"style/pageMiddle1.css\" />\n <link rel=\"stylesheet\" media=\"only screen and (max-width: 1250px)\" href=\"style/pageMiddle2.css\" />\n <link rel=\"stylesheet\" media=\"only screen and (max-width: 700px)\" href=\"style/pageMiddle3.css\" />\n <link rel=\"icon\" href=\"style/tabicon.png\" type=\"image/x-icon\" />\n <link rel=\"shortcut icon\" href=\"style/tabicon.png\" type=\"image/x-icon\" />\n <style type=\"text/css\">\n.back-content > h1 {\n color: #00B3FF;\n}\n.back-content > h2 {\n color: #00B3FF;\n}\n.back-content > h3 {\n color: #00B3FF;\n}\n.header {\n text-align: center;\n color: #00B3FF;\n background-color: #fff;\n width: 85%;\n height: 100px;\n margin: 0 auto;\n border-bottom: 2px dashed #00B3FF;\n margin-bottom:0px;\n padding-bottom: 0px;\n padding: 5px\n}\n.back-content {\n background-color: #00B3FF;\n padding: 5px;\n margin-top: -18px;\n border-bottom: 3px solid #999;\n\tborder: none;\n}\n#fundraising_sec {\n background-color: #fff;\n width: 65%;\n margin: 0 auto;\n text-align: center;\n color: #555;\n}\n#compare {\n text-align: center;\n width: 100%;\n height: 250px;\n display: block;\n}\n.compare-img1 {\n height: 200px;\n width: 300px;\n padding: 5px;\n float:left;\n transition: all 0.5s ease;\n}\n.compare-img1:hover {\n zoom: 1.1;\n transform: rotate(-7deg)\n}\n.compare-img2 {\n height: 200px;\n width: 300px;\n padding: 5px;\n float:right;\n transition: all 0.5s ease;\n}\n.compare-img2:hover {\n zoom: 1.1;\n transform: rotate(7deg)\n}\n#compare-p {\n display: inline-block;\n color: #00B3FF;\n font-size: 35px;\n font-weight: bold;\n text-align: center;\n margin: 0 auto;\n margin-top: 80px;\n}\n</style>\n <script src=\"js/main.js\"></script>\n <script src=\"js/Ajax.js\"></script>\n <script src=\"js/autoScroll.js\"></script>\n <script src=\"js/fade.js\"></script>\n <script src=\"js/trBackground.js\"></script>\n <script src=\"js/trDrop.js\"></script>\n <script src=\"js/trSlide.js\"></script>\n<script>\nfunction emptyElement(x){\n\t_(x).innerHTML = \"\";\n}\n\nfunction login(){\n\tvar e = _(\"email\").value;\n\tvar p = _(\"password\").value;\n\tif(e == \"\" || p == \"\"){\n\t\t_(\"status2\").innerHTML = \"Please fill out all of the form data\";\n\t} else {\n\t\t_(\"loginbtn\").style.display = \"none\";\n\t\t_(\"loading\").style.display = 'inline-block';\n\t\tvar one = Math.floor((Math.random() * 20) + 1);\n\t\tvar two = Math.floor((Math.random() * 10) + 1);\n\t\tfadeIn('invite','invite_pop');\n\t\t_('invite_p').innerHTML = \"\";\n\t\t_(\"invite_h2\").innerHTML = 'Question';\n\t\t_(\"invite_div\").innerHTML = '<h3 style=\"color: #999\">Please answer the question below.</h3><input type=\"text\" style=\"border: 1px solid #00C7FF;height: 29px;width: 242px;margin: 5px;border-radius: 15px;padding-left: 8px;\" class=\"textBox textBox1\" name=\"answer\" placeholder=\"What\\'s '+one+' plus '+two+'?\" id=\"robot\" /><button type=\"submit\" style=\"height: 29px;border-radius: 18px;\" class=\"logIn\" id=\"loginbtn\" onclick=\"answer('+one+', '+two+')\">Answer</button>';\n\t\t\n\t}\n}\nfunction answer(one, two) {\n\tvar total = one + two;\n\tif (_(\"robot\").value != total) {\n\t\tfadeOut('invite','invite_pop');\t\t\t\t\n\t\t_(\"loginbtn\").style.display = \"inline-block\";\n\t\t_(\"loading\").style.display = 'none';\n\t\t_(\"status2\").innerHTML = \"Please prove you're not a robot.\";\n\t\treturn false;\n\t} else {\n\t\tvar ajax = ajaxObj(\"POST\", \"index.php\");\n\t\tvar e = _(\"email\").value;\n\t\tvar p = _(\"password\").value;\n\t\t\n\t\tfadeOut('invite','invite_pop');\n\t\t_(\"loginbtn\").style.display = \"none\";\n\t\t_(\"loading\").style.display = 'inline-block';\n\t\tajax.onreadystatechange = function() {\n\t\t\tif(ajaxReturn(ajax) == true) {\n\t\t\t\tif(ajax.responseText == \"login_failed\"){\t\t\t\t\t\t\t\t\n\t\t\t\t\t_(\"loginbtn\").style.display = \"inline-block\";\n\t\t\t\t\t_(\"loading\").style.display = 'none';\n\t\t\t\t\t_(\"status2\").innerHTML = \"Login unsuccessful, please try again.\";\n\t\t\t\t} else if (ajax.responseText == \"robot\") {\t\t\t\t\t\t\t\t\n\t\t\t\t\t_(\"loginbtn\").style.display = \"inline-block\";\n\t\t\t\t\t_(\"loading\").style.display = 'none';\n\t\t\t\t\t_(\"status2\").innerHTML = \"Please prove you're not a robot.\";\n\t\t\t\t} else {\n\t\t\t\t\twindow.location = \"https://nosettles.com/user.php?u=\"+ajax.responseText;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tajax.send(\"e=\"+e+\"&p=\"+p);\n\t}\n}\nfunction validateEmail(email) {\n var re = /^([\\w-]+(?:\\.[\\w-]+)*)@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$/i;\n return re.test(email);\n}\n</script>\n</head>\n<body style=\"background-color: #eee;\">\n<div id=\"pageTop1\">\n <div id=\"pageTopWrap\">\n <div><a class=\"pageTopLogo\" href=\"/\"></a>\n </div>\n <div id=\"up\">\n <div class=\"right\">\n <form name=\"loginform\" onSubmit=\"return false;\">\n\t <input type=\"email\" class=\"textBox textBox1\" name=\"Email\" placeholder=\"Email\" id=\"email\" onfocus=\"emptyElement('status2')\" maxlength=\"88\">\n\t </div>\n </div>\n <div id=\"middle\">\n <div class=\"right\">\n\t\t<input type=\"password\" class=\"textBox textbox2\" placeholder=\"Password\" id=\"password\" onfocus=\"emptyElement('status2')\" maxlength=\"100\" />\n <button type=\"submit\" class=\"logIn\" id=\"loginbtn\" onclick=\"login()\">\n Log in\n </button><img id=\"loading\" src=\"style/ajax-loader1.gif\" class=\"load\" style=\"height: 27px; width: 47px;\" alt=\"Loading...\" />\n </form>\n </div>\n </div>\n <div id=\"down\"> \n <div class=\"right\">\n <a class=\"links link1\" href=\"forgot_pass.php\">Forgot Password?</a>\n <p id=\"status2\" style=\"color: #f00\"></p>\n </div>\n </div>\n </div>\n </div>\n</div>\n<?php include_once(\"template_nav.php\"); ?>\n\n<div id=\"java_pop_up\"></div>\n<div id=\"pop_up\"><p>Secure Checkout</p><div id=\"wepay_checkout\"></div></div>\n<div id=\"invite\" onclick=\"fadeOut('invite','invite_pop')\"></div>\n<div id=\"invite_pop\" style=\"padding: 5px;\"><h2 id=\"invite_h2\" style=\"border-bottom: 2px solid #C2BCBC;\"></h2><div id=\"invite_div\"></div><p id=\"invite_p\"></p></div>\n<script type=\"text/javascript\" src=\"https://stage.wepay.com/min/js/iframe.wepay.js\">\n</script>\n\n<div id=\"pageMiddle\" style=\"margin-top: 0px; padding-top: 25px;\">\n<div id=\"fundraising_sec\" class=\"back-content\">\n <h1 class=\"header\">Easy Fundraising Ideas</h1>\n <h2>Are you searching for Easy Fundraising Ideas?</h2>\n <p>Have you been searching for easy fundraising ideas for hours and you're now frustrated on how to make a fundraiser. Are you looking at fundraisers and trying to figure out how they got their funds? Are you looking for money but don't know how to start a fundraiser that can get popular and get funded.</p>\n <h2>Well, you have found what you are looking for.</h2>\n <p>If the answer to the questions above were mostly yes, then you have found the right place. The place where you can find easy fundraising ideas. The place where you can generate funds easily and with the lowest fees possible.</p>\n <h3>Introducing NoSettles</h3>\n <p>NoSettles is a fund-free website where you can post whatever you want and receive donations for that. You will not need to pay fees that take your money for no reason. Here you are able to sign up for free under 5 minutes and get donations as quickly as possible.</p>\n <h2>Start your own fundraiser without having to overthink it.</h2>\n <p>If you want to start your own fundraiser but you are looking around in Google, looking for websites where you can find easy fundraising ideas, then you are wasting your time. Instead you could start your fundraiser right away without having to research for hours.</p>\n <h3>Don't wait any longer, no need for searching for Easy Fundraising Ideas.</h3>\n <p>Just make your own fundraiser. You deserve better. If you want something but you can't afford it, then make a fundraiser. You don't have to settle for cheap products that don't last a month. You don't have to go with low-cost products. You deserve more!</p>\n <h2>Judge for yourself</h2>\n <div id=\"compare\">\n <img src=\"images/good-laptop.jpg\" alt=\"Easy Fundraising Ideas\" class=\"compare-img1\" />\n <p id=\"compare-p\">OR</p>\n <img src=\"images/bad-laptop.jpg\" alit=\"Easy Fundraising Ideas\" class=\"compare-img2\" />\n </div>\n <div id=\"compare\">\n <img src=\"images/good-car.jpg\" alt=\"Easy Fundraising Ideas\" class=\"compare-img1\" />\n <p id=\"compare-p\">OR</p>\n <img src=\"images/bad-car.jpg\" alit=\"Easy Fundraising Ideas\" class=\"compare-img2\" />\n </div>\n <div id=\"compare\">\n <img src=\"images/good-plane.jpg\" alt=\"Easy Fundraising Ideas\" class=\"compare-img1\" />\n <p id=\"compare-p\">OR</p>\n <img src=\"images/bad-plane.jpg\" alit=\"Easy Fundraising Ideas\" class=\"compare-img2\" />\n </div>\n <?php include_once(\"template_SignUp.php\"); ?>\n </div>\n</div>\n<script>\nfunction fadeIn(el, elen){\n\tvar element = document.getElementById(elen);\n\tvar elem = document.getElementById(el);\n\telement.style.transition = \"all 0.5s linear 0s\";\n\telem.style.transition = \"all 0.5s linear 0s\";\n\telement.style.opacity = 1;\n\telem.style.opacity = 1;\n\telement.style.visibility = \"visible\";\n\telem.style.visibility = \"visible\";\n\tvar body=document.getElementsByTagName('body')[0];\n\tbody.style.overflow = \"hidden\";\n}\nfunction hint() {\n\t_('invite_div').innerHTML = \"\";\n\t_('invite_h2').innerHTML = \"Invitation Code\";\n\t_('invite_p').innerHTML = 'Invitation Code is a string that every None-Settler has. If you know any friends that is a member, you can ask them for the code. Otherwise, you can <a href=\"mailto:PI:FP:contact@nosettles.comEND_PI\">contact us</a>,tell us why you want to join and how you found us, then simply ask for the Invitation Code.';\n}\nfunction fadeOut(el, elen){\n\tvar element = document.getElementById(elen);\n\tvar elem = document.getElementById(el);\n\telement.style.opacity = 0;\n\telem.style.opacity = 0;\n\telement.style.visibility = \"hidden\";\n\telem.style.visibility = \"hidden\";\n\tvar body=document.getElementsByTagName('body')[0];\n\tbody.style.overflowY = \"scroll\";\t\n}\n function mostRecent() {\n\t var ajax = ajaxObj(\"POST\", \"index.php\");\n ajax.onreadystatechange = function() {\n\t if(ajaxReturn(ajax) == true) {\n\t if(ajax.responseText == \"login_failed\"){\n\t\t\t\t\t_(\"status2\").innerHTML = \"Login unsuccessful, please try again.\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n ajax.send(\"action=mostRecent\");\n }\n</script>\n<div id=\"pageBottom\" style=\"margin-top: 20px;\"><div style=\"margin-top: -20px;\">NoSettles Copyright &copy; 2015</div>\n <div style=\"padding-top: 5px;\">\n <span id=\"siteseal\">\n\t <script type=\"text/javascript\" src=\"https://seal.godaddy.com/getSeal?sealID=6EFg6BS5bspEZsmRQHWfXAsaePte8smuuUzp4HtCti6trGWAiijB5qh7GRLG\">\n </script>\n </span>\n </div>\n</div>\n</body>\n</html>", "/*\n * Copyright (C) 2015 - 2016 VREM Software Development <PI:FP:VREMSoftwareDevelopment@gmail.comEND_PI>\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.vrem.wifianalyzer.wifi.graph.channel;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.support.v4.util.Pair;\nimport android.view.View;\n\nimport com.jjoe64.graphview.GraphView;\nimport com.vrem.wifianalyzer.BuildConfig;\nimport com.vrem.wifianalyzer.Configuration;\nimport com.vrem.wifianalyzer.RobolectricUtil;\nimport com.vrem.wifianalyzer.settings.Settings;\nimport com.vrem.wifianalyzer.wifi.band.WiFiBand;\nimport com.vrem.wifianalyzer.wifi.band.WiFiChannel;\nimport com.vrem.wifianalyzer.wifi.graph.tools.GraphLegend;\nimport com.vrem.wifianalyzer.wifi.graph.tools.GraphViewWrapper;\nimport com.vrem.wifianalyzer.wifi.model.SortBy;\nimport com.vrem.wifianalyzer.wifi.model.WiFiConnection;\nimport com.vrem.wifianalyzer.wifi.model.WiFiData;\nimport com.vrem.wifianalyzer.wifi.model.WiFiDetail;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.robolectric.RobolectricGradleTestRunner;\nimport org.robolectric.annotation.Config;\n\nimport java.util.ArrayList;\nimport java.util.Set;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\n@RunWith(RobolectricGradleTestRunner.class)\n@Config(constants = BuildConfig.class)\npublic class ChannelGraphViewTest {\n private Context context;\n private Resources resources;\n private Settings settings;\n private Configuration configuration;\n private GraphViewWrapper graphViewWrapper;\n\n private ChannelGraphView fixture;\n\n @Before\n public void setUp() throws Exception {\n RobolectricUtil.INSTANCE.getMainActivity();\n\n graphViewWrapper = mock(GraphViewWrapper.class);\n context = mock(Context.class);\n resources = mock(Resources.class);\n settings = mock(Settings.class);\n configuration = mock(Configuration.class);\n\n fixture = new ChannelGraphView(WiFiBand.GHZ2, new Pair<>(WiFiChannel.UNKNOWN, WiFiChannel.UNKNOWN));\n fixture.setGraphViewWrapper(graphViewWrapper);\n fixture.setContext(context);\n fixture.setResources(resources);\n fixture.setSettings(settings);\n fixture.setConfiguration(configuration);\n\n }\n\n @Test\n public void testUpdate() throws Exception {\n // setup\n WiFiData wiFiData = new WiFiData(new ArrayList<WiFiDetail>(), WiFiConnection.EMPTY, new ArrayList<String>());\n withSettings();\n // execute\n fixture.update(wiFiData);\n // validate\n verify(graphViewWrapper).removeSeries(any(Set.class));\n verify(graphViewWrapper).updateLegend(GraphLegend.RIGHT);\n verify(graphViewWrapper).setVisibility(View.VISIBLE);\n verifySettings();\n }\n\n private void verifySettings() {\n verify(settings).getChannelGraphLegend();\n verify(settings).getSortBy();\n verify(settings).getWiFiBand();\n }\n\n private void withSettings() {\n when(settings.getChannelGraphLegend()).thenReturn(GraphLegend.RIGHT);\n when(settings.getSortBy()).thenReturn(SortBy.CHANNEL);\n when(settings.getWiFiBand()).thenReturn(WiFiBand.GHZ2);\n }\n\n @Test\n public void testGetGraphView() throws Exception {\n // setup\n GraphView expected = mock(GraphView.class);\n when(graphViewWrapper.getGraphView()).thenReturn(expected);\n // execute\n GraphView actual = fixture.getGraphView();\n // validate\n assertEquals(expected, actual);\n verify(graphViewWrapper).getGraphView();\n }\n}", "package com.bitdubai.fermat_api.layer.all_definition.common.system.annotations;\n\nimport com.bitdubai.fermat_api.layer.all_definition.enums.Developers;\nimport com.bitdubai.fermat_api.layer.all_definition.enums.Layers;\nimport com.bitdubai.fermat_api.layer.all_definition.enums.Platforms;\nimport com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * The annotation <code>NeededPluginReference</code>\n * contains all the data needed to build the plugin version reference to assign it to the plugin.\n * <p/>\n * Created by Leon Acosta - (PI:FP:laion.cj91@gmail.comEND_PI) on 28/10/2015.\n */\n@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.FIELD)\npublic @interface NeededPluginReference {\n\n Platforms platform();\n Layers layer();\n Plugins plugin();\n Developers developer() default Developers.BITDUBAI;\n String version() default \"1.0.0\";\n\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 React from 'react';\nimport { shallow } from 'enzyme';\nimport { UserList } from '.';\nimport * as i18n from '../case_view/translations';\n\ndescribe('UserList ', () => {\n const title = 'Case Title';\n const caseLink = 'http://reddit.com';\n const user = { username: 'username', fullName: 'Full Name', email: 'PI:FP:testemail@elastic.coEND_PI' };\n const open = jest.fn();\n beforeAll(() => {\n window.open = open;\n });\n beforeEach(() => {\n jest.resetAllMocks();\n });\n it('triggers mailto when email icon clicked', () => {\n const wrapper = shallow(\n <UserList\n email={{\n subject: i18n.EMAIL_SUBJECT(title),\n body: i18n.EMAIL_BODY(caseLink),\n }}\n headline={i18n.REPORTER}\n users={[user]}\n />\n );\n wrapper.find('[data-test-subj=\"user-list-email-button\"]').simulate('click');\n expect(open).toBeCalledWith(\n `mailto:${user.email}?subject=${i18n.EMAIL_SUBJECT(title)}&body=${i18n.EMAIL_BODY(caseLink)}`,\n '_blank'\n );\n });\n});\n", "\"\"\"\nTest command line commands.\n\"\"\"\nfrom pathlib import Path\nfrom subprocess import PIPE, Popen\n\n__author__ = \"Sergey Vartanov\"\n__email__ = \"PI:FP:me@enzet.ruEND_PI\"\n\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element\n\nfrom map_machine.ui.cli import COMMAND_LINES\n\nLOG: bytes = (\n b\"INFO Constructing ways...\\n\"\n b\"INFO Constructing nodes...\\n\"\n b\"INFO Drawing ways...\\n\"\n b\"INFO Drawing main icons...\\n\"\n b\"INFO Drawing extra icons...\\n\"\n b\"INFO Drawing texts...\\n\"\n)\n\n\ndef error_run(arguments: list[str], message: bytes) -> None:\n \"\"\"Run command that should fail and check error message.\"\"\"\n with Popen([\"map-machine\"] + arguments, stderr=PIPE) as pipe:\n _, error = pipe.communicate()\n assert pipe.returncode != 0\n assert error == message\n\n\ndef run(arguments: list[str], message: bytes) -> None:\n \"\"\"Run command that should fail and check error message.\"\"\"\n with Popen([\"map-machine\"] + arguments, stderr=PIPE) as pipe:\n _, error = pipe.communicate()\n assert pipe.returncode == 0\n assert error == message\n\n\ndef test_wrong_render_arguments() -> None:\n \"\"\"Test `render` command with wrong arguments.\"\"\"\n error_run(\n [\"render\", \"-z\", \"17\"],\n b\"CRITICAL Specify either --input, or --boundary-box, or --coordinates \"\n b\"and --size.\\n\",\n )\n\n\ndef test_render() -> None:\n \"\"\"Test `render` command.\"\"\"\n run(\n COMMAND_LINES[\"render\"] + [\"--cache\", \"tests/data\"],\n LOG + b\"INFO Writing output SVG to out/map.svg...\\n\",\n )\n with Path(\"out/map.svg\").open(encoding=\"utf-8\") as output_file:\n root: Element = ElementTree.parse(output_file).getroot()\n\n # 4 expected elements: `defs`, `rect` (background), `g` (outline),\n # `g` (icon), 4 `text` elements (credits).\n assert len(root) == 8\n assert len(root[3][0]) == 0\n assert root.get(\"width\") == \"186.0\"\n assert root.get(\"height\") == \"198.0\"\n\n\ndef test_render_with_tooltips() -> None:\n \"\"\"Test `render` command.\"\"\"\n run(\n COMMAND_LINES[\"render_with_tooltips\"] + [\"--cache\", \"tests/data\"],\n LOG + b\"INFO Writing output SVG to out/map.svg...\\n\",\n )\n with Path(\"out/map.svg\").open(encoding=\"utf-8\") as output_file:\n root: Element = ElementTree.parse(output_file).getroot()\n\n # 4 expected elements: `defs`, `rect` (background), `g` (outline),\n # `g` (icon), 4 `text` elements (credits).\n assert len(root) == 8\n assert len(root[3][0]) == 1\n assert root[3][0][0].text == \"natural: tree\"\n assert root.get(\"width\") == \"186.0\"\n assert root.get(\"height\") == \"198.0\"\n\n\ndef test_icons() -> None:\n \"\"\"Test `icons` command.\"\"\"\n run(\n COMMAND_LINES[\"icons\"],\n b\"INFO Icons are written to out/icons_by_name and out/icons_by_id.\\n\"\n b\"INFO Icon grid is written to out/icon_grid.svg.\\n\"\n b\"INFO Icon grid is written to doc/grid.svg.\\n\",\n )\n\n assert (Path(\"out\") / \"icon_grid.svg\").is_file()\n assert (Path(\"out\") / \"icons_by_name\").is_dir()\n assert (Path(\"out\") / \"icons_by_id\").is_dir()\n assert (Path(\"out\") / \"icons_by_name\" / \"R\u00f6ntgen apple.svg\").is_file()\n assert (Path(\"out\") / \"icons_by_id\" / \"apple.svg\").is_file()\n\n\ndef test_mapcss() -> None:\n \"\"\"Test `mapcss` command.\"\"\"\n run(\n COMMAND_LINES[\"mapcss\"],\n b\"INFO MapCSS 0.2 scheme is written to out/map_machine_mapcss.\\n\",\n )\n\n assert (Path(\"out\") / \"map_machine_mapcss\").is_dir()\n assert (Path(\"out\") / \"map_machine_mapcss\" / \"icons\").is_dir()\n assert (\n Path(\"out\") / \"map_machine_mapcss\" / \"icons\" / \"apple.svg\"\n ).is_file()\n assert (Path(\"out\") / \"map_machine_mapcss\" / \"map_machine.mapcss\").is_file()\n\n\ndef test_element() -> None:\n \"\"\"Test `element` command.\"\"\"\n run(\n COMMAND_LINES[\"element\"],\n b\"INFO Element is written to out/element.svg.\\n\",\n )\n assert (Path(\"out\") / \"element.svg\").is_file()\n\n\ndef test_tile() -> None:\n \"\"\"Test `tile` command.\"\"\"\n run(\n COMMAND_LINES[\"tile\"] + [\"--cache\", \"tests/data\"],\n LOG + b\"INFO Tile is drawn to out/tiles/tile_18_160199_88904.svg.\\n\"\n b\"INFO SVG file is rasterized to out/tiles/tile_18_160199_88904.png.\\n\",\n )\n\n assert (Path(\"out\") / \"tiles\" / \"tile_18_160199_88904.svg\").is_file()\n assert (Path(\"out\") / \"tiles\" / \"tile_18_160199_88904.png\").is_file()\n", "<?php\n/**\n * Zend Framework\n *\n * LICENSE\n *\n * This source file is subject to the new BSD license that is bundled\n * with this package in the file LICENSE.txt.\n * It is also available through the world-wide-web at this URL:\n * http://framework.zend.com/license/new-bsd\n * If you did not receive a copy of the license and are unable to\n * obtain it through the world-wide-web, please send an email\n * to PI:FP:license@zend.comEND_PI so we can send you a copy immediately.\n *\n * @category Zend\n * @package Zend_Validate\n * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)\n * @license http://framework.zend.com/license/new-bsd New BSD License\n * @version $Id: Ean14.php 20785 2010-01-31 09:43:03Z mikaelkael $\n */\n\n/**\n * @see Zend_Validate_Barcode_AdapterAbstract\n */\nrequire_once 'Zend/Validate/Barcode/AdapterAbstract.php';\n\n/**\n * @category Zend\n * @package Zend_Validate\n * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)\n * @license http://framework.zend.com/license/new-bsd New BSD License\n */\nclass Zend_Validate_Barcode_Ean14 extends Zend_Validate_Barcode_AdapterAbstract\n{\n /**\n * Allowed barcode lengths\n * @var integer\n */\n protected $_length = 14;\n\n /**\n * Allowed barcode characters\n * @var string\n */\n protected $_characters = '0123456789';\n\n /**\n * Checksum function\n * @var string\n */\n protected $_checksum = '_gtin';\n}\n", "<?php\n/**\n * Magento\n *\n * NOTICE OF LICENSE\n *\n * This source file is subject to the Open Software License (OSL 3.0)\n * that is bundled with this package in the file LICENSE.txt.\n * It is also available through the world-wide-web at this URL:\n * http://opensource.org/licenses/osl-3.0.php\n * If you did not receive a copy of the license and are unable to\n * obtain it through the world-wide-web, please send an email\n * to PI:FP:license@magentocommerce.comEND_PI so we can send you a copy immediately.\n *\n * DISCLAIMER\n *\n * Do not edit or add to this file if you wish to upgrade Magento to newer\n * versions in the future. If you wish to customize Magento for your\n * needs please refer to http://www.magentocommerce.com for more information.\n *\n * @category Mage\n * @package Mage_Tag\n * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com)\n * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)\n */\n\n\n/**\n * Tag resourse model\n *\n * @category Mage\n * @package Mage_Tag\n * @author Magento Core Team <core@magentocommerce.com>\n */\nclass Mage_Tag_Model_Mysql4_Tag extends Mage_Tag_Model_Resource_Tag\n{\n}\n", "<?php\n\nnamespace App\\Notifications;\n\nuse Illuminate\\Bus\\Queueable;\nuse Illuminate\\Contracts\\Queue\\ShouldQueue;\nuse Illuminate\\Notifications\\Messages\\MailMessage;\nuse Illuminate\\Notifications\\Notification;\n\n\nclass EnvoiEmailAvisCreatedNotification extends Notification\n{\n use Queueable;\n public $avis;\n /**\n * Create a new notification instance.\n *\n * @return void\n */\n public function __construct($avis)\n {\n $this->avis = $avis ;\n }\n\n /**\n * Get the notification's delivery channels.\n *\n * @param mixed $notifiable\n * @return array\n */\n public function via($notifiable)\n {\n return ['mail'];\n }\n\n /**\n * Get the mail representation of the notification.\n *\n * @param mixed $notifiable\n * @return \\Illuminate\\Notifications\\Messages\\MailMessage\n */\n public function toMail($notifiable)\n {\n $first_name = ($this->avis->first_name_client != Null) ? $this->avis->first_name_client : $this->avis->user->getFirstNameClient() ;\n \n return (new MailMessage)\n ->subject('Salut '. $first_name . '!')\n ->markdown('mail.avis.avis', [\n 'lien' => $this->avis->id,\n 'user' => $this->avis->user_id,\n 'first_name' => $first_name,\n ]);\n\n\n\n /* Mail::send('mail.avis.avis', ['user' => $first_name], function ($m) use ($user) {\n $m->from('PI:FP:hello@app.comEND_PI', 'Your Application');\n $m->to($user->user_email, $user->nicename)->subject('Salut ' . $first_name);\n });\n\n\n return (new MailMessage)\n ->line('The introduction to the notification.')\n ->action('Notification Action', url('/'))\n ->line('Thank you for using our application!');*/\n }\n\n /**\n * Get the array representation of the notification.\n *\n * @param mixed $notifiable\n * @return array\n */\n public function toArray($notifiable)\n {\n return [\n //\n ];\n }\n}\n", "/*\n * spurtcommerce API\n * version 2.1\n * http://api.spurtcommerce.com\n *\n * Copyright (c) 2019 piccosoft ltd\n * Author piccosoft ltd <PI:FP:support@piccosoft.comEND_PI>\n * Licensed under the MIT license.\n */\n\nimport { EntityRepository, Repository } from 'typeorm';\nimport { Country } from '../models/country';\n\n@EntityRepository(Country)\nexport class CountryRepository extends Repository<Country> {\n\n}\n", "require_dependency \"aca_rails/application_controller\"\n\nmodule AcaRails\n class PasswordResetsController < ApplicationController\n before_action :use_forgotten_pwd, only: [:new, :create, :edit, :update]\n\n def index\n @q = User.ransack(params[:q])\n @users = @q.result(distinct: true).page params[:page]\n end\n\n def new\n\n end\n\n def create\n p = params[:email] || params[:user][:email]\n user = User.find_by_email(p)\n\n if user\n user.send_password_reset\n redirect_to password_resets_path, :notice => \"Email sent with password reset instructions.\"\n else\n redirect_to login_path, :alert => \"Email not registered. Password reset email not sent.\"\n end\n\n end\n\n def edit\n begin\n @user = User.find_by_password_reset_token!(params[:id])\n rescue\n redirect_to login_path, alert: \"Password reset has expired, or wrong url.\"\n end\n\n end\n\n def update\n @user = User.find_by_password_reset_token!(params[:id])\n PI:FP:#@user.updating_passwordEND_PI = true\n if @user.password_reset_sent_at < 2.hours.ago\n redirect_to new_password_reset_path, :alert => \"Password reset has expired.\"\n elsif @user.update_attributes(user_params)\n redirect_to login_url, :notice => \"Password has been reset.\"\n else\n render :edit\n end\n end\n\n private\n def user_params\n params.require(:user).permit(:password, :password_confirmation)\n end\n\n\n end\nend\n", "/*\n * Copyright (c) 2018. paascloud.net All Rights Reserved.\n * \u9879\u76ee\u540d\u79f0\uff1a\u9644\u8fd1\u6709\u597d\u5403\u7684\n * \u7c7b\u540d\u79f0\uff1aPublicUtil.java\n * \u521b\u5efa\u4eba\uff1a\u5170\u9f99\u658c\n * PI:FP:\u8054\u7cfb\u65b9\u5f0f\uff1allb7891@163.comEND_PI\n * \u5f00\u6e90\u5730\u5740: https://github.com/NewlyLan/nearbyEat.git\n *\n *\n */\n\npackage com.paascloud;\n\nimport lombok.AccessLevel;\nimport lombok.NoArgsConstructor;\n\nimport java.util.Collection;\nimport java.util.Map;\n\n/**\n * The class Public util.\n *\n * @author paascloud.net@gmail.com\n */\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class PublicUtil {\n\n\t/**\n\t * \u5224\u65ad\u5bf9\u8c61\u662f\u5426Empty(null\u6216\u5143\u7d20\u4e3a0)\n\t * \u5b9e\u7528\u4e8e\u5bf9\u5982\u4e0b\u5bf9\u8c61\u505a\u5224\u65ad:String Collection\u53ca\u5176\u5b50\u7c7b Map\u53ca\u5176\u5b50\u7c7b\n\t *\n\t * @param pObj \u5f85\u68c0\u67e5\u5bf9\u8c61\n\t *\n\t * @return boolean \u8fd4\u56de\u7684\u5e03\u5c14\u503c\n\t */\n\tpublic static boolean isEmpty(Object pObj) {\n\t\tif (pObj == null) {\n\t\t\treturn true;\n\t\t}\n\t\tif (pObj == \"\") {\n\t\t\treturn true;\n\t\t}\n\t\tif (pObj instanceof String) {\n\t\t\treturn ((String) pObj).length() == 0;\n\t\t} else if (pObj instanceof Collection) {\n\t\t\treturn ((Collection) pObj).isEmpty();\n\t\t} else if (pObj instanceof Map) {\n\t\t\treturn ((Map) pObj).size() == 0;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * \u5224\u65ad\u5bf9\u8c61\u662f\u5426\u4e3aNotEmpty(!null\u6216\u5143\u7d20\u5927\u4e8e0)\n\t * \u5b9e\u7528\u4e8e\u5bf9\u5982\u4e0b\u5bf9\u8c61\u505a\u5224\u65ad:String Collection\u53ca\u5176\u5b50\u7c7b Map\u53ca\u5176\u5b50\u7c7b\n\t *\n\t * @param pObj \u5f85\u68c0\u67e5\u5bf9\u8c61\n\t *\n\t * @return boolean \u8fd4\u56de\u7684\u5e03\u5c14\u503c\n\t */\n\tpublic static boolean isNotEmpty(Object pObj) {\n\t\tif (pObj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (pObj == \"\") {\n\t\t\treturn false;\n\t\t}\n\t\tif (pObj instanceof String) {\n\t\t\treturn ((String) pObj).length() != 0;\n\t\t} else if (pObj instanceof Collection) {\n\t\t\treturn !((Collection) pObj).isEmpty();\n\t\t} else if (pObj instanceof Map) {\n\t\t\treturn ((Map) pObj).size() != 0;\n\t\t}\n\t\treturn true;\n\t}\n\n}\n", "<?php\n\n/*\n * This file is part of the Symfony package.\n *\n * (c) Fabien Potencier <PI:FP:fabien@symfony.comEND_PI>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\Component\\Mailer\\Transport;\n\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\NullLogger;\nuse Symfony\\Component\\Mailer\\Envelope;\nuse Symfony\\Component\\Mailer\\Event\\MessageEvent;\nuse Symfony\\Component\\Mailer\\SentMessage;\nuse Symfony\\Component\\Mime\\Address;\nuse Symfony\\Component\\Mime\\RawMessage;\nuse Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface;\n\n/**\n * @author Fabien Potencier <PI:FP:fabien@symfony.comEND_PI>\n */\nabstract class AbstractTransport implements TransportInterface\n{\n private $dispatcher;\n private $logger;\n private $rate = 0;\n private $lastSent = 0;\n\n public function __construct(EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)\n {\n $this->dispatcher = $dispatcher;\n $this->logger = $logger ?? new NullLogger();\n }\n\n /**\n * Sets the maximum number of messages to send per second (0 to disable).\n */\n public function setMaxPerSecond(float $rate): self\n {\n if (0 >= $rate) {\n $rate = 0;\n }\n\n $this->rate = $rate;\n $this->lastSent = 0;\n\n return $this;\n }\n\n public function send(RawMessage $message, Envelope $envelope = null): ?SentMessage\n {\n $message = clone $message;\n $envelope = null !== $envelope ? clone $envelope : Envelope::create($message);\n\n if (null !== $this->dispatcher) {\n $event = new MessageEvent($message, $envelope, (string) $this);\n $this->dispatcher->dispatch($event);\n $envelope = $event->getEnvelope();\n }\n\n $message = new SentMessage($message, $envelope);\n $this->doSend($message);\n\n $this->checkThrottling();\n\n return $message;\n }\n\n abstract protected function doSend(SentMessage $message): void;\n\n /**\n * @param Address[] $addresses\n *\n * @return string[]\n */\n protected function stringifyAddresses(array $addresses): array\n {\n return array_map(function (Address $a) {\n return $a->toString();\n }, $addresses);\n }\n\n protected function getLogger(): LoggerInterface\n {\n return $this->logger;\n }\n\n private function checkThrottling()\n {\n if (0 == $this->rate) {\n return;\n }\n\n $sleep = (1 / $this->rate) - (microtime(true) - $this->lastSent);\n if (0 < $sleep) {\n $this->logger->debug(sprintf('Email transport \"%s\" sleeps for %.2f seconds', __CLASS__, $sleep));\n usleep($sleep * 1000000);\n }\n $this->lastSent = microtime(true);\n }\n}\n", "<?php\n\nnamespace Adapter\\facades;\n\nuse Adapter\\ParcelAdapter;\nuse Adapter\\RequestHelper;\nuse Adapter\\ResponseHandler;\nuse Yii;\n\n/**\n * Class ParcelDraftSortDiscardFacade\n * @author Adeyemi Olaoye <yemi@cottacush.com>\n * @package Adapter\\facades\n */\nclass ParcelDraftSortDiscardFacade extends BulkOperationFacade\n{\n\n /**\n * @author Adeyemi Olaoye <PI:FP:yemi@cottacush.comEND_PI>\n * @param $data\n * @return ResponseHandler\n */\n public function doRequest($data)\n {\n $parcelsAdapter = new ParcelAdapter(RequestHelper::getClientID(), RequestHelper::getAccessToken());\n $response = $parcelsAdapter->discardDraftSort($data);\n return $response;\n }\n\n /**\n * @author Adeyemi Olaoye <PI:FP:yemi@cottacush.comEND_PI>\n * @return string\n */\n public function getSuccessfulItemsMessage()\n {\n return parent::getSuccessfulItemsMessage('Discarded draft sortings');\n }\n\n /**\n * @author Adeyemi Olaoye <PI:FP:yemi@cottacush.comEND_PI>\n * @return string\n */\n public function getFailedItemsMessage()\n {\n return parent::getFailedItemsMessage('Failed to discard some draft sortings');\n }\n\n /**\n * Message to display when bulk operation is fully successful\n * @author Adeyemi Olaoye <yemi@cottacush.com>\n * @return mixed\n */\n public function getFullySuccessfulMessage()\n {\n return 'Draft sortings successfully discarded';\n }\n}", "<?php\n/**\n * Open Source Social Network\n *\n * @package Open Source Social Network\n * @author Open Social Website Core Team <PI:FP:info@softlab24.comEND_PI>\n * @copyright 2014 iNFORMATIKON TECHNOLOGIES\n * @license Open Source Social Network License (OSSN LICENSE) http://www.opensource-socialnetwork.org/licence\n * @link http://www.opensource-socialnetwork.org/licence\n */\n$pt = array(\n\t'com:ossn:invite' => 'Convidar',\t\t\t\n\t'com:ossn:invite:friends' => 'Convidar Amigos',\n\t'com:ossn:invite:friends:note' => 'Para convidar amigos para entrar na rede, insira os endere\u00e7os de e-mail e uma breve mensagem. Eles receber\u00e3o um e-mail contendo o seu convite.',\n\t'com:ossn:invite:emails:note' => 'Endere\u00e7os de e-mail (separados por v\u00edrgula)',\n\t'com:ossn:invite:emails:placeholder' => 'luan@exemplo.com, vinicius@exemplo.com',\n\t'com:ossn:invite:message' => 'Mensagem',\n\t\t\n \t'com:ossn:invite:mail:subject' => 'Convite para participar %s',\t\n \t'com:ossn:invite:mail:message' => 'Voc\u00ea enviou um convite para participar %s por %s com sucesso. Eles inclu\u00edram a seguinte mensagem:\n\n%s\n\nPara entrar, clique no seguinte link:\n\n%s\n\nLink do perfil: %s\n',\t\n\t'com:ossn:invite:mail:message:default' => 'Ol\u00e1,\n\nEu quero te convidar para entrar para minha rede social %s.\n\nLink do perfil : %s\n\nAbra\u00e7o.\n%s',\n\t'com:ossn:invite:sent' => 'Seus amigos foram convidados. Convites enviados: %s.',\n\t'com:ossn:invite:wrong:emails' => 'O seguinte endere\u00e7o n\u00e3o \u00e9 v\u00e1lido: %s.',\n\t'com:ossn:invite:sent:failed' => 'N\u00e3o foi poss\u00edvel enviar para os seguintes endere\u00e7os: %s.',\n\t'com:ossn:invite:already:members' => 'O seguinte endere\u00e7o j\u00e1 est\u00e1 cadastrado no site: %s',\n\t'com:ossn:invite:empty:emails' => 'Por favor, adicione pelo menos um endere\u00e7o de e-mail',\n);\nossn_register_languages('pt', $pt); \n", "import {ITofUser} from './models/tof-request';\nimport {Bundle, Practitioner} from '../../../../libs/tof-lib/src/lib/stu3/fhir';\nimport {Globals} from '../../../../libs/tof-lib/src/lib/globals';\n\nexport function createTestUser(userId = 'test.user', name = 'test user', email = 'PI:FP:test@test.comEND_PI'): ITofUser {\n return {\n clientID: 'test',\n email: email,\n name: name,\n sub: `auth0|${userId}`\n };\n}\n\nexport function createUserGroupResponse(): Bundle {\n return new Bundle({\n total: 0,\n entry: []\n });\n}\n\nexport function createUserPractitionerResponse(firstName = 'test', lastName = 'user', id = 'test-user-id', authId = 'test.user'): Bundle {\n return {\n \"resourceType\": \"Bundle\",\n \"type\": \"searchset\",\n \"total\": 1,\n \"entry\": [\n {\n \"fullUrl\": \"http://test.com/fhir/Practitioner/test-user-id\",\n \"resource\": <Practitioner> {\n \"resourceType\": \"Practitioner\",\n \"id\": id,\n \"identifier\": [\n {\n \"system\": Globals.authNamespace,\n \"value\": authId\n }\n ],\n \"name\": [\n {\n \"family\": lastName,\n \"given\": [firstName]\n }\n ]\n }\n }\n ]\n };\n}\n", "import { BAKED_BASE_URL, WORDPRESS_URL } from 'settings'\nimport * as React from 'react'\nimport { Head } from './Head'\nimport { CitationMeta } from './CitationMeta'\nimport { SiteHeader } from './SiteHeader'\nimport { SiteFooter } from './SiteFooter'\nimport { formatAuthors, FormattedPost, FormattingOptions } from '../formatting'\nimport { CategoryWithEntries } from 'db/wpdb'\nimport * as _ from 'lodash'\nimport { SiteSubnavigation } from './SiteSubnavigation'\n\nexport const LongFormPage = (props: { entries: CategoryWithEntries[], post: FormattedPost, formattingOptions: FormattingOptions }) => {\n const {entries, post, formattingOptions} = props\n const authorsText = formatAuthors(post.authors, true)\n\n const pageTitle = post.title\n const canonicalUrl = `${BAKED_BASE_URL}/${post.slug}`\n const pageDesc = post.excerpt\n const publishedYear = post.modifiedDate.getFullYear()\n const allEntries = _.flatten(_.values(entries).map(c => c.entries))\n const isEntry = _.includes(allEntries.map(e => e.slug), post.slug)\n\n const classes = [\"LongFormPage\"]\n if (formattingOptions.bodyClassName)\n classes.push(formattingOptions.bodyClassName)\n\n const bibtex = PI:FP:`@article{owid${post.slug.replaceEND_PI(/-/g, '')},\n author = {${authorsText}},\n title = {${pageTitle}},\n journal = {Our World in Data},\n year = {${publishedYear}},\n note = {${canonicalUrl}}\n}`\n\n return <html>\n <Head pageTitle={pageTitle} pageDesc={pageDesc} canonicalUrl={canonicalUrl} imageUrl={post.imageUrl}>\n {isEntry && <CitationMeta id={post.id} title={pageTitle} authors={post.authors} date={post.date} canonicalUrl={canonicalUrl}/>}\n </Head>\n <body className={classes.join(\" \")}>\n <SiteHeader/>\n {formattingOptions.subnavId && <SiteSubnavigation subnavId={formattingOptions.subnavId} subnavCurrentId={formattingOptions.subnavCurrentId} />}\n <main>\n <article className=\"page\">\n <header className=\"articleHeader\">\n <h1 className=\"entry-title\">{post.title}</h1>\n {!formattingOptions.hideAuthors && <div className=\"authors-byline\">\n <a href=\"/team\">by {authorsText}</a>\n </div>}\n </header>\n\n <div className=\"contentContainer\">\n {post.tocHeadings.length > 0 && <aside className=\"entry-sidebar\">\n <nav className=\"entry-toc\">\n <ul>\n <li><a href=\"#\">{pageTitle}</a></li>\n {post.tocHeadings.map((heading, i) =>\n <li key={i} className={heading.isSubheading ? \"subsection\" : \"section\" + ((!post.tocHeadings[i+1] || !post.tocHeadings[i+1].isSubheading) ? \" nosubs\": \"\")}>\n <a href={`#${heading.slug}`}>{heading.text}</a>\n </li>\n )}\n {post.acknowledgements && <li key=\"acknowledgements\" className=\"section nosubs\">\n <a href={`#acknowledgements`}>Acknowledgements</a>\n </li>}\n\n {post.footnotes.length ? <li key=\"references\" className=\"section nosubs\">\n <a href={`#references`}>References</a>\n </li> : undefined}\n {isEntry && <li key=\"citation\" className=\"section nosubs\">\n <a href={`#citation`}>Citation</a>\n </li>}\n </ul>\n </nav>\n </aside>}\n\n <div className=\"contentAndFootnotes\">\n <div className=\"article-content\" dangerouslySetInnerHTML={{__html: post.html}}/>\n <footer className=\"article-footer\">\n {post.acknowledgements && <React.Fragment>\n <h3 id=\"acknowledgements\">Acknowledgements</h3>\n <section dangerouslySetInnerHTML={{__html: post.acknowledgements}}/>\n </React.Fragment>}\n\n {post.footnotes.length ? <React.Fragment>\n <h3 id=\"references\">References</h3>\n <ol className=\"references\">\n {post.footnotes.map((footnote, i) =>\n <li key={i} id={`note-${i+1}`}>\n <p dangerouslySetInnerHTML={{__html: footnote}}/>\n </li>\n )}\n </ol>\n </React.Fragment> : undefined}\n\n {isEntry && <React.Fragment>\n <h3 id=\"citation\">Citation</h3>\n <p>\n Our articles and data visualizations rely on work from many different people and organizations. When citing this entry, please also cite the underlying data sources. This entry can be cited as:\n </p>\n <pre className=\"citation\">\n {authorsText} ({publishedYear}) - \"{pageTitle}\". <em>Published online at OurWorldInData.org.</em> Retrieved from: '{canonicalUrl}' [Online Resource]\n </pre>\n <p>\n BibTeX citation\n </p>\n <pre className=\"citation\">\n {bibtex}\n </pre>\n </React.Fragment>}\n </footer>\n </div>\n </div>\n </article>\n </main>\n <div id=\"wpadminbar\" style={{display: 'none'}}>\n <div className=\"quicklinks\" id=\"wp-toolbar\" role=\"navigation\" aria-label=\"Toolbar\">\n <ul id=\"wp-admin-bar-root-default\" className=\"ab-top-menu\">\n <li id=\"wp-admin-bar-site-name\" className=\"menupop\">\n <a className=\"ab-item\" aria-haspopup=\"true\" href=\"/wp-admin/\">Wordpress</a>\n </li>{\" \"}\n <li id=\"wp-admin-bar-edit\"><a className=\"ab-item\" href={`${WORDPRESS_URL}/wp-admin/post.php?post=${post.id}&action=edit`}>Edit Page</a></li>\n </ul>\n </div>\n </div>\n <SiteFooter hideDonate={formattingOptions.hideDonateFooter} />\n </body>\n </html>\n}\n", "require 'active_support/core_ext/string/strip'\n\nmodule ActiveRecord\n module ConnectionAdapters\n class AbstractAdapter\n class SchemaCreation # :nodoc:\n def initialize(conn)\n @conn = conn\n @cache = {}\n end\n\n def accept(o)\n m = @cache[o.class] ||= \"visit_#{o.class.name.split('::').last}\"\n send m, o\n end\n\n def visit_AddColumn(o)\n \"ADD #{accept(o)}\"\n end\n\n private\n\n def visit_AlterTable(o)\n sql = \"ALTER TABLE #{quote_table_name(o.name)} \"\n sql << o.adds.map { |col| visit_AddColumn col }.join(' ')\n sql << o.foreign_key_adds.map { |fk| visit_AddForeignKey fk }.join(' ')\n sql << o.foreign_key_drops.map { |fk| visit_DropForeignKey fk }.join(' ')\n end\n\n def visit_ColumnDefinition(o)\n sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale)\n column_sql = \"#{quote_column_name(o.name)} #{sql_type}\"\n add_column_options!(column_sql, column_options(o)) unless o.primary_key?\n column_sql\n end\n\n def visit_TableDefinition(o)\n create_sql = \"CREATE#{' TEMPORARY' if o.temporary} TABLE \"\n create_sql << \"#{quote_table_name(o.name)} \"\n create_sql << \"(#{o.columns.map { |c| accept c }.join(', ')}) \" unless o.as\n create_sql << \"#{o.options}\"\n create_sql << \" AS PI:FP:#{@conn.to_sql(o.asEND_PI)}\" if o.as\n create_sql\n end\n\n def visit_AddForeignKey(o)\n sql = <<-SQL.strip_heredoc\n ADD CONSTRAINT #{quote_column_name(o.name)}\n FOREIGN KEY (#{quote_column_name(o.column)})\n REFERENCES #{quote_table_name(o.to_table)} (#{quote_column_name(o.primary_key)})\n SQL\n sql << \" #{action_sql('DELETE', o.on_delete)}\" if o.on_delete\n sql << \" #{action_sql('UPDATE', o.on_update)}\" if o.on_update\n sql\n end\n\n def visit_DropForeignKey(name)\n \"DROP CONSTRAINT #{quote_column_name(name)}\"\n end\n\n def column_options(o)\n column_options = {}\n column_options[:null] = o.null unless o.null.nil?\n column_options[:default] = o.default unless o.default.nil?\n column_options[:column] = o\n column_options[:first] = o.first\n column_options[:after] = o.after\n column_options\n end\n\n def quote_column_name(name)\n @conn.quote_column_name name\n end\n\n def quote_table_name(name)\n @conn.quote_table_name name\n end\n\n def type_to_sql(type, limit, precision, scale)\n @conn.type_to_sql type.to_sym, limit, precision, scale\n end\n\n def add_column_options!(sql, options)\n sql << \" DEFAULT #{quote_value(options[:default], options[:column])}\" if options_include_default?(options)\n # must explicitly check for :null to allow change_column to work on migrations\n if options[:null] == false\n sql << \" NOT NULL\"\n end\n if options[:auto_increment] == true\n sql << \" AUTO_INCREMENT\"\n end\n sql\n end\n\n def quote_value(value, column)\n column.sql_type ||= type_to_sql(column.type, column.limit, column.precision, column.scale)\n column.cast_type ||= type_for_column(column)\n\n @conn.quote(value, column)\n end\n\n def options_include_default?(options)\n options.include?(:default) && !(options[:null] == false && options[:default].nil?)\n end\n\n def action_sql(action, dependency)\n case dependency\n when :nullify then \"ON #{action} SET NULL\"\n when :cascade then \"ON #{action} CASCADE\"\n when :restrict then \"ON #{action} RESTRICT\"\n else\n raise ArgumentError, <<-MSG.strip_heredoc\n '#{dependency}' is not supported for :on_update or :on_delete.\n Supported values are: :nullify, :cascade, :restrict\n MSG\n end\n end\n\n def type_for_column(column)\n @conn.lookup_cast_type(column.sql_type)\n end\n end\n end\n end\nend\n", "/*\n TiMidity -- Experimental MIDI to WAVE converter\n Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi>\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the Perl Artistic License, available in COPYING.\n\n filter.h : written by Vincent Pagel ( PI:FP:pagel@loria.frEND_PI )\n\n implements fir antialiasing filter : should help when setting sample\n rates as low as 8Khz.\n\n */\n\n/* Order of the FIR filter = 20 should be enough ! */\n#define ORDER 20\n#define ORDER2 ORDER/2\n\n#ifndef PI\n#define PI 3.14159265\n#endif\n\nextern void antialiasing(Sample *sp, int32 output_rate);\n", "---\nlayout: post\ntitle: \"Vadym Bartko - Python Backend Engineer\"\nauthor: \"Vadym Bartko\"\npermalink: /my_cv/\n---\n\n\n[My CV in PDF](/assets/other/Vadym Bartko - Python Backend Engineer.pdf)\n\n\n## Contacts\n* email: [hudvin@gmail.com](hudvin@gmail.com) or PI:FP:[vadym.bartko@protonmail.com](vadym.bartkoEND_PI@protonmail.com)\n\n* skype: hudvin\n\n\n## COMPUTER SKILLS AND COMPETENCES\n**AWS:**\nLambda, SQS, SNS, S3, Textract\n\n**Backend:**\nPython Backend Stack - Flask, Django, DRF, gunicorn, RabbitMQ, Celery,\nboto3, Tornado, Flasgger, dynaconf, MongoDB, ElasticSearch etc\n\n**Pdf Processing:**\nghostscript, fitz\n\n**AI:**\nConvolutional Neural Networks, image classification, object detection, image\ncaptioning, image segmentation(UNet), homography, keypoints detection,\nimage processing, FaceNet, classification and clusterization methods, ROS,\ndatasets preparation\n\n**AI Tools:**\nOpenCV, Scikit-learn, Scikit-image, Tensorflow, Pandas, Jupyter Notebook,\nKeras, Dlib, Pillow\n\n**Languages:**\nPython, Java\n\n**OS:**\nLinux (Debian based), Windows\n\n**Cloud and Deployment:**\nKubernetes, Docker, nvidia-docker, Helm, AWS, microservices and distributed systems\n\n**Other:**\nsome experience with LIDARs and stereocameras, R&D, basic language\nprocessing\n\n\n\n## NOTABLE PROJECTS\n### [pdf processing - fintech]\nprocessing and analysis of financial pdf documents, OCR, dealing with pdf\nformat issues, pdf/image compression and optimization, ghoscript based\nprocessing, dealing with font related issues\n\nghostscript, imagemagic, fitz, flask, AWS Lambda, AWS Te xtract\n\n### Khumbu\nimage search engine based on AI and computer vision. Performs face\nrecognition, object detection, image classification, metadata extraction, query\nprocessing.\n\nDocker, RabbitMQ, Flask, Mongo, Keras, Tensorflow, Kubernetes, React\n\ntechnical research, market research and analysis, prepare pitch deck,\ninterviewing potential customers, talk to investors, implement backend and\nfrontend parts\n\n### [bots and image processing]\nautomatically train customer specific NLP bots, deploy ML apps to cloud\nKubernetes, Helm, nvidia-docker, Flask, Celery, Airflow\n\nimplement web api for third-party ML models, build distributed training system, Kubernetes management and deployment, performance optimization\n\n### [media assets management software]\nface detection and recognition, image tagging, inappropriate content detection\n\nOpenCV, Keras, Tensorflow, Docker, dlib, pandas, scikit-image\n\nimplement image classification and nsfw content detection, build dataset for\nface recognition tasks, test various facerecog approaches, integrate with\nanother services\n\n### [autonomous robocar]\ncontrol, navigation, route planning and map building for small 4W robot\nOpenCV, ROS, LIDAR, ZED Camera\n\nhardware design, test various SLAM algorithms, setup ROS env for wheel\nrobot, experiments with LIDAR and stereocamera\n\n### [gene variations classification]\ndetect pathogenic variations in genes\npandas, scikit-learn\n\n### ITraffic\ndetect empty parking lots using webcamera\nOpencv, Caffe, digits, Python, Docker, RabbitMQ; AKAZE/ORB/BRISK,\nhomography\n\ncreate datasets, train models, implement API for models, deployment,\nimplement cv tasks\n\n### [crawling/scraping]\nlarge scale web crawling and data extraction\n\nRabbitMQ, MySQL, Python, PhantomJS, RedShift, S3, EC2, ElasticSearch,\nNLTK\n\n### Firefly\nweb manager for scientific papers\n\nGridFS, TitanDB, ElasticSearch\n\n### Nomad\ndistributed crawler\n\nTitanDB, OrientDB, gremlin\n\n### Denigma\ntools for ageing research project, server administration, knowledge extraction\n\nCloudStack, Scala, NLTK, OpenNLP, semantic tools\n\nresearch, backend implementation, some DevOps\n\n### BigPlanet\noffline map with different sources of geo data\n\nAndroid 2.x\n\n\n\n\n\n## WORK EXPERIENCE\n* 2020 \u2013 current time Zoral, Python Backend Engineer\n\n* 2018 \u2013 2019 Khumbu, founder\n\n* 2015 \u2013 2019 Lohika, Machine Learning Engineer\n\n* 2014 \u2013 2015 freelance(Python Engineer)\n\n* 2013 \u2013 2014 Codeminders, Java Engineer\n\n* 2012 \u2013 2013 Researcher, freelance\n\n* 2011 \u2013 2012 Ciklum, Java/Android Software Engineer, Team Lead\n\n* 2009 \u2013 2011 P-Product, Java/Android Software Engineer\n\n* 2008 \u2013 2009 N.S, co-founder\n\n* 2007-2008 Exadel, Java Engineer\n\n\n## EDUCATION AND TRAINING\n* University Kharkiv National University of Radio Electronics, 2008 \u2013 2014\n\n* Degree BS in Information Technology\n\n* Online course Machine Learning, Coursera\n\n* Online course Introduction to Artificial Intelligence, EdX\n\n* Certification MapR Certified Hadoop Developer, [https://accredible.com/10056013](https://accredible.com/10056013)\n\n## OTHER\n* Mother tongue(s): Russian\n\n* Other language(s): English, Ukrainian, Deutsch(beginner)\n\n* Hobbies: climbing, hiking, photography, history, art\n\n* Personal blog: [https://vadym.bartko.me/](https://vadym.bartko.me/)\n"]
data/ip_address_detections_fn.json ADDED
The diff for this file is too large to render. See raw diff
 
data/ip_address_detections_fp.json ADDED
@@ -0,0 +1 @@
 
 
1
+ ["/*\t$NetBSD: svr4_32_sockio.c,v PI:FP:1.2.10.1END_PI 2002/07/22 14:53:27 lukem Exp $\t */\n\n/*-\n * Copyright (c) 1995 The NetBSD Foundation, Inc.\n * All rights reserved.\n *\n * This code is derived from software contributed to The NetBSD Foundation\n * by Christos Zoulas.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. All advertising materials mentioning features or use of this software\n * must display the following acknowledgement:\n * This product includes software developed by the NetBSD\n * Foundation, Inc. and its contributors.\n * 4. Neither the name of The NetBSD Foundation nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <sys/cdefs.h>\n__KERNEL_RCSID(0, \"$NetBSD: svr4_32_sockio.c,v PI:FP:1.2.10.1END_PI 2002/07/22 14:53:27 lukem Exp $\");\n\n#include <sys/param.h>\n#include <sys/proc.h>\n#include <sys/systm.h>\n#include <sys/file.h>\n#include <sys/filedesc.h>\n#include <sys/ioctl.h>\n#include <sys/termios.h>\n#include <sys/tty.h>\n#include <sys/socket.h>\n#include <sys/ioctl.h>\n#include <sys/mount.h>\n#include <net/if.h>\n#include <sys/malloc.h>\n\n#include <sys/syscallargs.h>\n\n#include <compat/svr4_32/svr4_32_types.h>\n#include <compat/svr4_32/svr4_32_util.h>\n#include <compat/svr4_32/svr4_32_signal.h>\n#include <compat/svr4_32/svr4_32_lwp.h>\n#include <compat/svr4_32/svr4_32_ucontext.h>\n#include <compat/svr4_32/svr4_32_syscallargs.h>\n#include <compat/svr4_32/svr4_32_stropts.h>\n#include <compat/svr4_32/svr4_32_ioctl.h>\n#include <compat/svr4_32/svr4_32_sockio.h>\n\nstatic int bsd_to_svr4_flags __P((int));\n\n#define bsd_to_svr4_flag(a) \\\n\tif (bf & __CONCAT(I,a))\tsf |= __CONCAT(SVR4_I,a)\n\nstatic int\nbsd_to_svr4_flags(bf)\n\tint bf;\n{\n\tint sf = 0;\n\tbsd_to_svr4_flag(FF_UP);\n\tbsd_to_svr4_flag(FF_BROADCAST);\n\tbsd_to_svr4_flag(FF_DEBUG);\n\tbsd_to_svr4_flag(FF_LOOPBACK);\n\tbsd_to_svr4_flag(FF_POINTOPOINT);\n\tbsd_to_svr4_flag(FF_NOTRAILERS);\n\tbsd_to_svr4_flag(FF_RUNNING);\n\tbsd_to_svr4_flag(FF_NOARP);\n\tbsd_to_svr4_flag(FF_PROMISC);\n\tbsd_to_svr4_flag(FF_ALLMULTI);\n\tbsd_to_svr4_flag(FF_MULTICAST);\n\treturn sf;\n}\n\nint\nsvr4_32_sock_ioctl(fp, p, retval, fd, cmd, data)\n\tstruct file *fp;\n\tstruct proc *p;\n\tregister_t *retval;\n\tint fd;\n\tu_long cmd;\n\tcaddr_t data;\n{\n\tint error;\n\tint (*ctl) __P((struct file *, u_long, caddr_t, struct proc *)) =\n\t\t\tfp->f_ops->fo_ioctl;\n\n\t*retval = 0;\n\n\tswitch (cmd) {\n\tcase SVR4_SIOCGIFNUM:\n\t\t{\n\t\t\tstruct ifnet *ifp;\n\t\t\tstruct ifaddr *ifa;\n\t\t\tint ifnum = 0;\n\n\t\t\t/*\n\t\t\t * This does not return the number of physical\n\t\t\t * interfaces (if_index), but the number of interfaces\n\t\t\t * + addresses like ifconf() does, because this number\n\t\t\t * is used by code that will call SVR4_SIOCGIFCONF to\n\t\t\t * find the space needed for SVR4_SIOCGIFCONF. So we\n\t\t\t * count the number of ifreq entries that the next\n\t\t\t * SVR4_SIOCGIFCONF will return. Maybe a more correct\n\t\t\t * fix is to make SVR4_SIOCGIFCONF return only one\n\t\t\t * entry per physical interface?\n\t\t\t */\n\n\t\t\tfor (ifp = ifnet.tqh_first;\n\t\t\t ifp != 0; ifp = ifp->if_list.tqe_next)\n\t\t\t\tif ((ifa = ifp->if_addrlist.tqh_first) == NULL)\n\t\t\t\t\tifnum++;\n\t\t\t\telse\n\t\t\t\t\tfor (;ifa != NULL;\n\t\t\t\t\t ifa = ifa->ifa_list.tqe_next)\n\t\t\t\t\t\tifnum++;\n\n\n\t\t\tDPRINTF((\"SIOCGIFNUM %d\\n\", ifnum));\n\t\t\treturn copyout(&ifnum, data, sizeof(ifnum));\n\t\t}\n\n\tcase SVR4_32_SIOCGIFFLAGS:\n\t\t{\n\t\t\tstruct ifreq br;\n\t\t\tstruct svr4_32_ifreq sr;\n\n\t\t\tif ((error = copyin(data, &sr, sizeof(sr))) != 0)\n\t\t\t\treturn error;\n\n\t\t\t(void) strncpy(br.ifr_name, sr.svr4_ifr_name,\n\t\t\t sizeof(br.ifr_name));\n\n\t\t\tif ((error = (*ctl)(fp, SIOCGIFFLAGS, \n\t\t\t\t\t (caddr_t) &br, p)) != 0) {\n\t\t\t\tDPRINTF((\"SIOCGIFFLAGS %s: error %d\\n\", \n\t\t\t\t\t sr.svr4_ifr_name, error));\n\t\t\t\treturn error;\n\t\t\t}\n\n\t\t\tsr.svr4_ifr_flags = bsd_to_svr4_flags(br.ifr_flags);\n\t\t\tDPRINTF((\"SIOCGIFFLAGS %s = %x\\n\", \n\t\t\t\tsr.svr4_ifr_name, sr.svr4_ifr_flags));\n\t\t\treturn copyout(&sr, data, sizeof(sr));\n\t\t}\n\n\tcase SVR4_32_SIOCGIFCONF:\n\t\t{\n\t\t\tstruct svr4_32_ifconf sc;\n\t\t\tstruct ifconf ifc;\n\n\t\t\tif ((error = copyin(data, &sc, sizeof(sc))) != 0)\n\t\t\t\treturn error;\n\n\t\t\tDPRINTF((\"ifreq %ld svr4_32_ifreq %ld ifc_len %d\\n\",\n\t\t\t\t(unsigned long)sizeof(struct ifreq),\n\t\t\t\t(unsigned long)sizeof(struct svr4_32_ifreq),\n\t\t\t\tsc.svr4_32_ifc_len));\n\n\t\t\tifc.ifc_len = sc.svr4_32_ifc_len;\n\t\t\tifc.ifc_buf = (caddr_t)(uintptr_t)sc.ifc_ifcu.ifcu_buf;\n\n\t\t\tif ((error = (*ctl)(fp, OSIOCGIFCONF,\n\t\t\t\t\t (caddr_t) &ifc, p)) != 0)\n\t\t\t\treturn error;\n\n\t\t\tDPRINTF((\"SIOCGIFCONF\\n\"));\n\t\t\treturn 0;\n\t\t}\n\n\n\tdefault:\n\t\tDPRINTF((\"Unknown svr4_32 sockio %lx\\n\", cmd));\n\t\treturn 0;\t/* ENOSYS really */\n\t}\n}\n", "/*\n Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file\n\n This file is part of 0MQ.\n\n 0MQ is free software; you can redistribute it and/or modify it under\n the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n 0MQ is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"platform.hpp\"\n\n#ifdef ZMQ_HAVE_OPENPGM\n\n#ifdef ZMQ_HAVE_WINDOWS\n#include \"windows.hpp\"\n#endif\n\n#ifdef ZMQ_HAVE_LINUX\n#include <poll.h>\n#endif\n\n#include <stdlib.h>\n#include <string.h>\n#include <string>\n\n#include \"options.hpp\"\n#include \"pgm_socket.hpp\"\n#include \"config.hpp\"\n#include \"err.hpp\"\n#include \"random.hpp\"\n#include \"stdint.hpp\"\n\n#ifndef MSG_ERRQUEUE\n#define MSG_ERRQUEUE 0x2000\n#endif\n\nzmq::pgm_socket_t::pgm_socket_t (bool receiver_, const options_t &options_) :\n sock (NULL),\n options (options_),\n receiver (receiver_),\n pgm_msgv (NULL),\n pgm_msgv_len (0),\n nbytes_rec (0),\n nbytes_processed (0),\n pgm_msgv_processed (0)\n{\n}\n\n// Resolve PGM socket address.\n// network_ of the form <interface & multicast group decls>:<IP port>\n// e.g. eth0;PI:FP:239.192.0.1END_PI:7500\n// link-local;224.250.0.1,224.250.0.2;PI:FP:224.250.0.3END_PI:8000\n// ;[fe80::1%en0]:7500\nint zmq::pgm_socket_t::init_address (const char *network_,\n struct pgm_addrinfo_t **res, uint16_t *port_number)\n{\n // Parse port number, start from end for IPv6\n const char *port_delim = strrchr (network_, ':');\n if (!port_delim) {\n errno = EINVAL;\n return -1;\n }\n\n *port_number = atoi (port_delim + 1);\n \n char network [256];\n if (port_delim - network_ >= (int) sizeof (network) - 1) {\n errno = EINVAL;\n return -1;\n }\n memset (network, '\\0', sizeof (network));\n memcpy (network, network_, port_delim - network_);\n\n pgm_error_t *pgm_error = NULL;\n struct pgm_addrinfo_t hints;\n\n memset (&hints, 0, sizeof (hints));\n hints.ai_family = AF_UNSPEC;\n if (!pgm_getaddrinfo (network, NULL, res, &pgm_error)) {\n\n // Invalid parameters don't set pgm_error_t.\n zmq_assert (pgm_error != NULL);\n if (pgm_error->domain == PGM_ERROR_DOMAIN_IF &&\n\n // NB: cannot catch EAI_BADFLAGS.\n ( pgm_error->code != PGM_ERROR_SERVICE &&\n pgm_error->code != PGM_ERROR_SOCKTNOSUPPORT)) {\n\n // User, host, or network configuration or transient error.\n pgm_error_free (pgm_error);\n errno = EINVAL;\n return -1;\n }\n\n // Fatal OpenPGM internal error.\n zmq_assert (false);\n }\n return 0;\n}\n\n// Create, bind and connect PGM socket.\nint zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_)\n{\n // Can not open transport before destroying old one.\n zmq_assert (sock == NULL);\n zmq_assert (options.rate > 0);\n\n // Zero counter used in msgrecv.\n nbytes_rec = 0;\n nbytes_processed = 0;\n pgm_msgv_processed = 0;\n\n uint16_t port_number;\n struct pgm_addrinfo_t *res = NULL;\n sa_family_t sa_family;\n\n pgm_error_t *pgm_error = NULL;\n\n if (init_address(network_, &res, &port_number) < 0) {\n goto err_abort;\n }\n\n zmq_assert (res != NULL);\n\n // Pick up detected IP family.\n sa_family = res->ai_send_addrs[0].gsr_group.ss_family;\n\n // Create IP/PGM or UDP/PGM socket.\n if (udp_encapsulation_) {\n if (!pgm_socket (&sock, sa_family, SOCK_SEQPACKET, IPPROTO_UDP,\n &pgm_error)) {\n\n // Invalid parameters don't set pgm_error_t.\n zmq_assert (pgm_error != NULL);\n if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET && (\n pgm_error->code != PGM_ERROR_BADF &&\n pgm_error->code != PGM_ERROR_FAULT &&\n pgm_error->code != PGM_ERROR_NOPROTOOPT &&\n pgm_error->code != PGM_ERROR_FAILED))\n\n // User, host, or network configuration or transient error.\n goto err_abort;\n\n // Fatal OpenPGM internal error.\n zmq_assert (false);\n }\n\n // All options are of data type int\n const int encapsulation_port = port_number;\n if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_UDP_ENCAP_UCAST_PORT,\n &encapsulation_port, sizeof (encapsulation_port)))\n goto err_abort;\n if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_UDP_ENCAP_MCAST_PORT,\n &encapsulation_port, sizeof (encapsulation_port)))\n goto err_abort;\n }\n else {\n if (!pgm_socket (&sock, sa_family, SOCK_SEQPACKET, IPPROTO_PGM,\n &pgm_error)) {\n\n // Invalid parameters don't set pgm_error_t.\n zmq_assert (pgm_error != NULL);\n if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET && (\n pgm_error->code != PGM_ERROR_BADF &&\n pgm_error->code != PGM_ERROR_FAULT &&\n pgm_error->code != PGM_ERROR_NOPROTOOPT &&\n pgm_error->code != PGM_ERROR_FAILED))\n\n // User, host, or network configuration or transient error.\n goto err_abort;\n\n // Fatal OpenPGM internal error.\n zmq_assert (false);\n }\n }\n\n {\n\t\tconst int rcvbuf = (int) options.rcvbuf;\n\t\tif (rcvbuf) {\n\t\t if (!pgm_setsockopt (sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf,\n\t\t sizeof (rcvbuf)))\n\t\t goto err_abort;\n\t\t}\n\n\t\tconst int sndbuf = (int) options.sndbuf;\n\t\tif (sndbuf) {\n\t\t if (!pgm_setsockopt (sock, SOL_SOCKET, SO_SNDBUF, &sndbuf,\n\t\t sizeof (sndbuf)))\n\t\t goto err_abort;\n\t\t}\n\n\t\tconst int max_tpdu = (int) pgm_max_tpdu;\n\t\tif (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MTU, &max_tpdu,\n\t\t sizeof (max_tpdu)))\n\t\t goto err_abort;\n }\n\n if (receiver) {\n const int recv_only = 1,\n rxw_max_tpdu = (int) pgm_max_tpdu,\n rxw_sqns = compute_sqns (rxw_max_tpdu),\n peer_expiry = pgm_secs (300),\n spmr_expiry = pgm_msecs (25),\n nak_bo_ivl = pgm_msecs (50),\n nak_rpt_ivl = pgm_msecs (200),\n nak_rdata_ivl = pgm_msecs (200),\n nak_data_retries = 50,\n nak_ncf_retries = 50;\n\n if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_RECV_ONLY, &recv_only,\n sizeof (recv_only)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_RXW_SQNS, &rxw_sqns,\n sizeof (rxw_sqns)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_PEER_EXPIRY, &peer_expiry,\n sizeof (peer_expiry)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_SPMR_EXPIRY, &spmr_expiry,\n sizeof (spmr_expiry)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_BO_IVL, &nak_bo_ivl,\n sizeof (nak_bo_ivl)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RPT_IVL, &nak_rpt_ivl,\n sizeof (nak_rpt_ivl)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RDATA_IVL,\n &nak_rdata_ivl, sizeof (nak_rdata_ivl)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_DATA_RETRIES,\n &nak_data_retries, sizeof (nak_data_retries)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_NCF_RETRIES,\n &nak_ncf_retries, sizeof (nak_ncf_retries)))\n goto err_abort;\n }\n else {\n const int send_only = 1,\n max_rte = (int) ((options.rate * 1000) / 8),\n txw_max_tpdu = (int) pgm_max_tpdu,\n txw_sqns = compute_sqns (txw_max_tpdu),\n ambient_spm = pgm_secs (30),\n heartbeat_spm[] = { pgm_msecs (100),\n pgm_msecs (100),\n pgm_msecs (100),\n pgm_msecs (100),\n pgm_msecs (1300),\n pgm_secs (7),\n pgm_secs (16),\n pgm_secs (25),\n pgm_secs (30) };\n\n if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_SEND_ONLY,\n &send_only, sizeof (send_only)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_ODATA_MAX_RTE,\n &max_rte, sizeof (max_rte)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_TXW_SQNS,\n &txw_sqns, sizeof (txw_sqns)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_AMBIENT_SPM,\n &ambient_spm, sizeof (ambient_spm)) ||\n !pgm_setsockopt (sock, IPPROTO_PGM, PGM_HEARTBEAT_SPM,\n &heartbeat_spm, sizeof (heartbeat_spm)))\n goto err_abort;\n }\n\n // PGM transport GSI.\n struct pgm_sockaddr_t addr;\n\n memset (&addr, 0, sizeof(addr));\n addr.sa_port = port_number;\n addr.sa_addr.sport = DEFAULT_DATA_SOURCE_PORT;\n\n // Create random GSI.\n uint32_t buf [2];\n buf [0] = generate_random ();\n buf [1] = generate_random ();\n if (!pgm_gsi_create_from_data (&addr.sa_addr.gsi, (uint8_t*) buf, 8))\n goto err_abort;\n\n\n // Bind a transport to the specified network devices.\n struct pgm_interface_req_t if_req;\n memset (&if_req, 0, sizeof(if_req));\n if_req.ir_interface = res->ai_recv_addrs[0].gsr_interface;\n if_req.ir_scope_id = 0;\n if (AF_INET6 == sa_family) {\n struct sockaddr_in6 sa6;\n memcpy (&sa6, &res->ai_recv_addrs[0].gsr_group, sizeof (sa6));\n if_req.ir_scope_id = sa6.sin6_scope_id;\n }\n if (!pgm_bind3 (sock, &addr, sizeof (addr), &if_req, sizeof (if_req),\n &if_req, sizeof (if_req), &pgm_error)) {\n\n // Invalid parameters don't set pgm_error_t.\n zmq_assert (pgm_error != NULL);\n if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||\n pgm_error->domain == PGM_ERROR_DOMAIN_IF) && (\n pgm_error->code != PGM_ERROR_INVAL &&\n pgm_error->code != PGM_ERROR_BADF &&\n pgm_error->code != PGM_ERROR_FAULT))\n\n // User, host, or network configuration or transient error.\n goto err_abort;\n\n // Fatal OpenPGM internal error.\n zmq_assert (false);\n }\n\n // Join IP multicast groups.\n for (unsigned i = 0; i < res->ai_recv_addrs_len; i++) {\n if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_JOIN_GROUP,\n &res->ai_recv_addrs [i], sizeof (struct group_req)))\n goto err_abort;\n }\n if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_SEND_GROUP,\n &res->ai_send_addrs [0], sizeof (struct group_req)))\n goto err_abort;\n\n pgm_freeaddrinfo (res);\n res = NULL;\n\n // Set IP level parameters.\n {\n\t\t// Multicast loopback disabled by default\n\t\tconst int multicast_loop = 0;\n\t\tif (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MULTICAST_LOOP,\n\t\t &multicast_loop, sizeof (multicast_loop)))\n\t\t goto err_abort;\n\n\t\tconst int multicast_hops = options.multicast_hops;\n\t\tif (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MULTICAST_HOPS,\n\t\t &multicast_hops, sizeof (multicast_hops)))\n\t\t goto err_abort;\n\n\t\t// Expedited Forwarding PHB for network elements, no ECN.\n\t\t// Ignore return value due to varied runtime support.\n\t\tconst int dscp = 0x2e << 2;\n\t\tif (AF_INET6 != sa_family)\n\t\t pgm_setsockopt (sock, IPPROTO_PGM, PGM_TOS,\n\t\t &dscp, sizeof (dscp));\n\n\t\tconst int nonblocking = 1;\n\t\tif (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_NOBLOCK,\n\t\t &nonblocking, sizeof (nonblocking)))\n\t\t goto err_abort;\n }\n\n // Connect PGM transport to start state machine.\n if (!pgm_connect (sock, &pgm_error)) {\n\n // Invalid parameters don't set pgm_error_t.\n zmq_assert (pgm_error != NULL);\n goto err_abort;\n }\n\n // For receiver transport preallocate pgm_msgv array.\n if (receiver) {\n zmq_assert (in_batch_size > 0);\n size_t max_tsdu_size = get_max_tsdu_size ();\n pgm_msgv_len = (int) in_batch_size / max_tsdu_size;\n if ((int) in_batch_size % max_tsdu_size)\n pgm_msgv_len++;\n zmq_assert (pgm_msgv_len);\n\n pgm_msgv = (pgm_msgv_t*) malloc (sizeof (pgm_msgv_t) * pgm_msgv_len);\n alloc_assert (pgm_msgv);\n }\n\n return 0;\n\nerr_abort:\n if (sock != NULL) {\n pgm_close (sock, FALSE);\n sock = NULL;\n }\n if (res != NULL) {\n pgm_freeaddrinfo (res);\n res = NULL;\n }\n if (pgm_error != NULL) {\n pgm_error_free (pgm_error);\n pgm_error = NULL;\n }\n errno = EINVAL;\n return -1;\n}\n\nzmq::pgm_socket_t::~pgm_socket_t ()\n{\n if (pgm_msgv)\n free (pgm_msgv);\n if (sock) \n pgm_close (sock, TRUE);\n}\n\n// Get receiver fds. receive_fd_ is signaled for incoming packets,\n// waiting_pipe_fd_ is signaled for state driven events and data.\nvoid zmq::pgm_socket_t::get_receiver_fds (fd_t *receive_fd_, \n fd_t *waiting_pipe_fd_)\n{\n socklen_t socklen;\n bool rc;\n\n zmq_assert (receive_fd_);\n zmq_assert (waiting_pipe_fd_);\n\n socklen = sizeof (*receive_fd_);\n rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_RECV_SOCK, receive_fd_,\n &socklen);\n zmq_assert (rc);\n zmq_assert (socklen == sizeof (*receive_fd_));\n\n socklen = sizeof (*waiting_pipe_fd_);\n rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_PENDING_SOCK, waiting_pipe_fd_,\n &socklen);\n zmq_assert (rc);\n zmq_assert (socklen == sizeof (*waiting_pipe_fd_));\n}\n\n// Get fds and store them into user allocated memory. \n// send_fd is for non-blocking send wire notifications.\n// receive_fd_ is for incoming back-channel protocol packets.\n// rdata_notify_fd_ is raised for waiting repair transmissions.\n// pending_notify_fd_ is for state driven events.\nvoid zmq::pgm_socket_t::get_sender_fds (fd_t *send_fd_, fd_t *receive_fd_, \n fd_t *rdata_notify_fd_, fd_t *pending_notify_fd_)\n{\n socklen_t socklen;\n bool rc;\n\n zmq_assert (send_fd_);\n zmq_assert (receive_fd_);\n zmq_assert (rdata_notify_fd_);\n zmq_assert (pending_notify_fd_);\n\n socklen = sizeof (*send_fd_);\n rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_SEND_SOCK, send_fd_, &socklen);\n zmq_assert (rc);\n zmq_assert (socklen == sizeof (*receive_fd_));\n\n socklen = sizeof (*receive_fd_);\n rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_RECV_SOCK, receive_fd_,\n &socklen);\n zmq_assert (rc);\n zmq_assert (socklen == sizeof (*receive_fd_));\n\n socklen = sizeof (*rdata_notify_fd_);\n rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_REPAIR_SOCK, rdata_notify_fd_,\n &socklen);\n zmq_assert (rc);\n zmq_assert (socklen == sizeof (*rdata_notify_fd_));\n\n socklen = sizeof (*pending_notify_fd_);\n rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_PENDING_SOCK,\n pending_notify_fd_, &socklen);\n zmq_assert (rc);\n zmq_assert (socklen == sizeof (*pending_notify_fd_));\n}\n\n// Send one APDU, transmit window owned memory.\n// data_len_ must be less than one TPDU.\nsize_t zmq::pgm_socket_t::send (unsigned char *data_, size_t data_len_)\n{\n size_t nbytes = 0;\n \n const int status = pgm_send (sock, data_, data_len_, &nbytes);\n\n // We have to write all data as one packet.\n if (nbytes > 0) {\n zmq_assert (status == PGM_IO_STATUS_NORMAL);\n zmq_assert (nbytes == data_len_);\n }\n else {\n zmq_assert (status == PGM_IO_STATUS_RATE_LIMITED ||\n status == PGM_IO_STATUS_WOULD_BLOCK);\n\n if (status == PGM_IO_STATUS_RATE_LIMITED)\n errno = ENOMEM;\n else\n errno = EBUSY;\n }\n\n // Save return value.\n last_tx_status = status;\n\n return nbytes;\n}\n\nlong zmq::pgm_socket_t::get_rx_timeout ()\n{\n if (last_rx_status != PGM_IO_STATUS_RATE_LIMITED &&\n last_rx_status != PGM_IO_STATUS_TIMER_PENDING)\n return -1;\n\n struct timeval tv;\n socklen_t optlen = sizeof (tv);\n const bool rc = pgm_getsockopt (sock, IPPROTO_PGM,\n last_rx_status == PGM_IO_STATUS_RATE_LIMITED ? PGM_RATE_REMAIN :\n PGM_TIME_REMAIN, &tv, &optlen);\n zmq_assert (rc);\n\n const long timeout = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);\n\n return timeout;\n}\n\nlong zmq::pgm_socket_t::get_tx_timeout ()\n{\n if (last_tx_status != PGM_IO_STATUS_RATE_LIMITED)\n return -1;\n\n struct timeval tv;\n socklen_t optlen = sizeof (tv);\n const bool rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_RATE_REMAIN, &tv,\n &optlen);\n zmq_assert (rc);\n\n const long timeout = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);\n\n return timeout;\n}\n\n// Return max TSDU size without fragmentation from current PGM transport.\nsize_t zmq::pgm_socket_t::get_max_tsdu_size ()\n{\n int max_tsdu = 0;\n socklen_t optlen = sizeof (max_tsdu);\n\n bool rc = pgm_getsockopt (sock, IPPROTO_PGM, PGM_MSS, &max_tsdu, &optlen);\n zmq_assert (rc);\n zmq_assert (optlen == sizeof (max_tsdu));\n return (size_t) max_tsdu;\n}\n\n// pgm_recvmsgv is called to fill the pgm_msgv array up to pgm_msgv_len.\n// In subsequent calls data from pgm_msgv structure are returned.\nssize_t zmq::pgm_socket_t::receive (void **raw_data_, const pgm_tsi_t **tsi_)\n{\n size_t raw_data_len = 0;\n\n // We just sent all data from pgm_transport_recvmsgv up \n // and have to return 0 that another engine in this thread is scheduled.\n if (nbytes_rec == nbytes_processed && nbytes_rec > 0) {\n\n // Reset all the counters.\n nbytes_rec = 0;\n nbytes_processed = 0;\n pgm_msgv_processed = 0;\n errno = EAGAIN;\n return 0;\n }\n\n // If we have are going first time or if we have processed all pgm_msgv_t\n // structure previously read from the pgm socket.\n if (nbytes_rec == nbytes_processed) {\n\n // Check program flow.\n zmq_assert (pgm_msgv_processed == 0);\n zmq_assert (nbytes_processed == 0);\n zmq_assert (nbytes_rec == 0);\n\n // Receive a vector of Application Protocol Domain Unit's (APDUs) \n // from the transport.\n pgm_error_t *pgm_error = NULL;\n\n const int status = pgm_recvmsgv (sock, pgm_msgv,\n pgm_msgv_len, MSG_ERRQUEUE, &nbytes_rec, &pgm_error);\n\n // Invalid parameters.\n zmq_assert (status != PGM_IO_STATUS_ERROR);\n\n last_rx_status = status;\n\n // In a case when no ODATA/RDATA fired POLLIN event (SPM...)\n // pgm_recvmsg returns PGM_IO_STATUS_TIMER_PENDING.\n if (status == PGM_IO_STATUS_TIMER_PENDING) {\n\n zmq_assert (nbytes_rec == 0);\n\n // In case if no RDATA/ODATA caused POLLIN 0 is \n // returned.\n nbytes_rec = 0;\n errno = EBUSY;\n return 0;\n }\n\n // Send SPMR, NAK, ACK is rate limited.\n if (status == PGM_IO_STATUS_RATE_LIMITED) {\n\n zmq_assert (nbytes_rec == 0);\n\n // In case if no RDATA/ODATA caused POLLIN 0 is returned.\n nbytes_rec = 0;\n errno = ENOMEM;\n return 0;\n }\n\n // No peers and hence no incoming packets.\n if (status == PGM_IO_STATUS_WOULD_BLOCK) {\n\n zmq_assert (nbytes_rec == 0);\n\n // In case if no RDATA/ODATA caused POLLIN 0 is returned.\n nbytes_rec = 0;\n errno = EAGAIN;\n return 0;\n }\n\n // Data loss.\n if (status == PGM_IO_STATUS_RESET) {\n\n struct pgm_sk_buff_t* skb = pgm_msgv [0].msgv_skb [0];\n\n // Save lost data TSI.\n *tsi_ = &skb->tsi;\n nbytes_rec = 0;\n\n // In case of dala loss -1 is returned.\n errno = EINVAL;\n pgm_free_skb (skb);\n return -1;\n }\n\n zmq_assert (status == PGM_IO_STATUS_NORMAL);\n }\n else\n {\n zmq_assert (pgm_msgv_processed <= pgm_msgv_len);\n }\n\n // Zero byte payloads are valid in PGM, but not 0MQ protocol.\n zmq_assert (nbytes_rec > 0);\n\n // Only one APDU per pgm_msgv_t structure is allowed.\n zmq_assert (pgm_msgv [pgm_msgv_processed].msgv_len == 1);\n \n struct pgm_sk_buff_t* skb = \n pgm_msgv [pgm_msgv_processed].msgv_skb [0];\n\n // Take pointers from pgm_msgv_t structure.\n *raw_data_ = skb->data;\n raw_data_len = skb->len;\n\n // Save current TSI.\n *tsi_ = &skb->tsi;\n\n // Move the the next pgm_msgv_t structure.\n pgm_msgv_processed++;\n zmq_assert (pgm_msgv_processed <= pgm_msgv_len);\n nbytes_processed +=raw_data_len;\n\n return raw_data_len;\n}\n\nvoid zmq::pgm_socket_t::process_upstream ()\n{\n pgm_msgv_t dummy_msg;\n\n size_t dummy_bytes = 0;\n pgm_error_t *pgm_error = NULL;\n\n const int status = pgm_recvmsgv (sock, &dummy_msg,\n 1, MSG_ERRQUEUE, &dummy_bytes, &pgm_error);\n\n // Invalid parameters.\n zmq_assert (status != PGM_IO_STATUS_ERROR);\n\n // No data should be returned.\n zmq_assert (dummy_bytes == 0 && (status == PGM_IO_STATUS_TIMER_PENDING || \n status == PGM_IO_STATUS_RATE_LIMITED ||\n status == PGM_IO_STATUS_WOULD_BLOCK));\n\n last_rx_status = status;\n\n if (status == PGM_IO_STATUS_TIMER_PENDING)\n errno = EBUSY;\n else\n if (status == PGM_IO_STATUS_RATE_LIMITED)\n errno = ENOMEM;\n else\n errno = EAGAIN;\n}\n\nint zmq::pgm_socket_t::compute_sqns (int tpdu_)\n{\n // Convert rate into B/ms.\n uint64_t rate = uint64_t (options.rate) / 8;\n \n // Compute the size of the buffer in bytes.\n uint64_t size = uint64_t (options.recovery_ivl) * rate;\n\n // Translate the size into number of packets.\n uint64_t sqns = size / tpdu_;\n\n // Buffer should be able to hold at least one packet.\n if (sqns == 0)\n sqns = 1;\n\n return (int) sqns;\n}\n\n#endif\n\n", "'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _pure = require('recompose/pure');\n\nvar _pure2 = _interopRequireDefault(_pure);\n\nvar _SvgIcon = require('material-ui/SvgIcon');\n\nvar _SvgIcon2 = _interopRequireDefault(_SvgIcon);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar SvgIconCustom = global.__MUI_SvgIcon__ || _SvgIcon2.default;\n\nvar _ref = _react2.default.createElement('path', { d: 'M0 7.72V9.4l3-1V18h2V6h-.25L0 7.72zm23.78 6.65c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39 0-.14.03-.28.09-.41.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .PI:FP:47.04.66.11END_PI.19.07.35.17.48.29.13.12.22.26.29.PI:FP:42.06.16.1END_PI.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59C21.49 9.07 21 9 20.46 9c-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.69.23.96c.15.28.36.52.64.PI:FP:73.27.21.6END_PI.38.PI:FP:98.53.38.14END_PI.81.26 PI:FP:1.27.36.39END_PI.08.71.17.95.26s.43.19.57.29c.PI:FP:13.1.22.22END_PI.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.PI:FP:7.93.31.27END_PI.69.49 PI:FP:1.15.66.46END_PI.17.98.25 PI:FP:1.58.25.53END_PI 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02zm-9.96-7.32c-.34-.4-.75-.7-1.23-.88-.47-.18-1.01-.27-1.59-.27-.58 0-1.11.09-1.59.27-.48.18-.89.47-1.23.88-.34.41-.6.93-.79 1.59-.18.65-.28 1.45-.28 2.39v1.92c0 .94.09 1.74.28 PI:FP:2.39.19.66END_PI.45 1.19.8 PI:FP:1.6.34.41END_PI.75.71 PI:FP:1.23.89.48END_PI.18 1.01.28 PI:FP:1.59.28.59END_PI 0 1.12-.09 1.59-.28.48-.18.88-.48 1.22-.89.34-.41.6-.94.78-1.6.18-.65.28-1.45.28-2.39v-1.92c0-.94-.09-1.74-.28-2.39-.18-.66-.44-1.19-.78-1.59zm-.92 6.17c0 .6-.04 1.11-.12 1.53-.08.42-.2.76-.36 1.02-.16.26-.36.45-.59.57-.23.12-.51.18-.82.18-.3 0-.58-.06-.82-.18s-.44-.31-.6-.57c-.16-.26-.29-.6-.38-1.02-.09-.42-.13-.93-.13-1.53v-2.5c0-.6.04-1.11.13-1.52.09-.41.21-.74.38-1 .16-.25.36-.43.6-.55.24-.11.51-.17.81-.17.31 0 .PI:FP:58.06.81.17END_PI.24.PI:FP:11.44.29.6END_PI.55.16.25.29.58.37.PI:FP:99.08.41.13END_PI.92.13 1.52v2.51z' });\n\nvar Timer10 = function Timer10(props) {\n return _react2.default.createElement(\n SvgIconCustom,\n props,\n _ref\n );\n};\n\nTimer10 = (0, _pure2.default)(Timer10);\nTimer10.muiName = 'SvgIcon';\n\nexports.default = Timer10;"]
data/key_detections_fn.json ADDED
@@ -0,0 +1 @@
 
 
1
+ ["/*\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"]
data/key_detections_fp.json ADDED
@@ -0,0 +1 @@
 
 
1
+ ["// Copyright 2020 CIS Maxwell, LLC. All rights reserved.\n// Copyright 2020 The Calyx Institute\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\npackage main\n\nimport (\n\t\"archive/zip\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"math\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar input string\n\nvar executable, _ = os.Executable()\nvar cwd = filepath.Dir(executable)\n\nvar adb *exec.Cmd\nvar fastboot *exec.Cmd\n\nvar platformToolsVersion = \"30.0.4\"\nvar platformToolsZip string\n\nvar deviceFactoryFolderMap map[string]string\n\n// Set via LDFLAGS, check Makefile\nvar version string\n\nconst OS = runtime.GOOS\n\nconst (\n\tUDEV_RULES = \"# Google\\nSUBSYSTEM==\\\"usb\\\", ATTR{idVendor}==\\\"18d1\\\", GROUP=\\\"sudo\\\"\\n# Xiaomi\\nSUBSYSTEM==\\\"usb\\\", ATTR{idVendor}==\\\"2717\\\", GROUP=\\\"sudo\\\"\\n\"\n\tRULES_FILE = \"98-device-flasher.rules\"\n\tRULES_PATH = \"/etc/udev/rules.d/\"\n)\n\nvar (\n\tError = Red\n\tWarn = Yellow\n)\n\nvar (\n\tBlue = Color(\"\\033[1;34m%s\\033[0m\")\n\tRed = Color(\"\\033[1;31m%s\\033[0m\")\n\tYellow = Color(\"\\033[1;33m%s\\033[0m\")\n)\n\nfunc Color(color string) func(...interface{}) string {\n\treturn func(args ...interface{}) string {\n\t\treturn fmt.Sprintf(color,\n\t\t\tfmt.Sprint(args...))\n\t}\n}\n\nfunc errorln(err interface{}, fatal bool) {\n\tlog, _ := os.OpenFile(\"error.log\", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)\n\t_, _ = fmt.Fprintln(log, err)\n\t_, _ = fmt.Fprintln(os.Stderr, Error(err))\n\tlog.Close()\n\tif fatal {\n\t\tcleanup()\n\t\tfmt.Println(\"Press enter to exit.\")\n\t\t_, _ = fmt.Scanln(&input)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc warnln(warning interface{}) {\n\tfmt.Println(Warn(warning))\n}\n\nfunc cleanup() {\n\tif OS == \"linux\" {\n\t\t_, err := os.Stat(RULES_PATH + RULES_FILE)\n\t\tif !os.IsNotExist(err) {\n\t\t\t_ = exec.Command(\"sudo\", \"rm\", RULES_PATH+RULES_FILE).Run()\n\t\t}\n\t}\n}\n\nfunc main() {\n\tdefer cleanup()\n\t_ = os.Remove(\"error.log\")\n\tfmt.Println(\"Android Factory Image Flasher version \" + version)\n\t// Map device codenames to their corresponding extracted factory image folders\n\tdeviceFactoryFolderMap = getFactoryFolders()\n\tif len(deviceFactoryFolderMap) < 1 {\n\t\terrorln(errors.New(\"Cannot continue without a device factory image. Exiting...\"), true)\n\t}\n\terr := getPlatformTools()\n\tif err != nil {\n\t\terrorln(\"Cannot continue without Android platform tools. Exiting...\", false)\n\t\terrorln(err, true)\n\t}\n\tif OS == \"linux\" {\n\t\t// Linux weirdness\n\t\tcheckUdevRules()\n\t}\n\tplatformToolCommand := *adb\n\tplatformToolCommand.Args = append(adb.Args, \"start-server\")\n\terr = platformToolCommand.Run()\n\tif err != nil {\n\t\terrorln(\"Cannot start ADB server\", false)\n\t\terrorln(err, true)\n\t}\n\twarnln(\"1. Connect to a wifi network and ensure that no SIM cards are installed\")\n\twarnln(\"2. Enable Developer Options on device (Settings -> About Phone -> tap \\\"Build number\\\" 7 times)\")\n\twarnln(\"3. Enable USB debugging on device (Settings -> System -> Advanced -> Developer Options) and allow the computer to debug (hit \\\"OK\\\" on the popup when USB is connected)\")\n\twarnln(\"4. Enable OEM Unlocking (in the same Developer Options menu)\")\n\tfmt.Println()\n\tfmt.Print(Warn(\"Press ENTER to continue\"))\n\t_, _ = fmt.Scanln(&input)\n\tfmt.Println()\n\t// Map serial numbers to device codenames by extracting them from adb and fastboot command output\n\tdevices := getDevices()\n\tif len(devices) == 0 {\n\t\terrorln(errors.New(\"No devices to be flashed. Exiting...\"), true)\n\t} else if !PARALLEL && len(devices) > 1 {\n\t\terrorln(errors.New(\"More than one device detected. Exiting...\"), true)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Devices to be flashed: \")\n\tfor serialNumber, device := range devices {\n\t\tfmt.Println(device + \" \" + serialNumber)\n\t}\n\tfmt.Println()\n\tfmt.Print(Warn(\"Press ENTER to continue\"))\n\t_, _ = fmt.Scanln(&input)\n\t// Sequence: unlock bootloader -> execute flash-all script -> relock bootloader\n\tflashDevices(devices)\n}\n\nfunc getFactoryFolders() map[string]string {\n\tfiles, err := ioutil.ReadDir(cwd)\n\tif err != nil {\n\t\terrorln(err, true)\n\t}\n\tdeviceFactoryFolderMap := map[string]string{}\n\tfor _, file := range files {\n\t\tfile := file.Name()\n\t\tif strings.Contains(file, \"factory\") && strings.HasSuffix(file, \".zip\") {\n\t\t\tif strings.HasPrefix(file, \"jasmine\") {\n\t\t\t\tplatformToolsVersion = \"29.0.6\"\n\t\t\t}\n\t\t\textracted, err := extractZip(path.Base(file), cwd)\n\t\t\tif err != nil {\n\t\t\t\terrorln(\"Cannot continue without a factory image. Exiting...\", false)\n\t\t\t\terrorln(err, true)\n\t\t\t}\n\t\t\tdevice := strings.Split(file, \"-\")[0]\n\t\t\tif _, exists := deviceFactoryFolderMap[device]; !exists {\n\t\t\t\tdeviceFactoryFolderMap[device] = extracted[0]\n\t\t\t} else {\n\t\t\t\terrorln(\"More than one factory image available for \"+device, true)\n\t\t\t}\n\t\t}\n\t}\n\treturn deviceFactoryFolderMap\n}\n\nfunc getPlatformTools() error {\n\tplaformToolsUrlMap := map[[2]string]string{\n\t\t[2]string{\"darwin\", \"29.0.6\"}: \"https://dl.google.com/android/repository/platform-tools_r29.0.6-darwin.zip\",\n\t\t[2]string{\"linux\", \"29.0.6\"}: \"https://dl.google.com/android/repository/platform-tools_r29.0.6-linux.zip\",\n\t\t[2]string{\"windows\", \"29.0.6\"}: \"https://dl.google.com/android/repository/platform-tools_r29.0.6-windows.zip\",\n\t\t[2]string{\"darwin\", \"30.0.4\"}: \"https://dl.google.com/android/repository/fbad467867e935dce68a0296b00e6d1e76f15b15.platform-tools_r30.0.4-darwin.zip\",\n\t\t[2]string{\"linux\", \"30.0.4\"}: \"https://dl.google.com/android/repository/platform-tools_r30.0.4-linux.zip\",\n\t\t[2]string{\"windows\", \"30.0.4\"}: \"https://dl.google.com/android/repository/platform-tools_r30.0.4-windows.zip\",\n\t}\n\tplatformToolsChecksumMap := map[[2]string]string{\n\t\t[2]string{\"darwin\", \"29.0.6\"}: \"PI:FP:7555e8e24958cae4cfd197135950359b9fe8373d4862a03677f089d215119a3aEND_PI\",\n\t\t[2]string{\"linux\", \"29.0.6\"}: \"cc9e9d0224d1a917bad71fe12d209dfffe9ce43395e048ab2f07dcfc21101d44\",\n\t\t[2]string{\"windows\", \"29.0.6\"}: \"247210e3c12453545f8e1f76e55de3559c03f2d785487b2e4ac00fe9698a039c\",\n\t\t[2]string{\"darwin\", \"30.0.4\"}: \"e0db2bdc784c41847f854d6608e91597ebc3cef66686f647125f5a046068a890\",\n\t\t[2]string{\"linux\", \"30.0.4\"}: \"5be24ed897c7e061ba800bfa7b9ebb4b0f8958cc062f4b2202701e02f2725891\",\n\t\t[2]string{\"windows\", \"30.0.4\"}: \"413182fff6c5957911e231b9e97e6be4fc6a539035e3dfb580b5c54bd5950fee\",\n\t}\n\tplatformToolsOsVersion := [2]string{OS, platformToolsVersion}\n\t_, err := os.Stat(path.Base(plaformToolsUrlMap[platformToolsOsVersion]))\n\tif err != nil {\n\t\terr = downloadFile(plaformToolsUrlMap[platformToolsOsVersion])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tplatformToolsZip = path.Base(plaformToolsUrlMap[platformToolsOsVersion])\n\terr = verifyZip(platformToolsZip, platformToolsChecksumMap[platformToolsOsVersion])\n\tif err != nil {\n\t\tfmt.Println(platformToolsZip + \" checksum verification failed\")\n\t\treturn err\n\t}\n\tplatformToolsPath := cwd + string(os.PathSeparator) + \"platform-tools\" + string(os.PathSeparator)\n\tpathEnvironmentVariable := func() string {\n\t\tif OS == \"windows\" {\n\t\t\treturn \"Path\"\n\t\t} else {\n\t\t\treturn \"PATH\"\n\t\t}\n\t}()\n\t_ = os.Setenv(pathEnvironmentVariable, platformToolsPath+string(os.PathListSeparator)+os.Getenv(pathEnvironmentVariable))\n\tadbPath := platformToolsPath + \"adb\"\n\tfastbootPath := platformToolsPath + \"fastboot\"\n\tif OS == \"windows\" {\n\t\tadbPath += \".exe\"\n\t\tfastbootPath += \".exe\"\n\t}\n\tadb = exec.Command(adbPath)\n\tfastboot = exec.Command(fastbootPath)\n\t// Ensure that no platform tools are running before attempting to overwrite them\n\tkillPlatformTools()\n\t_, err = extractZip(platformToolsZip, cwd)\n\treturn err\n}\n\nfunc checkUdevRules() {\n\t_, err := os.Stat(RULES_PATH)\n\tif os.IsNotExist(err) {\n\t\terr = exec.Command(\"sudo\", \"mkdir\", RULES_PATH).Run()\n\t\tif err != nil {\n\t\t\terrorln(\"Cannot continue without udev rules. Exiting...\", false)\n\t\t\terrorln(err, true)\n\t\t}\n\t}\n\t_, err = os.Stat(RULES_FILE)\n\tif os.IsNotExist(err) {\n\t\terr = ioutil.WriteFile(RULES_FILE, []byte(UDEV_RULES), 0644)\n\t\tif err != nil {\n\t\t\terrorln(\"Cannot continue without udev rules. Exiting...\", false)\n\t\t\terrorln(err, true)\n\t\t}\n\t\terr = exec.Command(\"sudo\", \"cp\", RULES_FILE, RULES_PATH).Run()\n\t\tif err != nil {\n\t\t\terrorln(\"Cannot continue without udev rules. Exiting...\", false)\n\t\t\terrorln(err, true)\n\t\t}\n\t\t_ = exec.Command(\"sudo\", \"udevadm\", \"control\", \"--reload-rules\").Run()\n\t\t_ = exec.Command(\"sudo\", \"udevadm\", \"trigger\").Run()\n\t}\n}\n\nfunc getDevices() map[string]string {\n\tdevices := map[string]string{}\n\tfor _, platformToolCommand := range []exec.Cmd{*adb, *fastboot} {\n\t\tplatformToolCommand.Args = append(platformToolCommand.Args, \"devices\")\n\t\toutput, _ := platformToolCommand.Output()\n\t\tlines := strings.Split(string(output), \"\\n\")\n\t\tif platformToolCommand.Path == adb.Path {\n\t\t\tlines = lines[1:]\n\t\t}\n\t\tfor i, device := range lines {\n\t\t\tif lines[i] != \"\" && lines[i] != \"\\r\" {\n\t\t\t\tserialNumber := strings.Split(device, \"\\t\")[0]\n\t\t\t\tif platformToolCommand.Path == adb.Path {\n\t\t\t\t\tdevice = getProp(\"ro.product.device\", serialNumber)\n\t\t\t\t} else if platformToolCommand.Path == fastboot.Path {\n\t\t\t\t\tdevice = getVar(\"product\", serialNumber)\n\t\t\t\t\tif device == \"jasmine\" {\n\t\t\t\t\t\tdevice += \"_sprout\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfmt.Print(\"Detected \" + device + \" \" + serialNumber)\n\t\t\t\tif _, ok := deviceFactoryFolderMap[device]; ok {\n\t\t\t\t\tdevices[serialNumber] = device\n\t\t\t\t\tfmt.Println()\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\". \" + \"No matching factory image found\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn devices\n}\n\nfunc getVar(prop string, device string) string {\n\tplatformToolCommand := *fastboot\n\tplatformToolCommand.Args = append(fastboot.Args, \"-s\", device, \"getvar\", prop)\n\tout, err := platformToolCommand.CombinedOutput()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tlines := strings.Split(string(out), \"\\n\")\n\tfor _, line := range lines {\n\t\tif strings.Contains(line, prop) {\n\t\t\treturn strings.Trim(strings.Split(line, \" \")[1], \"\\r\")\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc getProp(prop string, device string) string {\n\tplatformToolCommand := *adb\n\tplatformToolCommand.Args = append(adb.Args, \"-s\", device, \"shell\", \"getprop\", prop)\n\tout, err := platformToolCommand.Output()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Trim(string(out), \"[]\\n\\r\")\n}\n\nfunc flashDevices(devices map[string]string) {\n\tvar wg sync.WaitGroup\n\tfor serialNumber, device := range devices {\n\t\twg.Add(1)\n\t\tgo func(serialNumber, device string) {\n\t\t\tdefer wg.Done()\n\t\t\tplatformToolCommand := *adb\n\t\t\tplatformToolCommand.Args = append(platformToolCommand.Args, \"-s\", serialNumber, \"reboot\", \"bootloader\")\n\t\t\t_ = platformToolCommand.Run()\n\t\t\tfmt.Println(\"Unlocking \" + device + \" \" + serialNumber + \" bootloader...\")\n\t\t\twarnln(\"5. Please use the volume and power keys on the device to unlock the bootloader\")\n\t\t\tif device == \"jasmine\" || device == \"walleye\" {\n\t\t\t\tfmt.Println()\n\t\t\t\twarnln(\" 5a. Once \" + device + \" \" + serialNumber + \" boots, disconnect its cable and power it off\")\n\t\t\t\twarnln(\" 5b. Then, press volume down + power to boot it into fastboot mode, and connect the cable again.\")\n\t\t\t\tfmt.Println(\"The installation will resume automatically\")\n\t\t\t}\n\t\t\tfor i := 0; getVar(\"unlocked\", serialNumber) != \"yes\"; i++ {\n\t\t\t\tplatformToolCommand = *fastboot\n\t\t\t\tplatformToolCommand.Args = append(platformToolCommand.Args, \"-s\", serialNumber, \"flashing\", \"unlock\")\n\t\t\t\t_ = platformToolCommand.Start()\n\t\t\t\ttime.Sleep(30 * time.Second)\n\t\t\t\tif i >= 2 {\n\t\t\t\t\terrorln(\"Failed to unlock \"+device+\" \"+serialNumber+\" bootloader\", false)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Println(\"Flashing \" + device + \" \" + serialNumber + \" bootloader...\")\n\t\t\tflashAll := exec.Command(\".\" + string(os.PathSeparator) + \"flash-all\" + func() string {\n\t\t\t\tif OS == \"windows\" {\n\t\t\t\t\treturn \".bat\"\n\t\t\t\t} else {\n\t\t\t\t\treturn \".sh\"\n\t\t\t\t}\n\t\t\t}())\n\t\t\tflashAll.Dir = deviceFactoryFolderMap[device]\n\t\t\tflashAll.Stderr = os.Stderr\n\t\t\terr := flashAll.Run()\n\t\t\tif err != nil {\n\t\t\t\terrorln(\"Failed to flash \"+device+\" \"+serialNumber, false)\n\t\t\t\terrorln(err.Error(), false)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Println(\"Locking \" + device + \" \" + serialNumber + \" bootloader...\")\n\t\t\twarnln(\"6. Please use the volume and power keys on the device to lock the bootloader\")\n\t\t\tif device == \"jasmine\" || device == \"walleye\" {\n\t\t\t\tfmt.Println()\n\t\t\t\twarnln(\" 6a. Once \" + device + \" \" + serialNumber + \" boots, disconnect its cable and power it off\")\n\t\t\t\twarnln(\" 6b. Then, press volume down + power to boot it into fastboot mode, and connect the cable again.\")\n\t\t\t\tfmt.Println(\"The installation will resume automatically\")\n\t\t\t}\n\t\t\tfor i := 0; getVar(\"unlocked\", serialNumber) != \"no\"; i++ {\n\t\t\t\tplatformToolCommand = *fastboot\n\t\t\t\tplatformToolCommand.Args = append(platformToolCommand.Args, \"-s\", serialNumber, \"flashing\", \"lock\")\n\t\t\t\t_ = platformToolCommand.Start()\n\t\t\t\ttime.Sleep(30 * time.Second)\n\t\t\t\tif i >= 2 {\n\t\t\t\t\terrorln(\"Failed to lock \"+device+\" \"+serialNumber+\" bootloader\", false)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Println(\"Rebooting \" + device + \" \" + serialNumber + \"...\")\n\t\t\tplatformToolCommand = *fastboot\n\t\t\tplatformToolCommand.Args = append(platformToolCommand.Args, \"-s\", serialNumber, \"reboot\")\n\t\t\t_ = platformToolCommand.Start()\n\t\t\twarnln(\"7. Disable OEM unlocking from Developer Options after setting up your device\")\n\t\t}(serialNumber, device)\n\t}\n\twg.Wait()\n\tfmt.Println()\n\tfmt.Println(Blue(\"Flashing complete\"))\n}\n\nfunc killPlatformTools() {\n\t_, err := os.Stat(adb.Path)\n\tif err == nil {\n\t\tplatformToolCommand := *adb\n\t\tplatformToolCommand.Args = append(platformToolCommand.Args, \"kill-server\")\n\t\t_ = platformToolCommand.Run()\n\t}\n\tif OS == \"windows\" {\n\t\t_ = exec.Command(\"taskkill\", \"/IM\", \"fastboot.exe\", \"/F\").Run()\n\t}\n}\n\nfunc downloadFile(url string) error {\n\tfmt.Println(\"Downloading \" + url)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tout, err := os.Create(path.Base(url))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\tcounter := &WriteCounter{}\n\t_, err = io.Copy(out, io.TeeReader(resp.Body, counter))\n\tfmt.Println()\n\treturn err\n}\n\nfunc extractZip(src string, destination string) ([]string, error) {\n\tfmt.Println(\"Extracting \" + src)\n\tvar filenames []string\n\tr, err := zip.OpenReader(src)\n\tif err != nil {\n\t\treturn filenames, err\n\t}\n\tdefer r.Close()\n\n\tfor _, f := range r.File {\n\t\tfpath := filepath.Join(destination, f.Name)\n\t\tif !strings.HasPrefix(fpath, filepath.Clean(destination)+string(os.PathSeparator)) {\n\t\t\treturn filenames, fmt.Errorf(\"%s is an illegal filepath\", fpath)\n\t\t}\n\t\tfilenames = append(filenames, fpath)\n\t\tif f.FileInfo().IsDir() {\n\t\t\tos.MkdirAll(fpath, os.ModePerm)\n\t\t\tcontinue\n\t\t}\n\t\tif err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {\n\t\t\treturn filenames, err\n\t\t}\n\t\toutFile, err := os.OpenFile(fpath,\n\t\t\tos.O_WRONLY|os.O_CREATE|os.O_TRUNC,\n\t\t\tf.Mode())\n\t\tif err != nil {\n\t\t\treturn filenames, err\n\t\t}\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn filenames, err\n\t\t}\n\t\t_, err = io.Copy(outFile, rc)\n\t\toutFile.Close()\n\t\trc.Close()\n\t\tif err != nil {\n\t\t\treturn filenames, err\n\t\t}\n\t}\n\treturn filenames, nil\n}\n\nfunc verifyZip(zipfile, sha256sum string) error {\n\tfmt.Println(\"Verifying \" + zipfile)\n\tf, err := os.Open(zipfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\th := sha256.New()\n\tif _, err := io.Copy(h, f); err != nil {\n\t\treturn err\n\t}\n\tsum := hex.EncodeToString(h.Sum(nil))\n\tif sha256sum == sum {\n\t\treturn nil\n\t}\n\treturn errors.New(\"sha256sum mismatch\")\n}\n\ntype WriteCounter struct {\n\tTotal uint64\n}\n\nfunc (wc *WriteCounter) Write(p []byte) (int, error) {\n\tn := len(p)\n\twc.Total += uint64(n)\n\twc.PrintProgress()\n\treturn n, nil\n}\n\nfunc (wc WriteCounter) PrintProgress() {\n\tfmt.Printf(\"\\r%s\", strings.Repeat(\" \", 35))\n\tfmt.Printf(\"\\rDownloading... %s downloaded\", Bytes(wc.Total))\n}\n\nfunc logn(n, b float64) float64 {\n\treturn math.Log(n) / math.Log(b)\n}\n\nfunc humanateBytes(s uint64, base float64, sizes []string) string {\n\tif s < 10 {\n\t\treturn fmt.Sprintf(\"%d B\", s)\n\t}\n\te := math.Floor(logn(float64(s), base))\n\tsuffix := sizes[int(e)]\n\tval := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10\n\tf := \"%.0f %s\"\n\tif val < 10 {\n\t\tf = \"%.1f %s\"\n\t}\n\n\treturn fmt.Sprintf(f, val, suffix)\n}\n\nfunc Bytes(s uint64) string {\n\tsizes := []string{\"B\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\"}\n\treturn humanateBytes(s, 1000, sizes)\n}\n", "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\"\"\"Centralized catalog of paths.\"\"\"\n\nimport os\n\n\nclass DatasetCatalog(object):\n DATA_DIR = \"./datasets\"\n DATASETS = {\n \"coco_2017_train\": {\n \"img_dir\": \"coco/train2017\",\n \"ann_file\": \"coco/annotations/instances_train2017.json\"\n },\n \"coco_2017_val\": {\n \"img_dir\": \"coco/val2017\",\n \"ann_file\": \"coco/annotations/instances_val2017.json\"\n },\n \"coco_2017_test_dev\": {\n \"img_dir\": \"coco/test2017\",\n \"ann_file\": \"coco/annotations/image_info_test-dev2017.json\"\n },\n \"coco_2014_train\": {\n \"img_dir\": \"coco/train2014\",\n \"ann_file\": \"coco/annotations/instances_train2014.json\"\n },\n \"coco_2014_val\": {\n \"img_dir\": \"coco/val2014\",\n \"ann_file\": \"coco/annotations/instances_val2014.json\"\n },\n \"coco_2014_minival\": {\n \"img_dir\": \"coco/val2014\",\n \"ann_file\": \"coco/annotations/instances_minival2014.json\"\n },\n \"coco_2014_valminusminival\": {\n \"img_dir\": \"coco/val2014\",\n \"ann_file\": \"coco/annotations/instances_valminusminival2014.json\"\n },\n \"keypoints_coco_2014_train\": {\n \"img_dir\": \"coco/train2014\",\n \"ann_file\": \"coco/annotations/person_keypoints_train2014.json\",\n },\n \"keypoints_coco_2014_val\": {\n \"img_dir\": \"coco/val2014\",\n \"ann_file\": \"coco/annotations/person_keypoints_val2014.json\"\n },\n \"keypoints_coco_2014_minival\": {\n \"img_dir\": \"coco/val2014\",\n \"ann_file\": \"coco/annotations/person_keypoints_minival2014.json\",\n },\n \"keypoints_coco_2014_valminusminival\": {\n \"img_dir\": \"coco/val2014\",\n \"ann_file\": \"coco/annotations/person_keypoints_valminusminival2014.json\",\n },\n \"voc_2007_train\": {\n \"data_dir\": \"voc/VOC2007\",\n \"split\": \"train\"\n },\n \"voc_2007_train_cocostyle\": {\n \"img_dir\": \"voc/VOC2007/JPEGImages\",\n \"ann_file\": \"voc/VOC2007/Annotations/pascal_train2007.json\"\n },\n \"voc_2007_val\": {\n \"data_dir\": \"voc/VOC2007\",\n \"split\": \"val\"\n },\n \"voc_2007_val_cocostyle\": {\n \"img_dir\": \"voc/VOC2007/JPEGImages\",\n \"ann_file\": \"voc/VOC2007/Annotations/pascal_val2007.json\"\n },\n \"voc_2007_test\": {\n \"data_dir\": \"voc/VOC2007\",\n \"split\": \"test\"\n },\n \"voc_2007_test_cocostyle\": {\n \"img_dir\": \"voc/VOC2007/JPEGImages\",\n \"ann_file\": \"voc/VOC2007/Annotations/pascal_test2007.json\"\n },\n \"voc_2012_train\": {\n \"data_dir\": \"voc/VOC2012\",\n \"split\": \"train\"\n },\n \"voc_2012_train_cocostyle\": {\n \"img_dir\": \"voc/VOC2012/JPEGImages\",\n \"ann_file\": \"voc/VOC2012/Annotations/pascal_train2012.json\"\n },\n \"voc_2012_val\": {\n \"data_dir\": \"voc/VOC2012\",\n \"split\": \"val\"\n },\n \"voc_2012_val_cocostyle\": {\n \"img_dir\": \"voc/VOC2012/JPEGImages\",\n \"ann_file\": \"voc/VOC2012/Annotations/pascal_val2012.json\"\n },\n \"voc_2012_test\": {\n \"data_dir\": \"voc/VOC2012\",\n \"split\": \"test\"\n # PASCAL VOC2012 doesn't made the test annotations available, so there's no json annotation\n },\n \"cityscapes_fine_instanceonly_seg_train_cocostyle\": {\n \"img_dir\": \"cityscapes/images\",\n \"ann_file\": \"cityscapes/annotations/instancesonly_filtered_gtFine_train.json\"\n },\n \"cityscapes_fine_instanceonly_seg_val_cocostyle\": {\n \"img_dir\": \"cityscapes/images\",\n \"ann_file\": \"cityscapes/annotations/instancesonly_filtered_gtFine_val.json\"\n },\n \"cityscapes_fine_instanceonly_seg_test_cocostyle\": {\n \"img_dir\": \"cityscapes/images\",\n \"ann_file\": \"cityscapes/annotations/instancesonly_filtered_gtFine_test.json\"\n }\n }\n\n @staticmethod\n def get(name):\n if \"coco\" in name:\n data_dir = DatasetCatalog.DATA_DIR\n attrs = DatasetCatalog.DATASETS[name]\n args = dict(\n root=os.path.join(data_dir, attrs[\"img_dir\"]),\n ann_file=os.path.join(data_dir, attrs[\"ann_file\"]),\n )\n return dict(\n factory=\"COCODataset\",\n args=args,\n )\n elif \"voc\" in name:\n data_dir = DatasetCatalog.DATA_DIR\n attrs = DatasetCatalog.DATASETS[name]\n args = dict(\n data_dir=os.path.join(data_dir, attrs[\"data_dir\"]),\n split=attrs[\"split\"],\n )\n return dict(\n factory=\"PascalVOCDataset\",\n args=args,\n )\n raise RuntimeError(\"Dataset not available: {}\".format(name))\n\n\nclass ModelCatalog(object):\n S3_C2_DETECTRON_URL = \"https://dl.fbaipublicfiles.com/detectron\"\n C2_IMAGENET_MODELS = {\n \"MSRA/R-50\": \"ImageNetPretrained/MSRA/R-50.pkl\",\n \"MSRA/R-50-GN\": \"ImageNetPretrained/47261647/R-50-GN.pkl\",\n \"MSRA/R-101\": \"ImageNetPretrained/MSRA/R-101.pkl\",\n \"MSRA/R-101-GN\": \"ImageNetPretrained/47592356/R-101-GN.pkl\",\n \"FAIR/20171220/X-101-32x8d\": \"ImageNetPretrained/20171220/X-101-32x8d.pkl\",\n \"FAIR/20171220/X-101-64x4d\": \"ImageNetPretrained/20171220/X-101-64x4d.pkl\",\n }\n\n C2_DETECTRON_SUFFIX = \"output/train/{}coco_2014_train%3A{}coco_2014_valminusminival/generalized_rcnn/model_final.pkl\"\n C2_DETECTRON_MODELS = {\n \"35857197/e2e_faster_rcnn_R-50-C4_1x\": \"01_33_49.iAX0mXvW\",\n \"35857345/e2e_faster_rcnn_R-50-FPN_1x\": \"01_36_30.cUF7QR7I\",\n \"35857890/e2e_faster_rcnn_R-101-FPN_1x\": \"01_38_50.sNxI7sX7\",\n \"36761737/e2e_faster_rcnn_X-101-32x8d-FPN_1x\": \"06_31_39.5MIHi1fZ\",\n \"35858791/e2e_mask_rcnn_R-50-C4_1x\": \"01_45_57.ZgkA7hPB\",\n \"35858933/e2e_mask_rcnn_R-50-FPN_1x\": \"01_48_14.DzEQe4wC\",\n \"35861795/e2e_mask_rcnn_R-101-FPN_1x\": \"02_31_37.KqyEK4tT\",\n \"36761843/e2e_mask_rcnn_X-101-32x8d-FPN_1x\": \"06_35_59.RZotkLKI\",\n \"37129812/e2e_mask_rcnn_X-152-32x8d-FPN-IN5k_1.44x\": \"09_35_36.8pzTQKYK\",\n # keypoints\n \"PI:FP:37697547/e2e_keypoint_rcnn_R-50-FPN_1xEND_PI\": \"08_42_54.kdzV35ao\"\n }\n\n @staticmethod\n def get(name):\n if name.startswith(\"Caffe2Detectron/COCO\"):\n return ModelCatalog.get_c2_detectron_12_2017_baselines(name)\n if name.startswith(\"ImageNetPretrained\"):\n return ModelCatalog.get_c2_imagenet_pretrained(name)\n raise RuntimeError(\"model not present in the catalog {}\".format(name))\n\n @staticmethod\n def get_c2_imagenet_pretrained(name):\n prefix = ModelCatalog.S3_C2_DETECTRON_URL\n name = name[len(\"ImageNetPretrained/\"):]\n name = ModelCatalog.C2_IMAGENET_MODELS[name]\n url = \"/\".join([prefix, name])\n return url\n\n @staticmethod\n def get_c2_detectron_12_2017_baselines(name):\n # Detectron C2 models are stored following the structure\n # prefix/<model_id>/2012_2017_baselines/<model_name>.yaml.<signature>/suffix\n # we use as identifiers in the catalog Caffe2Detectron/COCO/<model_id>/<model_name>\n prefix = ModelCatalog.S3_C2_DETECTRON_URL\n dataset_tag = \"keypoints_\" if \"keypoint\" in name else \"\"\n suffix = ModelCatalog.C2_DETECTRON_SUFFIX.format(dataset_tag, dataset_tag)\n # remove identification prefix\n name = name[len(\"Caffe2Detectron/COCO/\"):]\n # split in <model_id> and <model_name>\n model_id, model_name = name.split(\"/\")\n # parsing to make it match the url address from the Caffe2 models\n model_name = \"{}.yaml\".format(model_name)\n signature = ModelCatalog.C2_DETECTRON_MODELS[name]\n unique_name = \".\".join([model_name, signature])\n url = \"/\".join([prefix, model_id, \"12_2017_baselines\", unique_name, suffix])\n return url\n", "# coding: utf-8\n#\n# Copyright 2014 The Oppia Authors. 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, softwar\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\nfrom extensions.rich_text_components import base\n\n\nNONNEGATIVE_INT_SCHEMA = {\n 'type': 'int',\n 'validators': [{\n 'id': 'is_at_least',\n 'min_value': 0\n }],\n}\n\n\nclass Video(base.BaseRichTextComponent):\n \"\"\"A rich-text component representing a YouTube video.\"\"\"\n\n name = 'Video'\n category = 'Basic Input'\n description = 'A YouTube video.'\n frontend_name = 'video'\n tooltip = 'Insert video'\n\n _customization_arg_specs = [{\n 'name': 'video_id',\n 'description': (\n 'The YouTube id for this video. This is the 11-character string '\n 'after \\'v=\\' in the video URL.'),\n 'schema': {\n 'type': 'unicode',\n },\n 'default_value': '',\n }, {\n 'name': 'start',\n 'description': (\n 'Video start time in seconds: (leave at 0 to start at the '\n 'beginning.)'),\n 'schema': NONNEGATIVE_INT_SCHEMA,\n 'default_value': 0\n }, {\n 'name': 'end',\n 'description': (\n 'Video end time in seconds: (leave at 0 to play until the end.)'),\n 'schema': NONNEGATIVE_INT_SCHEMA,\n 'default_value': 0\n }, {\n 'name': 'autoplay',\n 'description': (\n 'Autoplay this video once the question has loaded?'),\n 'schema': {\n 'type': 'bool'\n },\n 'default_value': False,\n }]\n\n icon_data_url = (\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAA'\n 'ABGdBTUEAAK/INwWK6QAAABl0RVh0%0AU29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZ'\n 'TwAAAIfSURBVDjLpZNPaBNBGMXfbrubzBqbg4kL%0A0lJLgiVKE/AP6Kl6UUFQNAeDIAj'\n 'VS08aELx59GQPAREV/4BeiqcqROpRD4pUNCJSS21OgloISWME%0AZ/aPb6ARdNeTCz92m'\n 'O%2B9N9/w7RphGOJ/nsH%2Bolqtvg%2BCYJR8q9VquThxuVz%2BoJTKeZ63Uq/XC38E%0'\n 'A0Jj3ff8%2BOVupVGLbolkzQw5HOqAxQU4wXWWnZrykmYD0QsgAOJe9hpEUcPr8i0GaJ8'\n 'n2vs/sL2h8%0AR66TpVfWTdETHWE6GRGKjGiiKNLii5BSLpN7pBHpgMYhMkm8tPUWz3sL'\n '2D1wFaY/jvnWcTTaE5Dy%0AjMfTT5J0XIAiTRYn3ASwZ1MKbTmN7z%2BKaHUOYqmb1fcP'\n 'iNa4kQBuyvWAHYfcHGzDgYcx9NKrwJYH%0ACAyF21JiPWBnXMAQOea6bmn%2B4ueYGZi8'\n 'gtymNVobF7BG5prNpjd%2BeW6X4BSUD0gOdCpzA8MpA/v2%0Av15kl4%2BpK0emwHSbjJ'\n 'GBlz%2BvYM1fQeDrYOBTdzOGvDf6EFNr%2BLYjHbBgsaCLxr%2BmoNQjU2vYhRXp%0AgI'\n 'PI:FP:UOmSWWnsJRfjlOZhrexgtYDZ/gWbetNRbNs6QT10GJglNk64HMaGgbAkoMo5fiFNy7CKDEND_PI'\n 'QUGqE%0A5r38YktxAfSqW7Zt33l66WtkAkACjuNsaLVaDxlw5HdJ/86aYrG4WCgUZD6fX'\n '%2Bjv/U0ymfxoWVZo%0AmuZyf%2B8XqfGP49CCrBUAAAAASUVORK5CYII%3D%0A'\n )\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 \"PI:FP:signature=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=OH18GuQto_mEpxj99UimKskvo4k=\")\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", "require 'spec_helper'\nrequire 'yt/models/playlist_item'\n\ndescribe Yt::PlaylistItem, :device_app do\n subject(:item) { Yt::PlaylistItem.new id: id, auth: $account }\n\n context 'given an existing playlist item' do\n let(:id) { 'PI:FP:PLjW_GNR5Ir0GMlbJzA-aW0UV8TchJFb8p3uzrLNcZKPYEND_PI' }\n\n it 'returns valid metadata' do\n expect(item.title).to be_a String\n expect(item.description).to be_a String\n expect(item.thumbnail_url).to be_a String\n expect(item.published_at).to be_a Time\n expect(item.channel_id).to be_a String\n expect(item.channel_title).to be_a String\n expect(item.playlist_id).to be_a String\n expect(item.position).to be_an Integer\n expect(item.video_id).to be_a String\n expect(item.video).to be_a Yt::Video\n expect(item.privacy_status).to be_a String\n end\n end\n\n context 'given an unknown playlist item' do\n let(:id) { 'not-a-playlist-item-id' }\n\n it { expect{item.snippet}.to raise_error Yt::Errors::RequestError }\n end\n\n\n context 'given one of my own playlist items that I want to update' do\n before(:all) do\n @my_playlist = $account.create_playlist title: \"Yt Test Update Playlist Item #{rand}\"\n @my_playlist.add_video 'MESycYJytkU'\n @my_playlist_item = @my_playlist.add_video 'MESycYJytkU'\n end\n after(:all) { @my_playlist.delete }\n\n let(:id) { @my_playlist_item.id }\n let!(:old_title) { @my_playlist_item.title }\n let!(:old_privacy_status) { @my_playlist_item.privacy_status }\n let(:update) { @my_playlist_item.update attrs }\n\n context 'given I update the position' do\n let(:attrs) { {position: 0} }\n\n specify 'only updates the position' do\n expect(update).to be true\n expect(@my_playlist_item.position).to be 0\n expect(@my_playlist_item.title).to eq old_title\n expect(@my_playlist_item.privacy_status).to eq old_privacy_status\n end\n end\n end\nend"]