diff --git "a/3779.jsonl" "b/3779.jsonl" new file mode 100644--- /dev/null +++ "b/3779.jsonl" @@ -0,0 +1,685 @@ +{"seq_id":"107197044","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n\nimport sys\nimport gzip\nimport io\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import Normalizer\n\ndef main(argv):\n\tif len(argv) <= 1:\n\t\tprint('Error. Please provide features.csv file')\n\t\tsys.exit(0)\n\n\tfeatures = pd.read_csv(argv[1])\n\tfeatures.drop(columns=['Unnamed: 0'], inplace=True)\n\n\tnum_features = features.shape[1]\n\tprint(features)\n\tprint(num_features)\n\tscaler = MinMaxScaler(feature_range=(-1, 1))\n\tscaled_features = scaler.fit_transform(features)\n\tfeatures = pd.DataFrame(scaled_features, index=features.index, columns=features.columns)\n\n\t'''\n\tnorm_scaler = Normalizer()\n\tnorm_features = norm_scaler.fit_transform(features)\n\tfeatures = pd.DataFrame(norm_features, index=features.index, columns=features.columns)\n\t'''\n\n\tprint(features)\n\n\tttf_idx = features.columns.get_loc('time_to_failure')\n\n\t#fig = plt.figure()\n\t#ax = plt.gca()\n\tfig, axes = plt.subplots(nrows=2, ncols=3)\n\t#features.reset_index().plot(kind='line', y=[features.columns[i], 'time_to_failure'], use_index=True, subplots=True, layout=(3, 2), sharex=True, sharey=False, legend=True)\n\tfor i in range(6):\n\t\t#fig.add_subplot(2, int(i/3)+1, (i%3)+1)\n\t\t#plt.imshow(img[i], cmap=cm.Greys_r)\n\t\t#print(features.iloc[0, :])\n\t\t#print(features.iloc[0, :]['mean'])\n\t\tprint(i/3, i%3)\n\t\t#features.reset_index().plot(kind='line', y=[features.columns[i], 'time_to_failure'], use_index=True, subplots=True, ax=axes[int(i/3), i%3])\n\t\t# Nice, see: https://stackoverflow.com/questions/45985877/slicing-multiple-column-ranges-from-a-dataframe-using-iloc\n\t\tnew_df = features.iloc[:, np.r_[i, ttf_idx]]\n\t\tnew_df.plot(kind='line', use_index=True, ax=axes[int(i/3), i%3])\n\t\t#features.reset_index().plot(kind='line', y='time_to_failure', use_index=True) #, ax=ax)\n\n\tplt.show()\n\n\tsys.exit(0)\n\n'''\n\t# gca stands for 'get current axis'\n\tax = plt.gca()\n\t\n\tsubmission.reset_index().plot(kind='line', y='time_to_failure', use_index=True, ax=ax)\n\t#submission.plot(kind='line',x='name',y='num_pets', color='red', ax=ax)\n\t\n\tplt.show()\n\tsys.exit(0)\n\n\n\tfor i, seg_id in enumerate(submission.index):\n\t\tseg = pd.read_csv(base_dir + '/test/' + seg_id + '.csv')\n\t\tsummary = get_stat_summaries(seg, 4096, run_parallel=False, include_y=False)\n\t\tsubmission.time_to_failure[i] = model.predict(summary.values)\n\t\tprint('Prediction for submission no.:', i, ' - id: ', seg_id, ' - time to failure:', submission.time_to_failure[i])\n\n\tsubmission.head()\n\tsubmission.to_csv('submission.csv')\n'''\n\n'''\ndef main(argv):\n\n\tif len(argv) > 1:\n\t\tprint('Loading features from file:', argv[1])\n\t\tsummary = pd.read_csv(argv[1])\n\t\tsummary.drop(columns=['Unnamed: 0'], inplace=True)\n\t\tprint(summary)\n\telse:\n\t\tfname = base_dir + '/train.csv.gz'\n\t\t#fname = base_dir + '/LANL-Earthquake-Prediction-series-no-000.csv.gz'\n\t\tprint('Opening and reading file:', fname)\n\t\tgzipped_file = gzip.open(fname, 'r')\n\t\tfile_content = gzipped_file.read()\n\n\t\tprint('Finished reading file, filling the DataFrame...')\n\t\ttraining_set = pd.read_csv(io.BytesIO(file_content), dtype={'acoustic_data': np.float32, 'time_to_failure': np.float64})\n\t\t#save_summary_plot(training_set)\n\n\t\tprint('Extracting features...')\n\t\tsummary = get_stat_summaries(training_set, 4096, run_parallel=True)\n\t\tsummary.to_csv(base_dir + '/stat_summary.csv')\n\t\tprint('Features have been saved to:', base_dir + '/stat_summary.csv')\n\n\ttraining_set = summary.values\n\tfeature_count = training_set.shape[-1] - 1\n\tprint(feature_count)\n\tprint(training_set)\n\n\t# Training parameters\n\tbatch_size=93\n\tepochs=2000\n\t\n\tmodel_name = base_dir + '/earthquake-predictions-keras-model-' + datetime.now().strftime('%Y-%m-%d_%H.%M.%S') + '-feature_count-' + str(feature_count) + '-batch_size-' + str(batch_size) + '-epochs-' + str(epochs) + '.hdf5'\n\n\t# extract(summary.iloc[:, :-1], summary.iloc[:, -1])\n\n\tprint(20*'*', 'Start of training', 20*'*')\n\tprint(20*'*', 'Keras model will be saved to:', model_name, 20*'*')\n\tmodel = Rnn(feature_count)\n\tmodel.fit(training_set, batch_size=batch_size, epochs=epochs, model_name=model_name)\n\tprint(20*'*', 'End of training', 20*'*')\n\n\tprint(20*'*', 'Start of prediction ', 20*'*')\n\tpredict(model)\n\tprint(20*'*', 'End of prediction ', 20*'*')\n'''\n\nif __name__ == '__main__':\n\tmain(sys.argv)\n","sub_path":"src/submissions/plot-features-old.py","file_name":"plot-features-old.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"108843084","text":"\"\"\"\nA commander script to deploy AMO in production.\n\nhttps://github.com/oremj/commander\n\"\"\"\nimport os\n\nfrom commander.deploy import hostgroups, task\n\n\nAMO_PYTHON_ROOT = '/data/amo_python'\nAMO_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\n_amo_dir = lambda *p: os.path.join(AMO_DIR, *p)\n\n_git_lcmd = lambda ctx, c: ctx.local(\"/usr/bin/git %s\" % c)\n\ndef _git_checkout_tag(ctx, tag):\n _git_lcmd(ctx, \"fetch -t origin\")\n _git_lcmd(ctx, \"checkout %s\" % tag)\n _git_lcmd(ctx, \"submodule sync\")\n _git_lcmd(ctx, \"submodule update --init\")\n\n@task\ndef update_code(ctx, tag, vendor_tag=None):\n with ctx.lcd(AMO_DIR):\n _git_checkout_tag(ctx, tag)\n\n if vendor_tag:\n with ctx.lcd(\"vendor\"):\n _git_checkout_tag(ctx, vendor_tag)\n\n@task\ndef update_locales(ctx):\n with ctx.lcd(_amo_dir(AMO_DIR, 'locale')):\n ctx.local(\"svn revert -R .\")\n ctx.local(\"svn up\")\n\n\n@task\ndef update_products(ctx):\n with ctx.lcd(AMO_DIR):\n ctx.local('python2.6 manage.py update_product_details')\n\n\n@task\ndef disable_cron(ctx):\n ctx.local(\"mv /etc/cron.d/addons-prod-maint /tmp/addons-prod-maint\")\n\n\n@task\ndef enable_cron(ctx):\n with ctx.lcd(AMO_DIR):\n ctx.local(\"cp scripts/crontab/prod /etc/cron.d/addons-prod-maint\")\n\n\ndef manage_cmd(ctx, command):\n \"\"\"Call a manage.py command.\"\"\"\n with ctx.lcd(AMO_DIR):\n ctx.local(\"python2.6 manage.py %s\" % command)\n\n\n@task\ndef compress_assets(ctx, arg=''):\n with ctx.lcd(AMO_DIR):\n ctx.local(\"python2.6 manage.py compress_assets %s\" % arg)\n\n\n@task\ndef schematic(ctx):\n with ctx.lcd(AMO_DIR):\n ctx.local(\"python2.6 ./vendor/src/schematic/schematic migrations\")\n\n\n@task\ndef make_crons(ctx):\n with ctx.lcd(AMO_DIR):\n ctx.local(\"python2.6 ./scripts/crontab/make-crons.py\")\n\n\n@hostgroups(['amo_gearman'])\ndef restart_celery(ctx):\n ctx.remote(\"service celeryd-prod restart\")\n ctx.remote(\"service celeryd-prod-devhub restart\")\n ctx.remote(\"service celeryd-prod-images restart\")\n ctx.remote(\"service celeryd-prod-bulk restart\")\n\n\n@hostgroups(['amo'])\ndef stop_appserver_cron(ctx):\n ctx.remote(\"service crond stop\")\n\n\n@hostgroups(['amo'])\ndef start_appserver_cron(ctx):\n ctx.remote(\"service crond start\")\n\n\n@task\ndef deploy_code(ctx, subdir='', reload_apache=True):\n stop_appserver_cron()\n try:\n with ctx.lcd(AMO_PYTHON_ROOT):\n src = os.path.join(\"src/prod/zamboni/\", subdir, '')\n www = os.path.join(\"www/prod/zamboni/\", subdir, '')\n\n ctx.local(\"/usr/bin/rsync -aq --exclude '.git*' --delete %s %s\" % (src, www))\n with ctx.lcd(\"www\"):\n ctx.local(\"/usr/bin/git add .\")\n ctx.local(\"/usr/bin/git commit -q -a -m 'AMO PUSH'\")\n pull_code(reload_apache)\n finally:\n start_appserver_cron()\n\n\n@task\ndef deploy_media(ctx):\n deploy_code('media', False)\n\n\n@hostgroups(['amo', 'amo_gearman'], remote_limit=5)\ndef pull_code(ctx, reload_apache=True):\n ctx.remote(\"/data/bin/libget/get-php5-www-git.sh\")\n if reload_apache:\n ctx.remote(\"apachectl graceful\")\n\n\n@hostgroups(['amo_memcache'])\ndef clear_memcache(ctx):\n ctx.remote('service memcached restart')\n\n\n@hostgroups(['amo_redis'])\ndef clear_redis(ctx):\n ctx.remote('pkill -9 -f \"redis.*/amo.conf\"; sleep 3; /etc/init.d/redis-amo start')\n\n\n@task\ndef start_update(ctx, tag, vendor_tag):\n disable_cron()\n update_code(tag, vendor_tag)\n\n\n@task\ndef update_amo(ctx):\n # BEGIN: The normal update/push cycle.\n update_locales()\n update_products()\n compress_assets()\n schematic()\n make_crons()\n # Sync out media to all the servers first.\n deploy_media()\n enable_cron()\n deploy_code()\n restart_celery()\n # END: The normal update/push cycle.\n\n # Run management commands like this:\n # manage_cmd(ctx, 'cmd')\n","sub_path":"scripts/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"368892391","text":"#!/usr/bin/env python\n#cense removeid for brevity\nimport rospy\nimport re\nimport sys\nimport os\nfrom nav_msgs.msg import Odometry\n\nglobal recFlag\n# send initial pose once we have from the topic we want\n\ndef startSensors(data):\n global recFlag\n if recFlag == False:\n print('odom received starting sensors')\n rospy.loginfo('ODOM HAS BEEN RECEIVED, GOOD TO START')\n os.system('roslaunch magni_2dnav magni_configuration.launch')\n recFlag = True\n\ndef startup():\n global recFlag\n recFlag = False\n rospy.init_node('startupSensors', anonymous=True)\n sub = rospy.Subscriber('odom',Odometry,startSensors)\n # idle around until we get data from the pointcloud\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n startup()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"magni_2dnav/scripts/startupSensors.py","file_name":"startupSensors.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"296873875","text":"import psycopg2 as db\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS, cross_origin\nfrom flask_injector import FlaskInjector\nimport dataspect \n\nfrom config import CONNECTION\nfrom services import (\n fetch_tables, fetch_table_info, fetch_data, parse_url_root, CustomJSONEncoder, \n jsonify_sample, jsonify_data, load_metadata_from_file)\n\napp = Flask(__name__)\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\napp.json_encoder = CustomJSONEncoder\n\n### Routes\n\n@app.route('/tables')\n@cross_origin()\ndef get_tables(inspection: dataspect.Inspection):\n\n result = fetch_tables(inspection)\n return jsonify(result)\n\n\n@app.route('/tables/')\n@cross_origin()\ndef get_table_info(inspection: dataspect.Inspection, table):\n \n return fetch_table_info(inspection, table)\n\n\n@app.route('/sample/
')\n@cross_origin()\ndef get_sample(connection: db.extensions.connection, inspection: dataspect.Inspection, table):\n\n params = parse_url_root(request.full_path)\n result = fetch_data(connection, inspection, params, table, True)\n\n if result.is_success: \n (columns, result, count) = result.value\n return jsonify_sample(columns, result, count)\n \n return jsonify(result.value)\n\n\n@app.route('/data/
')\n@cross_origin()\ndef get_data(connection: db.extensions.connection, inspection: dataspect.Inspection, table):\n \n params = parse_url_root(request.full_path)\n result = fetch_data(connection, inspection, params, table, False)\n if result.is_success:\n (columns, result, count) = result.value\n return jsonify_data(columns, result, count)\n\n return jsonify(result.value)\n\n\n@app.route('/metadata')\ndef get_metadata():\n data = load_metadata_from_file()\n return jsonify(data)\n\n### Dependency injection binding\n\ndef inspect(binder):\n binder.bind(\n dataspect.Inspection, \n to=dataspect.PostgreSQLInspection(db.connect(CONNECTION)), \n scope=request,\n )\n\n\ndef connection(binder):\n binder.bind(\n db.extensions.connection, \n to=db.connect(CONNECTION), \n scope=request,\n )\n\n### App\n\nif __name__ == \"__main__\":\n FlaskInjector(app=app, modules=[inspect, connection])\n app.run(debug=True)","sub_path":"pureset/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"226135502","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/insights/parsers/scheduler.py\n# Compiled at: 2019-05-16 13:41:33\nfrom .. import parser, get_active_lines, Parser\nimport re\nfrom insights.specs import Specs\n\n@parser(Specs.scheduler)\nclass Scheduler(Parser):\n\n def parse_content(self, content):\n active_scheduler_regex = re.compile('\\\\[.*]')\n result = {}\n for line in get_active_lines(content):\n for sched in line.split():\n active_scheduler = active_scheduler_regex.search(sched)\n if active_scheduler:\n result[self.file_path.split('/')[3]] = active_scheduler.group()\n\n self.data = result","sub_path":"pycfiles/insights_core-3.0.162-py2.7/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255938895","text":"#Topic: DT - Diabetis Data Set\n#-----------------------------\n#pip install graphviz #install whichever library is not present\n#pip install pydotplus\n\n# Load libraries\nimport pandas as pd\nimport numpy as np\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics, tree\nfrom graphviz import Source\nfrom IPython.display import Image, SVG\nimport pydotplus\n\n#%%%% : Load Data\ncol_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']\nurl='https://raw.githubusercontent.com/DUanalytics/datasets/master/csv/pima-indians-diabetes.csv'\n#This dataset is originally from the National Institute of Diabetes and Digestive and Kidney Diseases. The objective of the dataset is to diagnostically predict whether or not a patient has diabetes, based on certain diagnostic measurements included in the dataset. Several constraints were placed on the selection of these instances from a larger database. In particular, all patients here are females at least 21 years old of Pima Indian heritage.\n#https://www.kaggle.com/uciml/pima-indians-diabetes-database\n#he datasets consists of several medical predictor variables and one target variable, Outcome. Predictor variables includes the number of pregnancies the patient has had, their BMI, insulin level, age, and so on.\n# load dataset\npima = pd.read_csv(url, header=None, names=col_names)\npima.head()\npima.label.value_counts() #how many are diabetic - 268\npima.shape\n.7 * 768 #70% of 768 go into train set rest to test\n\n#%%% : Feature Selection\n#need to divide given columns into two types of variables dependent(or target variable) and independent variable(or feature variables).\n\n#split dataset in features and target variable\nfeature_cols = ['pregnant', 'insulin', 'bmi', 'age', 'glucose', 'bp', 'pedigree']\nX = pima[feature_cols] # Features - bmi, age etc\ny = pima.label # Target variable : has diabetes =1\n#predict y on X\n#%%% Splitting Data\n#To understand model performance, dividing the dataset into a training set and a test set is a good strategy.\n#Let's split the dataset by using function train_test_split(). You need to pass 3 parameters features, target, and test_set size.\n# Split dataset into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) \n# 70% training and 30% test : each for train and test (X & y)\nX_train.head()\n\n#%%%: Building Decision Tree Model :create a Decision Tree Model using Scikit-learn.\n# Create Decision Tree classifer object\nclf = DecisionTreeClassifier(max_depth=3)\n# Train Decision Tree Classifer\nclf = clf.fit(X_train,y_train)\ny_train\n#Predict the response for test dataset\ny_pred = clf.predict(X_test)\ny_pred\n#%%% : Evaluating Model\n# estimate, how accurately the classifier or model can predict the type of cultivars.# Accuracy can be computed by comparing actual test set values and predicted values.\n# Model Accuracy, how often is the classifier correct?\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))\n#classification rate of 67.53%, considered as good accuracy. You can improve this accuracy by tuning the parameters in the Decision Tree Algorithm.\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix = confusion_matrix(y_test, y_pred)\nprint(confusion_matrix)\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test, y_pred))\n#%%% \ny_test.shape, y_pred.shape\ny_test.head()\ny_pred[0:6]\n#%%%\nfrom graphviz import Source\nfrom sklearn import tree\nfrom IPython.display import SVG\n#libraries & path of graphviz\nimport os\nos.environ[\"PATH\"] += os.pathsep + 'c:/Program Files (x86)/Graphviz2.38/bin/'\n#%%\ngraph1 = Source(tree.export_graphviz(clf, out_file=None, class_names= ['0', '1'] , filled = True))\ndisplay(SVG(graph1.pipe(format='svg')))\n#change labels names\ngraph2 = Source( tree.export_graphviz(clf, out_file=None, feature_names=X.columns, filled=True, class_names=['NoDiabetis','Diabetis']))\ngraph2\nX_train\ny_train.value_counts()\n#change max_depth : 1 to 4\nSource(tree.export_graphviz(clf, out_file=None, max_depth=1, feature_names=X.columns, class_names=['NonDB','DB'], label='all', filled=True, leaves_parallel=True, impurity=True, node_ids=True, proportion=True, rotate=True, rounded=True, special_characters=False, precision=1))\n#https://stackoverflow.com/questions/27817994/visualizing-decision-tree-in-scikit-learn\n# This is for saving image in file system\n#https://scikit-learn.org/stable/modules/generated/sklearn.tree.export_graphviz.html\n\n#visualise using dotfile\n\n#True should be returned. goto location and see the file\n\n#%%% Create Decision Tree classifer object\n#change max_depth at the time of creation and method\n#criterio= entropy, gini\nclf3 = DecisionTreeClassifier(criterion=\"entropy\", max_depth=3)\n# Train Decision Tree Classifer\nclf3 = clf3.fit(X_train,y_train)\n#Visualise\nSource(tree.export_graphviz(clf3, out_file=None, class_names= ['0', '1'] , filled = True, feature_names=X.columns,node_ids=True))\n#display(SVG(graph3b.pipe(format='svg')))\nX_train[0:1] \n#Class:1 : glucose > 127, glucose < 158, bmi, age,\n#Predict the response for test dataset\ny_pred3 = clf3.predict(X_test)\nlen(X_test)\ny_pred3\nlen(y_pred3)\n# Model Accuracy, how often is the classifier correct?\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred3))\n#classification rate increased to 77.05%, which is better accuracy than the previous model.\n\n#----\nclf4 = DecisionTreeClassifier(criterion=\"gini\", max_depth=3)\n# Train Decision Tree Classifer\nclf4 = clf4.fit(X_train,y_train)\ny_pred4 = clf4.predict(X_test)\nSource(tree.export_graphviz(clf4, out_file=None, class_names= ['0', '1'] , filled = True, feature_names=X.columns))\n#display(SVG(graph4b.pipe(format='svg')))\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred4))\n\n\n#%%% : Features\n#Decision trees are easy to interpret and visualize.\n#It can easily capture Non-linear patterns.\n#It requires fewer data preprocessing from the user, for example, there is no need to normalize columns.\n#It can be used for feature engineering such as predicting missing values, suitable for variable selection.\n#The decision tree has no assumptions about distribution because of the non-parametric nature of the algorithm\n#%%% : Cons\n#Sensitive to noisy data. It can overfit noisy data.\n#The small variation(or variance) in data can result in the different decision tree. This can be reduced by bagging and boosting algorithms.\n#Decision trees are biased with imbalance dataset, so it is recommended that balance out the dataset before creating the decision tree.\n\n\n#%%% : Visualizing Decision Trees\n#You can use Scikit-learn's export_graphviz function for display the tree within a Jupyter notebook. For plotting tree, you also need to install graphviz and pydotplus.\n#pip install graphviz\n#pip install pydotplus\n#export_graphviz function converts decision tree classifier into dot file and pydotplus convert this dot file to png or displayable form\nfrom sklearn.tree import export_graphviz\nfrom io import StringIO\nfrom IPython.display import Image \nimport pydotplus\n\ndot_data = StringIO()\n\nexport_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols, class_names=['0', '1'])\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue()) \ngraph.write_png('diabetes.png')\nImage(graph.create_png())\n\n\n\n\n\n#%%%%\n#Optimizing Decision Tree Performance\n#criterion : optional (default=”gini”) or Choose attribute selection measure: This parameter allows us to use the different-different attribute selection measure. Supported criteria are “gini” for the Gini index and “entropy” for the information gain.\n\n#splitter : string, optional (default=”best”) or Split Strategy: This parameter allows us to choose the split strategy. Supported strategies are “best” to choose the best split and “random” to choose the best random split.\n\n#max_depth : int or None, optional (default=None) or Maximum Depth of a Tree: The maximum depth of the tree. If None, then nodes are expanded until all the leaves contain less than min_samples_split samples. The higher value of maximum depth causes overfitting, and a lower value causes underfitting (Source).\n\n#%%%% - short summary\n# Create Decision Tree classifer object\nclf = DecisionTreeClassifier(criterion=\"entropy\", max_depth=3)\n\n# Train Decision Tree Classifer\nclf = clf.fit(X_train,y_train)\n\n#Predict the response for test dataset\ny_pred = clf.predict(X_test)\n\n# Model Accuracy, how often is the classifier correct?\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))\n\n\n\n#%% end her","sub_path":"01C-IIM/DT02_diabetis.py","file_name":"DT02_diabetis.py","file_ext":"py","file_size_in_byte":8669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"3000586","text":"import boto3\nimport sys\nimport aws_common\n\n\ndef main():\n instance_name = sys.argv[1]\n region_name = sys.argv[2] if len(sys.argv) > 2 else 'us-west-2'\n ec2 = boto3.client('ec2', region_name=region_name)\n print(aws_common.stop_instance(ec2, instance_name))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"aws_scripts/aws-stop.py","file_name":"aws-stop.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"626165895","text":"# Does not require any tables\n# Requires XML: \n#\ttraits.xml\n#\ttraittypes.xml\n#\tstringtablex.xml\n\nimport MySQLdb\nimport xml.dom\nfrom xml.dom import minidom\nimport slugs\nimport databaseConfig\n\nclass ItemType:\n\tdef __init__(self, name, aoe):\n\t\tself.name = name\n\t\tself.aoe = aoe\n\t\t\n\t\tself.reference = slugs.slugify(name)\n\tdef __str__(self):\n\t\treturn \"%s %s\" % (self.name, self.aoe)\n\tdef __repr__(self):\n\t\treturn \"%s %s\" % (self.name, self.aoe)\n\n\nxml = minidom.parse('traits.xml')\ntraits = xml.getElementsByTagName('trait')\n\nxml = minidom.parse('traittypes.xml')\ntypes = xml.getElementsByTagName('traittype')\n\nxml = minidom.parse('stringtablex.xml')\nstringx = xml.getElementsByTagName('string')\n\n\ncompletedValues = []\n\ntraitInfo = {}\nfor trait in traits:\n\ttempTrait = {}\n\tfor traitChild in trait.childNodes:\n\t\tif traitChild.localName == 'traittype':\n\t\t\ttempTrait['type'] = traitChild.childNodes[0].data\n\t\tif traitChild.localName == 'rollovertextid':\n\t\t\tfor strxValue in stringx:\n\t\t\t\tif strxValue.attributes['_locid'].value == traitChild.childNodes[0].data:\n\t\t\t\t\ttempTrait['name'] = strxValue.childNodes[0].data\n\t\t\t\t\tbreak\n\t\n\tif len(tempTrait) == 2:\n\t\ttraitInfo[tempTrait['type']] = tempTrait['name']\n\n\nfor itemType in types:\n\tinfo = {}\n\tif itemType.attributes['name'].value.find('Vanity') == -1 and itemType.attributes['name'].value.find('Club') == -1:\n\t\tif traitInfo.has_key(itemType.attributes['name'].value):\n\t\t\tinfo['aoe'] = itemType.attributes['name'].value\n\t\t\tinfo['name'] = traitInfo[itemType.attributes['name'].value]\n\t\n\tif len(info) == 2:\n\t\tit = ItemType(info['name'], info['aoe'])\n\t\tcompletedValues.append(it)\n\n\n#print completedValues\n\n# mysql\nconn = MySQLdb.connect (host = databaseConfig.host, user = databaseConfig.username, passwd = databaseConfig.password, db = databaseConfig.database)\ncursor = conn.cursor()\n\ncursor.execute(\"TRUNCATE TABLE item_types;\")\n\nfor value in completedValues:\n\tquery = \"INSERT INTO item_types (aoe, name, reference) VALUES ('%s', '%s', '%s');\" % (value.aoe, MySQLdb.escape_string(value.name), value.reference)\n\tcursor.execute(query)\n\n\n#end mysql\ncursor.close()\nconn.commit()\nconn.close()\n\n\n\n","sub_path":"scripts/item-types-sql.py","file_name":"item-types-sql.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"640918420","text":"\nfrom comet_ml import Experiment\nimport time\n\nimport tensorflow as tf \nimport numpy as np\nfrom tensorflow.keras import layers,optimizers,regularizers,initializers,models\nfrom tensorflow.keras.utils import to_categorical\nimport h5py\n\nfrom helper import rgb2gray,data\n\n# Use comet ML if defined\ntry: \n from config import COMET_API_KEY\n experiment = Experiment(api_key=COMET_API_KEY,\n project_name=\"general\", workspace=\"aasimsani\")\n\nexcept ImportError as e:\n pass\n\n\n\nprint(tf.VERSION)\nprint(tf.keras.__version__)\n\n\n\n# Load data\ntrain_x, train_y, test_x, test_y = data()\n\n\ndef create_model(x_train,y_train,x_test,y_test):\n \"\"\"\n Function to create the ML model\n \"\"\"\n\n # Define input size for first layer\n in_size = (64,64,1)\n\n # Define number of classes predicted\n out_classes = 2\n\n\n # Define a sequential model so we can quickly make a model by adding layers to the API\n model = tf.keras.Sequential()\n\n # Convolve input once\n L1 = layers.Conv2D(filters=32,kernel_size=(4,4),strides=[2,2],input_shape=in_size,activation='relu',\n kernel_initializer=initializers.glorot_uniform(seed=None),padding='same',\n kernel_regularizer=regularizers.l2(0.01))\n model.add(L1)\n\n # Convolve input again\n L2 = layers.Conv2D(filters=16,kernel_size=(2,2),strides=[2,2],input_shape=in_size,activation='relu',\n kernel_initializer=initializers.glorot_uniform(seed=None),padding='same',\n kernel_regularizer=regularizers.l2(0.01))\n model.add(L2)\n\n\n # Pool the convolutions and extract important parts\n P1 = layers.MaxPooling2D(pool_size=3,strides=2, padding='valid',name=\"P1\")\n model.add(P1)\n\n # Flatten the pooled layer\n F = layers.Flatten(name=\"flatten\")\n model.add(F)\n\n # Add dropout to the flattened layers to generalize better\n dO = layers.Dropout(0.01)\n model.add(dO)\n\n # First dense layer \n D1 = layers.Dense(256,activation='relu',name='D1',kernel_initializer=initializers.glorot_uniform(seed=None),\n kernel_regularizer=regularizers.l2(0.01))\n model.add(D1)\n\n\n\n # Output layer\n D2 = layers.Dense(out_classes,activation='softmax', name='D2')\n model.add(D2)\n\n # Output the structure of the model\n model.summary()\n\n\n model.compile(loss='categorical_crossentropy', metrics=['accuracy'],\n optimizer=optimizers.Adam(lr=0.00001))\n\n\n # 1000 is a lot but since the initialization might different at all times. 1000 guarantees convergence\n result = model.fit(train_x,train_y,epochs=1000,\n verbose=2,validation_data=(test_x,test_y))\n\n # Store model after training acoording to time it was made\n filepath = \"./models/model-\"+ str(time.time()) +\".h5\"\n tf.keras.models.save_model(\n model,\n filepath,\n overwrite=True,\n include_optimizer=True\n )\n\n\n\n# Run model training\ncreate_model(train_x,train_y,test_x,test_y)\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"457430731","text":"import math\r\ndef foo(a,b,c,d):\r\n e=[a,b,c,d]\r\n min1=a\r\n min2=b\r\n i=0\r\n while(i<4):\r\n if e[i]min1 and e[i] INFO\n\n # I. Import Loans from CSV File. -> Loop LoanCollect to create LoanPool object of 1500 Loans.\n # File Saved as CSV File...\n\n # (1) READ FILE\n s = ('\\\\') # splitter\n cwd = os.getcwd().split(s) # get working directory\n cwd.insert(len(cwd), 'Loans.csv')\n # Test print(cwd)... Correct!\n\n cwd = s.join(cwd)\n logging.debug(f'\\nFile path as been set: {cwd}')\n\n # Create list from the CSV\n autoloanList = []\n with open(cwd, 'r') as loanSource:\n for line in loanSource.readlines():\n line = line.strip('\\n').split(',') # Remove space and separate each into different elements\n lineFinal = line[:-4]\n autoloanList.append(lineFinal)\n\n # Clean-up (Remove 1st Line)\n autoloanList.pop(0)\n # logging.info(autoloanList)\n logging.info(f'\\nSample: {autoloanList[0]}')\n\n # Clean-up (Each String turn to a list)\n # newautoloanList = []\n # commaSplitter = (',')\n # for item in autoloanList:\n # list(item.split(commaSplitter))\n # newautoloanList.append(item)\n\n # logging.info(newautoloanList)\n\n # (2) Create 1500 Loan objects and place in Loan Pool\n lP = LoanPool() # Instantiate Loan Pool\n\n # Instantiate Loan Class\n # Name the Loan Class\n # Fead to Loan Pool\n\n i = 1\n for item in autoloanList:\n # term, rate, notional, car\n # TERM IS IN MONTHS. LOAN CLASS MODIFICATION NEEDED\n forAppend = locals()['autoLoan' + str(i)] = autoLoan(float(item[4]), float(item[3]), float(item[2]), Car(float(item[6])))\n lP.loanCollect(forAppend)\n i = i + 1\n\n # logging.info(lP). Works FINE.\n logging.info(f'Loan Pool Total Principal: {lP.totalPrincipal()}')\n # WORKS! for loan in lP:\n # logging.info(loan.notional)\n\n # II. Instantiate your StructuredSecurities object. Specify (1) Total Notional (2) 2 Std Tranches (3) .a Sequential / .b Pro-Rata (4) Rates: tr A < tr B\n # + Call simulateWaterfall\n\n # (A) Tested for SEQUENTIAL.\n # Instantiate Structured Security Object\n StructSecObject = StructuredSecurities(lP.totalPrincipal())\n\n # Instantiate Tranches (MC Simulation REQUIREMENTS: with 0.05 and 0.08)\n StructSecObject.addTranche('Tranche_1', .75, .05, 'A') # trancheName, notionalPercent, rate, flagInput\n StructSecObject.addTranche('Tranche_2', .25, .08, 'B')\n\n # Test MC Simulation (5 runs, simulateWaterfall version 1):\n StructSecObject.flagMode('Sequential') # Test Sequential\n results = ssPackage.simulateWaterfall(lP, StructSecObject, 3)\n # results = ssPackage.simulateWaterfall(lP, StructSecObject, 2000) # simulateWaterfall (Working GOOD. Just need to deal with ERRORS).\n # Taking too long. 30 minutes for 170 runs. Will take 7+ hours to complete 2k runs.\n\n logging.info(f'\\n############################################################')\n logging.info(f'Tranche 1 average DIRR: {results[0][0]}')\n logging.info(f'Tranche 2 average DIRR: {results[0][1]}')\n logging.info(f'Tranche 1 average AL: {results[1][0]}')\n logging.info(f'Tranche 2 average AL: {results[1][1]}')\n logging.info(f'############################################################\\n')\n\n StructSecObject.clearSim() # Clears EVERYTHING except tranche list so that pro rata runs can proceed well. If not,\n # Will only keep appending to existing AL and DIRR list.\n\n StructSecObject.flagMode('Pro Rata') # Test Pro Rata\n results = ssPackage.simulateWaterfall(lP, StructSecObject, 3) # simulateWaterfall (Working GOOD. Just need to deal with ERRORS).\n # results = ssPackage.simulateWaterfall(lP, StructSecObject, 2000) # simulateWaterfall (Working GOOD. Just need to deal with ERRORS).\n # Taking too long. 30 minutes for 170 runs. Will take 7+ hours to complete 2k runs.\n\n logging.info(f'\\n############################################################')\n logging.info(f'Tranche 1 average DIRR: {results[0][0]}')\n logging.info(f'Tranche 2 average DIRR: {results[0][1]}')\n logging.info(f'Tranche 1 average AL: {results[1][0]}')\n logging.info(f'Tranche 2 average AL: {results[1][1]}')\n logging.info(f'############################################################\\n')\n\n # TEST CODE TO VIEW RESULTS:\n # for index in range(len(results)):\n # value = results[index]\n # print(index, value)\n # resultsa = results[0]\n # resultsb = results[1]\n # logging.info(f'Length of Results List (Sequential) for Liabilities: {len(resultsa)}')\n # logging.info(f'Length of Results List (Sequential) for Asset: {len(resultsb)}')\n\n # (A) PRO RATA TEST\n # StructSecObject2 = StructuredSecurities(lP.totalPrincipal())\n\n # Instantiate Tranches\n # StructSecObject2.addTranche('Tranche_1', .75, .06, 'A') # trancheName, notionalPercent, rate, flagInput\n # StructSecObject2.addTranche('Tranche_2', .25, .1, 'B')\n\n # StructSecObject2.flagMode('Pro Rata') # Test Sequential\n\n '''\n results2 = ssPackage.doWaterfall(lP, StructSecObject2) # do Waterfall (Working GOOD. Just need to deal with ERRORS).\n\n # TEST CODE TO VIEW RESULTS:\n # for index in range(len(results2)):\n # value = results2[index]\n # print(index, value)\n results2a = results2[0]\n results2b = results2[1]\n logging.info(f'\\nSample Output:')\n logging.info(f'{results2a[0]}')\n logging.info(f'{results2b[0]}')\n\n # results2afinal = flatList(results2a)\n # logging.info(f'{results2afinal[0]}')\n\n # for result in results2a:\n # # term, rate, notional, car\n # # TERM IS IN MONTHS. LOAN CLASS MODIFICATION NEEDED\n # flattenedList = [item for sublist in result for item in sublist]\n # results2afinal.append(flattenedList)\n # i = i + 1\n\n logging.info(f'\\nLength of Results List (Sequential) for Liabilities: {len(results2a)}')\n logging.info(f'Length of Results List (Sequential) for Asset: {len(results2b)}')\n \n logging.info(f'\\nAverage DIRR for tranche 1: {len(results2a)}')\n logging.info(f'Average DIRR for tranche 2: {len(results2a)}')\n logging.info(f'Length of Results List (Sequential) for Asset: {len(results2b)}')\n\n\n # III. (1) Save results in two CSV Files. (2) Each result in a single row. (3) Reserve should be in Liabs. (4) Each Time Period gets its own row.\n # REQUIREMENT: LIST COMPREHENSION AND STRING PARSING.\n # Output: I. sequentialLiabsWF II. sequentialAssetWF III. prorataLiabsWF IV. prorataAssetWF\n logging.info('\\nImporting to CSV Files (4x)')\n logging.info('I. sequentialLiabsWFMC II. sequentialAssetWFMC III. prorataLiabsWFMC IV. prorataAssetWFMC')\n\n # I. sequentialLiabsWF\n rootDir = os.getcwd() # get working directory\n logging.debug('Setting directory for new file...')\n\n # filenames\n filenames = ['sequentialLiabsWFMC.csv', 'sequentialAssetWFMC.csv', 'prorataLiabsWFMC.csv', 'prorataAssetWFMC.csv']\n\n # listnames (prepare)\n listnames = [flatList(resultsa), resultsb, flatList(results2a), results2b] # No need to flatten LP items...\n\n # headers\n header1 = ['TR_A_interestDueVal_t', 'TR_A_interestPayment_t', 'TR_A_interestShortfall_t', 'TR_A_principalPayment_t', 'TR_A_notionalBalanceVal_t',\n 'TR_B_interestDueVal_t', 'TR_B_interestPayment_t', 'TR_B_interestShortfall_t', 'TR_B_principalPayment_t', 'TR_B_notionalBalanceVal_t',\n 'reserveAccount_t']\n header2 = ['monthlyPayment_t', 'principalDue_t', 'totalBalance_t', 'interestDue_t', 'activeLoanCount_t']\n\n try:\n i = 0\n for listname in listnames:\n dirFinal = os.path.join(rootDir, filenames[i])\n logging.info(f'\\nInitialization complete, final file path = {dirFinal}')\n logging.debug(f'Writing information on loan list to {dirFinal}...')\n s = ','\n\n if len(listname[0]) > 5:\n with open(dirFinal, 'w', newline='') as finalList:\n finalList.write(s.join(header1) + '\\n')\n for list in listname:\n finalList.write(s.join(map(str, list)) + '\\n')\n logging.info(f'File {filenames[i]} was successfully created.')\n else:\n with open(dirFinal, 'w', newline='') as finalList:\n finalList.write(s.join(header2) + '\\n')\n for list in listname:\n list = [str(i) for i in list]\n finalList.write(s.join(map(str, list)) + '\\n')\n logging.info(f'File {filenames[i]} was successfully created.')\n i = i + 1\n except Exception as generalEx:\n logging.info('Please ensure that the csv files have not been opened before running the program. Exiting...')\n logging.info(f'Exception: {generalEx}')\n\n # Clean up:\n logging.info('\\n')\n StructSecObject.cleanSlate()\n StructSecObject2.cleanSlate()\n\n # Q: Did each tranche's balance get successfully paid down to 0? If they did, was there any money left in the end?\n # A: Yes and Yes. Money was left in the end as there were still active loans that were providing cash flow, and it took a few periods to fully receive those\n # cash flows, which were then stored in the Reserve Balance.\n\n # Moreover, Reserve balance tends to be higher for pro-rata as extra money is not being used as a maximum payment to pay off a loan at any given point in time.\n # This is especially evident in the case where you have multiple loans and your tranches' principal is way less i.e. 100,000 to total notional of millions.\n\n # Update! MUCH FASTER PAYMENT OF LOANS THIS TIME. Defaults Lead to lowering of balances.\n '''\n\n#########################\nif __name__ == '__main__':\n main()","sub_path":"Level7_FinalProject_ABS/mainWaterfall_MC_simulateWaterfall.py","file_name":"mainWaterfall_MC_simulateWaterfall.py","file_ext":"py","file_size_in_byte":11425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"229673902","text":"from models.shared import db, Serializable\n\nclass RecipeItem(db.Model, Serializable):\n from_item_id = db.Column(db.Integer, db.ForeignKey('item.id'), primary_key=True)\n dest_item_id = db.Column(db.Integer, db.ForeignKey('item.id'), primary_key=True)\n count = db.Column(db.Integer)\n\n from_item = db.relationship('Item', foreign_keys=[from_item_id],\n backref=db.backref('recipe_items', lazy=\"dynamic\", cascade=\"all, delete-orphan\"))\n dest_item = db.relationship('Item', foreign_keys=[dest_item_id],\n backref=db.backref('recipes_using', lazy=\"dynamic\", cascade=\"all, delete-orphan\"))\n\n @staticmethod\n def make_recipe(from_item, dest_item, count):\n recipe = RecipeItem.query.filter(RecipeItem.from_item == from_item,\n RecipeItem.dest_item == dest_item).first()\n if recipe is None:\n print('Create recipe from %s : %d %s' % (from_item.name, count, dest_item.name))\n recipe = RecipeItem(from_item=from_item, dest_item=dest_item)\n db.session.add(recipe)\n recipe.count = count\n return recipe\n\n def serialize(self, **kwargs):\n attrs = { 'count': self.count }\n if self.dest_item.recipe_items.count():\n attrs['recipe'] = self.dest_item.recipe()\n return { self.dest_item.name: attrs }\n","sub_path":"models/item/recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"213854693","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n#通过传递一个numpy array,日期索引以及列标签来创建一个DataFrame:\ndates = pd.date_range('20130101', periods=6)\n\ndf = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))\nprint(df)\n\n#通过传递一个能够被转换为类似series的dict对象来创建一个DataFrame:\ndf2 = pd.DataFrame({ 'A' : 1.,\n 'B' : pd.Timestamp('20130102'),\n 'C' : pd.Series(1,index=list(range(4)),dtype='float32'),\n 'D' : np.array([3]*4,dtype='int32'),\n 'E' : pd.Categorical([\"test\",\"train\",\"test\",\"train\"]),\n 'F' : 'foo' })\n\nprint(df2)\n\n\n#查看frame中头部和尾部的几行:\nprint(df.head())\nprint(df.tail(3))\n\n#显示索引、列名以及底层的numpy数据\nprint(df.index)\nprint(df.columns)\nprint(df.values)\n\n#选择某一列数据,它会返回一个Series,等同于df.A:\nprint(df['A'])\n\n#通过使用:进行切片选取:\nprint(df[0:3])\n\n#对于DataFrame类型,plot()能很方便地画出所有列及其标签\nts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))\nts = ts.cumsum()\nts.plot()\nplt.show()\n\ndf = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=['A', 'B', 'C', 'D'])\ndf = df.cumsum()\nplt.figure()\ndf.plot()\nplt.legend(loc='best')\nplt.show()\n\n\n#写入一个csv文件\ndf.to_csv('data/foo.csv')\n\n#从一个csv文件读入\npd.read_csv('data/foo.csv')\n\n#写入一个Excel文件\ndf.to_excel('data/foo.xlsx', sheet_name='Sheet1')\n\n#从一个excel文件读入\npd.read_excel('data/foo.xlsx', 'Sheet1', index_col=None, na_values=['NA'])\n","sub_path":"PandasNote.py","file_name":"PandasNote.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"448586571","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\n\n\nclass EncoderCNN(nn.Module):\n def __init__(self, embed_size):\n super(EncoderCNN, self).__init__()\n resnet = models.resnet50(pretrained=True)\n for param in resnet.parameters():\n param.requires_grad_(False)\n \n modules = list(resnet.children())[:-1]\n self.resnet = nn.Sequential(*modules)\n self.embed = nn.Linear(resnet.fc.in_features, embed_size)\n\n def forward(self, images):\n features = self.resnet(images)\n features = features.view(features.size(0), -1)\n features = self.embed(features)\n return features\n \n\nclass DecoderRNN(nn.Module):\n def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):\n super(DecoderRNN, self).__init__()\n self.embed_size = embed_size\n self.hidden_size = hidden_size\n self.vocab_size = vocab_size\n self.num_layers = num_layers\n\n self.Embedding = nn.Embedding(self.vocab_size, self.embed_size)\n\n self.lstm = nn.LSTM(self.embed_size, self.hidden_size, self.num_layers, batch_first=True)\n\n self.hidden_2_vocab = nn.Linear(self.hidden_size, self.vocab_size) \n\n \n def forward(self, features, captions):\n #hidden_state = \n #cell_state = \n\n word_embeddings = self.Embedding(captions[:,:-1])\n\n inputs = torch.cat((features.unsqueeze(dim=1),word_embeddings), dim=1)\n\n outputs, _ = self.lstm(inputs)#, (hidden_state, cell_state))\n\n final_outputs = self.hidden_2_vocab(outputs)\n\n return final_outputs\n \n\n \n \n def sample(self, inputs, states=None, max_len=20):\n \" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) \"\n \n captions = []\n\n batch_size = inputs.size(0)\n hidden = (torch.randn(1, 1, self.hidden_size).cuda(), torch.randn(1, 1, self.hidden_size).cuda())\n \n for i in range(max_len):\n out, hidden = self.lstm(inputs, hidden) \n output_words = self.hidden_2_vocab(out) \n output_words = output_words.squeeze(1) \n word = output_words.argmax(dim=1) \n captions.append(word.item())\n inputs = self.Embedding(word.unsqueeze(0)) \n \n return captions\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"319979254","text":"#!/usr/bin/env python\n\nimport sys, os\nif sys.version < \"2.6\":\n os.execl(\"/usr/local/bin/python2.6\", \"python2.6\", *sys.argv)\n\nimport ConfigParser\nimport logging\nimport threading\n\nsys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"packages\"))\n\nimport tornado.escape\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.template\nimport tornado.web\nimport tornado.wsgi\nfrom tornado.options import define, options\n\nimport controllers.uimodules\nfrom logic import constants as constants_module\nfrom logic import cache\n\n# setup site.cfg\nsetup = False\nconfig_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"site.cfg\")\nif not os.path.exists(config_path):\n setup = True\n constants = dict(constants_module.dictionary.items() +\n constants_module.defaults.items())\nelse:\n config = ConfigParser.ConfigParser()\n config.read(config_path)\n constants = dict(constants_module.dictionary.items() +\n constants_module.defaults.items() + config.items('general'))\n for constant in constants:\n try:\n constants[constant] = int(constants[constant])\n except:\n pass\n\ndefine(\"port\", default=constants['port'], type=int, help=\"Port to listen on.\")\ndefine(\"debug\", default=constants['debug'], type=int,\n help=\"Run in debug mode.\")\n\nif constants['debug']:\n logging_level = logging.DEBUG\nelse:\n logging_level = logging.INFO\nlogging.basicConfig(level=logging_level,\n format='%(asctime)s %(levelname)s %(message)s',\n filename=(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"server.log\")))\n\ntornado.options.parse_command_line()\ntornado.locale.load_translations(os.path.join(os.path.dirname(__file__),\n \"translations\"))\n\nsettings = {\n \"constants\": constants,\n \"base_path\": os.path.dirname(os.path.realpath(__file__)),\n \"private_path\": os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"private\"),\n \"resource_path\": os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"static/resource\"),\n \"cache_path\": os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"static/cache\"),\n \"update_feeds_path\":\n os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"tools/update_feeds.py\"),\n \"prune_entries_path\":\n os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"tools/prune_old_entries.py\"),\n \"restart_path\": os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"tmp/restart.txt\"),\n \"app_path\": os.path.realpath(__file__),\n \"resource_url\": \"static/resource\",\n \"static_path\": os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"static\"),\n \"static_url\": \"static\",\n \"config_path\": config_path,\n \"login_url\": \"/login\",\n \"xsrf_cookies\": True,\n \"debug\": (options.debug == 1),\n \"ui_modules\": controllers.uimodules,\n \"cookie_secret\": constants['xsrf_secret'],\n \"template_loader\":\n tornado.template.Loader(os.path.join(os.path.dirname(\n os.path.realpath(__file__)), \"templates\")),\n \"db_lock\": threading.Lock(),\n \"twitter_consumer_key\": constants['twitter_consumer_key'],\n \"twitter_consumer_secret\": constants['twitter_consumer_secret'],\n \"google_api_key\": constants['google_api_key'],\n \"google_secret\": constants['google_secret'],\n \"facebook_api_key\": constants['facebook_api_key'],\n \"facebook_secret\": constants['facebook_secret'],\n \"tumblr_consumer_key\": constants['tumblr_consumer_key'],\n \"tumblr_consumer_secret\": constants['tumblr_consumer_secret'],\n}\n\nprefix = r\"(?:\" + tornado.escape.url_escape(\n constants['https_prefix']).replace('%2F', '/') + r\")?\"\nprefix += r\"(?:\" + tornado.escape.url_escape(\n constants['http_prefix']).replace('%2F', '/') + r\")?\"\n\nif not constants['ioloop'] and not constants['use_mod_rails']:\n prefix += r\"/helloworld.py\"\n\nif setup:\n handlers = [\n (r\".*\", \"controllers.setup.SetupHandler\"),\n ]\n settings[\"xsrf_cookies\"] = False\nelse:\n handlers = [ ]\n for source in constants['external_sources']:\n handlers += [ (prefix + \"/\" + source, \"controllers.\" + source + \".\" +\n source.capitalize() + \"Handler\") ]\n\n handlers += [\n (prefix + r\"/\\.well-known/host-meta\",\n \"controllers.host_meta.HostMetaHandler\"),\n (prefix + r\"/admin(?:$|/.*)\",\n \"controllers.dashboard.DashboardHandler\"), # for WP users :P\n (prefix + r\"/api\", \"controllers.api.ApiHandler\"),\n (prefix + r\"/check_broken_links\",\n \"controllers.check_broken_links.CheckBrokenLinksHandler\"),\n (prefix + r\"/customize\", \"controllers.customize.CustomizeHandler\"),\n (prefix + r\"/dashboard(?:$|/.*)\",\n \"controllers.dashboard.DashboardHandler\"),\n (prefix + r\"/data_liberation\",\n \"controllers.data_liberation.DataLiberationHandler\"),\n (prefix + r\"/data_liberation\\.zip\",\n \"controllers.data_liberation.DataLiberationDownloadHandler\",\n {\"path\": \"/tmp\"}),\n (prefix + r\"/(favicon\\.ico)\", tornado.web.StaticFileHandler,\n {\"path\": settings['static_path']}),\n (prefix + r\"(?:/[^/]+)?/feed\", \"controllers.feed.FeedHandler\"),\n (prefix + r\"(?:/[^/]+)?/foaf\", \"controllers.foaf.FoafHandler\"),\n (prefix + r\"/(humans\\.txt)\", \"controllers.humans.HumansTxtHandler\",\n {\"path\": settings['static_path']}),\n (prefix + r\"/login\", \"controllers.auth.AuthHandler\"),\n (prefix + r\"/logout\", \"controllers.auth.AuthLogoutHandler\"),\n (prefix + r\"/media\", \"controllers.media.MediaHandler\"),\n (prefix + r\"/oembed\", \"controllers.oembed.OembedHandler\"),\n (prefix + r\"(?:/[^/]+)?/opensearch\",\n \"controllers.opensearch.OpenSearchHandler\"),\n (prefix + r\"/private/(.*)\", \"controllers.private.PrivateResourceHandler\",\n {\"path\": settings['private_path']}),\n (prefix + r\"(?:/[^/]+)?/push\", \"controllers.push.PushHandler\"),\n (prefix + r\"/restart\", \"controllers.restart.RestartHandler\"),\n (prefix + r\"/(robots\\.txt)\", tornado.web.StaticFileHandler,\n {\"path\": settings['static_path']}),\n (prefix + r\"/salmon(?:$|/.*)\", \"controllers.salmon.SalmonHandler\"),\n (prefix + r\"(?:/[^/]+)?/search(?:$|/.*)\",\n \"controllers.search.SearchHandler\"),\n (prefix + r\"/stats\", \"controllers.stats.StatsStaticHandler\",\n {\"path\": \"./static\"}),\n (prefix + r\"/upload\", \"controllers.upload.UploadHandler\"),\n (prefix + r\"/users(?:$|/.*)\", \"controllers.users.UsersHandler\"),\n (prefix + r\"/webfinger(?:$|/.*)\",\n \"controllers.webfinger.WebfingerHandler\"),\n (prefix + r\"/webmention(?:$|/.*)\",\n \"controllers.webmention.WebmentionHandler\"),\n (r\".*\", \"controllers.view.ViewHandler\"),\n ]\n\n# add cache_invalidate to crontab\ntry:\n cache_script = 'rm -rf ' + settings['cache_path']\n cache_cron_line = '0 5 * * * ' + cache_script\n f = os.popen('crontab -l')\n crontab = f.readlines()\n if (cache_cron_line + '\\n') not in crontab:\n os.system('(crontab -l ; echo \"' + cache_cron_line + '\") | crontab -')\n\n update_feeds_script = 'python ' + settings['update_feeds_path']\n update_feed_line = '0 1 * * * ' + update_feeds_script\n if (update_feed_line + '\\n') not in crontab:\n os.system('(crontab -l ; echo \"' + update_feed_line + '\") | crontab -')\n\n prune_feeds_script = 'python ' + settings['prune_entries_path']\n prune_feed_line = '0 9 * * * ' + prune_feeds_script\n if (prune_feed_line + '\\n') not in crontab:\n os.system('(crontab -l ; echo \"' + prune_feed_line + '\") | crontab -')\nexcept:\n pass\n\nif constants['ioloop']:\n application = tornado.web.Application(handlers, **settings)\n http_server = tornado.httpserver.HTTPServer(application)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\nelse:\n application = tornado.wsgi.WSGIApplication(handlers, **settings)\n if not constants['use_mod_rails']:\n from tools import fastcgi\n fastcgi.runfastcgi(application, method=\"threaded\", pidfile=\"hello.pid\",\n daemonize=\"false\")\n","sub_path":"helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":7835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"621519231","text":"import codecs\nimport os\nimport shutil\nimport smtplib\nimport ssl\nimport time\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom selenium import webdriver\nfrom secret import *\n\n'''\nThere has to be a file called secret.py with following arg:\npasswort_g='' \nrecipent='' ['test@mail.com','test2@mail.com ... ] You can give this variable n parameters\nsender_email = \"\"\nusername=''\npassword=''\n'''\n\n\n# Scraping the current grades for the DHBW Ravensburg\nclass scrape_Grades():\n def Scrape(self):\n # Open chrome with a few options so that it's harder for sites to detect a bot\n options = webdriver.ChromeOptions()\n options.add_argument('--headless')\n options.add_argument(\"--disable-blink-features=AutomationControlled\")\n options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n options.add_experimental_option('useAutomationExtension', False)\n driver = webdriver.Chrome(options=options, executable_path=r'D:\\Python\\webdriver\\chromedriver.exe')\n driver.execute_cdp_cmd(\"Network.setExtraHTTPHeaders\", {\"headers\": {\"User-Agent\": \"browserClientA\"}})\n print('Open Chrome')\n driver.get(\n \"https://dualis.dhbw.de/scripts/mgrqispi.dll?APPNAME=CampusNet&PRGNAME=EXTERNALPAGES&ARGUMENTS=-N000000000000001,-N000324,-Awelcome\")\n driver.find_element_by_xpath('//*[@id=\"field_user\"]').send_keys(username)\n time.sleep(2)\n driver.find_element_by_xpath('//*[@id=\"field_pass\"]').send_keys(password)\n driver.find_element_by_xpath('//*[@id=\"logIn_btn\"]').click()\n print('Logged in')\n time.sleep(2)\n driver.find_element_by_xpath('//*[@id=\"link000310\"]/a').click()\n time.sleep(2)\n Noten = driver.find_element_by_xpath('//*[@id=\"contentSpacer_IE\"]/div').text\n element = driver.find_element_by_tag_name('body')\n element_png = element.screenshot_as_png\n driver.close()\n print('Close Chrome')\n # Saving the scraped grades as a picture and as plain text\n with open(\"D:/Noten.png\", \"wb\") as file:\n file.write(element_png)\n file.close()\n with codecs.open('D:/Noten.txt', 'w') as f:\n f.write(Noten)\n f.close()\n print('Files saved')\n\n def Send_Mail(self):\n # Copy the current script; I have to save the file as a txt file bc. some email providers don't like executables\n shutil.copy(__file__, 'D:/main.txt')\n port = 465 # For SSL\n # Create a secure SSL context\n context = ssl.create_default_context()\n # reading the file in binary mode. Because it is saved as a UTF-8 file and there is a error, if you try to convert it to ASCII\n print('Creating E-Mail')\n msg = MIMEMultipart()\n msg.attach(MIMEText(\n 'Dies ist eine automatisch generierte E-Mail für die Abfrage und Speicherung der Noten der DHBW Ravensburg!'))\n msg['Subject'] = 'Dualis'\n msg['From'] = sender_email\n msg['To'] = \", \".join(recipent) # Therefore you can achieve mutliple recipents\n # path = \"D:/\"\n file = ('D:/main.txt', 'D:/Noten.txt', 'D:/Noten.png')\n # This is in my opinion a cleaner option to send multiple files, but some programs (e.g. 7zip) can't open this zip file\n '''zip = ZipFile(\"Attachment.zip\",mode=\"w\") #Save all files as a zip bc some email providers don't like executables\n for files in file:\n zip.write(path + files, files)\n zip.close()\n zipped_file = open('Attachment.zip', 'rb')\n p = MIMEBase('application', 'zip')\n p.set_payload(zipped_file.read())\n p.add_header(\"Content-Disposition\", \"attachment; filename=\\\"%s.zip\\\"\" % (\"Attachment\"))\n msg.attach(p)\n zipped_file.close()'''\n\n for files in file: # Attaching the grades as plain text file and picture and the current script\n part = MIMEBase('application', \"octet-stream\")\n part.set_payload(open(files, \"rb\").read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(files))\n msg.attach(part)\n\n with smtplib.SMTP_SSL(\"smtp.gmail.com\", port, context=context) as server:\n server.login(sender_email, passwort_g)\n print(\"Login for E-Mail\")\n server.sendmail(sender_email, recipent, msg.as_bytes())\n print(\"Email send\")\n\n\nif __name__ == \"__main__\":\n o = scrape_Grades()\n o.Scrape()\n o.Send_Mail()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"81251116","text":"class Solution(object):\n def merge(self, one, two):\n \tif not one:return two\n \tif not two:return one\n \tmain, plus = None, None\n \tif one.val>=two.val:main,plus= two,one\n \telse:main,plus = one,two\n \tdummy,temp= ListNode(0),None\n \tdummy.next,cur = main, dummy\n \twhile cur.next and plus:\n \t\tif plus.val 0 and number_results[0] != '0'):\n number_results = int(number_results[0])\n self.display_message(\"Found %s results\" % number_results)\n number_pages = int(math.ceil(number_results / 20)) + 1\n\n pattern = 'rel=\"nofollow\">([a-z\\.\\-A-Z0-9]+)'\n subdomains = re.findall(pattern, req.content.decode('utf-8'))\n res.extend(subdomains)\n last_result = subdomains[-1]\n\n for index_page in range(1, number_pages):\n url = \"http://searchdns.netcraft.com/?host=*.%s&last=%s.%s&from=%s&restriction=site contains&position=limited\" % (domain, last_result, domain, (index_page * 20 + 1))\n req = s.get(url, headers=headers)\n pattern = 'rel=\"nofollow\">([a-z\\-\\.A-Z0-9]+)'\n subdomains = re.findall(pattern, req.content.decode('utf-8'))\n res.extend(subdomains)\n for subdomain in subdomains:\n self.display_message('[!] Found: %s ' % subdomain)\n last_result = subdomains[-1]\n return res\n else:\n self.display_message(\"No results found for %s\" % domain)\n return res\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) < 2:\n sys.exit(\"NetcraftAPI.py DOMAIN\")\n else:\n for i in NetcraftAPI().search(sys.argv[1]):\n print(i)\n","sub_path":"NetcraftAPI.py","file_name":"NetcraftAPI.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"130407458","text":"#\n# @lc app=leetcode id=979 lang=python3\n#\n# [979] Distribute Coins in Binary Tree\n#\n# https://leetcode.com/problems/distribute-coins-in-binary-tree/description/\n#\n# algorithms\n# Medium (68.14%)\n# Likes: 1230\n# Dislikes: 46\n# Total Accepted: 33.8K\n# Total Submissions: 49.6K\n# Testcase Example: '[3,0,0]'\n#\n# Given the root of a binary tree with N nodes, each node in the tree has\n# node.val coins, and there are N coins total.\n# \n# In one move, we may choose two adjacent nodes and move one coin from one node\n# to another.  (The move may be from parent to child, or from child to\n# parent.)\n# \n# Return the number of moves required to make every node have exactly one\n# coin.\n# \n# \n# \n# \n# Example 1:\n# \n# \n# \n# \n# Input: [3,0,0]\n# Output: 2\n# Explanation: From the root of the tree, we move one coin to its left child,\n# and one coin to its right child.\n# \n# \n# \n# Example 2:\n# \n# \n# \n# \n# Input: [0,3,0]\n# Output: 3\n# Explanation: From the left child of the root, we move two coins to the root\n# [taking two moves]. Then, we move one coin from the root of the tree to the\n# right child.\n# \n# \n# \n# Example 3:\n# \n# \n# \n# \n# Input: [1,0,2]\n# Output: 2\n# \n# \n# \n# Example 4:\n# \n# \n# \n# \n# Input: [1,0,0,null,3]\n# Output: 4\n# \n# \n# \n# \n# Note:\n# \n# \n# 1<= N <= 100\n# 0 <= node.val <= N\n# \n# \n# \n# \n# \n#\n\n# @lc code=start\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\ndef move_coins(root):\n if not root:\n return (0, 0)\n if root.left is None and root.right is None:\n if root.val == 0:\n return (1, -1)\n else:\n return (root.val - 1, root.val - 1)\n mov_left, coins_left = move_coins(root.left)\n mov_right, coins_right = move_coins(root.right)\n coins_in_parent = coins_left + coins_right + root.val - 1\n return (mov_left + mov_right + abs(coins_in_parent), coins_in_parent)\n\n\nclass Solution:\n def distributeCoins(self, root: TreeNode) -> int:\n moves, _ = move_coins(root)\n return moves\n \n# @lc code=end\n","sub_path":"python3/979.distribute-coins-in-binary-tree.314594293.ac.py","file_name":"979.distribute-coins-in-binary-tree.314594293.ac.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"330238027","text":"import matplotlib.pyplot as plt\nplt.figure()\nplt.scatter(df_low['forecast'],df_low['power'],c='r')\n#adding a line at 45 deg (4000 here is the maximum power reached)\n#To see if above or below mean\nplt.plot([0,max(df_low['forecast'])],[0,max(df_low['forecast'])])\nplt.ylabel('observed power')\nplt.xlabel('forecast')\nplt.savefig('Plots/2D_speed_direction_low_actual.png')\nplt.close()\n\n#####Set axis limit\naxes = plt.gca()\nMAX=max(counts + counts_nom)\naxes.set_xlim(0,1.2*MAX)\n\n\n###Scatter plot with color on z axis (not very telling, but possible)\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.figure()\n\npointsize = 10;\nplt.scatter(scales_up, scales_dwn, pointsize, scores)\nplt.show()\n","sub_path":"scatter_plot.py","file_name":"scatter_plot.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"64013432","text":"import uuid\nfrom pathlib import Path\n\nimport sqlalchemy\nfrom sqlalchemy.orm import aliased\nfrom sqlalchemy.orm.exc import NoResultFound\nimport click\n\nimport fire.cli\nfrom fire.cli import firedb\nimport fire.api\nfrom fire.api.model import (\n Punkt,\n PunktInformation,\n PunktInformationType,\n Sag,\n Sagsinfo,\n Sagsevent,\n SagseventInfo,\n)\n\nPOINT_FILE = Path(__file__).parents[0] / Path(\"definerende_dvr90_punkter.txt\")\nATTRIBUT = \"NET:DVR90\"\n\ndef get_punkt(ident: str) -> str:\n \"\"\"\n Vis al tilgængelig information om et fikspunkt\n\n IDENT kan være enhver form for navn et punkt er kendt som, blandt andet\n GNSS stationsnummer, G.I.-nummer, refnr, landsnummer osv.\n\n Søgningen er versalfølsom.\n \"\"\"\n pi = aliased(PunktInformation)\n pit = aliased(PunktInformationType)\n\n punktinfo = (\n firedb.session.query(pi)\n .filter(pit.name.startswith(\"IDENT:\"), pi.tekst == ident)\n .all()\n )\n n = len(punktinfo)\n if n == 0:\n raise NoResultFound\n\n punkt = punktinfo[0].punkt\n\n return punkt\n\n\nsagsbeskrivelse = f\"\"\"Registrering af punkter der indgik i den oprindelige DVR90-udjævning.\n\nPunkterne markeres med {ATTRIBUT}.\n\nSe \"Klaus Schmidt, 2000, The Danish height system DVR90\" for yderligere information om udjævningen.\n\"\"\"\n\n\ndef main():\n\n firedb.indset_punktinformationtype(\n PunktInformationType(\n name=ATTRIBUT,\n anvendelse=fire.api.model.PunktInformationTypeAnvendelse.FLAG,\n beskrivelse=\"Punkter i den oprindelige DVR90-udjævning\",\n )\n )\n infotype = firedb.hent_punktinformationtype(ATTRIBUT)\n\n sagsinfo = Sagsinfo(\n aktiv=\"true\", behandler=\"Kristian Evers\", beskrivelse=sagsbeskrivelse\n )\n sagid = str(uuid.uuid4())\n firedb.indset_sag(Sag(id=sagid, sagsinfos=[sagsinfo]))\n sag = firedb.hent_sag(sagid)\n\n\n with open(POINT_FILE) as f:\n punkter = [punkt.strip() for punkt in f.readlines()]\n\n punktinformationer = []\n # interaktion med databasen er pokkers langsomt, vis fremdrift\n with click.progressbar(punkter, label=\"Punkter\") as punkter_progress:\n for ident in punkter_progress:\n try:\n punkt = get_punkt(ident)\n except sqlalchemy.orm.exc.NoResultFound:\n print(f\"Ident ikke fundet: {ident}\")\n continue\n\n pi = PunktInformation(infotype=infotype, punkt=punkt)\n punktinformationer.append(pi)\n\n sagseventinfo = SagseventInfo(beskrivelse=f\"Indsættelse af {ATTRIBUT} attibutter\")\n sagsevent = Sagsevent(\n id=str(uuid.uuid4()),\n sag=sag,\n eventtype=fire.api.model.EventType.PUNKTINFO_TILFOEJET,\n sagseventinfos=[sagseventinfo],\n punktinformationer=punktinformationer,\n )\n firedb.indset_sagsevent(sagsevent)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"post-migration/dvr90net/indset_dvr90net.py","file_name":"indset_dvr90net.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"85830089","text":"import os.path\nfrom codecs import open\n\nfrom setuptools import setup\n\nwith open(\n os.path.join(os.path.abspath(os.path.dirname(__file__)), \"README.rst\"),\n encoding=\"utf-8\",\n) as f:\n LONG_DESCRIPTION = f.read()\n\nVERSION = {}\nwith open(os.path.join(\"pypianoroll\", \"version.py\")) as f:\n exec(f.read(), VERSION)\n\nsetup(\n name=\"pypianoroll\",\n packages=[\"pypianoroll\"],\n version=VERSION[\"__version__\"],\n description=\"A python package for handling multitrack pianorolls.\",\n long_description=LONG_DESCRIPTION,\n author=\"Hao-Wen Dong\",\n author_email=\"salu.hwdong@gmail.com\",\n url=\"https://github.com/salu133445/pypianoroll\",\n download_url=(\n \"https://github.com/salu133445/pypianoroll/archive/v\"\n + VERSION[\"__version__\"]\n + \".tar.gz\"\n ),\n project_urls={\"Documentation\": \"https://salu133445.github.io/pypianoroll/\"},\n keywords=[\"music\", \"audio\", \"pianoroll\", \"multitrack\"],\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Topic :: Multimedia :: Sound/Audio\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python\",\n ],\n setup_requires=[\"pytest-runner>=2.0,<3.0\"],\n install_requires=[\n \"six>=1.0.0,<2.0\",\n \"numpy>=1.10.0,<2.0\",\n \"scipy>=1.0.0,<2.0\",\n \"pretty_midi>=0.2.8,<1.0\",\n ],\n extras_require={\n \"plot\": [\"matplotlib>=1.5\"],\n \"animation\": [\"moviepy>=0.2.3.2\"],\n \"pytest\": [\n \"pytest>=3.0.0,<4.0\",\n \"pytest-cov>=2.5.1,<3.0\",\n \"coveralls>=1.1,<2.0\",\n ],\n },\n test_suite=\"tests\",\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"110399715","text":"from decimal import Decimal\n\nfrom hummingbot.connector.derivative.position import Position\nfrom hummingbot.core.event.events import (\n PositionSide,\n TradeType\n)\nfrom hummingbot.connector.derivative.leverj_perpetual.leverj_perpetual_in_flight_order import LeverjPerpetualInFlightOrder\n\n\nclass LeverjPerpetualPosition(Position):\n def __init__(self,\n trading_pair: str,\n position_side: PositionSide,\n unrealized_pnl: Decimal,\n entry_price: Decimal,\n amount: Decimal,\n leverage: Decimal,\n is_open: bool = True):\n super().__init__(\n trading_pair,\n position_side,\n unrealized_pnl,\n entry_price,\n amount,\n leverage\n )\n self.is_open = is_open\n\n @property\n def leverage(self):\n return round(self._leverage, 2)\n\n @classmethod\n def from_leverj_fill(cls,\n in_flight_order: LeverjPerpetualInFlightOrder,\n amount: Decimal,\n price: Decimal,\n leverage: int):\n position_side, signed_amount = (PositionSide.LONG, amount) if in_flight_order.trade_type == TradeType.BUY else (PositionSide.SHORT, -amount)\n return LeverjPerpetualPosition(\n in_flight_order.trading_pair,\n position_side,\n Decimal('0'),\n price,\n signed_amount,\n leverage,\n True)\n\n def update_from_fill(self,\n in_flight_order: LeverjPerpetualInFlightOrder,\n price: Decimal,\n amount: Decimal):\n if self.position_side == PositionSide.SHORT:\n if in_flight_order.trade_type == TradeType.BUY:\n self._amount += amount\n elif in_flight_order.trade_type == TradeType.SELL:\n total_quote: Decimal = (self.entry_price * abs(self.amount)) + (price * amount)\n self._amount -= amount\n self._entry_price: Decimal = total_quote / abs(self.amount)\n elif self.position_side == PositionSide.LONG:\n if in_flight_order.trade_type == TradeType.BUY:\n total_quote: Decimal = (self.entry_price * self.amount) + (price * amount)\n self._amount += amount\n self._entry_price: Decimal = total_quote / self.amount\n elif in_flight_order.trade_type == TradeType.SELL:\n self._amount -= amount\n\n def update_position(self,\n entry_price,\n amount,\n leverage):\n self._leverage = leverage\n self._amount = amount\n self._entry_price = entry_price\n","sub_path":"hummingbot/connector/derivative/leverj_perpetual/leverj_perpetual_position.py","file_name":"leverj_perpetual_position.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"181254975","text":"import numpy as np\nimport matplotlib.pyplot as plt\n \nnumber=1000\nx = np.random.rand( number )\ny = np.random.rand( number )\npercentages=[1, 2, 5, 10, 20, 30, 50, 75]\nfig = plt.figure(figsize=(8.27,11.69))\n \nfor i in range(8):\n percent=percentages[i]\n black = np.round( percent*(number/100.0) )\n color = np.array( black*['black'] + (number-black)*['lightgrey'] )\n np.random.shuffle(color) #randomise so black aren't all at the bottom\n # define a marker shape here to make something that looks more like rocks\n marker=[(0.17,0.12),(0.15,0.42),(0.14,0.75),(0.35,0.87),(0.68,0.90),\n (0.98,0.86),(0.90,0.29),(0.72,0.14),(0.45,0.05),(0.17,0.12)]\n ax=plt.subplot(4,2,i+1)\n plt.scatter(x, y, color=color, s=60, linewidth=0.25, edgecolors='black',\n marker=(marker,0))\n plt.xlim(0,1)\n plt.ylim(0,1)\n plt.title('%i%% black' % (percent), fontsize=12)\n ax=plt.gca()\n ax.xaxis.set_ticklabels([])\n ax.yaxis.set_ticklabels([])\nplt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, hspace=0.15, wspace=0.1)\nplt.suptitle('Visual estimates of proportions of mixtures', fontsize=18, y=0.97)\nplt.suptitle('http://all-geo.org/volcan01010/2012/09/pumicelithicsproportions',\n x=0.95, y=0.045, horizontalalignment='right',\n verticalalignment='top', fontsize='x-small')\nplt.savefig('PumiceLithicsProportions.png', dpi=150)\nplt.ion()\nplt.show()\n\n#test\n\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"400365488","text":"from sqlalchemy import Table, Column, Integer, String\nfrom sqlalchemy.orm import mapper\n\nfrom app.models import metadata, db_session\n\nclass Media(object):\n\tquery = db_session.query_property()\n\t\n\tdef __init__(self, id_users=None, filename=None, width=None, height=None, size=None, mimetype=None, hash=None):\n\t\t\tself.id_users = id_users\n\t\t\tself.filename = filename\n\t\t\tself.width = width\n\t\t\tself.height = height\n\t\t\tself.size = size\n\t\t\tself.mimetype = mimetype\n\t\t\tself.hash = hash\n\n\tdef __repr__(self):\n\t\t\treturn '' % (self.id_media)\n\n\tdef GetData(self, tags):\n\t\tdata = {\n\t\t\t\t\"media_id\": self.id_media,\n\t\t\t\t\"media_name\": self.filename,\n\t\t\t\t\"media_hash\": self.hash,\n\t\t\t\t\"media_path\": \"storage/%s\" % (self.filename),\n\t\t\t\t\"media_thumb\": \"storage/t%s\" % (self.filename),\n\t\t\t\t\"media_mime\": self.mimetype,\n\t\t\t\t\"media_tags\": tags,\n\t\t\t\t\"media_width\": self.width,\n\t\t\t\t\"media_height\": self.height\n\t\t\t\t}\n\t\treturn (data)\n\nmedia = Table('media', metadata,\n\tColumn('id_media', Integer, primary_key=True),\n\tColumn('id_users', Integer),\n\tColumn('filename', String),\n\tColumn('width', Integer),\n\tColumn('height', Integer),\n\tColumn('size', Integer),\n\tColumn('mimetype', String),\n\tColumn('hash', String)\n)\n\nmapper(Media, media)\n","sub_path":"app/models/media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"567615854","text":"#!/bin/env python\r\n# -*- coding: cp1252 -*-\r\n\"\"\"\r\nHtmlWindow derived class that adds support for detection of click\r\ncoordinates in the BGA results image.\r\n\r\nCreated on: Feb 19, 2011\r\nAuthor: Tennessee Carmel-Veilleux (tcv -at- ro.boto.ca)\r\nRevision: $Rev$\r\n\r\nCopyright 2011 Tennessee Carmel-Veilleux\r\n\r\nDescription: \r\nHtmlWindow derived class that adds support for detection of click\r\ncoordinates in the BGA results image. Assumes the image is wrapped\r\nin a link, so that the onLinkClicked() method uses the last clicked\r\ncoordinate from the last onCellClicked() event.\r\n\r\nLicense:\r\nCopyright (c) 2011, Tennessee Carmel-Veilleux\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without \r\nmodification, are permitted provided that the following conditions are \r\nmet:\r\n\r\n * Redistributions of source code must retain the above copyright \r\nnotice, this list of conditions and the following disclaimer.\r\n * Redistributions in binary form must reproduce the above \r\ncopyright notice, this list of conditions and the following disclaimer \r\nin the documentation and/or other materials provided with the \r\ndistribution.\r\n * Neither the name of SONIA AUV nor the names of its contributors \r\nmay be used to endorse or promote products derived from this software \r\nwithout specific prior written permission.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \r\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT \r\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR \r\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT \r\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \r\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT \r\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \r\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY \r\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \r\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \r\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\"\"\"\r\nimport wx\r\nimport wx.html as html\r\n\r\nclass ImageHandlingHtmlWindow(html.HtmlWindow):\r\n def __init__(self, parent, id, pos, size, style):\r\n html.HtmlWindow.__init__(self, parent, id, pos, size, style = style | wx.NO_FULL_REPAINT_ON_RESIZE)\r\n if \"gtk2\" in wx.PlatformInfo:\r\n self.SetStandardFonts()\r\n \r\n self.owner = None\r\n \r\n # Last clicked coordinate in image\r\n self.lastCoord = None\r\n # Size of last cell clicked\r\n self.lastCellSize = None\r\n \r\n def SetOwner(self, owner):\r\n self.owner = owner\r\n \r\n def OnLinkClicked(self, linkinfo):\r\n href = linkinfo.GetHref() \r\n if href != \"resultImage\":\r\n # Regular link: handle through parent\r\n super(ImageHandlingHtmlWindow, self).OnLinkClicked(linkinfo)\r\n else:\r\n # Image link: Tell parent that image was clicked\r\n if self.lastCoord != None and self.lastCellSize != None:\r\n self.owner.onImageClicked(self.lastCoord, self.lastCellSize)\r\n\r\n def OnCellClicked(self, cell, x, y, evt):\r\n # Record data about the click for the OnLinkClicked() method\r\n self.lastCoord = (x, y)\r\n self.lastCellSize = (cell.GetWidth(), cell.GetHeight())\r\n \r\n # Also run default handler in case\r\n super(ImageHandlingHtmlWindow, self).OnCellClicked(cell, x, y, evt)\r\n","sub_path":"AutoBGA/ImageHandlingHtmlWindow.py","file_name":"ImageHandlingHtmlWindow.py","file_ext":"py","file_size_in_byte":3538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"491126517","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport uuid\nimport unicodedata\n\nfrom pyramid import compat\n\n\n_filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.-]')\n_windows_device_files = ('CON', 'AUX', 'COM1', 'COM2', 'COM3', 'COM4', 'LPT1',\n 'LPT2', 'LPT3', 'PRN', 'NUL')\n\n\ndef secure_filename(filename):\n \"\"\"\n This is a port of :meth:`werkzeug.utils.secure_filename` with\n python 3.2 compatibility.\n\n :param filename: the filename to secure\n \"\"\"\n if isinstance(filename, compat.text_type):\n filename = unicodedata.normalize(\n 'NFKD', filename).encode('ascii', 'ignore')\n if compat.PY3:\n filename = filename.decode('ascii')\n for sep in os.path.sep, os.path.altsep:\n if sep:\n filename = filename.replace(sep, ' ')\n filename = str(_filename_ascii_strip_re.sub('', '_'.join(\n filename.split()))).strip('._')\n\n # on nt a couple of special files are present in each folder. We\n # have to ensure that the target file is not such a filename. In\n # this case we prepend an underline\n if (os.name == 'nt' and filename and\n filename.split('.')[0].upper() in _windows_device_files):\n filename = '_' + filename\n\n return filename\n\n\ndef random_filename(filename):\n \"\"\"Generates a randomized (uuid4) filename,\n preserving the original extension.\n\n :param filename: the original filename\n \"\"\"\n _, ext = os.path.splitext(filename)\n return str(uuid.uuid4()) + ext.lower()\n","sub_path":"pyramid_storage/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"391288542","text":"n = int(input())\narr = [int(x) for x in input().split()]\n\ndef dist(now, target):\n now = list(now)\n loc = {x:i for i,x in enumerate(now)}\n ret = 0\n for i,t in enumerate(target):\n if now[i] != t:\n j = loc[t]\n loc[t], loc[now[i]] = loc[now[i]], loc[t]\n now[i], now[j] = now[j], now[i]\n ret += 1\n return ret\n\nprint(min(dist(arr, sorted(arr)), dist(arr, sorted(arr)[::-1])))\n","sub_path":"juice500/week2/lilys_homework.py","file_name":"lilys_homework.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"435873827","text":"class ExchangeVersion:\n '''Used to validate compatible Exchange Versions across multiple service endpoints\n\n Examples:\n To determine if a version number is a valid ExchangeVersion then would pass in the value when instantiating this object:\n\n ```python\n version = ExchangeVersion('15.20.5').exchangeVersion\n print(version)\n ```\n\n ```text\n # output\n Exchange2016\n ```\n\n To verify an ExchangeVersion is supported, you can view the supported version by access the EXCHANGE_VERSIONS attribute\n\n ```python\n versions = ExchangeVersion('15.20.5').EXCHANGE_VERSIONS\n print(versions)\n ```\n\n ```text \n ['Exchange2019', 'Exchange2016', 'Exchange2013_SP1', 'Exchange2013', 'Exchange2010_SP2', 'Exchange2010_SP1', 'Exchange2010']\n ```\n\n Args:\n version (str): An Exchange Version number. Example: 15.20.5 = Exchange2016\n '''\n\n # Borrowed from exchangelib: https://github.com/ecederstrand/exchangelib/blob/master/exchangelib/version.py#L54\n # List of build numbers here: https://docs.microsoft.com/en-us/Exchange/new-features/build-numbers-and-release-dates?view=exchserver-2019 \n API_VERSION_MAP = {\n 8: {\n 0: 'Exchange2007',\n 1: 'Exchange2007_SP1',\n 2: 'Exchange2007_SP1',\n 3: 'Exchange2007_SP1',\n },\n 14: {\n 0: 'Exchange2010',\n 1: 'Exchange2010_SP1',\n 2: 'Exchange2010_SP2',\n 3: 'Exchange2010_SP2',\n },\n 15: {\n 0: 'Exchange2013', # Minor builds starting from 847 are Exchange2013_SP1, see api_version()\n 1: 'Exchange2016',\n 2: 'Exchange2019',\n 20: 'Exchange2016', # This is Office365. See issue #221\n }\n }\n\n EXCHANGE_VERSIONS = ['Exchange2019', 'Exchange2016', 'Exchange2015', 'Exchange2013_SP1', 'Exchange2013', 'Exchange2010_SP2', 'Exchange2010_SP1', 'Exchange2010']\n\n def __init__(self, version):\n self.exchange_version = self._get_api_version(version)\n\n def _get_api_version(self, version):\n '''Gets a string representation of an Exchange Version number\n\n Args:\n version (str): An Exchange Version number. Example: 15.20.5\n\n Returns:\n str: A string representation of a Exchange Version number. Example: Exchange2016\n '''\n\n if version == '15.0.847.32':\n return 'Exchange2013_SP1'\n elif version == '15.20.3955.27':\n return 'Exchange2015'\n else:\n ver = version.split('.')\n return self.API_VERSION_MAP[int(ver[0])][int(ver[1])]\n\n @staticmethod\n def valid_version(version):\n '''Determines if a string version name is in list of accepted Exchange Versions\n\n Args:\n version (str): String used to determine if it is an acceptable Exchange Version\n\n Returns:\n bool: Returns either True or False if the passed in version is an acceptable Exchange Version\n '''\n if version == 'Office365':\n return True\n elif version in ExchangeVersion.EXCHANGE_VERSIONS:\n return True\n return False\n","sub_path":"pyews/core/exchangeversion.py","file_name":"exchangeversion.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"43277990","text":"#!/usr/bin/python\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU 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# Ansible 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 General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'\n}\n\nDOCUMENTATION = '''\n---\nmodule: aws_emr\nshort_description: Manage AWS EMR\ndescription:\n - \"This is my longer description explaining my sample module\"\nversion_added: \"2.5.5\"\nauthor: \"Mengfan Shan (fox)\"\noptions:\n aws_access_key:\n description:\n - aws access key\n required: true\n default: null\n aws_secret_key:\n description:\n - aws secret key\n required: true\n default: null\n region:\n description:\n - regions support by AWS, valid values are ['us-east-1', 'us-west-2', 'us-west-1', 'eu-west-1', 'eu-central-1', 'ap-southeast-1', 'ap-northeast-1', 'ap-southeast-2', 'ap-northeast-2', 'ap-south-1', 'sa-east-1']\n required: true\n default: null\n mode:\n description:\n - operations, valid values are ['create', 'get-cluster-id', 'get-cluster-ids', 'terminate', 'terminate-all', 'describe', 'check-status']\n required: true\n default: describe\n name:\n description:\n - cluster name\n required: false\n default: null\n id:\n description:\n - Cluster id of target cluster\n required: false\n default: null\n auto_scaling_role:\n description:\n - the auto scaling role to create EMR cluster\n required: false\n default: 'EMR_AutoScaling_DefaultRole'\n applications:\n description:\n - the applications we need to create an EMR cluster\n required: false\n default: ['Hadoop', 'Spark']\n log_url:\n description:\n - log url to keep logs of EMR clusters and batches running on EMR\n required: false\n default: null\n release_label:\n description:\n - release_label is the version of EMR\n required: false\n default: 'emr-5.8.0'\n service_role:\n description:\n - the iam role of EMR cluster\n required: false\n default: 'iam-role-emr'\n ec2_service_role:\n description:\n - the iam role of EMR ec2 instances\n required: false\n default: 'iam-role-emr-ec2'\n scale_down_behavior:\n description:\n - the scale down behavior when an instance is scaled in\n required: false\n default: 'TERMINATE_AT_TASK_COMPLETION'\n tags:\n description:\n - tags for ec2 instances when create an EMR cluster\n required: false\n default: [{'Key':'Name', 'Value':'EMR Instance'}]\n'''\n\nEXAMPLES = '''\n# Create EMR cluster\n- name: get cluster id\n aws_emr:\n aws_access_key: AKIAIOSFODNN7EXAMPLE\n aws_secret_key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n region: ap-northeast-1\n mode: get-cluster-id\n name: EMR-test\n'''\n\nimport os\nimport json\n\ntry:\n import boto3\n import botocore\n HAS_BOTO3 = True\nexcept ImportError:\n HAS_BOTO3 = False\n\ndef convert_application(applications):\n result = []\n for application in applications:\n result.append({'Name':application})\n return result\n\ndef convert_tag(tags):\n result = []\n for tag in tags:\n result.append({'Key':tag.items()[0][0], 'Value':tag.items()[0][1]})\n return result\n\ndef get_client(region, access_key, secret_key):\n return boto3.client(\n 'emr',\n region_name=region,\n aws_access_key_id=access_key,\n aws_secret_access_key=secret_key,\n )\n\ndef list_active_clusters_by_name(emr_client, cluster_name):\n cluster_list = emr_client.list_clusters(\n ClusterStates=[\n 'STARTING',\n 'BOOTSTRAPPING',\n 'RUNNING',\n 'WAITING',\n ]\n ).get('Clusters')\n result = []\n for cluster in cluster_list:\n if cluster.get('Name') == cluster_name:\n result.append(cluster)\n return result\n\ndef list_terminated_clusters_by_name(emr_client, cluster_name):\n cluster_list = emr_client.list_clusters(\n ClusterStates=[\n 'TERMINATING',\n 'TERMINATED',\n 'TERMINATED_WITH_ERRORS',\n ]\n ).get('Clusters')\n result = []\n for cluster in cluster_list:\n if cluster.get('Name') == cluster_name:\n result.append(cluster)\n return result\n\ndef list_all_clusters_by_name(emr_client, cluster_name):\n cluster_list = emr_client.list_clusters().get('Clusters')\n result = []\n for cluster in cluster_list:\n if cluster.get('Name') == cluster_name:\n result.append(cluster)\n return result\n\ndef terminate_emr(emr_client, cluster_id):\n emr_client.set_termination_protection(\n JobFlowIds=[\n cluster_id,\n ],\n TerminationProtected=False\n )\n return emr_client.terminate_job_flows(\n JobFlowIds=[\n cluster_id,\n ]\n )\n\ndef get_cluster_ids(module, emr_client, cluster_name):\n if cluster_name in ('', None):\n module.exit_json(msg='name cannot be null or empty')\n cluster_list = list_active_clusters_by_name(emr_client, cluster_name)\n result = []\n for cluster in cluster_list:\n if cluster.get('Name') == cluster_name:\n result.append(cluster.get('Id'))\n return result\n\ndef get_cluster_id(module, emr_client, cluster_name):\n id_list = get_cluster_ids(emr_client, cluster_name)\n if len(id_list) == 0:\n module.exit_json(msg='Not active cluster by name: ' + cluster_name + ' was found')\n if len(id_list) > 1:\n module.fail_json(msg='More than one active cluster with name: ' + cluster_name + ' was found')\n return id_list[0]\n\ndef describle_cluster(emr_client, cluster_id):\n return emr_client.describe_cluster(\n ClusterId = cluster_id\n ).get('Cluster')\n\ndef list_instance_groups(emr_client, cluster_id):\n return emr_client.list_instance_groups(\n ClusterId=cluster_id\n ).get('InstanceGroups')\n\ndef list_instance_fleets(emr_client, cluster_id):\n return emr_client.list_instance_fleets(\n ClusterId=cluster_id\n ).get('InstanceFleets')\n\ndef list_instance_by_group_id(emr_client, cluster_id, instance_group_id):\n return emr_client.list_instances(\n ClusterId=cluster_id,\n InstanceGroupId=instance_group_id,\n InstanceStates=['BOOTSTRAPPING', 'RUNNING']\n ).get(\"Instances\")\n\ndef list_instance_by_group_type(emr_client, cluster_id, instance_group_type):\n return emr_client.list_instances(\n ClusterId=cluster_id,\n InstanceGroupTypes=[instance_group_type],\n InstanceStates=['BOOTSTRAPPING', 'RUNNING']\n ).get(\"Instances\")\n\ndef get_private_ip_address(instance_detail_list):\n result = []\n for instance_detail in instance_detail_list:\n result.append(instance_detail.get('PrivateIpAddress'))\n return result\n\ndef get_cluster_state(cluster):\n return cluster.get('Status').get('State')\n\ndef get_cluster_state_change_reason(cluster):\n return cluster.get('Status').get('StateChangeReason').get('Message')\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils._text import to_bytes, to_native\n\ndef run_module():\n # define the available arguments/parameters that a user can pass to\n # the module\n module_args = dict(\n aws_access_key=dict(type='str', required=True),\n aws_secret_key=dict(type='str', required=True),\n region=dict(choices=['us-east-1', 'us-west-2', 'us-west-1', 'eu-west-1', 'eu-central-1', 'ap-southeast-1', 'ap-northeast-1', 'ap-southeast-2', 'ap-northeast-2', 'ap-south-1', 'sa-east-1'], required=True),\n mode=dict(choices=['create', 'get-cluster-id', 'get-cluster-ids', 'terminate', 'terminate-all', 'describe', 'check-status', 'get-master-ip', 'get-core-ips', 'get-task-ips', 'get-group-id-by-name'], required=True),\n name=dict(type='str'),\n id=dict(type='str'),\n auto_scaling_role=dict(type='str', default='EMR_AutoScaling_DefaultRole'),\n applications=dict(type='list', default=['Hadoop', 'Spark']),\n log_url=dict(type='str'),\n release_label=dict(type='str', default='emr-5.8.0'),\n service_role=dict(type='str', default='iam-role-emr'),\n ec2_service_role=dict(type='str', default='iam-role-emr-ec2'),\n scale_down_behavior=dict(type='str', default='TERMINATE_AT_TASK_COMPLETION'),\n tags=dict(type='list'),\n ec2_key_file_name=dict(type='str', default=''),\n emr_master_security_group=dict(type='str'),\n emr_slave_security_group=dict(type='str'),\n emr_service_security_group=dict(type='str'),\n key_alive_when_no_steps=dict(type='bool', default=True),\n termination_protection=dict(type='bool', default=True),\n ec2_subnet=dict(type='str'),\n ec2_subnets=dict(type='list'),\n bootstrap_actions=dict(type='path'),\n configurations=dict(type='path'),\n instances=dict(type='path'),\n instance_group_name=dict(type='str')\n )\n\n result = dict(\n changed=False\n )\n\n module = AnsibleModule(\n argument_spec=module_args,\n supports_check_mode=True\n )\n\n if module.check_mode:\n return result\n\n if not HAS_BOTO3:\n module.fail_json(msg='boto3 and botocore required for this module')\n\n #Prepare params\n aws_access_key = module.params.get('aws_access_key')\n aws_secret_key = module.params.get('aws_secret_key')\n region = module.params.get('region')\n mode = module.params.get('mode')\n name = module.params.get('name')\n id = module.params.get('id')\n auto_scaling_role = module.params.get('auto_scaling_role')\n applications = module.params.get('applications')\n log_url = module.params.get('log_url')\n release_label = module.params.get('release_label')\n service_role = module.params.get('service_role')\n ec2_service_role = module.params.get('ec2_service_role')\n scale_down_behavior = module.params.get('scale_down_behavior')\n tags = module.params.get('tags')\n ec2_key_file_name = module.params.get('ec2_key_file_name')\n emr_master_security_group = module.params.get('emr_master_security_group')\n emr_slave_security_group = module.params.get('emr_slave_security_group')\n emr_service_security_group = module.params.get('emr_service_security_group')\n key_alive_when_no_steps = module.params.get('key_alive_when_no_steps')\n termination_protection = module.params.get('termination_protection')\n ec2_subnet = module.params.get('ec2_subnet')\n ec2_subnets = module.params.get('ec2_subnets')\n bootstrap_actions = module.params.get('bootstrap_actions')\n configurations = module.params.get('configurations')\n instances = module.params.get('instances')\n instance_group_name = module.params.get('instance_group_name')\n\n emr_client = get_client(region, aws_access_key, aws_secret_key)\n\n if mode == 'get-cluster-id':\n id = get_cluster_id(module, emr_client, name)\n result['changed'] = True\n result['id'] = id[0]\n\n if mode == 'get-cluster-ids':\n id_list = get_cluster_ids(module, emr_client, name)\n if len(id_list) == 0:\n module.exit_json(msg='Not active cluster by name: ' + name + ' was found')\n result['changed'] = True\n result['id'] = id_list\n\n if mode == 'terminate':\n if id in ('', None):\n id = get_cluster_id(module, emr_client, name)\n terminate_emr(emr_client, id)\n result['changed'] = True\n result['id'] = id\n\n if mode == 'terminate-all':\n id_list = get_cluster_ids(module, emr_client, name)\n for cluster_id in id_list:\n terminate_emr(emr_client, cluster_id)\n result['changed'] = True\n result['id'] = id_list\n\n if mode == 'check-status':\n cluster = describle_cluster(emr_client, id)\n result['changed'] = True\n result['state'] = get_cluster_state(cluster)\n result['state-changed-reason'] = get_cluster_state_change_reason(cluster)\n\n if mode == 'get-master-ip':\n if id in ('', None):\n id = get_cluster_id(module, emr_client, name)\n master_instance_list = list_instance_by_group_type(emr_client, id, 'MASTER')\n result['master_private_ip'] = get_private_ip_address(master_instance_list)[0]\n\n if mode == 'get-core-ips':\n if id in ('', None):\n id = get_cluster_id(module, emr_client, name)\n core_instance_list = list_instance_by_group_type(emr_client, id, 'CORE')\n result['core_private_ips'] = get_private_ip_address(core_instance_list)\n\n if mode == 'get-task-ips':\n if id in ('', None):\n id = get_cluster_id(module, emr_client, name)\n task_instance_list = list_instance_by_group_type(emr_client, id, 'TASK')\n result['task_private_ips'] = get_private_ip_address(task_instance_list)\n\n if mode == 'get-group-id-by-name':\n if id in ('', None):\n id = get_cluster_id(module, emr_client, name)\n if instance_group_name in ('', None):\n module.fail_json(msg='instance_group_name is required to get instance group id')\n instance_group_list = list_instance_groups(emr_client, id)\n for instance_group in instance_group_list:\n if instance_group.get('Name') == instance_group_name:\n instance_group_id = instance_group.get('Id')\n if instance_group_id in ('', None):\n module.exit_json(msg='No instance group was found', **result)\n result['instance_group_id'] = instance_group_id\n\n\n if mode == 'create':\n #Validation Check\n if name in ('', None):\n module.fail_json(msg='name is required to create a cluster')\n\n if log_url in ('', None):\n module.fail_json(msg='log_url is required to create a cluster')\n\n if ec2_key_file_name in ('', None):\n module.fail_json(msg='ec2_key_file_name is required to create a cluster')\n\n if emr_master_security_group in ('', None):\n module.fail_json(msg='emr_master_security_group is required to create a cluster')\n\n if emr_slave_security_group in ('', None):\n module.fail_json(msg='emr_slave_security_group is required to create a cluster')\n\n if emr_service_security_group in ('', None):\n module.fail_json(msg='emr_service_security_group is required to create a cluster')\n\n if (ec2_subnet in ('', None)) and (ec2_subnets is None or ec2_subnets == []):\n module.fail_json(msg='ec2_subnet or ec2_subnets is required to create a cluster')\n\n if instances is ('', None):\n module.fail_json(msg='instances is required to create a cluster')\n\n\n\n application_list = convert_application(applications)\n\n tag_list = convert_tag(tags)\n\n emr_config = []\n if configurations not in ('', None):\n config_file_path = to_bytes(configurations, errors='surrogate_or_strict')\n with open(config_file_path) as json_file:\n emr_config = json.load(json_file)\n\n bootstrap_list = []\n if bootstrap_actions not in ('', None):\n bootstrap_file_path = to_bytes(bootstrap_actions, errors='surrogate_or_strict')\n with open(bootstrap_file_path) as boot_file:\n bootstrap_list = json.load(boot_file)\n\n instance_config = {}\n instance_list = []\n instance_file_path = to_bytes(instances, errors='surrogate_or_strict')\n with open(instance_file_path) as instance_file:\n instance_list = json.load(instance_file)\n instance_config['InstanceGroups'] = instance_list\n instance_config['Ec2KeyName'] = ec2_key_file_name\n instance_config['ServiceAccessSecurityGroup'] = emr_service_security_group\n instance_config['EmrManagedMasterSecurityGroup'] = emr_master_security_group\n instance_config['EmrManagedSlaveSecurityGroup'] = emr_slave_security_group\n instance_config['KeepJobFlowAliveWhenNoSteps'] = key_alive_when_no_steps\n instance_config['TerminationProtected'] = termination_protection\n instance_config['Ec2SubnetId'] = ec2_subnet\n\n cluster_id = emr_client.run_job_flow(\n AutoScalingRole=auto_scaling_role,\n Applications=application_list,\n Name=name,\n LogUri=log_url,\n ReleaseLabel=release_label,\n ServiceRole=service_role,\n JobFlowRole=ec2_service_role,\n BootstrapActions=bootstrap_list,\n Configurations=emr_config,\n ScaleDownBehavior=scale_down_behavior,\n Instances=instance_config,\n VisibleToAllUsers=True,\n Tags=tag_list\n )\n\n result['changed'] = True\n result['id'] = cluster_id\n\n module.exit_json(**result)\n\ndef main():\n run_module()\n\nif __name__ == '__main__':\n main()","sub_path":"modules/aws_emr.py","file_name":"aws_emr.py","file_ext":"py","file_size_in_byte":17333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"351199547","text":"LOG_FILE_LOCATION = '/var/log/xroad/audit.log'\n\nLOGIN = 'Log in user'\nLOGOUT = 'Log out user'\n\nADD_GROUP = 'Add group'\nADD_GROUP_FAILED = 'Add group failed'\n\nADD_CLIENT = 'Add client'\nADD_MEMBER = 'Add member'\nADD_SUBSYSTEM = 'Add subsystem'\nEDIT_MEMBER_NAME_FAILED = 'Edit member name failed'\nEDIT_MEMBER_NAME = 'Edit member name'\nDELETE_MEMBER = 'Delete member'\n\nADD_WSDL_FAILED = 'Add WSDL failed'\nADD_WSDL = 'Add WSDL'\n\nADD_GLOBAL_GROUP = 'Add global group'\nADD_GLOBAL_GROUP_FAILED = 'Add global group failed'\nADD_MEMBER_TO_GROUP = 'Add member to global group'\n\nREGISTER_MEMBER_AS_SEC_SERVER_CLIENT = 'Register member as security server client'\nREVOKE_CLIENT_REGISTRATION_REQUEST = 'Revoke client registration request'\n\nEDIT_SERVICE_PARAMS = 'Edit service parameters'\n\nMSG_SERVICE_CENTER = 'X-Road Center UI'\nMSG_SERVICE_SECURITY = 'X-Road Proxy UI'\n","sub_path":"common/xrd-ui-tests-python/view_models/log_constants.py","file_name":"log_constants.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"629503119","text":"import cv2\nimport itertools\nimport numpy as np\n\nfrom shape import ShapeList\n\ndef distance(a, b):\n (ax, ay) = a\n (bx, by) = b\n\n return np.sqrt((ax-bx)**2+(ay-by)**2)\n\ndef threshold(img):\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n thresh = 255-cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\n thresholdType=cv2.THRESH_BINARY, blockSize=151, C=50)\n\n k5 = np.ones((5,5),np.uint8)\n k7 = np.ones((7,7),np.uint8)\n g = cv2.erode(cv2.dilate(thresh, k7, iterations=1), k5, iterations=1)\n # g = cv2.Canny(g, 50, 150, apertureSize=5)\n return g\n\ndef threshold_shape_sizes(shapes):\n # Detect if any corners are within a few pixels of each other. If so,\n # we've screwed up somewhere.\n for shape in shapes:\n for v1, v2 in itertools.combinations(shape.get_vertices(), 2):\n if distance(v1, v2) < 10:\n shapes.delete_shape_with_vertex(v1)\n break\n\ndef order_shapes(img, shapes):\n pass\n\ndef find_largest_container(img, shapes):\n sizes = []\n for i, shape in enumerate(shapes):\n if len(shape['extra']) == 4:\n # Detect area\n pass\n\ndef recognize_linear_shapes(img, shapes):\n threshold_shape_sizes(shapes)\n for shape in shapes:\n if shape.is_complete():\n # Recognize the shapes\n if len(shape) == 3:\n color = (255, 0, 0)\n elif len(shape) == 4:\n color = (0, 255, 0)\n elif len(shape) > 4:\n color = (255, 255, 0)\n\n # Add the first vertex to the end, so I can iterate over\n # consecutive pairs and nicely get the ordered shape\n vs = shape.get_vertices()\n for i, v in enumerate(vs):\n cv2.line(img, v, vs[(i+1)%len(vs)], color, 2)\n color = (color[0], color[1], color[2] + np.uint8(255./(len(shape)-1)))\n\ndef process(img, g):\n gf = np.float32(g)\n\n dst = cv2.cornerHarris(gf,7,15,0.04)\n dst = cv2.dilate(dst,None)\n g[dst>0.02*dst.max()]=0\n\n line_endpoints = []\n\n x = 0\n\n contours, hierarchy = cv2.findContours(g, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n for c in contours:\n if cv2.contourArea(c) > 100:\n ellipse = cv2.fitEllipse(c)\n\n (x,y), (minor_axis, major_axis), angle = ellipse\n ecc = major_axis/minor_axis\n\n if ecc > 5:\n if abs(angle-90) > 30:\n # Vertical\n # cv2.drawContours(img, c, -1, (0, 0, 255), 1)\n\n # Find extrema points\n # via http://opencv-python-tutroals.readthedocs.org/en/...\n # latest/py_tutorials/py_imgproc/py_contours/...\n # py_contour_properties/py_contour_properties.html\n topmost = tuple(c[c[:,:,1].argmin()][0])\n bottommost = tuple(c[c[:,:,1].argmax()][0])\n\n line_endpoints.append((topmost, bottommost))\n\n # cv2.line(img, topmost, bottommost, (255, 255, 0), 1)\n else:\n # Horizontal\n # cv2.drawContours(img, c, -1, (0, 255, 255), 1)\n\n leftmost = tuple(c[c[:,:,0].argmin()][0])\n rightmost = tuple(c[c[:,:,0].argmax()][0])\n\n line_endpoints.append((leftmost, rightmost))\n\n # cv2.line(img, leftmost, rightmost, (0, 255, 255), 1)\n elif ecc < 1.5: # Need to draw pretty carefully to not pass 1.5\n # Circles\n # cv2.drawContours(img, c, -1, (255, 0, 0), 1)\n cv2.ellipse(img, ellipse, (0, 255, 255), 2)\n else:\n # Some weird line shape\n cv2.drawContours(img, c, -1, (255, 0, x), 2)\n x += 125\n pass\n else:\n # Small objects\n cv2.drawContours(img, c, -1, (0, 255, 0), 1)\n pass\n\n linear_shapes = ShapeList()\n\n for (a, b) in line_endpoints:\n cv2.line(img, a, b, (255, 255, 0), 1)\n for (c, d) in line_endpoints:\n if (a, b) != (c, d):\n for (m, n) in itertools.combinations([a, b, c, d], 2):\n if distance(m, n) < 20:\n # Likely found two line segments that should connect\n \n (x1, y1) = np.float32(a)\n (x2, y2) = np.float32(b)\n (x3, y3) = np.float32(c)\n (x4, y4) = np.float32(d)\n\n # Detect the intersection point (surely can be nicer!)\n px_n = np.linalg.det(np.array(\n [[np.linalg.det(np.array([[x1, y1], [x2, y2]])),\n np.linalg.det(np.array([[x1, 1 ], [x2, 1 ]]))],\n [np.linalg.det(np.array([[x3, y3], [x4, y4]])),\n np.linalg.det(np.array([[x3, 1 ], [x4, 1 ]]))]]))\n py_n = np.linalg.det(np.array(\n [[np.linalg.det(np.array([[x1, y1], [x2, y2]])),\n np.linalg.det(np.array([[y1, 1 ], [y2, 1 ]]))],\n [np.linalg.det(np.array([[x3, y3], [x4, y4]])),\n np.linalg.det(np.array([[y3, 1 ], [y4, 1 ]]))]]))\n p_d = np.linalg.det(np.array(\n [[np.linalg.det(np.array([[x1, 1 ], [x2, 1]])),\n np.linalg.det(np.array([[y1, 1 ], [y2, 1 ]]))],\n [np.linalg.det(np.array([[x3, 1 ], [x4, 1]])),\n np.linalg.det(np.array([[y3, 1 ], [y4, 1 ]]))]]))\n\n # Should probably validate that there is an intersection\n # before crashing here by division with zero. It is\n # extraordinarily unlikely, though.\n\n p = tuple(np.int32((px_n/p_d, py_n/p_d)))\n if distance(m, p) < 20 and distance(n, p) < 20:\n cv2.line(img, m, p, (0, 0, 255), 1)\n cv2.line(img, n, p, (0, 0, 255), 1)\n # linear_shapes.add((a, b), (c, d), extra=p)\n linear_shapes.add((a, b), (c, d), p)\n\n recognize_linear_shapes(img, linear_shapes)\n\n return img\n\ndef test_img(filename):\n img = cv2.imread(filename)\n\n img = cv2.resize(img, (0,0), fx=0.2, fy=0.2)\n thresh = threshold(img)\n\n img = process(img, thresh)\n\n cv2.imshow(filename, img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n test_img('input-images/training/square.jpg')\n test_img('input-images/slides/slide1.jpg')\n test_img('input-images/slides/slide2.jpg')\n test_img('input-images/slides/slide3.jpg')\n test_img('input-images/slides/slide4.jpg')\n test_img('input-images/slides/slide5.jpg')\n test_img('input-images/slides/slide6.jpg')\n test_img('input-images/slides/slide7.jpg')\n test_img('input-images/slides/slide8.jpg')\n test_img('input-images/slides/slide9.jpg')\n test_img('input-images/slides/slide10.jpg')\n test_img('input-images/slides/slide11.jpg')\n test_img('input-images/slides/slide12.jpg') # Need help on thresholding\n test_img('input-images/slides/slide13.jpg')\n","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":7403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"601515685","text":"from conf import default_conf\nfrom torch.utils.data import DataLoader\nfrom datasets.bigearth.bigearth_dataset import BigEarthDataset\nfrom datasets.bigearth.bigearth_dataset import lab2rgb\nfrom datasets.bigearth.quantizer import quantization\nfrom torch.utils.data import SubsetRandomSampler\nimport os\nimport json\nimport torch\nimport cv2\nimport numpy as np\nimport glob\nimport shutil\n\n\nclass Utilities:\n\n def __init__(self, load_dir, dataset_name=default_conf['DATASET_NAME'], overwrite=False):\n \"\"\"\n loading config file from json file or\n creating a new experiment from the current default configuration\n default configuration is stored in conf.py\n :param load_dir: name of the folder in the experiment dir\n :param dataset_name: {bigearth|lfw}\n :return: new experiment dir or loaded experiment dir\n \"\"\"\n\n save_dir = os.path.join(default_conf['OUT_DIR'], dataset_name, load_dir)\n\n # if overwrite flag is on, whatever there's on the savedir path\n # gonna be overwritten\n if os.path.exists(save_dir) and overwrite:\n print(\"overwriting \", save_dir)\n shutil.rmtree(save_dir)\n\n if not os.path.exists(save_dir): # NEW EXPERIMENT\n print(\"creating new experiment with name: \", load_dir)\n # creating folders for model, config and results\n os.mkdir(save_dir)\n\n if default_conf['TEST_CVAE']:\n os.mkdir(os.path.join(save_dir, 'results_cvae'))\n\n # dump DEFAULT configuration file\n with open(os.path.join(save_dir, 'config.json'), \"w\") as write_file:\n json.dump(default_conf, write_file, indent=4)\n self.conf = default_conf\n\n else:\n print(\"loading previous experiment: \", load_dir)\n # loading config file from json\n with open(os.path.join(save_dir, 'config.json'), 'r') as handle:\n config = json.load(handle)\n\n # cleaning previous results folders\n for prev_exp in glob.glob(os.path.join(save_dir, 'results*')):\n shutil.rmtree(prev_exp)\n\n # create new results folders\n if config['TEST_CVAE'] and not os.path.isdir(os.path.join(save_dir, 'results_cvae')):\n os.mkdir(os.path.join(save_dir, 'results_cvae'))\n\n self.conf = config\n\n # saving class attributes\n self.title = load_dir\n self.save_dir = save_dir\n self.dataset_name = dataset_name\n\n def epoch_checkpoint(self, model, epoch):\n \"\"\"\n update the json file with the current achieved epoch number and print it to the config file\n epoch: epoch number\n \"\"\"\n if model == 'CVAE':\n self.conf['LOAD_CVAE'] = True\n self.conf['CVAE_EPOCH_CHECKPOINT'] = epoch\n else:\n raise Exception('invalid model in epoch checkpoint!')\n # saving the new configuration\n with open(os.path.join(self.save_dir, 'config.json'), \"w\") as write_file:\n json.dump(self.conf, write_file, indent=4)\n\n def test_complete(self):\n self.conf['LOAD_CVAE'] = False\n with open(os.path.join(self.save_dir, 'config.json'), \"w\") as write_file:\n json.dump(self.conf, write_file, indent=4)\n\n def load_data(self, split, mode, rgb, writer=None):\n \"\"\"\n generate dataloader according to the dataset\n :param split: {train|test}\n :return: pytorch dataloader object\n \"\"\"\n # BIG EARTH DATA LOADER\n if self.dataset_name == 'bigearth':\n\n big_earth = BigEarthDataset(\n self.conf['BIG_EARTH_CVS_NAME'],\n 42,\n self.conf['BANDS'],\n n_samples=self.conf['SAMPLES_NUM'],\n mode=mode,\n RGB=rgb,\n weights_file=self.conf['WEIGHT_FILENAME'],\n skip_weights=(not self.conf['USE_WEIGHTS'])\n )\n train_idx, val_idx, test_idx = big_earth.split_dataset(0.2, 0.3)\n\n train_loader = torch.utils.data.DataLoader(\n big_earth,\n batch_size=self.conf['BATCHSIZE'],\n sampler=SubsetRandomSampler(train_idx),\n num_workers=self.conf['NTHREADS'],\n drop_last=True,\n )\n test_loader = torch.utils.data.DataLoader(\n big_earth,\n batch_size=self.conf['TEST_BATCHSIZE'],\n sampler=SubsetRandomSampler(test_idx),\n num_workers=self.conf['NTHREADS'],\n drop_last=True,\n )\n val_loader = torch.utils.data.DataLoader(\n big_earth,\n batch_size=self.conf['TEST_BATCHSIZE'],\n sampler=SubsetRandomSampler(val_idx),\n num_workers=self.conf['NTHREADS'],\n drop_last=True,\n )\n return train_loader, test_loader, val_loader\n\n else:\n raise Exception('dataset not valid')\n\n def reload_weights(self):\n # calculate histogram for this dataset\n quantization(conf=self.conf, q_factor=self.conf['Q_FACTOR'])\n\n def restore(self, img_enc):\n \"\"\"\n perform conversion to RGB\n :param img_enc: CIELAB channels\n :return: RGB conversion\n \"\"\"\n img_dec = (((img_enc + 1.) * 1.) / 2.) * 255.\n # img_dec = img_enc\n img_dec[img_dec < 0.] = 0.\n img_dec[img_dec > 255.] = 255.\n return img_dec.type(torch.uint8)\n\n def generate_header(self, W, with_posterior=True):\n font = cv2.FONT_HERSHEY_SIMPLEX\n\n header = 255 * np.ones((1, 3, 40, W))\n\n # print gt same for both cases\n cv2.putText(header, 'GT', (10, 25), font, 0.5, (0, 0, 0), 2, cv2.LINE_AA)\n '''\n if with_posterior:\n cv2.putText(header, 'posterior', (self.conf['IMG_W'] + bordershape, 25), font, 0.5, (0, 0, 0), 2,\n cv2.LINE_AA)\n cv2.putText(header, 'samples',\n ((2 + int(self.conf['NMIX'] / 2)) * self.conf['IMG_W'] + 2 * bordershape, 25),\n font, 0.5, (0, 0, 0), 2, cv2.LINE_AA)\n else:\n cv2.putText(header, 'samples', (self.conf['IMG_W'] + bordershape, 25), font, 0.5, (0, 0, 0), 2, cv2.LINE_AA)\n '''\n return header\n\n def dump_results(self, color, grey, gt, nmix, model_name, file_name='result', tb_writer=None, posterior=None):\n \"\"\"\n :param color: network output 32x(8)x2x64x64\n :param grey: grey input 32x64x64\n :param gt: original image 32x2x64x64\n :param nmix: number of samples from the mdn\n :param model_name: {mdn|cvae}\n :param file_name: name of the new image\n :param tb_writer: tensorboardX writer\n :param posterior: output image if decoder sample from posterior\n \"\"\"\n\n # reducing the number of images to print for a better shape\n samples = min(color.size(0), 10)\n gt = gt[:samples, ...]\n grey = grey[:samples, ...]\n color = color[:samples, ...]\n H = samples * self.conf['IMG_H']\n # in here we print the output image for the batch (max H elems)\n # net_result = np.zeros((H, nmix * self.conf['IMG_W'], 3),\n # dtype='uint8')\n # black stripes between sections\n border_img = 0 * np.ones((1, 3, H, 10))\n\n # swap axes and reshape layers to fit correct format when reshaping\n grey = grey.reshape((H, self.conf['IMG_W']))\n\n if nmix != 1:\n color = color.permute((0, 3, 1, 4, 2))\n else:\n color = color.squeeze(1)\n color = color.permute((0, 2, 3, 1))\n\n color = color.reshape((H, nmix * self.conf['IMG_W'], 2))\n gt = gt.permute((0, 2, 3, 1))\n gt = gt.reshape((H, self.conf['IMG_W'], 2))\n\n # fitting the shape for my friend's code\n grey = grey[np.newaxis, np.newaxis]\n gt = gt.permute(2, 0, 1).unsqueeze(0)\n color = color.permute(2, 0, 1).unsqueeze(0)\n\n # LAB -> RGB\n gt_print = lab2rgb(grey, gt)\n net_result = lab2rgb(grey.repeat(1, 1, 1, nmix), color)\n\n # gt_print = cv2.merge((self.restore(grey).data.numpy(), self.restore(gt).data.numpy()))\n # net_result[:, :, 0] = self.restore(grey.repeat((1, nmix)))\n # net_result[:, :, 1:3] = self.restore(color).detach().cpu()\n # gt_print = cv2.cvtColor(gt_print, cv2.COLOR_LAB2BGR)\n # net_result = cv2.cvtColor(net_result, cv2.COLOR_LAB2BGR)\n\n if posterior is not None:\n # one more colomn for\n posterior = posterior[:samples, ...]\n posterior = posterior.permute((0, 2, 3, 1))\n posterior = posterior.reshape((H, self.conf['IMG_W'], 2))\n posterior = posterior.permute((2, 0, 1)).unsqueeze(dim=0)\n posterior = lab2rgb(grey, posterior)\n # posterior = cv2.merge((self.restore(grey).data.numpy(), self.restore(posterior).cpu().data.numpy()))\n # posterior = cv2.cvtColor(posterior, cv2.COLOR_LAB2BGR)\n result_image = np.concatenate((gt_print, border_img, posterior, border_img, net_result), axis=3)\n else:\n result_image = np.concatenate((gt_print, border_img, net_result), axis=3)\n\n header = self.generate_header(result_image.shape[3], with_posterior=(posterior is not None))\n result_image = np.concatenate((header, result_image), axis=2)\n\n # finally removing the annoying 1 dim\n result_image = result_image.squeeze()\n\n # create output dir if not exists and save result on disk\n # out_fn_pred = os.path.join(self.save_dir, model_name, str(file_name) + '.jpg')\n # if not os.path.exists(os.path.join(self.save_dir, model_name)):\n # os.mkdir(os.path.join(self.save_dir, model_name))\n # cv2.imwrite(out_fn_pred, result_image.transpose(1, 2, 0))\n\n # saving path for tensorboard will be something like mdn/result on iteration == batch idx\n # tensorboard needs input as 3 x H x W\n if tb_writer is not None:\n # result_image = result_image[:, :, ::-1]\n # result_image = np.transpose(result_image.astype('uint8'), (2, 0, 1))\n tb_writer.add_image('{}/img_results'.format(model_name), result_image, int(file_name))\n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":10371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"426887295","text":"\n\nfrom xai.brain.wordbase.verbs._falsify import _FALSIFY\n\n#calss header\nclass _FALSIFIES(_FALSIFY, ):\n\tdef __init__(self,): \n\t\t_FALSIFY.__init__(self)\n\t\tself.name = \"FALSIFIES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"falsify\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_falsifies.py","file_name":"_falsifies.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"411585863","text":"from functools import wraps\nimport os, re\nimport json as j\nfrom glob import glob\nfrom flask import request, current_app\nfrom app.extensions import jsonschema\n\njsonschema_classes = [\n 'AdminLogin',\n 'CreateConsultant', 'UpdateConsultant',\n 'CreateConsultionTime',\n 'User',\n]\n\njsonschema_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../jsonschema')\n\ndef write_schemas_to_file():\n pattern = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"*.py\")\n for file in glob(pattern):\n name = os.path.splitext(os.path.basename(file))[0]\n module = __import__('app.jsons.%s' % name, fromlist=[''])\n for item in dir(module):\n if item in jsonschema_classes:\n jsl_class = getattr(module, item)\n path = os.path.join(jsonschema_path, camel_to_underscore(item) + '.json')\n with open(path ,'w') as file:\n file.write(j.dumps(jsl_class.get_schema()))\n \n\n\ndef get_schema(jsonschema_name):\n try:\n path = os.path.join(jsonschema_path, jsonschema_name + '.json')\n with open(path) as file:\n string = file.read()\n jsonschema = j.loads(string)\n return jsonschema\n except:\n return {}\n \n\ndef validate(jsonschema_name):\n return jsonschema.validate(get_schema(jsonschema_name))\n\ndef camel_to_underscore(string):\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', string)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()","sub_path":"server/app/jsons/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"258950828","text":"import sys\nfrom tkinter import *\nfrom tkinter import colorchooser\nfrom tkinter import ttk\nfrom tkinter import Tk\n\ndef vp_start_gui():\n global window\n window = Tk()\n\n window.geometry('500x500')\n window.title('Hello Tkinter')\n\n c = []\n b = StringVar()\n b = colorchooser.askcolor(initialcolor='#FFFFFF')\n word_list = list(b) # list of words\n c = word_list[-1]\n\n window.clipboard_clear()\n window.clipboard_append(c)\n window.update()\n window.configure(bg=c)\n\n label = ttk.Label(window, text=c + '\\ncopied')\n label.config(foreground='black', background=c,font=('Fiera', 60, 'bold'))\n label.place(relx=0.5, rely=0.5, anchor=CENTER)\n\n ttk.Button(window, text=\"quit\", compound=CENTER, command=window.quit).grid(row=1)\n\n window.mainloop()\n\n\nif __name__ == '__main__':\n def refresh():\n window.destroy()\n vp_start_gui()\n\n vp_start_gui()\n","sub_path":"Python/Tkinter Tutorial/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"470959420","text":"# Courserea: Divide and Conquer, Sorting and Searching, and \n# Randomized Algorithms by Stanford University\n\ndef countSplitInv(arrLeft:list, arrRight:list) -> int:\n \"\"\"\n Counts split inversions where one elements is on left array while \n the second one is in right array. \n Sort input arrays before counting inversions and then count them\n with sorted array which if more efficient.\n\n Returns:\n count of inversions\n \"\"\"\n\n invNum = 0\n\n arrL = sorted(arrLeft)\n arrR = sorted(arrRight)\n\n leftCount = len(arrL)\n rightCount = len(arrR)\n\n leftIdx = rightIdx = 0\n\n while (True):\n if arrL[leftIdx] <= arrR[rightIdx]:\n leftIdx += 1\n elif arrL[leftIdx] > arrR[rightIdx]:\n rightIdx += 1\n invNum += leftCount - leftIdx\n \n if leftIdx == leftCount or rightIdx == rightCount:\n break\n\n return invNum\n\n\ndef countInversions(arr) -> int:\n \"\"\"\n Count all inversions with Divide and conquer algorithm.\n Splits array into two arrays and counts inversions in each of them.\n Afterwards counts all inversions where one elements is on left array while \n the second one is in right array\n \"\"\"\n\n l = len(arr)\n invNum = 0\n\n if l > 1:\n leftArr = arr[:l // 2]\n rightArr = arr[l // 2:]\n\n invNum += countInversions(leftArr)\n invNum += countInversions(rightArr)\n invNum += countSplitInv(leftArr, rightArr)\n\n return invNum\n\na = [36, 1, 3, 5, 7, 9, 2, 4, 6, 10, 11]\n\nprint(countInversions(a))\n","sub_path":"Divide_And_Conquer/count_inversions.py","file_name":"count_inversions.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"57651538","text":"import numpy as np\n\ndef set_matrix(n):\n A = np.zeros((n,n))\n for i in range(n):\n for j in range(n):\n A[i,j] = 1/(i + j + 1)\n return A\n\n\n\ndef update_step_cg(x_k, p_k, r_k, A):\n\n alpha_k = (r_k**2).sum()/(p_k.T @ A @ p_k)\n x_k1 = x_k + p_k * alpha_k\n r_k1 = r_k + alpha_k * (A @ p_k)\n beta_k1 = (r_k1 ** 2).sum()/(r_k**2).sum()\n p_k1 = -r_k1 + beta_k1 * p_k\n\n return x_k1, r_k1, p_k1\n\n\ndef conjugate_gradient(N):\n b = np.ones(N)\n A = set_matrix(N)\n tol = 1e-5\n\n x_0 = np.zeros(N)\n r_0 = A @ x_0 - b\n p_0 = -r_0\n\n x_old = x_0\n r_old = r_0\n p_old = p_0\n crit = 100\n i = 1\n while crit>tol:\n x_new, r_new, p_new = update_step_cg(x_old, p_old, r_old, A)\n crit = np.linalg.norm(x_new - x_old)\n\n x_old = x_new.copy()\n r_old = r_new.copy()\n p_old = p_new.copy()\n i += 1\n\n print('Conjugate Gradient with %i dimensions, converged after %i iterations' % (N, i))\n pass\n\nfor n in [5, 8, 12, 20]:\n conjugate_gradient(n)","sub_path":"H3/HW3_EX1.py","file_name":"HW3_EX1.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"425012344","text":"import matplotlib.pyplot\n\nfile_data = list()\nwith open(\"Chart data.txt\", \"r\") as file:\n for line in file.readlines():\n file_data.append(list(str(line).split()))\n\nfigure = matplotlib.pyplot.figure()\ntarjan_line = figure.gca(projection='3d')\nbfs_line = figure.gca(projection='3d')\nbfs_line = figure.gca(projection='3d')\nx_vertex = list()\ny_edge = list()\nz_tarjan = list()\nz_bfs = list()\n\nfor line in file_data:\n x_vertex.append(int(line[0]))\n y_edge.append(int(line[1]))\n z_tarjan.append(int(line[2]))\n z_bfs.append(int(line[3]))\n\ntarjan_line.plot(x_vertex, y_edge, z_tarjan, label='Tarjan Time Cost')\ntarjan_line.legend()\nbfs_line.plot(x_vertex, y_edge, z_bfs, label='BFS Time Cost')\nbfs_line.legend()\n\nmatplotlib.pyplot.show()","sub_path":"src/3D chart.py","file_name":"3D chart.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"262425249","text":"import config\nimport time\nimport pandas as pd\nfrom variable_names import list_of_headers, intent_entity_titles, batch_test_set\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\n\noption = webdriver.ChromeOptions()\noption.add_argument(\" - incognito\")\nbrowser = webdriver.Chrome(executable_path=config.home_path, options=option)\n\n\ndef login_luis():\n \"\"\"\n Logs in to EU Luis portal using username and password\n\n :parameter: config.username is the username var loaded from the config file\n :parameter: config.password is the password var loaded from the config file\n :return: None\n \"\"\"\n browser.get(\"https://eu.luis.ai\")\n WebDriverWait(browser, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, \"Sign in\")))\n browser.find_element_by_link_text('Sign in').click()\n WebDriverWait(browser, 5).until(EC.element_to_be_clickable((By.ID, \"idSIButton9\")))\n browser.find_element_by_id('i0116').send_keys(config.username)\n browser.find_element_by_id('idSIButton9').click()\n WebDriverWait(browser, 5).until(EC.element_to_be_clickable((By.ID, \"idSIButton9\")))\n browser.find_element_by_id('i0118').send_keys(config.password)\n browser.find_element_by_id('idSIButton9').click()\n\n\ndef batch_test_open():\n \"\"\"\n Navigates Luis portal and opens the batch testing pane\n\n :return: None\n \"\"\"\n try:\n WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.CLASS_NAME, \"cdk-overlay-pane\")))\n ActionChains(browser).send_keys(Keys.ESCAPE).perform()\n except:\n print(\"No migration pop-up\")\n\n WebDriverWait(browser, 2).until(EC.element_to_be_clickable((By.LINK_TEXT, config.app_name)))\n browser.find_element_by_link_text(config.app_name).click()\n WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.CLASS_NAME, 'nav-section')))\n buttons = browser.find_elements_by_class_name('nav-section')\n buttons[1].click()\n WebDriverWait(browser, 5).until(EC.visibility_of_element_located((By.XPATH, '//button[contains(text(), '\n '\"Batch testing\")]')))\n browser.find_element_by_xpath('//button[contains(text(), \"Batch testing\")]').click()\n\n\ndef batch_test_run():\n \"\"\"\n Runs all available batch tests in the batch testing panel\n\n :return: none\n \"\"\"\n WebDriverWait(browser, 15).until(EC.visibility_of_element_located((By.XPATH, '//button[contains(text(), ''\"Run\")]')))\n batch_run_button = browser.find_elements_by_xpath('//button[contains(text(), \"Run\")]')\n for test in batch_run_button:\n test.click()\n time.sleep(4)\n\n\ndef batch_tests_results():\n \"\"\"\n Opens each batch test and extracts the results information from it. NB: This goes through each of the intents in\n the 'overview' table of links and extracts the score. Eg. (78/123). It does not currently extract the confusion\n matrix scores. If required, the code can be adapted to do this. It then outputs these results to csv file.\n The list of intents and entities, csv headers and all batch tests to be run should be provided in variable_names.py.\n\n :return: None\n \"\"\"\n df = pd.DataFrame(columns=list_of_headers)\n loaded_batch_tests = []\n batch_results_button = browser.find_elements_by_xpath('//a[contains(text(), \"See results\")]')\n\n for results_number in range(len(batch_results_button)):\n scores_dict = {}\n batch_results_button = browser.find_elements_by_xpath('//a[contains(text(), \"See results\")]')\n batch_results_button[results_number].click()\n time.sleep(3)\n back = browser.find_element_by_xpath('//button[contains(text(), \"Back to list\")]')\n title_batch_test = browser.find_element_by_xpath('//h3[contains(text(), \"Dataset\")]').text.split()[1][1:-1]\n loaded_batch_tests.append(title_batch_test)\n scores_dict['Intent'] = title_batch_test\n utterances = browser.find_element_by_xpath('//*[contains(text(), \"utterances passed\")]').text[1:-1].split()\n utterances = utterances[0].split('/')[1]\n scores_dict['Size'] = utterances\n\n for intent_entity in intent_entity_titles:\n try:\n xpath_string = '//*[@title=\"' + intent_entity + '\"]'\n batch_result = browser.find_element_by_xpath(xpath_string)\n element, score = batch_result.text.split(\"(\")\n element = element.strip()\n scores_dict[element] = \"=\" + (score[:-1])\n except (NoSuchElementException, ValueError):\n print(intent_entity, \"not in batch test, continuing to iterate over Intents provided\")\n\n df = df.append(scores_dict, ignore_index=True)\n remaining_batch_tests(loaded_batch_tests)\n back.click()\n time.sleep(1)\n df.to_csv(\"batch_test_results.csv\", index=False)\n\n\ndef remaining_batch_tests(loaded_batch_tests):\n \"\"\"\n Uses the batch tests names set from variable_names.py to determine which batch tests have been run and which remain.\n The remaining batch tests are outputted to a text file 'remaining_tests.txt' for the user to review.\n\n :param loaded_batch_tests:\n :return: None\n \"\"\"\n remaining_tests = batch_test_set - set(loaded_batch_tests)\n with open('remaining_tests.txt', mode='w') as outfile:\n for batch_test in remaining_tests:\n outfile.write(\"%s\\n\" % batch_test)\n\n\ndef main():\n \"\"\"\n Runs all functions\n\n :return: None\n \"\"\"\n login_luis()\n batch_test_open()\n batch_test_run()\n batch_tests_results()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"luis_scraper.py","file_name":"luis_scraper.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"265581293","text":"from enforce_typing import enforce_types\nimport pytest\n\nfrom agents.BaseAgent import *\nfrom agents.test.conftest import _DT_INIT, _DT_STAKE \n\n@enforce_types\nclass MyTestAgent(BaseAgent):\n def takeStep(self, state):\n pass\n\n@enforce_types\ndef testInit():\n agent = MyTestAgent(\"agent1\", USD=1.1, OCEAN=1.2)\n assert agent.name == \"agent1\"\n assert agent.USD() == 1.1\n assert agent.OCEAN() == 1.2\n assert \"MyTestAgent\" in str(agent)\n\n@enforce_types\ndef testReceiveAndSend():\n #agents are of arbitary classes\n agent = MyTestAgent(\"agent1\", USD=0.0, OCEAN=3.30)\n agent2 = MyTestAgent(\"agent2\", USD=0.0, OCEAN=3.30)\n\n #USD\n assert pytest.approx(agent.USD()) == 0.00\n agent.receiveUSD(13.25)\n assert pytest.approx(agent.USD()) == 13.25\n\n agent._transferUSD(None, 1.10)\n assert pytest.approx(agent.USD()) == 12.15\n\n assert pytest.approx(agent2.USD()) == 0.00\n agent._transferUSD(agent2, 1.00)\n assert pytest.approx(agent.USD()) == (12.15 - 1.00)\n assert pytest.approx(agent2.USD()) == (0.00 + 1.00)\n\n #OCEAN\n assert pytest.approx(agent.OCEAN()) == 3.30\n agent.receiveOCEAN(2.01)\n assert pytest.approx(agent.OCEAN()) == 5.31\n\n agent._transferOCEAN(None, 0.20)\n assert pytest.approx(agent.OCEAN()) == 5.11\n\n assert pytest.approx(agent2.OCEAN()) == 3.30\n agent._transferOCEAN(agent2, 0.10)\n assert pytest.approx(agent.OCEAN()) == (5.11 - 0.10)\n assert pytest.approx(agent2.OCEAN()) == (3.30 + 0.10)\n \n\n#===================================================================\n# datatoken and pool-related\n@enforce_types\ndef test_DT(alice_agent: BaseAgent, alice_DT: datatoken.Datatoken): \n alice_DT_amt: float = alice_agent._wallet.DT(alice_DT)\n assert alice_DT_amt == (_DT_INIT - _DT_STAKE)\n\n@enforce_types\ndef test_BPT(alice_agent: BaseAgent, alice_pool: bpool.BPool): \n assert alice_agent.BPT(alice_pool) == 100.0\n\n@enforce_types\ndef test_stakeOCEAN(alice_agent: BaseAgent, alice_pool): \n OCEAN_before:float = alice_agent.OCEAN()\n BPT_before:float = alice_agent.BPT(alice_pool)\n \n alice_agent.stakeOCEAN(OCEAN_stake=20.0, pool=alice_pool)\n \n OCEAN_after:float = alice_agent.OCEAN()\n BPT_after:float = alice_agent.BPT(alice_pool)\n assert OCEAN_after == (OCEAN_before - 20.0)\n assert BPT_after > BPT_before\n\n@enforce_types\ndef test_unstakeOCEAN(alice_agent, alice_pool):\n BPT_before:float = alice_agent.BPT(alice_pool)\n \n alice_agent.unstakeOCEAN(BPT_unstake=20.0, pool=alice_pool)\n \n BPT_after:float = alice_agent.BPT(alice_pool)\n assert BPT_after == (BPT_before - 20.0)\n \n\n","sub_path":"agents/test/test_BaseAgent.py","file_name":"test_BaseAgent.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"291372679","text":"import re\nimport os\nimport shutil\nimport time\nimport pickle\nimport math\nfrom typing import List, Optional, Dict\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\nfrom torch.optim import Adam, lr_scheduler, Optimizer\n\nfrom torchtext.data.field import Field\nfrom torchtext.data.iterator import Iterator\n\nfrom qanta import qlogging\nfrom qanta.torch.dataset import QuizBowl\nfrom qanta.config import conf\nfrom qanta.guesser.abstract import AbstractGuesser\nfrom qanta.datasets.abstract import QuestionText\nfrom qanta.torch import (\n BaseLogger, TerminateOnNaN, EarlyStopping, ModelCheckpoint,\n MaxEpochStopping, TrainingManager\n)\nfrom sklearn.neighbors import KDTree\nimport random\n\nlog = qlogging.get(__name__)\n\n\nPT_RNN_WE_TMP = '/tmp/qanta/deep/pt_rnn_we.pickle'\nPT_RNN_WE = 'pt_rnn_we.pickle'\nCUDA = torch.cuda.is_available()\n\n\ndef create_save_model(model):\n def save_model(path):\n torch.save(model.state_dict(), path)\n return save_model\n\nextracted_grads = {}\ndef extract_grad_hook(name):\n def hook(grad):\n extracted_grads[name] = grad\n return hook\n\nqb_patterns = {\n '\\n',\n ', for 10 points,',\n ', for ten points,',\n '--for 10 points--',\n 'for 10 points, ',\n 'for 10 points--',\n 'for ten points, ',\n 'for 10 points ',\n 'for ten points ',\n ', ftp,'\n 'ftp,',\n 'ftp',\n '(*)'\n}\nre_pattern = '|'.join([re.escape(p) for p in qb_patterns])\nre_pattern += r'|\\[.*?\\]|\\(.*?\\)'\n\n\nclass DanEncoder(nn.Module):\n def __init__(self, embedding_dim, n_hidden_layers, n_hidden_units, dropout_prob):\n super(DanEncoder, self).__init__()\n encoder_layers = []\n for i in range(n_hidden_layers):\n if i == 0:\n input_dim = embedding_dim\n else:\n input_dim = n_hidden_units\n\n encoder_layers.extend([\n nn.Linear(input_dim, n_hidden_units),\n nn.BatchNorm1d(n_hidden_units),\n nn.ELU(),\n nn.Dropout(dropout_prob),\n ])\n self.encoder = nn.Sequential(*encoder_layers)\n\n def forward(self, x_array):\n return self.encoder(x_array)\n\n\nclass TiedModel(nn.Module):\n def __init__(self, text_field: Field, n_classes,\n init_embeddings=True, emb_dim=300,\n n_hidden_units=1000, n_hidden_layers=1, nn_dropout=.265, sm_dropout=.158):\n super(TiedModel, self).__init__()\n vocab = text_field.vocab\n self.vocab_size = len(vocab)\n self.emb_dim = emb_dim\n self.n_classes = n_classes\n self.n_hidden_units = n_hidden_units\n self.n_hidden_layers = n_hidden_layers\n self.nn_dropout = nn_dropout\n self.sm_dropout = sm_dropout\n\n self.dropout = nn.Dropout(nn_dropout)\n pad_idx = vocab.stoi[text_field.pad_token]\n self.general_embeddings = nn.Embedding(self.vocab_size, emb_dim, padding_idx=pad_idx)\n self.qb_embeddings = nn.Embedding(self.vocab_size, emb_dim, padding_idx=pad_idx)\n self.wiki_embeddings =nn.Embedding(self.vocab_size, emb_dim, padding_idx=pad_idx)\n qb_mask = torch.cat([torch.ones(1, 600), torch.zeros(1, 300)], dim=1)\n wiki_mask = torch.cat([torch.ones(1, 300), torch.zeros(1, 300), torch.ones(1, 300)], dim=1)\n self.combined_mask = torch.cat([qb_mask, wiki_mask], dim=0).float().cuda()\n\n if init_embeddings:\n mean_emb = vocab.vectors.mean(0)\n vocab.vectors[vocab.stoi[text_field.unk_token]] = mean_emb\n self.general_embeddings.weight.data = vocab.vectors.cuda()\n self.qb_embeddings.weight.data = vocab.vectors.cuda()\n self.wiki_embeddings.weight.data = vocab.vectors.cuda()\n\n # One averaged embedding for each of general, qb, and wiki\n self.encoder = DanEncoder(3 * emb_dim, self.n_hidden_layers, self.n_hidden_units, self.nn_dropout)\n self.classifier = nn.Sequential(\n nn.Linear(self.n_hidden_units, n_classes),\n nn.BatchNorm1d(n_classes),\n nn.Dropout(self.sm_dropout)\n )\n\n def forward(self, input_: Variable, lengths, qnums):\n \"\"\"\n :param input_: [batch_size, seq_len] of word indices\n :param lengths: Length of each example\n :param qnums: QB qnum if a qb question, otherwise -1 for wikipedia, used to get domain as source/target\n :return:\n \"\"\"\n if not isinstance(lengths, Variable):\n lengths = Variable(lengths.float(), volatile=not self.training)\n\n g_embed = self.general_embeddings(input_)\n g_embed = g_embed.sum(1) / lengths.float().view(input_.size()[0], -1)\n g_embed = self.dropout(g_embed)\n\n qb_embed = self.qb_embeddings(input_)\n qb_embed = qb_embed.sum(1) / lengths.float().view(input_.size()[0], -1)\n qb_embed = self.dropout(qb_embed)\n\n wiki_embed = self.wiki_embeddings(input_)\n wiki_embed = wiki_embed.sum(1) / lengths.float().view(input_.size()[0], -1)\n wiki_embed = self.dropout(wiki_embed)\n\n # Need to use qnum to mask either qb or wiki embeddings here\n concat_embed = torch.cat([g_embed, qb_embed, wiki_embed], dim=1)\n mask = Variable(self.combined_mask[(qnums < 0).long()])\n masked_embed = concat_embed * mask\n\n encoded = self.encoder(masked_embed)\n return self.classifier(encoded)\n\n\nclass TiedGuesser(AbstractGuesser):\n def __init__(self):\n super(TiedGuesser, self).__init__()\n guesser_conf = conf['guessers']['Tied']\n self.gradient_clip = guesser_conf['gradient_clip']\n self.n_hidden_units = guesser_conf['n_hidden_units']\n self.n_hidden_layers = guesser_conf['n_hidden_layers']\n self.lr = guesser_conf['lr']\n self.nn_dropout = guesser_conf['nn_dropout']\n self.sm_dropout = guesser_conf['sm_dropout']\n self.batch_size = guesser_conf['batch_size']\n self.use_wiki = guesser_conf['use_wiki']\n self.n_wiki_sentences = guesser_conf['n_wiki_sentences']\n self.wiki_title_replace_token = guesser_conf['wiki_title_replace_token']\n self.lowercase = guesser_conf['lowercase']\n self.tied_l2 = guesser_conf['tied_l2']\n\n self.page_field: Optional[Field] = None\n self.qnum_field: Optional[Field] = None\n self.text_field: Optional[Field] = None\n self.n_classes = None\n self.emb_dim = None\n\n self.model = None\n self.optimizer = None\n self.criterion = None\n self.scheduler = None\n\n @property\n def ans_to_i(self):\n return self.page_field.vocab.stoi\n\n @property\n def i_to_ans(self):\n return self.page_field.vocab.itos\n\n def parameters(self):\n return conf['guessers']['Tied'].copy()\n\n def train(self, training_data):\n log.info('Loading Quiz Bowl dataset')\n train_iter, val_iter, dev_iter = QuizBowl.iters(\n batch_size=self.batch_size, lower=self.lowercase,\n use_wiki=self.use_wiki, n_wiki_sentences=self.n_wiki_sentences,\n replace_title_mentions=self.wiki_title_replace_token\n )\n log.info(f'N Train={len(train_iter.dataset.examples)}')\n log.info(f'N Test={len(val_iter.dataset.examples)}')\n fields: Dict[str, Field] = train_iter.dataset.fields\n self.page_field = fields['page']\n self.n_classes = len(self.ans_to_i)\n self.qnum_field = fields['qnum']\n self.text_field = fields['text']\n self.emb_dim = self.text_field.vocab.vectors.shape[1]\n log.info(f'Vocab={len(self.text_field.vocab)}')\n\n log.info('Initializing Model')\n self.model = TiedModel(\n self.text_field, self.n_classes, emb_dim=self.emb_dim,\n n_hidden_units=self.n_hidden_units, n_hidden_layers=self.n_hidden_layers,\n nn_dropout=self.nn_dropout, sm_dropout=self.sm_dropout,\n )\n if CUDA:\n self.model = self.model.cuda()\n log.info(f'Parameters:\\n{self.parameters()}')\n log.info(f'Model:\\n{self.model}')\n self.optimizer = Adam(self.model.parameters(), lr=self.lr)\n self.criterion = nn.CrossEntropyLoss()\n self.scheduler = lr_scheduler.ReduceLROnPlateau(self.optimizer, patience=5, verbose=True, mode='max')\n\n manager = TrainingManager([\n BaseLogger(log_func=log.info), TerminateOnNaN(), EarlyStopping(monitor='test_acc', patience=10, verbose=1),\n MaxEpochStopping(100), ModelCheckpoint(create_save_model(self.model), '/tmp/rnn.pt', monitor='test_acc')\n ])\n\n log.info('Starting training')\n while True:\n self.model.train()\n train_acc, train_loss, train_time = self.run_epoch(train_iter)\n\n self.model.eval()\n test_acc, test_loss, test_time = self.run_epoch(val_iter)\n\n stop_training, reasons = manager.instruct(\n train_time, train_loss, train_acc,\n test_time, test_loss, test_acc\n )\n\n if stop_training:\n log.info(' '.join(reasons))\n break\n else:\n self.scheduler.step(test_acc)\n\n def run_epoch(self, iterator: Iterator):\n is_train = iterator.train\n batch_accuracies = []\n batch_losses = []\n epoch_start = time.time()\n for batch in iterator:\n text, lengths = batch.text\n page = batch.page\n qnums = batch.qnum.cuda()\n\n if is_train:\n self.model.zero_grad()\n\n out = self.model(text, lengths, qnums)\n _, preds = torch.max(out, 1)\n accuracy = torch.mean(torch.eq(preds, page).float()).data[0]\n batch_loss = self.criterion(out, page)\n if self.tied_l2 != 0:\n w_general = self.model.general_embeddings.weight\n w_source = self.model.wiki_embeddings.weight\n w_target = self.model.qb_embeddings.weight\n tied_weight_l2 = self.tied_l2 / 2 * (\n (w_general ** 2).sum() +\n ((w_source - w_general) ** 2).sum() +\n ((w_target - w_general) ** 2).sum()\n )\n batch_loss += tied_weight_l2\n if is_train:\n batch_loss.backward()\n torch.nn.utils.clip_grad_norm(self.model.parameters(), self.gradient_clip)\n self.optimizer.step()\n\n batch_accuracies.append(accuracy)\n batch_losses.append(batch_loss.data[0])\n\n epoch_end = time.time()\n\n return np.mean(batch_accuracies), np.mean(batch_losses), epoch_end - epoch_start\n\n def guess(self, questions: List[QuestionText], max_n_guesses: Optional[int]):\n examples = [self.text_field.preprocess(q) for q in questions]\n text, lengths = self.text_field.process(examples, None, False)\n qnums = self.qnum_field.process([0 for _ in questions]).cuda()\n guesses = []\n out = self.model(text, lengths, qnums)\n probs = F.softmax(out)\n scores, preds = torch.max(probs, 1)\n scores = scores.data.cpu().numpy()\n preds = preds.data.cpu().numpy()\n\n for p, s in zip(preds, scores):\n guesses.append([(self.i_to_ans[p], s)])\n\n return guesses\n\n\n def save(self, directory: str):\n shutil.copyfile('/tmp/rnn.pt', os.path.join(directory, 'rnn.pt'))\n with open(os.path.join(directory, 'rnn.pkl'), 'wb') as f:\n pickle.dump({\n 'page_field': self.page_field,\n 'text_field': self.text_field,\n 'qnum_field': self.qnum_field,\n 'n_classes': self.n_classes,\n 'emb_dim': self.emb_dim,\n 'gradient_clip': self.gradient_clip,\n 'n_hidden_units': self.n_hidden_units,\n 'n_hidden_layers': self.n_hidden_layers,\n 'lr': self.lr,\n 'nn_dropout': self.nn_dropout,\n 'sm_dropout': self.sm_dropout,\n 'batch_size': self.batch_size,\n 'use_wiki': self.use_wiki,\n 'n_wiki_sentences': self.n_wiki_sentences,\n 'wiki_title_replace_token': self.wiki_title_replace_token,\n 'lowercase': self.lowercase,\n 'tied_l2': self.tied_l2\n }, f)\n\n @classmethod\n def load(cls, directory: str):\n with open(os.path.join(directory, 'rnn.pkl'), 'rb') as f:\n params = pickle.load(f)\n\n guesser = TiedGuesser()\n guesser.page_field = params['page_field']\n guesser.text_field = params['text_field']\n guesser.qnum_field = params['qnum_field']\n guesser.n_classes = params['n_classes']\n guesser.emb_dim = params['emb_dim']\n guesser.gradient_clip = params['gradient_clip']\n guesser.n_hidden_units = params['n_hidden_units']\n guesser.n_hidden_layers = params['n_hidden_layers']\n guesser.lr = params['lr']\n guesser.nn_dropout = params['nn_dropout']\n guesser.sm_dropout = params['sm_dropout']\n guesser.use_wiki = params['use_wiki']\n guesser.n_wiki_sentences = params['n_wiki_sentences']\n guesser.wiki_title_replace_token = params['wiki_title_replace_token']\n guesser.lowercase = params['lowercase']\n guesser.tied_l2 = params['tied_l2']\n guesser.model = TiedModel(\n guesser.text_field, guesser.n_classes,\n init_embeddings=False, emb_dim=guesser.emb_dim\n )\n guesser.model.load_state_dict(torch.load(\n os.path.join(directory, 'rnn.pt'), map_location=lambda storage, loc: storage\n ))\n guesser.model.eval()\n if CUDA:\n guesser.model = guesser.model.cuda()\n return guesser\n\n @classmethod\n def targets(cls):\n return ['rnn.pt', 'rnn.pkl']\n\n # Runs query through the model and computes gradient based attacks\n \n def attack(self, query):\n text = TEXT.preprocess(query)\n text, lengths = self.text_field.process([text], None, False)\n \n text = TEXT.preprocess(query)\n text = [[TEXT.vocab.stoi[x] for x in text]]\n x = TEXT.tensor_type(text)\n lengths = torch.FloatTensor([x.size()[1]]).cuda()\n x = Variable(x).cuda()\n \n qnums = self.qnum_field.process([0]).cuda()\n y = self.model(x, lengths, qnums, extract_grad_hook('g_embed'))\n label = torch.max(y, 1)[1] # assume prediction is correct\n \n #print(self.i_to_ans[label.data.cpu().numpy()[0]]) #make sure label is the same as when you guess\n \n loss = criterion(y, label)\n self.model.zero_grad()\n loss.backward()\n \n grads = extracted_grads['g_embed'].transpose(0, 1)\n grads = grads.data.cpu() \n scores = grads.sum(dim=2).numpy()\n grads = grads.numpy()\n text = x.transpose(0, 1).data.cpu().numpy()\n y = y.data.cpu().numpy()\n \n scores = scores.tolist()\n sorted_scores = list(scores) # make copy\n sorted_scores.sort(reverse=True)\n \n # we want the line above for the general case, but for DAN all the gradients are the same for each word, so just pick some\n #order = [scores.index(index) for index in sorted_scores] \n order = random.sample(range(x.size()[1]), n_replace) \n \n returnVal = \"\"\n for j in order[:n_replace]:\n returnVal = returnVal + TEXT.vocab.itos[text[j][0]] + \"*\"\n old_embed = TEXT.vocab.vectors[text[j][0]].numpy()\n \n _, inds = tree.query([old_embed], k=2)\n repl = inds[0][0] if inds[0][0] != text[j] else inds[0][1] \n \n returnVal = returnVal + TEXT.vocab.itos[repl.item()] + \"**\"\n \n return returnVal\n #return \"Server*is**Not*Running**Currently*Please**Come*Back**Tomorrow*Thanks\"\n\n# Hyperparameters\nn_replace = 5\neps = 10\nnorm = np.inf\n\n# Load model\nsave_path = './output/guesser/qanta.guesser.tied.TiedGuesser/'\nguesser = TiedGuesser.load(save_path)\nTEXT = guesser.text_field\n\ndef attack(query):\n return guesser.attack(query)\n\n# Create KD tree for nearest neighbor\ntree = KDTree(TEXT.vocab.vectors.numpy())\nprint('KDTree built for {} words'.format(len(TEXT.vocab)))\n\ncriterion = nn.CrossEntropyLoss()\n\ndef to_numpy(x):\n if isinstance(x, Variable):\n x = x.data\n try:\n if x.is_cuda:\n x = x.cpu()\n except AttributeError:\n pass\n if isinstance(x, torch.LongTensor) or isinstance(x, torch.FloatTensor):\n x = x.numpy()\n return x\n\ndef to_sentence(words):\n words = to_numpy(words)\n words = [TEXT.vocab.itos[w] for w in words]\n words = [w for w in words if w != '']\n return ' '.join(words)\n\n","sub_path":"qanta/guesser/tied.py","file_name":"tied.py","file_ext":"py","file_size_in_byte":16817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"164015684","text":"import numpy as np\nimport os\nimport struct\n\ndef load_mnist(path, kind = 'train'):\n labels_path = os.path.join(path, '%s-labels-idx1-ubyte' %kind)\n images_path = os.path.join(path, '%s-images-idx3-ubyte' %kind)\n\n with open(labels_path, 'rb') as lbpath:\n magic, n = struct.unpack('>II', lbpath.read(8))#8byte 읽어오기\n#struct.unpack(fmt, buffer):\n#Unpack from the buffer buffer (presumably packed by pack(fmt, ...)) \n#according to the format string fmt. The result is a tuple even if it contains exactly one item. \n#format에서:\n#> : Big-endian is an order in which the \"big end\" (most significant value in the sequence) \n#is stored first\n#I = unsigned integer\n\n labels = np.fromfile(lbpath, dtype = np.uint8)\n#Construct an array from data in a text or binary file.\n#A highly efficient way of reading binary data with a known data-type, \n#as well as parsing simply formatted text files. \n#Data written using the tofile method can be read using this function. \n with open(images_path, 'rb') as imgpath:\n magic, num, rows, cols = struct.unpack(\">IIII\", imgpath.read(16))#16바이트 읽어오기\n \n images = np.fromfile(imgpath, dtype = np.uint8).reshape(len(labels), 784)\n \n return images, labels","sub_path":"chapter13/load_mnist.py","file_name":"load_mnist.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"511627694","text":"def get_int(start_message, error_message, end_message):\n print(start_message)\n while True:\n try:\n x = int(input())\n print(end_message)\n return x\n except ValueError:\n print(error_message)\n\n\nx = get_int('Input int number: ', 'Wrong value. Input int number:', 'Thank you.')\nprint(x)\n","sub_path":"stepik_python_tasks/5_23.py","file_name":"5_23.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"128501321","text":"#!/usr/bin/env python3\n\ndef pancake(stack):\n n = len(stack)\n f = '+'*n\n k = 0\n while stack != f:\n i = 0\n s = stack[0]\n while s == stack[0]:\n i += 1\n if i <= n-1:\n s = stack[i]\n else:\n break\n stack = return_pancake(stack, i)\n k += 1\n return k\n\ndef return_pancake(stack, i):\n s = list(stack)\n for j in range(i):\n if s[j] == '-':\n s[j] = '+'\n else:\n s[j] = '-'\n return \"\".join(s)\n\ndef print_answer(n, result):\n res = \"\"\n if type(result) in [list, tuple]:\n res = \" \".join(map(str, result))\n elif type(result) == int:\n res = str(result)\n elif type(result) == str:\n res = result\n print(\"Case #{}: {}\".format(n, res))\n\ndef main():\n T = int(input())\n for t in range(T):\n stack = input()\n print_answer(t + 1, pancake(stack))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"codes/CodeJamCrawler/16_0_2/glegoux/B-answer.py","file_name":"B-answer.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"227589597","text":"import typer\nfrom colorama import Fore, Back, Style, init\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport datetime\n\ninit()\n\nunprocessed_file = \"~/Sync/arxiv/unprocessed.csv\"\nprocessed_file = \"~/Sync/arxiv/processed.csv\"\n\napp = typer.Typer()\n\ndef install(section):\n url = f\"http://export.arxiv.org/rss/{section}\"\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"xml\")\n articles = soup.find(\"rdf:RDF\").find_all(\"item\")\n\n arts = []\n for article in articles:\n arts.append({\n \"time\": datetime.datetime.utcnow().isoformat(),\n \"section\": section,\n \"link\": article.find(\"link\").text,\n \"title\": article.find(\"title\").text.split(\" (arXiv\")[0]\n })\n\n already_processed = pd.read_csv(processed_file)[\"link\"].tolist()\n downloaded = pd.DataFrame(arts)\n downloaded = downloaded[~downloaded[\"link\"].isin(already_processed)]\n unprocessed = pd.read_csv(unprocessed_file)\n\n new = downloaded.append(unprocessed).drop_duplicates()\n new.to_csv(unprocessed_file, index=False)\n\n\n@app.command(\"install\")\ndef install_articles():\n typer.secho(\"installing computer vision\", fg=typer.colors.YELLOW)\n install(\"cs.CV\")\n typer.secho(\"installing artificial intelligence\", fg=typer.colors.YELLOW)\n install(\"cs.AI\")\n typer.secho(\"installing computation and language\", fg=typer.colors.YELLOW)\n install(\"cs.CL\")\n typer.secho(\"installing computers and society\", fg=typer.colors.YELLOW)\n install(\"cs.CY\")\n typer.secho(\"installing data structures and algorithms\", fg=typer.colors.YELLOW)\n install(\"cs.DS\")\n typer.secho(\"installing human-computer interaction\", fg=typer.colors.YELLOW)\n install(\"cs.HC\")\n typer.secho(\"installing information retrieval\", fg=typer.colors.YELLOW)\n install(\"cs.IR\")\n typer.secho(\"installing machine learning\", fg=typer.colors.YELLOW)\n install(\"cs.LG\")\n typer.secho(\"installing programming languages\", fg=typer.colors.YELLOW)\n install(\"cs.PL\")\n typer.secho(\"installing statistics\", fg=typer.colors.YELLOW)\n install(\"stat\")\n\n\n\n@app.command(\"review\")\ndef review():\n to_process = pd.read_csv(\"~/Sync/arxiv/unprocessed.csv\")[[\"link\", \"title\"]]\n shuffled = to_process.sample(frac=1)\n\n to_review = shuffled.head(10).to_dict(orient='records')\n\n reviewed = []\n for article in to_review:\n typer.secho(article[\"title\"], fg=typer.colors.GREEN)\n save = typer.prompt(\"save? [y/n]\")\n if save.lower() in [\"y\", \"yes\"]:\n os.system(f\"buku -a {article['link']}\")\n reviewed.append(article[\"link\"])\n\n unprocessed = to_process[~to_process[\"link\"].isin(reviewed)]\n processed = to_process[to_process[\"link\"].isin(reviewed)]\n\n already_processed = pd.read_csv(processed_file)\n already_processed.append(processed).drop_duplicates().to_csv(processed_file, index=False)\n unprocessed.to_csv(unprocessed_file, index=False)\n\n typer.secho(f\"{unprocessed.shape[0]} left to process\", fg=typer.colors.YELLOW)\n","sub_path":"arxiv/arxiv/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"422570690","text":"# -*- coding: utf-8 -*-\nfrom django import forms\n\nfrom django.forms.widgets import HiddenInput\nfrom django.utils.translation import ugettext_lazy as _\nfrom core.models import Address, Photo, Response, Message, ReportError,\\\n ReportContent, ReportUser, Comment, ErrorType\nclass CommentForm( forms.ModelForm ):\n class Meta:\n model = Comment\n fields = [\"text\", \"content\" ]\n widgets = {\n 'content': HiddenInput()\n }\nclass ReportUserForm( forms.ModelForm ):\n class Meta:\n model = ReportUser\n fields = [ \"user\", \"comment\", \"reason\" ]\n widgets = {\n \"user\" : forms.HiddenInput()\n }\n \nclass ReportContentForm( forms.ModelForm ):\n class Meta:\n model = ReportContent\n fields = [ \"content\", \"comment\", \"reason\" ]\n widgets = {\n \"content\" : forms.HiddenInput()\n }\nclass ReportErrorForm( forms.ModelForm ):\n class Meta:\n model = ReportError\n fields = [ \"type\", \"comment\" ]\n widgets = {\n \"type\": forms.Select( choices = ErrorType.objects.all() )\n }\n \nclass MessageForm( forms.Form ):\n title = forms.CharField( max_length = 255 )\n users = forms.CharField()\n text = forms.CharField( widget = forms.Textarea() )\n \n \nclass ResponseForm( forms.ModelForm ):\n class Meta:\n model = Response\n fields = [ \"message\", \"text\" ]\n widgets = { \"message\" : forms.HiddenInput() }\nclass ProfilePhotoForm( forms.ModelForm ):\n class Meta:\n model = Photo\n fields = [\"image\"]\nclass AddressForm( forms.ModelForm ):\n class Meta:\n model = Address\n exclude = [ \"user\" ]\n \n\nclass RegisterForm( forms.Form ):\n username = forms.CharField( max_length = 32 )\n password = forms.CharField( \n max_length = 32, \n widget = forms.widgets.PasswordInput(),\n \n )\n repassword = forms.CharField( max_length = 32, widget = forms.widgets.PasswordInput() )\n first_name = forms.CharField( max_length = 255 )\n last_name = forms.CharField( max_length = 255 )\n email = forms.EmailField()\n captcha_id = forms.IntegerField( widget = forms.widgets.HiddenInput() )\n captcha = forms.CharField( max_length = 8 )","sub_path":"core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"492695243","text":"import os\nimport GLOVAR as gl\n\n# initialization\ngl._init()\n\nsoftware_home = '/home/export/online1/amd_dev1/software'\n#software_home = '/home/export/online1/amd_dev1/liuhb/hsf/library'\nhdf5_path = software_home + '/HDF5/hdf5-1.10.5/gcc_build'\ncgns_path = software_home + '/CGNS/CGNS-3.4.0/src/SampleScripts'\n#yaml_path = software_home + '/yaml-cpp/yaml-cpp-0.6.2'\nyaml_path = software_home + '/yaml-cpp/yaml-cpp-yaml-cpp-0.5.3'\n\nparmetis_path = software_home + '/ParMETIS/parmetis-4.0.3/gccInstall_64_64'\n\n\n# Set our required environment\nlibraries \t\t= ['yaml-cpp', 'cgns', 'hdf5', 'parmetis', 'metis', 'stdc++', 'm', 'z', 'dl']\nlibrary_paths \t= [hdf5_path + '/lib',\n\t\t\t\t cgns_path + '/lib',\n\t\t\t\t parmetis_path + '/lib',\n\t\t\t\t yaml_path + '/lib']\ncppDefines \t\t= {}\n#cppFlags \t\t= ['-fPIC', '-MMD', '-MP', '-DSCALAR_FLOAT64']\ncppFlags \t\t= ['-fPIC', '-DSCALAR_FLOAT64', '-Wno-write-strings']\ndebugFlags = ['-g', '-O0', '-DDEBUG', '-Wall', '-Wextra', '-Werror', '-fno-elide-constructors']\n#debugFlags = ['-g']\noptFlags\t\t= ['-O2']\nf90Flags\t\t= ['-g', '-fcray-pointer']\n\n# define the attributes of the build environment\nenv = Environment(ENV = os.environ)\nenv.Append(LIBS \t = libraries)\nenv.Append(LIBPATH \t\t= library_paths)\nenv.Append(CPPDEFINES \t= cppDefines)\nenv.Append(CPPFLAGS \t= cppFlags)\nenv.Append(F90FLAGS \t= f90Flags)\nenv.Append(CCCOMSTR = \"CC $SOURCES\")\n#env.Append(LINKCOMSTR = \"LINK $TARGET\")\n\n# get debug flag, the default is -O3\ndebug = ARGUMENTS.get('debug', '')\nDBGFLAG = ''\n\nif debug == 'true':\n\tenv.Append(CPPFLAGS = debugFlags)\n\tDBGFLAG = 'Debug'\nelse:\n\tenv.Append(CPPFLAGS = optFlags)\n\tDBGFLAG = 'Opt'\n\nSWOPT = ''\nINTFLAG = '-DLABEL_INT64'\nINTSize = ''\n\nif INTFLAG == '-DLABEL_INT32':\n INTSize = 'Int32'\nelif INTFLAG == '-DLABEL_INT64':\n INTSize = 'Int64'\nelse:\n print('Error: label size is not defined!')\n\nenv.Append(CPPFLAGS = INTFLAG)\n\n\n# get platform information, the default is x86\n# if sw preferred, using \"scons pla=sw\"\ngl.platform = ARGUMENTS.get('pla', 'x86')\n\nif gl.platform == 'sw':\n\tenv['CC'] = 'sw5cc'\n\tenv['CXX'] = 'swg++453'\n\tenv['F90'] = 'mpif90'\n\tenv['AR'] = 'swar'\n\tenv['LINK'] = 'swg++453'\n\tenv.Append(CPPPATH = ['/usr/sw-mpp/mpi2/include'])\nelse:\n\n\tmpi_path = software_home + '/MPICH/gcc_build'\n\tenv['CC'] = mpi_path + '/bin/mpicc'\n\tenv['CXX'] = mpi_path + '/bin/mpicxx'\n\tenv['F90'] = mpi_path + '/bin/mpifort'\n\t#env['AR'] = 'ar'\n\t#env['LINK'] = software_home + '/MPICH/bin/mpicc'\n\t#env['LINK'] = software_home + '/MPICH/bin/mpicxx'\n\tenv.Append(CPPPATH = [cgns_path + '/include'])\n\tenv.Append(CPPPATH = [mpi_path + '/include'])\n\tenv.Append(CPPPATH = [parmetis_path + '/include'])\n\tenv.Append(CPPPATH = [yaml_path + '/include'])\n\tenv.Append(F90PATH = [mpi_path + '/include'])\n\n\t# for unap\n\tenv.Append(CPPPATH = ['/home/export/online1/amd_dev1/guhf/unap/x86Install/include'])\n\n# env['LINKFLAGS'] = '-lstdc++'\n\nExport('env')\n\nsrc_name = 'src'\nbuild_name = 'build'\ntest_name = 'test'\n\ngl.include_path = gl.root_path + '/' + build_name + '/Include'\nprint(gl.root_path)\n\n# add include path to -I\nenv.Append(CPPPATH = gl.include_path)\n\nCXXNAME = os.path.basename(env['CXX'])\n\ngl.fullName = CXXNAME + DBGFLAG + INTSize + SWOPT\ngl.build_path = gl.root_path + '/' + build_name + '/' + gl.fullName\ngl.source_path = gl.root_path + '/' + src_name\nbuild_src_path = gl.build_path + '/' + src_name\nbuild_test_path = gl.build_path + '/' + test_name\n\n# out of source compiling settings\nenv.VariantDir(build_src_path, gl.source_path, duplicate=1)\nenv.SConscript(build_src_path + '/SConscript', duplicate=0, exports = 'env' )\n\nenv.VariantDir(build_test_path, gl.root_path + '/' + test_name, duplicate=1)\nenv.SConscript(build_test_path + '/SConscript', duplicate=0, exports = 'env' )\n","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"183933816","text":"import os\nimport os.path as osp\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom layers.detection2 import Detect\nfrom models.vgg import vgg, base_config\nfrom layers.block import BasicConv\nfrom utils.init import xavier_init\n\n\nclass FSSD(nn.Module):\n\n \"\"\"\n FSSD architecture\n \"\"\"\n\n def __init__(self,\n mode,\n base,\n extras,\n fusion_module,\n pyramid_module,\n head,\n anchors,\n class_count):\n super(FSSD, self).__init__()\n self.mode = mode\n self.base = nn.ModuleList(base)\n self.extras = nn.ModuleList(extras)\n self.fusion_module = nn.ModuleList(fusion_module)\n self.bn = nn.BatchNorm2d(num_features=256 * len(self.fusion_module))\n self.pyramid_module = nn.ModuleList(pyramid_module)\n\n self.class_head = nn.ModuleList(head[0])\n self.loc_head = nn.ModuleList(head[1])\n self.anchors = anchors\n self.class_count = class_count\n\n if mode == 'test':\n self.softmax = nn.Softmax(dim=-1)\n self.detect = Detect(class_count)\n\n def forward(self, x):\n sources = []\n class_preds = []\n loc_preds = []\n\n b, _, _, _ = x.shape\n # apply vgg up to conv4_3 relu\n for i in range(23):\n x = self.base[i](x)\n sources.append(x)\n\n # apply vgg up to fc7\n for i in range(23, len(self.base)):\n x = self.base[i](x)\n sources.append(x)\n\n for layer in self.extras:\n x = F.relu(layer(x), inplace=True)\n sources.append(x)\n\n features = []\n assert len(self.fusion_module) == len(sources)\n for i, layer in enumerate(self.fusion_module):\n features.append(layer(sources[i]))\n\n features = torch.cat(features, 1)\n x = self.bn(features)\n\n feature_pyramid = []\n for layer in self.pyramid_module:\n x = layer(x)\n feature_pyramid.append(x)\n\n # apply multibox head to sources\n for (x, c, l) in zip(feature_pyramid, self.class_head, self.loc_head):\n class_preds.append(c(x).permute(0, 2, 3, 1).contiguous())\n loc_preds.append(l(x).permute(0, 2, 3, 1).contiguous())\n\n class_preds = torch.cat([pred.view(b, -1) for pred in class_preds], 1)\n loc_preds = torch.cat([pred.view(b, -1) for pred in loc_preds], 1)\n\n class_preds = class_preds.view(b, -1, self.class_count)\n loc_preds = loc_preds.view(b, -1, 4)\n\n if self.mode == \"test\":\n output = self.detect(\n self.softmax(class_preds),\n loc_preds,\n self.anchors\n )\n else:\n output = (\n class_preds,\n loc_preds\n )\n return output\n\n def init_weights(self, model_save_path, basenet):\n if basenet:\n weights_path = osp.join(model_save_path, basenet)\n vgg_weights = torch.load(weights_path)\n self.base.load_state_dict(vgg_weights)\n else:\n self.base.apply(fn=xavier_init)\n self.extras.apply(fn=xavier_init)\n self.fusion_module.apply(fn=xavier_init)\n self.pyramid_module.apply(fn=xavier_init)\n self.class_head.apply(fn=xavier_init)\n self.loc_head.apply(fn=xavier_init)\n\n def load_weights(self, base_file):\n other, ext = os.path.splitext(base_file)\n if ext == '.pkl' or '.pth':\n print('Loading weights into state dict...')\n self.load_state_dict(torch.load(base_file,\n map_location=lambda storage, loc: storage))\n print('Finished!')\n else:\n print('Sorry only .pth and .pkl files supported.')\n\n\ndef get_extras(config, in_channels, batch_norm=False):\n layers = []\n flag = False\n\n for k, v in enumerate(config):\n if in_channels != 'S':\n if v == 'S':\n layers += [nn.Conv2d(in_channels=in_channels,\n out_channels=config[k + 1],\n kernel_size=(1, 3)[flag],\n stride=2,\n padding=1)]\n else:\n layers += [nn.Conv2d(in_channels=in_channels,\n out_channels=v,\n kernel_size=(1, 3)[flag])]\n flag = not flag\n in_channels = v\n\n return layers\n\n\ndef get_fusion_module(config, vgg, extras):\n\n layers = []\n # conv4_3\n layers += [BasicConv(in_channels=vgg[24].out_channels,\n out_channels=256,\n kernel_size=1)]\n # fc_7\n layers += [BasicConv(in_channels=vgg[-2].out_channels,\n out_channels=256,\n kernel_size=1,\n up_size=config)]\n\n layers += [BasicConv(in_channels=extras[-1].out_channels,\n out_channels=256,\n kernel_size=1,\n up_size=config)]\n\n return layers\n\n\ndef get_pyramid_module(config):\n\n layers = []\n\n for layer in config:\n layers += [BasicConv(in_channels=layer[0],\n out_channels=layer[1],\n kernel_size=layer[2],\n stride=layer[3],\n padding=layer[4])]\n\n return layers\n\n\ndef multibox(config, class_count):\n class_layers = []\n loc_layers = []\n\n for in_channels, num_anchors in config:\n class_layers += [nn.Conv2d(in_channels=in_channels,\n out_channels=num_anchors * class_count,\n kernel_size=3,\n padding=1)]\n loc_layers += [nn.Conv2d(in_channels=in_channels,\n out_channels=num_anchors * 4,\n kernel_size=3,\n padding=1)]\n\n return class_layers, loc_layers\n\n\nextras_config = {\n '300': [256, 512, 128, 'S', 256],\n '512': [256, 512, 128, 'S', 256]\n}\nfusion_config = {\n '300': 38,\n '512': 64\n}\npyramid_config = {\n '300': [[256 * 3, 512, 3, 1, 1],\n [512, 512, 3, 2, 1],\n [512, 256, 3, 2, 1],\n [256, 256, 3, 2, 1],\n [256, 256, 3, 1, 0],\n [256, 256, 3, 1, 0]],\n\n '512': [[256 * 3, 512, 3, 1, 1],\n [512, 512, 3, 2, 1],\n [512, 256, 3, 2, 1],\n [256, 256, 3, 2, 1],\n [256, 256, 3, 2, 1],\n [256, 256, 3, 2, 1],\n [256, 256, 4, 1, 1]]\n}\nmbox_config = {\n '300': [(512, 4),\n (512, 6),\n (256, 6),\n (256, 6),\n (256, 4),\n (256, 4)],\n '512': [(512, 4),\n (512, 6),\n (256, 6),\n (256, 6),\n (256, 6),\n (256, 4),\n (256, 4)]\n}\n\n\ndef build_fssd(mode, new_size, anchors, class_count):\n\n base = vgg(config=base_config[str(new_size)],\n in_channels=3)\n\n extras = get_extras(config=extras_config[str(new_size)],\n in_channels=1024)\n\n fusion_module = get_fusion_module(config=fusion_config[str(new_size)],\n vgg=base,\n extras=extras)\n\n pyramid_module = get_pyramid_module(config=pyramid_config[str(new_size)])\n\n head = multibox(config=mbox_config[str(new_size)],\n class_count=class_count)\n\n return FSSD(mode, base, extras, fusion_module,\n pyramid_module, head, anchors, class_count)\n","sub_path":"models/fssd.py","file_name":"fssd.py","file_ext":"py","file_size_in_byte":7769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"354164770","text":"# -*- coding: utf-8 -*-\r\nimport sys\r\nimport os\r\nimport glob\r\nimport configparser\r\nfrom bs4 import BeautifulSoup\r\nsys.path.insert(0, '/web/pluto/')\r\nimport scraper.wiki as wk\r\nimport parse.wiki.navbox as nb\r\nimport parse.wiki.infobox as info\r\nimport parse.wiki.content as ct\r\nimport parse.wiki.categoryPage as cp\r\nimport parse.wiki.categoryBox as cb\r\nimport graph.node as nd\r\nimport graph.relationship as rl\r\nimport urllib\r\n\r\nconfig = configparser.ConfigParser()\r\nconfigPath = './config/data.cfg'\r\nconfig.read(configPath)\r\ndataDir = config['data']['dataDir']\r\n#print(dataDir)\r\nunfinishedKeywordsFile = './log/unfinishedKeywords.log' \r\nlogDir = './log/doneKeywords.log'\r\n\r\nif not os.path.isdir(dataDir):\r\n os.mkdir(dataDir)\r\nif not os.path.isdir(dataDir + 'graph'):\r\n os.mkdir(dataDir + 'graph')\r\n os.mkdir(dataDir + 'graph/nodes')\r\n os.mkdir(dataDir + 'graph/relationships')\r\nif not os.path.isdir(dataDir + 'html'):\r\n os.mkdir(dataDir + 'html')\r\nif not os.path.isdir(dataDir + 'graph/nodes'):\r\n os.mkdir(dataDir + 'graph/nodes')\r\nif not os.path.isdir(dataDir + 'graph/relationships'):\r\n os.mkdir(dataDir + 'graph/relationships')\r\n\r\n\r\ndef iterateScrapeCategories(catbox, depth=0, depthLimit=1):\r\n print('Iteratively scrape categories...')\r\n print('now at depth', depth)\r\n catUrls = []\r\n for category in catbox['categories']:\r\n if 'url' in category.keys():\r\n catUrls.append(category['url'])\r\n #catUrls = [category['url'] for category in catbox['categories']]\r\n catResUrls = wk.scrapeUrls(catUrls)\r\n \r\n for catResUrl in catResUrls:\r\n print('Categories ', '(', catResUrls.index(catResUrl)+1, '/', len(catResUrl), ')')\r\n catName = catResUrl.replace('https://en.wikipedia.org/wiki/','')\r\n with open(dataDir + 'html/en.wikipedia.org--' + catName + '.html', 'rb') as f:\r\n html = f.read()\r\n catSoup = BeautifulSoup(html, 'lxml')\r\n categoryPage = cp.parse(catSoup)\r\n if categoryPage:\r\n nd.createNodesFromCategoryPage(categoryPage)\r\n \r\n#create relationships from categoryPage\r\n rl.createRelationshipFromCategoryPage(categoryPage)\r\n catbox1 = cb.parse(catSoup, catResUrl)\r\n \r\n if depth < depthLimit:\r\n iterateScrapeCategories(catbox1, depth+1)\r\n\r\n#keywordsConfigFile \r\ndef scrapeKeywords(keywords):\r\n #read keywords\r\n #print('Now scraping from keywords: ', keywordsConfigFile.split('/')[-1])\r\n \r\n# with open(keywordsConfigFile, 'r') as f:\r\n# keywords = [word.strip() for word in f.read().split(',')] \r\n \r\n #scrape keyword\r\n responsesUrl = wk.scrape(keywords)\r\n catboxes = []\r\n for responseUrl in responsesUrl:\r\n #print(keyword)\r\n #parse page to get elements\r\n print('Keyword ', '(', responsesUrl.index(responseUrl)+1, '/', len(responsesUrl), '): ', keywords[responsesUrl.index(responseUrl)])\r\n \r\n name = responseUrl.replace('https://en.wikipedia.org/wiki/','')\r\n try:\r\n with open(dataDir + 'html/en.wikipedia.org--' + name + '.html', 'rb') as f:\r\n html = f.read()\r\n except FileNotFoundError:\r\n continue\r\n soup = BeautifulSoup(html, 'lxml')\r\n \r\n #infobox\r\n infoBox = info.parse(info.infobox(soup))\r\n \r\n #navbox, as tables.\r\n n = nb.navboxes(soup)\r\n tables = []\r\n if n is not None:\r\n for navbox in n:\r\n d = nb.tableToKeyValue(navbox['navbox'])\r\n tables.append({'main':navbox['main'], 'navbox':d})\r\n #print(d)\r\n \r\n #content\r\n content = ct.extractContent(soup, responseUrl)\r\n \r\n #catbox\r\n catbox = cb.parse(soup, responseUrl)\r\n if catbox:\r\n catboxes.append(catbox)\r\n #create node from page, update properties from infobox\r\n nd.updateNodeFromPage(content, infoBox, responseUrl)\r\n \r\n \r\n #create nodes and labels from navbox, catbox\r\n nd.createNodesFromCategoryBox(catbox)\r\n \r\n #scrape all pages, and categoryPage# if tables != []:\r\n [nd.createNodeFromNavbox(table['navbox']) for table in tables]\r\n [nd.createMainNodeFromNavbox(table) for table in tables]\r\n if catbox:\r\n nd.labelNodeByCategoryBox(catbox)\r\n \r\n #create relationships from navbox, catbox\r\n rl.createRelationshipFromCategoryBox(catbox)\r\n [rl.createRelationshipFromNavbox(table) for table in tables]\r\n \r\n return catboxes\r\n\r\ndef queryUnfinishedKeywords(label=True):\r\n #Query all unfinished nodes, and schedule them into new keywords.cfg (unfinishedKeywords.cfg).\r\n \r\n path = dataDir + 'graph/nodes/'\r\n nodeFiles = [f for f in glob.glob(path + \"*.txt\")]\r\n print('nodes count: ', len(nodeFiles))\r\n kws = []\r\n \r\n try:\r\n with open(logDir,'r') as g:\r\n done = list(set([d.strip() for d in g.readlines()]))\r\n \r\n except FileNotFoundError:\r\n done = []\r\n \r\n \r\n for nodeFile in nodeFiles:\r\n with open(nodeFile, 'r') as g:\r\n lines = g.readlines()\r\n c = 0\r\n d = 0\r\n for line in lines:\r\n \r\n if 'label = ' in line:\r\n c += 1\r\n if 'definition = ' in line:\r\n d += 1\r\n if ((label and c == 0) or d == 0) and 'url = None' not in lines:\r\n name = nodeFile.split('/')[-1].replace('.txt','')\r\n #print(name, file=f)\r\n kws.append(name)\r\n else:\r\n name = nodeFile.split('/')[-1].replace('.txt','')\r\n done.append(name)\r\n with open(unfinishedKeywordsFile,'w') as f:\r\n [print(kw, file=f) for kw in kws]\r\n #print(kws)\r\n with open(logDir,'w') as h:\r\n [print(x, file=h) for x in done]\r\n return kws\r\n\r\n\r\ndef iterateScrapeKeywords(keywords, loopCount=0, loopLimit=0):\r\n \r\n with open(logDir,'r') as g:\r\n done = [d.strip() for d in g.readlines()]\r\n \r\n kwlist = []\r\n for keyword in keywords:\r\n if keyword not in done:\r\n kwlist.append(keyword)\r\n catboxes = scrapeKeywords(kwlist)\r\n\r\n ##scrape for nodes and relationships from catboxes\r\n [iterateScrapeCategories(catbox) for catbox in catboxes]\r\n \r\n ks = queryUnfinishedKeywords()\r\n updateKeywords(ks)\r\n print('iterateScrapeKeywords loop round completed: ', loopCount)\r\n if loopCount < loopLimit:\r\n with open(unfinishedKeywordsFile, 'r') as f:\r\n kws = [d.strip() for d in f.readlines()]\r\n iterateScrapeKeywords(kws, loopCount+1)\r\n \r\ndef updateKeywords(keywords):\r\n #read keywords\r\n #print('Now scraping from keywords: ', keywordsConfigFile.split('/')[-1])\r\n \r\n# with open(keywordsConfigFile, 'r') as f:\r\n# keywords = [word.strip() for word in f.read().split(',')] \r\n \r\n #scrape keyword\r\n responsesUrl = wk.scrape(keywords)\r\n\r\n for responseUrl in responsesUrl:\r\n #print(keyword)\r\n #parse page to get elements\r\n print('Keyword ', '(', responsesUrl.index(responseUrl)+1, '/', len(responsesUrl), '): ', keywords[responsesUrl.index(responseUrl)])\r\n \r\n name = responseUrl.replace('https://en.wikipedia.org/wiki/','')\r\n try:\r\n with open(dataDir + 'html/en.wikipedia.org--' + name + '.html', 'rb') as f:\r\n html = f.read()\r\n except (FileNotFoundError, OSError):\r\n continue\r\n soup = BeautifulSoup(html, 'lxml')\r\n \r\n #infobox\r\n infoBox = info.parse(info.infobox(soup))\r\n \r\n #content\r\n content = ct.extractContent(soup, responseUrl)\r\n \r\n #catbox\r\n catbox = cb.parse(soup, responseUrl)\r\n\r\n #create node from page, update properties from infobox\r\n nd.updateNodeFromPage(content, infoBox, responseUrl)\r\n \r\n #create nodes and labels from catbox\r\n\r\n if catbox:\r\n nd.labelNodeByCategoryBox(catbox)\r\n \r\ndef updateKeywordsFromHtmls(keywords):\r\n #read keywords\r\n #print('Now scraping from keywords: ', keywordsConfigFile.split('/')[-1])\r\n \r\n# with open(keywordsConfigFile, 'r') as f:\r\n# keywords = [word.strip() for word in f.read().split(',')] \r\n \r\n #scrape keyword\r\n #responsesUrl = wk.scrape(keywords)\r\n\r\n for keyword in keywords:\r\n #print(keyword)\r\n #parse page to get elements\r\n print('Keyword ', '(', keywords.index(keyword)+1, '/', len(keywords), '): ', keyword)\r\n \r\n name = urllib.parse.quote(keyword)\r\n responseUrl = 'https://en.wikipedia.org/wiki/' + name\r\n try:\r\n with open(dataDir + 'html/en.wikipedia.org--' + name + '.html', 'rb') as f:\r\n html = f.read()\r\n except (FileNotFoundError, OSError):\r\n continue\r\n soup = BeautifulSoup(html, 'lxml')\r\n \r\n #infobox\r\n infoBox = info.parse(info.infobox(soup))\r\n \r\n #content\r\n content = ct.extractContent(soup, responseUrl)\r\n \r\n #catbox\r\n catbox = cb.parse(soup, responseUrl)\r\n\r\n #create node from page, update properties from infobox\r\n nd.updateNodeFromPage(content, infoBox, responseUrl)\r\n \r\n #create nodes and labels from catbox\r\n\r\n if catbox:\r\n nd.labelNodeByCategoryBox(catbox)\r\n \r\ndef updateKeywordsFromHtmlsWithouLabelling(keywords):\r\n #read keywords\r\n #print('Now scraping from keywords: ', keywordsConfigFile.split('/')[-1])\r\n \r\n# with open(keywordsConfigFile, 'r') as f:\r\n# keywords = [word.strip() for word in f.read().split(',')] \r\n \r\n #scrape keyword\r\n #responsesUrl = wk.scrape(keywords)\r\n\r\n for keyword in keywords:\r\n #print(keyword)\r\n #parse page to get elements\r\n print('Keyword ', '(', keywords.index(keyword)+1, '/', len(keywords), '): ', keyword)\r\n \r\n name = urllib.parse.quote(keyword)\r\n responseUrl = 'https://en.wikipedia.org/wiki/' + name\r\n try:\r\n with open(dataDir + 'html/en.wikipedia.org--' + name + '.html', 'rb') as f:\r\n html = f.read()\r\n except (FileNotFoundError, OSError):\r\n continue\r\n soup = BeautifulSoup(html, 'lxml')\r\n \r\n #infobox\r\n infoBox = info.parse(info.infobox(soup))\r\n \r\n #content\r\n content = ct.extractContent(soup, responseUrl)\r\n\r\n #create node from page, update properties from infobox\r\n nd.updateNodeFromPage(content, infoBox, responseUrl)\r\n \r\ndef updateKeywordsFromWebWithouLabelling(keywords):\r\n #read keywords\r\n #print('Now scraping from keywords: ', keywordsConfigFile.split('/')[-1])\r\n \r\n# with open(keywordsConfigFile, 'r') as f:\r\n# keywords = [word.strip() for word in f.read().split(',')] \r\n \r\n #scrape keyword\r\n responsesUrl = wk.scrape(keywords)\r\n\r\n for responseUrl in responsesUrl:\r\n #print(keyword)\r\n #parse page to get elements\r\n print('Keyword ', '(', responsesUrl.index(responseUrl)+1, '/', len(responsesUrl), '): ', keywords[responsesUrl.index(responseUrl)])\r\n \r\n name = responseUrl.replace('https://en.wikipedia.org/wiki/','')\r\n try:\r\n with open(dataDir + 'html/en.wikipedia.org--' + name + '.html', 'rb') as f:\r\n html = f.read()\r\n except (FileNotFoundError, OSError):\r\n continue\r\n soup = BeautifulSoup(html, 'lxml')\r\n \r\n #infobox\r\n infoBox = info.parse(info.infobox(soup))\r\n \r\n #content\r\n content = ct.extractContent(soup, responseUrl)\r\n\r\n #create node from page, update properties from infobox\r\n nd.updateNodeFromPage(content, infoBox, responseUrl)\r\n\r\n############################################################\r\n#initialKeywordsFile = './config/keywords.cfg' \r\n#doneKeywordsFile = './log/doneKeywords.log' \r\n#unfinishedKeywordsFile = './log/unfinishedKeywords.log' \r\n#queryUnfinishedKeywords()\r\n#\r\n#with open(initialKeywordsFile, 'r') as f:\r\n# initialKeywords = [d.strip() for d in f.readlines()] \r\n#with open(doneKeywordsFile, 'r') as f:\r\n# doneKeywords = [d.strip() for d in f.readlines()] \r\n# \r\n#doneKeywords = []\r\n#with open(unfinishedKeywordsFile, 'r') as f:\r\n# unfinishedKeywords = [d.strip() for d in f.readlines()] \r\n##print(keywords)\r\n# \r\n#keywords = []\r\n#for k in initialKeywords:\r\n# if k not in doneKeywords:\r\n# keywords.append(k)\r\n#print(keywords)\r\n#\r\n#keywords += list(set(unfinishedKeywords))\r\n# \r\n#iterateScrapeKeywords(keywords)\r\n\r\nks = queryUnfinishedKeywords(label=True)\r\nprint(len(ks))\r\n\r\n#updateKeywords(ks)\r\nupdateKeywordsFromHtmls(ks)\r\n#updateKeywordsFromHtmlsWithouLabelling(ks)\r\n#updateKeywordsFromWebWithouLabelling(ks)\r\nnd.labelNodesFromRelationship()\r\nnd.formatLabels() \r\nqueryUnfinishedKeywords() \r\n \r\n\r\n\r\n\r\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":12960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"29225225","text":"#! python3\r\n# lowercase_count\r\n# Simply calculate the amount of lowercase characters in a fasta file to estimate\r\n# the proportion of the genome that is repetitive\r\n\r\nimport os, argparse, locale\r\nlocale.setlocale(locale.LC_ALL, '')\r\n\r\ndef n_lower_chars(string):\r\n return sum(1 for c in string if c.islower())\r\n\r\n##### USER INPUT SECTION\r\n\r\nusage = \"\"\"%(prog)s reads in a provided fasta file and calculates the proportion of\r\nthe genome that is lowercase\r\n\"\"\"\r\np = argparse.ArgumentParser(description=usage)\r\np.add_argument(\"-i\", \"--input\", dest=\"input\",\r\n help=\"fasta file name\")\r\np.add_argument(\"-o\", \"--output\", dest=\"output\",\r\n help=\"output file name\")\r\n\r\n# Parse arguments\r\nargs = p.parse_args()\r\ninName = args.input\r\noutName = args.output\r\n\r\nif os.path.isfile(outName):\r\n print(outName + ' already exists, specify a new name')\r\n quit()\r\n\r\n##### CORE PROCESS\r\n\r\n# Count the number of lowercase characters\r\nlowercase = 0\r\ntotal = 0\r\nwith open(inName, 'rU') as inFile, open(outName, 'w') as outFile:\r\n for line in inFile:\r\n if line.startswith('>'):\r\n continue\r\n else:\r\n total += len(line.rstrip('\\n'))\r\n lowercase += n_lower_chars(line.rstrip('\\n'))\r\n # Print results and generate output file\r\n genomeSize = locale.format(\"%d\", total, grouping=True)\r\n print('Genome size: ' + genomeSize)\r\n outFile.write('Genome size: ' + genomeSize + '\\n')\r\n repeats = locale.format(\"%d\", lowercase, grouping=True)\r\n print('Lowercase bp: ' + repeats)\r\n outFile.write('Lowercase bp: ' + repeats + '\\n')\r\n proportion = str(lowercase/total)\r\n print('Lowercase proportion: ' + proportion)\r\n outFile.write('Lowercase proportion: ' + proportion + '\\n') \r\n# Done!\r\n","sub_path":"lowercase_count.py","file_name":"lowercase_count.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"653977617","text":"# TO-DO: complete the helpe function below to merge 2 sorted arrays\ndef merge( arrA, arrB ):\n elements = len( arrA ) + len( arrB )\n merged_arr = [0] * elements\n # TO-DO\n # print(merged_arr)\n for j in range(len(arrA)):\n # print(j)\n merged_arr[j] = arrA[j]\n for j in range(len(arrB)):\n # print(j)\n merged_arr[j+len(arrA)] = arrB[j]\n return merged_arr\n\narrayA = [1,2,3,5,4,8,9]\narrayB = [5,6,9,7,8,5]\n\n# print(merge(arrayA, arrayB))\n\n# TO-DO: implement the Merge Sort function below USING RECURSION\ndef merge_sort( arr ):\n # TO-DO\n # sortedarr = [0] * len(arr)\n if len(arr) > 1:\n arr1 = arr[:len(arr)//2]\n # print(arr1)\n arr2 = arr[len(arr)//2:]\n # print(arr2)\n merge_sort(arr1)\n merge_sort(arr2)\n left = mid = right = 0\n # if arr[0] > sortedarr[i]:\n # i+=1\n # sortedarr.append(arr)\n while left < len(arr1) and mid < len(arr2):\n if arr1[left] < arr2[mid]:\n arr[right] = arr1[left]\n left+=1\n else:\n arr[right] = arr2[mid]\n mid+=1\n right+=1\n while left < len(arr1):\n arr[right] = arr1[left]\n left+=1\n right+=1\n while mid < len(arr2):\n arr[right] = arr2[mid]\n mid+=1\n right+=1\n return arr\n \n # return sortedarr\n \n\n\n\n# merge_sort(arrayA)\n# print(arrayA)\n\n# STRETCH: implement an in-place merge sort algorithm\ndef merge_in_place(arr, start, mid, end):\n # TO-DO\n\n return arr\n\ndef merge_sort_in_place(arr, l, r): \n # TO-DO\n\n return arr\n\n\n# STRETCH: implement the Timsort function below\n# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt\ndef timsort( arr ):\n\n return arr\n","sub_path":"src/recursive_sorting/recursive_sorting.py","file_name":"recursive_sorting.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"316518094","text":"import os\nfrom flask_sqlalchemy import SQLAlchemy\n\nSECRET_KEY = '9fxTuBTb5fNhFCxRiYMkK5QLPfrdz95BXstjpdSG'\n\n# twelve\nAPI_KEY = '5b42bf44132544eb99553f025eeb3779'\n# API_URL = 'https://paper-api.alpaca.markets'\n\nDIR = os.path.abspath(__file__)\nBASE_DIR = os.path.dirname(DIR)\nDB_FILE = os.path.join(BASE_DIR, 'site.db')\n\nresources_dir = os.path.join(BASE_DIR, \"images\")\n\n\nTIME_FRAME = ['minute', '5Min','15Min', 'day']\n\n\n\nif __name__ == \"_main_\":\n print(BASE_DIR)\n print(resources_dir)","sub_path":"flaskfromscratch/flaskfromscratch/database/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"401552315","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 10:35:12 2021\r\n\r\n@author: Inayara\r\n\"\"\"\r\n\r\n'''O mesmo professor do desafio 19 quer sortear a ordem de apresentação de \r\ntrabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos \r\ne mostre a ordem sorteada.'''\r\n\r\n\r\nimport random\r\nn1 = str(input('Nome do primeiro aluno: '))\r\nn2 = str(input('Nome do segundo aluno: '))\r\nn3 = str(input('Nome do terceiro aluno: '))\r\nn4 = str(input('Nome do quarto aluno: '))\r\nlista = [n1, n2, n3, n4]\r\nrandom.shuffle(lista)\r\nprint('A ordem de apresentação será: ')\r\nprint(lista)\r\n\r\n\r\n","sub_path":"exe020.py","file_name":"exe020.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"41598862","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom telegram_util import splitCommand, log_on_fail\nfrom telegram.ext import Updater, MessageHandler, Filters\nimport export_to_telegraph\nimport time\nimport yaml\nfrom db import DB\nimport threading\nimport link_extractor\n\nwith open('credential') as f:\n\tcredential = yaml.load(f, Loader=yaml.FullLoader)\nexport_to_telegraph.token = credential['telegraph_token']\n\ntele = Updater(credential['bot_token'], use_context=True) #@matters_subscribe_bot\ndebug_group = tele.bot.get_chat(420074357)\n\ndb = DB()\n\n@log_on_fail(debug_group)\ndef processNote(note, channels):\n\tif not db.existing.add(note):\n\t\treturn\n\tnote = export_to_telegraph.export(note, force=True) or note\n\tfor channel in channels:\n\t\ttime.sleep(10)\n\t\tchannel.send_message(note)\n\t\t\n@log_on_fail(debug_group)\ndef loopImp():\n\tfor user_id in db.sub.subscriptions():\n\t\tchannels = list(db.sub.channels(user_id, tele.bot))\n\t\tdomain = 'https://matters.news/'\n\t\tuser_url = domain + user_id\n\t\tfor note, _ in link_extractor.getLinks(user_url):\n\t\t\tprocessNote(note, channels)\n\ndef mattersLoop():\n\tloopImp()\n\tthreading.Timer(60 * 60 * 2, mattersLoop).start()\n\n@log_on_fail(debug_group)\ndef handleCommand(update, context):\n\tmsg = update.effective_message\n\tif not msg or not msg.text.startswith('/m'):\n\t\treturn\n\tcommand, text = splitCommand(msg.text)\n\tif 'remove' in command:\n\t\tdb.sub.remove(msg.chat_id, text)\n\telif 'add' in command:\n\t\tdb.sub.add(msg.chat_id, text)\n\tmsg.reply_text(db.sub.get(msg.chat_id), \n\t\tparse_mode='markdown', disable_web_page_preview=True)\n\nHELP_MESSAGE = '''\nCommands:\n/m_add - add Matters user / user link\n/m_remove - remove Matters user\n/m_view - view subscription\n\nCan be used in group/channel also.\n\nGithub: https://github.com/gaoyunzhi/matters_subscribe_bot\n'''\n\ndef handleHelp(update, context):\n\tupdate.message.reply_text(HELP_MESSAGE)\n\ndef handleStart(update, context):\n\tif 'start' in update.message.text:\n\t\tupdate.message.reply_text(HELP_MESSAGE)\n\nif __name__ == '__main__':\n\tthreading.Timer(1, mattersLoop).start() \n\tdp = tele.dispatcher\n\tdp.add_handler(MessageHandler(Filters.command, handleCommand))\n\tdp.add_handler(MessageHandler(Filters.private & (~Filters.command), handleHelp))\n\tdp.add_handler(MessageHandler(Filters.private & Filters.command, handleStart), group=2)\n\ttele.start_polling()\n\ttele.idle()","sub_path":"matters_subscribe_bot.py","file_name":"matters_subscribe_bot.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"446293579","text":"#!/usr/bin/env python\nimport logging, os, sys\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\n\nfrom tornado.options import define, options, parse_command_line, parse_config_file\nfrom ws.mountHandler import mountHandler\nfrom ws.usbHandler import usbHandler\nfrom ws.daemonHandler import daemonHandler\nfrom utils.transmission import Transmission\nfrom utils.daemon import daemon\n\ndaemon_directory=os.path.dirname(__file__)\ndefine('config_file', default=daemon_directory+'/alix.cfg', help='filename for additional configuration')\ndefine('app_name', default='app-name', type=str)\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n#define(\"serv\", default=[], help=\"List of services to administer\", type=list)\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/\", MainHandler),\n (r\"/usb\", usbHandler),\n (r\"/mount\", mountHandler),\n (r\"/daemon\", daemonHandler),\n (r\"(.*)\",MainHandler)\n ]\n settings = dict(\n template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n debug=True\n )\n tornado.web.Application.__init__(self, handlers, **settings)\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"home.html\", options=options)\n def get_error_html(self, status_code, **kwargs):\n self.write(\"

404!

\")\n\ndef main():\n f = open('/var/run/alixHttpd.pid','w')\n f.write(str(os.getpid()))\n f.close()\n\n tornado.options.parse_command_line()\n parse_config_file(options.config_file)\n\n # Demonizing Tornado\n log = open(daemon_directory+'/logs/' + options.app_name + '.log', 'w')\n ctx = daemon.DaemonContext(stdout=log, stderr=log, working_directory=daemon_directory)\n ctx.open()\n # Demonizing Tornado\n\n http_server = tornado.httpserver.HTTPServer(Application())\n http_server.listen(options.port)\n logging.info('Starting server on port %s' % options.port)\n print('Starting server on port %s' % options.port)\n tornado.ioloop.IOLoop.instance().start()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"alixHttp/alixHttpd.py","file_name":"alixHttpd.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96496742","text":"import os\nimport argparse\nimport importlib\n\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.callbacks import LearningRateScheduler\n\nfrom src.layers import EmbeddingSim, EmbeddingRet, PositionEmbedding, LayerNormalization, _get_encoder_component, gelu, ScaledDotProductAttention, MultiHeadAttention, FeedForward\nfrom src import encoder\nfrom src import net\nfrom src import utils\n\nparser = argparse.ArgumentParser(description='Input argument parser.')\n\nparser.add_argument('--model_dir', type=str, help='name of model')\n\nparser.add_argument('--custom_model', type=str, help='path to custom model')\n\nparser.add_argument('--eager', help='flag to turn on/off eager mode', action='store_true')\n\nparser.add_argument('--dataset_path', type=str, help='path to dataset')\n\nparser.add_argument('--num_epoch', type=int, help='number of training epochs',\n default=4)\n\nparser.add_argument('--base_lr', type=float, help='base learning rate',\n default=0.001)\n\nparser.add_argument('--decay_lr', type=float, help='learning rate decay rate',\n default=0.1)\n\nparser.add_argument('--decay_epochs', type=str, help='epoches to decay learning rate',\n default='1000,10000')\n\nparser.add_argument('--steps_per_epoch', type=int, help='number of training step for each epoch',\n default=100)\n\nparser.add_argument('--batch_size', type=int, help='batch size',\n default=1)\n\nparser.add_argument('--length', type=int, help='length of input sequence (number of tokens)',\n default=1024)\n\nparser.add_argument('--data_loader', type=str, help='type of dataset',\n choices=['text', 'cnndm', 'coqa'])\n\nparser.add_argument('--output_name', type=str, help='name of output model')\n\nargs = parser.parse_args()\n\n#python finetune.py --model_dir=models/124M/ --output_name=touhou_124_5x10.h5 --dataset_path=dataset/touhou-nsfw.txt --data_loader=text --num_epoch=5 --decay_epochs=\"4,5\" --steps_per_epoch=10\n\ndef main():\n\n if not args.model_dir:\n print('model_path must be provided')\n exit()\n\n if args.custom_model:\n args.model = args.custom_model\n else:\n args.model = args.model_dir + \"model.ckpt\"\n \n args.json_hparams = args.model_dir + \"hparams.json\"\n args.json_encoder = args.model_dir + \"encoder.json\"\n args.vocab_bpe = args.model_dir + \"vocab.bpe\"\n\n if not os.path.exists('output'):\n os.makedirs('output')\n\n enc = encoder.get_encoder(args.json_encoder, args.vocab_bpe)\n\n ds = importlib.import_module(\n \"src.load_\" + args.data_loader).create_dataset(\n enc, args.length, args.dataset_path, args.batch_size, args.steps_per_epoch, args.num_epoch)\n \n # Setup TensorFlow to use a distribution strategy to perform compute across multiple devices.\n strategy = tf.distribute.experimental.CentralStorageStrategy()\n with strategy.scope():\n if args.model.split('.')[-1] == 'h5':\n model = keras.models.load_model(\n args.model,\n custom_objects={'EmbeddingSim': EmbeddingSim,\n 'EmbeddingRet': EmbeddingRet,\n 'PositionEmbedding': PositionEmbedding,\n 'LayerNormalization': LayerNormalization,\n 'ScaledDotProductAttention': ScaledDotProductAttention,\n 'MultiHeadAttention': MultiHeadAttention,\n 'FeedForward': FeedForward,\n 'gelu': gelu,\n 'loss': net.loss})\n elif args.model.split('.')[-1] == 'ckpt':\n args.model_ckpt = args.model\n model = net.create_model(args)\n model = net.load_weights(model, args)\n else:\n print('Unrecognized model format')\n exit()\n\n model.compile(\n optimizer=keras.optimizers.Adam(),\n loss=net.loss\n )\n\n # fine tune\n model.fit(ds,\n epochs=args.num_epoch,\n steps_per_epoch=args.steps_per_epoch,\n callbacks=[LearningRateScheduler(net.create_schedule(args))])\n\n model.save(os.path.join('output', args.output_name), include_optimizer=False)\n\n model.evaluate(ds)\n\nif __name__ == '__main__':\n main()\n","sub_path":"finetune.py","file_name":"finetune.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"553330581","text":"########################################################\r\n#\r\n# Tagging Support Facilities\r\n# v1.0, Nov 5 1999\r\n# works with Quark5.11\r\n#\r\n#\r\n# by tiglari@hexenworld.com, with lots of advice\r\n# code snippets and additions from Armin Rigo\r\n#\r\n# Basic tagging facilities (non-interface) removed from\r\n# matagside.py\r\n#\r\n# You may freely distribute modified & extended versions of\r\n# this plugin as long as you give due credit to tiglari &\r\n# Armin Rigo. (It's free software, just like Quark itself.)\r\n#\r\n# Please notify bugs & possible improvements to\r\n# tiglari@hexenworld.com\r\n# \r\n#\r\n##########################################################\r\n\r\nimport quarkx\r\nimport quarkpy.qbaseeditor\r\nfrom quarkpy.maputils import *\r\n\r\n#\r\n# ----------- Tag storing & fetching --------------\r\n#\r\n\r\nclass Tagging:\r\n \"a place to stick side-tagging stuff, to be attached to editor;\"\r\n \"only real purpose is to forestall name-collisions\"\r\n\r\n#\r\n# Acessing Tags\r\n\r\n#\r\n# This is the oldest and first - it should be phased out\r\n# in favor of gettaggedface below\r\n#\r\ndef gettagged(editor):\r\n \" safe fetch of tagging.tagged attribute\"\r\n try:\r\n return editor.tagging.tagged\r\n except (AttributeError): return None\r\n\r\ndef gettaggedpt(editor):\r\n \"Returns the tagged point.\"\r\n try:\r\n return editor.tagging.tagpt\r\n except (AttributeError): return None\r\n\r\ndef gettaggedlist(editor):\r\n \"Returns a list of tagged faces\"\r\n try:\r\n return editor.tagging.taglist\r\n except (AttributeError): return None\r\n\r\n#\r\n# 2-point edges only\r\n#\r\ndef gettaggedvtxedge(editor):\r\n try:\r\n return editor.tagging.taggededge\r\n except (AttributeError): return None\r\n\r\n#\r\n# face edges\r\n#\r\ndef gettaggedfaceedge(editor):\r\n try:\r\n tagged = editor.tagging.taggedfaceedge\r\n return tagged\r\n except AttributeError:\r\n return None\r\n\r\n#\r\n# both kinds\r\n#\r\ndef gettaggededge(editor):\r\n \" safe fetch of tagging.taggededge attribute\"\r\n tagged = gettaggedfaceedge(editor)\r\n if tagged is not None:\r\n return (tagged.vtx1, tagged.vtx2)\r\n return gettaggedvtxedge(editor)\r\n\r\n#\r\n# This is the new one, it picks up either ordinary tagged\r\n# faces or faces tagged via tagging of edge-handles\r\n#\r\ndef gettaggedface(editor):\r\n tagged = gettagged(editor)\r\n if tagged is not None:\r\n return tagged\r\n tagged = gettaggedfaceedge(editor)\r\n if tagged is not None:\r\n return tagged.face\r\n\r\n\r\ndef anytag(o):\r\n \"Is anything tagged ?\"\r\n return gettagged(o) is not None or gettaggedpt(o) is not None or gettaggedlist(o) is not None\r\n\r\n#\r\n# --------- setting & clearing tags\r\n#\r\n\r\ndef cleartag(editor):\r\n try:\r\n del editor.tagging\r\n editor.invalidateviews()\r\n except AttributeError: pass\r\n \r\ndef tagface(face, editor):\r\n editor.tagging = Tagging()\r\n editor.tagging.tagged = face\r\n editor.invalidateviews()\r\n \r\ndef tagpoint(point, editor):\r\n editor.tagging = Tagging()\r\n editor.tagging.tagpt = point\r\n editor.invalidateviews()\r\n\r\ndef tagedge(p1, p2, editor):\r\n editor.tagging = Tagging()\r\n editor.tagging.taggededge = p1, p2\r\n editor.invalidateviews() \r\n\r\ndef tagfaceedge(edge, editor):\r\n editor.tagging = Tagging()\r\n editor.tagging.taggedfaceedge = edge\r\n editor.invalidateviews()\r\n\r\n\r\ndef addtotaggedfaces(face, editor):\r\n tagged = gettagged(editor)\r\n if not tagged is None:\r\n editor.tagging = Tagging()\r\n editor.tagging.taglist = [tagged, face]\r\n else:\r\n taglist = gettaggedlist(editor)\r\n if not taglist is None:\r\n taglist.append(face)\r\n editor.invalidateviews()\r\n \r\ndef removefromtaggedfaces(face, editor):\r\n tagged = gettagged(editor)\r\n if not tagged is None:\r\n cleartag(editor)\r\n else:\r\n taglist = gettaggedlist(editor)\r\n if not taglist is None:\r\n if face in taglist:\r\n taglist.remove(face)\r\n editor.invalidateviews()\r\n\r\n\r\n#\r\n# -------- map drawing routines\r\n#\r\n\r\ndef drawsquare(cv, o, side):\r\n \"function to draw a square around o\"\r\n if o.visible:\r\n dl = side/2\r\n cv.brushstyle = BS_CLEAR\r\n cv.rectangle(o.x+dl, o.y+dl, o.x-dl, o.y-dl)\r\n\r\ndef drawredface(view, cv, face):\r\n for vtx in face.vertices: # is a list of lists\r\n sum = quarkx.vect(0, 0, 0)\r\n p2 = view.proj(vtx[-1]) # the last one\r\n for v in vtx:\r\n p1 = p2\r\n p2 = view.proj(v)\r\n sum = sum + p2\r\n cv.line(p1,p2)\r\n drawsquare(cv, sum/len(vtx), 8)\r\n\r\ndef tagfinishdrawing(editor, view, oldmore=quarkpy.qbaseeditor.BaseEditor.finishdrawing):\r\n \"the new finishdrawing routine\"\r\n\r\n def checktagged(tagged, editor=editor):\r\n if not checktree(editor.Root, tagged):\r\n cleartag(editor)\r\n return 0\r\n return 1\r\n \r\n oldmore(editor, view)\r\n cv = view.canvas()\r\n cv.pencolor = MapColor(\"Tag\")\r\n tagged = gettaggedface(editor)\r\n if tagged is not None and checktagged(tagged):\r\n drawredface(view, cv, tagged)\r\n # don't return since there might also be a face edge\r\n tagged = gettaggedfaceedge(editor)\r\n if tagged is not None:\r\n p1, p2 = view.proj(tagged.vtx1), view.proj(tagged.vtx2)\r\n p = (p1+p2)/2\r\n radius = 2\r\n oldwidth = cv.penwidth\r\n cv.penwidth=3\r\n cv.ellipse(p.x-radius, p.y-radius, p.x+radius+1, p.y+radius+1)\r\n cv.penwidth=2\r\n cv.line(p1, p2)\r\n cv.penwidth = oldwidth\r\n return\r\n tagpt = gettaggedpt(editor)\r\n if tagpt is not None:\r\n drawsquare(cv, view.proj(tagpt), 8)\r\n return\r\n taglist = gettaggedlist(editor)\r\n if not taglist is None:\r\n for face in taglist:\r\n if not checktagged(face):\r\n return\r\n for face in taglist:\r\n drawredface(view, cv, face)\r\n return\r\n tagged = gettaggedvtxedge(editor)\r\n if tagged:\r\n pt1, pt2 = tagged\r\n p1 = view.proj(pt1)\r\n p2 = view.proj(pt2)\r\n cv.line(p1,p2)\r\n drawsquare(cv, (p1+p2)/2, 8)\r\n return\r\n \r\nquarkpy.qbaseeditor.BaseEditor.finishdrawing = tagfinishdrawing\r\n","sub_path":"runtime/tags/qk511b6/plugins/tagging.py","file_name":"tagging.py","file_ext":"py","file_size_in_byte":5861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281291965","text":"\"\"\"\n This is a controller that instantiates a SharedMemory core and builds a wrapper\n around it to make it programmable. This is exposed to the programmer.\n\n The function calls accepted:\n load \n store \n \"\"\"\nimport Queue\nimport sys\nfrom shared_memory import SharedMemory\n\nclass SharedMemoryController:\n\n def __init__(self):\n \"\"\"\n Initialize controller with an instance of SharedMemory\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n # configuration of L2 cache and DRAM are pre-defined in SharedMemory constructor\n self.bank = SharedMemory()\n self.read_queue_0 = Queue.Queue()\n self.read_queue_1 = Queue.Queue()\n self.write_queue_0 = Queue.Queue(maxsize=2)\n self.write_queue_1 = Queue.Queue(maxsize=2)\n # dictionary for cycle count for each active memory access\n self.cycles_left = dict()\n # FIX ME IN DEPENDENCY MANAGER LATER\n # create fields for each channel to allow reads and writes to the same address to happen simulatenously\n self.cycles_left['read_channel0'] = dict()\n self.cycles_left['write_channel0'] = dict()\n self.cycles_left['read_channel1'] = dict()\n self.cycles_left['write_channel1'] = dict()\n\n # dictionary for storing address for active memory access\n self.channel = dict()\n self.channel['read_channel0'] = 0\n self.channel['write_channel0'] = 0\n self.channel['read_channel1'] = 0\n self.channel['write_channel1'] = 0\n # store read response for each channel till cycle completion\n self.total_cycles = 0\n\n\n def run_cycle(self, read_channel0, write_channel0, read_channel1, write_channel1):\n \"\"\"\n This is the main function to call the read/write request\n \"\"\"\n # inputs\n araddr0, arvalid0 = read_channel0\n waddr0, wdata0, wvalid0 = write_channel0\n araddr1, arvalid1 = read_channel1\n waddr1, wdata1, wvalid1 = write_channel1\n\n # outputs\n rdata0 = 0\n rvalid0 = 0\n readID0 = None\n rdata1 = 0\n rvalid1 = 0\n readID1 = None\n read_cycles_channel0 = (None, 0, False)\n write_cycles_channel0 = (None, 0, False)\n read_cycles_channel1 = (None, 0, False)\n write_cycles_channel1 = (None, 0, False)\n\n ######### CHANNEL 0-1 #########\n\n #### WRITE ####\n # clear any previous completed accesses\n # check if a memory access is ongoing in the channel\n # if yes, decrement cycle count otherwise\n # pop write requests if any\n # debug\n #print(\"self.cycles_left: \", self.cycles_left)\n #print(\"self.channel['write_channel0']: \", self.channel['write_channel0'])\n if((self.channel['write_channel0'] != 0) and (self.cycles_left['write_channel0'][self.channel['write_channel0']] == 0)):\n # clear channel\n self.cycles_left['write_channel0'].pop(self.channel['write_channel0'])\n self.channel['write_channel0'] = 0\n\n if(self.channel['write_channel0'] != 0):\n self.cycles_left['write_channel0'][self.channel['write_channel0']] -= 1\n else:\n if(not self.write_queue_0.empty()):\n addr, data = self.write_queue_0.get()\n cycles_write_queue_0 = self.bank.write(data, addr)\n self.channel['write_channel0'] = addr\n # do not run one cycle of mem access now\n # this allows us to stay in sync with the corresponding store unit\n self.cycles_left['write_channel0'][addr] = cycles_write_queue_0\n # add cycles left to cycle channel of write_channel0 with valid signal\n write_cycles_channel0 = (addr, self.cycles_left['write_channel0'][addr], True)\n # debug\n print(\"Write Queue 0 -> addr: \", str(addr), \", data: \", str(data), \", write cycles : \", str(cycles_write_queue_0), \"write_cycles_channel0: \", write_cycles_channel0)\n else:\n pass\n\n if((self.channel['write_channel1'] != 0) and (self.cycles_left['write_channel1'][self.channel['write_channel1']] == 0)):\n # clear channel\n self.cycles_left['write_channel1'].pop(self.channel['write_channel1'])\n self.channel['write_channel1'] = 0\n\n if(self.channel['write_channel1'] != 0):\n self.cycles_left['write_channel1'][self.channel['write_channel1']] -= 1\n else:\n if(not self.write_queue_1.empty()):\n addr, data = self.write_queue_1.get()\n cycles_write_queue_1 = self.bank.write(data, addr)\n self.channel['write_channel1'] = addr\n # do not run one cycle of mem access now\n # this allows us to stay in sync with the corresponding store unit\n self.cycles_left['write_channel1'][addr] = cycles_write_queue_1\n # add cycles left to cycle channel of write_channel1 with valid signal\n write_cycles_channel1 = (addr, self.cycles_left['write_channel1'][addr], True)\n # debug\n print(\"Write Queue 1 -> addr: \", str(addr), \", data: \", str(data), \", write cycles : \", str(cycles_write_queue_1), \"write_cycles_channel1: \", write_cycles_channel1)\n else:\n pass\n\n # load write requests into the queue\n if(wvalid0):\n self.write_queue_0.put((waddr0, wdata0))\n if(wvalid1):\n self.write_queue_1.put((waddr1, wdata1))\n\n #### READ ####\n # no logic of outstanding reads in SharedMemory\n # clear any previous completed accesses\n # check if a memory access is ongoing in the channel\n # if yes, decrement cycle count otherwise\n # pop read requests if any\n valid_response_0 = False\n valid_response_1 = False\n if((self.channel['read_channel0'] != 0) and (self.cycles_left['read_channel0'][self.channel['read_channel0']] == 0)):\n # clear channel\n self.cycles_left['read_channel0'].pop(self.channel['read_channel0'])\n self.channel['read_channel0'] = 0\n\n if(self.channel['read_channel0'] != 0):\n self.cycles_left['read_channel0'][self.channel['read_channel0']] -= 1\n if(self.cycles_left['read_channel0'][self.channel['read_channel0']] == 0):\n # reperform load to update readID, rdata, rvalid values\n rvalid0, rdata0, readID0, cycles_read_queue_0 = self.bank.read(self.channel['read_channel0'])\n valid_response_0 = True\n else:\n if(not self.read_queue_0.empty()):\n addr, data = self.read_queue_0.get()\n rvalid0, rdata0, readID0, cycles_read_queue_0 = self.bank.read(addr)\n self.channel['read_channel0'] = addr\n # do not run one cycle of mem access now\n # this allows us to stay in sync with the corresponding load unit\n self.cycles_left['read_channel0'][addr] = cycles_read_queue_0\n # add cycles left to cycle channel of read_channel0 with valid signal\n read_cycles_channel0 = (addr, self.cycles_left['read_channel0'][addr], True)\n # debug\n print(\"Read Queue 0 -> addr: \", str(addr), \", read cycles to wait : \", str(cycles_read_queue_0), \"read_cycles_channel0: \", read_cycles_channel0)\n else:\n pass\n\n if((self.channel['read_channel1'] != 0) and (self.cycles_left['read_channel1'][self.channel['read_channel1']] == 0)):\n # clear channel\n self.cycles_left['read_channel1'].pop(self.channel['read_channel1'])\n self.channel['read_channel1'] = 0\n\n if(self.channel['read_channel1'] != 0):\n self.cycles_left['read_channel1'][self.channel['read_channel1']] -= 1\n if(self.cycles_left['read_channel1'][self.channel['read_channel1']] == 0):\n # reperform load to update readID, rdata, rvalid values\n rvalid1, rdata1, readID1, cycles_read_queue_1 = self.bank.read(self.channel['read_channel1'])\n valid_response_1 = True\n else:\n if(not self.read_queue_1.empty()):\n addr, data = self.read_queue_1.get()\n rvalid1, rdata1, readID1, cycles_read_queue_1 = self.bank.read(addr)\n self.channel['read_channel1'] = addr\n # do not run one cycle of mem access now\n # this allows us to stay in sync with the corresponding load unit\n self.cycles_left['read_channel1'][addr] = cycles_read_queue_1\n # add cycles left to cycle channel of read_channel1 with valid signal\n read_cycles_channel1 = (addr, self.cycles_left['read_channel1'][addr], True)\n # debug\n print(\"Read Queue 1 -> addr: \", str(addr), \", read cycles : \", str(cycles_read_queue_1), \"read_cycles_channel1: \", read_cycles_channel1)\n\n # push requests to the queue\n if(arvalid0):\n self.read_queue_0.put((araddr0, 0))\n if(arvalid1):\n self.read_queue_1.put((araddr1, 1))\n\n #### RESPONSE ####\n # combine results and respond\n # return load value only when cycles complete\n if(not valid_response_0):\n rvalid0 = 0\n if(not valid_response_1):\n rvalid1 = 0\n read_resp_channel0 = readID0, rdata0, rvalid0\n read_resp_channel1 = readID1, rdata1, rvalid1\n\n # combine all read/write_cycles_channels into one single tuple for ease of management\n # (r0,w0,r1,w1)\n cycles_resp_channel = (read_cycles_channel0, write_cycles_channel0, read_cycles_channel1, write_cycles_channel1)\n\n # increment total cycle count\n self.total_cycles += 1\n\n # debug\n #print(\"==== System status ====\")\n #print(\"Total cycles: \", self.total_cycles)\n #print(\"Read Queue 0 : \", list(self.read_queue_0.queue))\n #print(\"Read Queue 1 : \", list(self.read_queue_1.queue))\n #print(\"Write Queue 0 : \", list(self.write_queue_0.queue))\n #print(\"Write Queue 1 : \", list(self.write_queue_1.queue))\n #print(\"Read Channel 0 : \", self.channel['read_channel0'])\n #print(\"Read Channel 1 : \", self.channel['read_channel1'])\n #print(\"Write Channel 0 : \", self.channel['write_channel0'])\n #print(\"Write Channel 1 : \", self.channel['write_channel1'])\n\n #for i in self.cycles_left.keys():\n # print(\"addr: \", i,\" => \", self.cycles_left[i])\n\n return read_resp_channel0, read_resp_channel1, cycles_resp_channel\n\nif __name__ == \"__main__\":\n\n # instantiate a shared memory controller\n shmem_controller = SharedMemoryController()\n\n # initialize channels to something\n read_channel0 = 0,0\n read_channel1 = 0,0\n write_channel0 = 0,0,0\n write_channel1 = 0,0,0\n\n read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1)\n print(\"CYCLE 0\")\n print(\"READ RESP CHANNEL0 (ID, DATA, VALID): \", read_resp_channel0)\n print(\"READ RESP CHANNEL1 (ID, DATA, VALID): \", read_resp_channel1)\n print(\"CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: \", cycles_resp_channel)\n print(\"\\n-----------------------------\\n\\n\")\n\n read_channel0 = 0,0\n read_channel1 = 0,0\n write_channel0 = 1234,10,1\n write_channel1 = 0,0,0\n\n read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1)\n print(\"CYCLE 1\")\n print(\"READ RESP CHANNEL0 (ID, DATA, VALID): \", read_resp_channel0)\n print(\"READ RESP CHANNEL1 (ID, DATA, VALID): \", read_resp_channel1)\n print(\"CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: \", cycles_resp_channel)\n print(\"\\n-----------------------------\\n\\n\")\n\n read_channel0 = 2232,1\n read_channel1 = 0,0\n write_channel0 = 0,0,0\n write_channel1 = 0,0,0\n\n read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1)\n print(\"CYCLE 2\")\n print(\"READ RESP CHANNEL0 (ID, DATA, VALID): \", read_resp_channel0)\n print(\"READ RESP CHANNEL1 (ID, DATA, VALID): \", read_resp_channel1)\n print(\"CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: \", cycles_resp_channel)\n print(\"\\n-----------------------------\\n\\n\")\n\n read_channel0 = 0,0\n read_channel1 = 0,0\n write_channel0 = 0,0,0\n write_channel1 = 1336,12,1\n read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0,write_channel0, read_channel1, write_channel1)\n print(\"CYCLE 3\")\n print(\"READ RESP CHANNEL0 (ID, DATA, VALID): \", read_resp_channel0)\n print(\"READ RESP CHANNEL1 (ID, DATA, VALID): \", read_resp_channel1)\n print(\"CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: \", cycles_resp_channel)\n print(\"\\n-----------------------------\\n\\n\")\n\n read_channel0 = 0,0\n read_channel1 = 1500,1\n write_channel0 = 1260,11,1\n write_channel1 = 0,0,0\n\n read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1)\n print(\"CYCLE 4\")\n print(\"READ RESP CHANNEL0 (ID, DATA, VALID): \", read_resp_channel0)\n print(\"READ RESP CHANNEL1 (ID, DATA, VALID): \", read_resp_channel1)\n print(\"CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: \", cycles_resp_channel)\n print(\"\\n-----------------------------\\n\\n\")\n\n # modify range of iterator to see different accesses getting to completion\n for i in range(0,85):\n read_channel0 = 0,0\n read_channel1 = 0,0\n write_channel0 = 0,0,0\n write_channel1 = 0,0,0\n\n read_resp_channel0, read_resp_channel1, cycles_resp_channel = shmem_controller.run_cycle(read_channel0, write_channel0, read_channel1, write_channel1)\n print(\"CYCLE \", shmem_controller.total_cycles)\n print(\"READ RESP CHANNEL0 (ID, DATA, VALID): \", read_resp_channel0)\n print(\"READ RESP CHANNEL1 (ID, DATA, VALID): \", read_resp_channel1)\n print(\"CYCLES RESP CHANNEL (ID, CYCLES, VALID) X 4: \", cycles_resp_channel)\n print(\"\\n-----------------------------\\n\\n\")\n","sub_path":"utils/shared_memory_controller.py","file_name":"shared_memory_controller.py","file_ext":"py","file_size_in_byte":13221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"47469792","text":"# coding=utf-8\nimport os\nimport shutil\n\nfrom . import dclogger\n# cache_max_size_gb = 3\nfrom duckietown_challenges.utils import friendly_size\n\ncache_dir = '/tmp/duckietown/DT18/evaluator/cache'\ncache_dir_by_value = os.path.join(cache_dir, 'by-value', 'sha256hex')\n\ndisable_cache = False\n\n\ndef get_file_from_cache(fn, sha256hex):\n if disable_cache:\n dclogger.warning('Forcing cache disabled.')\n msg = 'cache disabled'\n raise KeyError(msg)\n if not os.path.exists(cache_dir_by_value):\n os.makedirs(cache_dir_by_value)\n have = os.path.join(cache_dir_by_value, sha256hex)\n if os.path.exists(have):\n shutil.copy(have, fn)\n else:\n msg = 'Hash not in cache'\n raise KeyError(msg)\n\n\ndef copy_to_cache(fn, sha256hex):\n if disable_cache:\n dclogger.warning('Forcing cache disabled.')\n return\n\n if not os.path.exists(cache_dir_by_value):\n os.makedirs(cache_dir_by_value)\n have = os.path.join(cache_dir_by_value, sha256hex)\n if not os.path.exists(have):\n msg = 'Copying %s to cache %s' % (friendly_size(os.stat(fn).st_size), have)\n dclogger.debug(msg)\n shutil.copy(fn, have)\n","sub_path":"src/duckietown_challenges_runner/runner_cache.py","file_name":"runner_cache.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"548210260","text":"#!/usr/bin/Python3\n\nimport neural_net\nimport rover_domain\nimport agent\nimport evolutionary\nimport cred_evals\nimport matplotlib.pyplot as mplot\nfrom parameters import parameter as p\nfrom visualizer import visualize\n\ndef main():\n ag = agent.rover(); rd = rover_domain.rover_domain(); nn = neural_net.neural_net()\n ev = evolutionary.ccea(); cr = cred_evals.rewards()\n\n rd.set_poi_pos(ag.rover_pos)\n dif_system_score = [0.0 for i in range(p.generations)] # Tracks system score for difference rewards\n glob_system_score = [0.0 for i in range(p.generations)] # Tracks system score for global rewards\n dpp_system_score = [0.0 for i in range(p.generations)] # Tracks system score for D++ rewards\n xaxis = [i for i in range(p.generations)] # X-axis for plot of system reward each generation\n\n #Output Files\n gfile = open('global_score.txt', 'w') # System score using global rewards for training\n dfile = open('difference_score.txt', 'w') # System score using difference rewards for training\n dppfile = open('dpp_score.txt', 'w') # System score using D++ rewards for training\n\n print('Reward: ', p.reward_id)\n\n for sr in range(p.stat_runs):\n print('Stat Run: ', sr)\n ev.reset_pops()\n\n for gen in range(p.generations): # Evolve populations\n print(\"Generation: \", gen)\n\n ev.create_offspring() # Create offspring population\n ev.select_teams() # Select policy teams for generation\n\n for i in range(p.pop_size*2):\n ag.agent_reset(); rd.poi_reset(); nn.reset_nn() # Reset rovers and NN for next team\n rd.get_joint_state(ag.rover_pos) # Update state vector for each agent\n\n for rv in range(p.n_rovers): # Create Teams\n nn.get_inputs(rd.joint_state[rv], rv) # Get state vector as input\n p_select = ev.team_selection[rv][i] # Get policy for team\n nn.get_weights(ev.combined_pops[rv][p_select], rv) # Weights assigned to NN for rover rv\n dx, dy = nn.get_output(rv) # NN outputs dx and dy\n ag.update_actions(rv, dx, dy) # Rover updates action list\n\n for t in range(p.n_time_steps): # Evaluate Teams\n rd.update_status(ag.rover_pos, t) # Update POI status and rov-poi distances\n ag.step() # Each rover takes an action according to output from NN\n rd.get_joint_state(ag.rover_pos) # Update state vectors for each agent\n\n for rover_id in range(p.n_rovers):\n nn.get_inputs(rd.joint_state[rover_id], rover_id) # Get updated state vec as input\n dx, dy = nn.get_output(rover_id) # Get output from NN\n ag.update_actions(rover_id, dx, dy) # Updates rover action list\n\n cr.calculate_global(rd.pr_distances, rd.poi_val) # Evaluate how team performed\n for rv in range(p.n_rovers):\n p_select = ev.team_selection[rv][i] # Choose which policy is being assigned a fitness score\n\n if p.reward_id == 0: # G\n ev.combined_fits[rv][p_select] = cr.greward # Assign fitness to appropriate policy\n\n if p.reward_id == 1: # D\n cr.calculate_difference(rd.pr_distances, rd.poi_val, rv) # Calculate D_i\n ev.combined_fits[rv][p_select] = cr.dreward # Assign fitness to appropriate policy\n\n if p.reward_id == 2: # D++\n cr.calculate_dpp(rd.pr_distances, rd.poi_val, rv, -1) # D++^-1\n d1 = cr.dppreward # D++^-1\n if p.asserts_on == True:\n cr.calculate_difference(rd.pr_distances, rd.poi_val, rv) # Calculate D_i\n assert(cr.dppreward == cr.dreward) # By Def. these should be the same\n cr.calculate_dpp(rd.pr_distances, rd.poi_val, rv, (p.coupling-1))\n d2 = cr.dppreward # D++^(TotalAgents-1)\n if d2 <= d1:\n ev.combined_fits[rv][p_select] = d1 # Assign fitness to appropriate policy\n if d2 > d1:\n cr.calculate_dpp(rd.pr_distances, rd.poi_val, rv, 1)\n ev.combined_fits[rv][p_select] = cr.dppreward # Assign fitness to appropriate policy\n\n ev.down_select() # Choose new parent population based on best fitness scores\n\n # Run a simulation with best policies from each population\n ag.agent_reset(); rd.poi_reset(); nn.reset_nn() # Reset rovers and NN\n rd.get_joint_state(ag.rover_pos) # Update state vector for each agent\n\n for rover_id in range(p.n_rovers):\n nn.get_weights(ev.parent_pops[rover_id][0], rover_id) # Import best policy from each pop\n nn.get_inputs(rd.joint_state[rover_id], rover_id) # State vector of each rover is input to NN\n dx, dy = nn.get_output(rover_id)\n ag.update_actions(rover_id, dx, dy)\n\n for t in range(p.n_time_steps): # Team executes best policies\n ag.update_path(t) # Update rover path for visualizer\n rd.update_status(ag.rover_pos, t) # Update POI status and rov-poi distances\n ag.step() # Each rover takes an action according to output from NN\n rd.get_joint_state(ag.rover_pos) # Update state vectors for each agent\n\n for rover_id in range(p.n_rovers):\n nn.get_inputs(rd.joint_state[rover_id], rover_id) # Input updates state vector to NN\n dx, dy = nn.get_output(rover_id) # Output from NN\n ag.update_actions(rover_id, dx, dy) # Updates rover action list\n\n cr.calculate_global(rd.pr_distances, rd.poi_val) # Evaluate how team performed\n if p.reward_id == 0: # Record system score\n glob_system_score[gen] += cr.greward\n gfile.write('%f' % cr.greward); gfile.write('\\t')\n\n if p.reward_id == 1:\n dif_system_score[gen] += cr.greward\n dfile.write('%f' % cr.greward); dfile.write('\\t')\n\n if p.reward_id == 2:\n dpp_system_score[gen] += cr.greward\n dppfile.write('%f' % cr.greward); dppfile.write('\\t')\n\n if p.visualizer_on == True: # Only use visuals on the final gen\n if p.visualize_only_last_generation == False: #visualize all generations\n visualize(p, rd, ag, cr.greward)\n else:\n if gen==p.generations-1: #only visualize last generation\n visualize(p, rd, ag, cr.greward)\n\n ag.agent_reset(); rd.poi_reset(); nn.reset_nn()\n\n if p.reward_id == 0: # New line in txt file for new stat run\n gfile.write('\\n')\n if p.reward_id == 1:\n dfile.write('\\n')\n if p.reward_id == 2:\n dppfile.write('\\n')\n\n gfile.close(); dfile.close(); dppfile.close()\n\n for gen in range(p.generations): # Average system score by number of stat runs\n glob_system_score[gen] /= p.stat_runs\n dif_system_score[gen] /= p.stat_runs\n dpp_system_score[gen] /= p.stat_runs\n\n # Plots of System Score per Generation for reward types\n if p.graphs_on == True:\n mplot.plot(xaxis, glob_system_score)\n mplot.plot(xaxis, dif_system_score)\n mplot.plot(xaxis, dpp_system_score)\n mplot.xlabel('Generations')\n mplot.ylabel('System Score')\n mplot.legend(('Global', 'Difference', 'D++'))\n mplot.show()\n\n\n\nmain() #Run main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"420427989","text":"# coding=utf-8\nimport paho.mqtt.client as mqtt\nimport sys\nimport os\nimport subprocess\nimport jsonify\nimport logging\nimport utils.settings\nimport time\nimport threading\nimport json\nimport API.measurement\nimport API.authentication as auth\nimport API.identity\nimport API.inventory\nimport psutil\nimport json\nimport datetime\n\nlogger = logging.getLogger('Device Status updater')\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogger.info('Logger for sending Docker Status to Platform')\n\n\ndef getUTC():\n return datetime.datetime.strptime(str(datetime.datetime.utcnow()), '%Y-%m-%d %H:%M:%S.%f').isoformat() +\"+00:00\"\n\ndef getMemoryStats():\n payload = {}\n payload['source'] = {\"id\": str(auth.get().internalID)}\n payload['type'] = \"c8y_ThinEdge_Device_Stats\"\n payload['time'] = getUTC()\n memory = {}\n memory['free'] = {\"value\": psutil.virtual_memory().free}\n memory['used'] = {\"value\": psutil.virtual_memory().used}\n memory['total'] = {\"value\": psutil.virtual_memory().total}\n memory['percent'] = {\"value\": psutil.virtual_memory().percent}\n payload['Virtual Memory'] = memory\n return payload\n\ndef getCPUStats():\n payload = {}\n payload['source'] = {\"id\": str(auth.get().internalID)}\n payload['type'] = \"c8y_ThinEdge_Device_Stats\"\n payload['time'] = getUTC()\n cpu = {}\n cpu['load'] = {'value': psutil.cpu_percent(0)}\n payload['CPU'] = cpu\n return payload\n\ndef getDiskStats():\n payload = {}\n payload['source'] = {\"id\": str(auth.get().internalID)}\n payload['type'] = \"c8y_ThinEdge_Device_Stats\"\n payload['time'] = getUTC()\n disk = {}\n disk['total'] = {'value': psutil.disk_usage('/').total}\n disk['used'] = {'value': psutil.disk_usage('/').used}\n disk['free'] = {'value': psutil.disk_usage('/').free}\n disk['percent'] = {'value': psutil.disk_usage('/').percent}\n payload['Disk'] = disk\n return payload\n\n\ndef main():\n logger.info('Sending new device stats')\n API.measurement.createMeasurement(json.dumps(getMemoryStats()))\n API.measurement.createMeasurement(json.dumps(getCPUStats()))\n API.measurement.createMeasurement(json.dumps(getDiskStats()))\n try:\n time.sleep(int(utils.settings.device()['c8y.device.status.update']))\n except:\n logger.warning('Configurated device update intervall not valid, using 10s instead.')\n time.sleep(10)\n\ndef start():\n try:\n while True:\n main()\n except KeyboardInterrupt:\n sys.exit(1)\n except Exception as e:\n logger.error('The following error occured: ' + str(e))\n pass\n\ndef stop():\n raise Exception\n","sub_path":"deviceStatus/sendDeviceStats.py","file_name":"sendDeviceStats.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"372402819","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef get_html():\n \"\"\"\"获取html信息\"\"\"\n r = requests.get(\"https://www.runoob.com\")\n text = r.content.decode('utf-8')\n soup = BeautifulSoup(text, 'lxml')\n index_nav = soup.find(id=\"index-nav\")\n li_list = index_nav.find_all('li')\n for li in li_list:\n print(li.text)\n # index = soup.find(class_='xxx')\n # print(index_nav)\n\nif __name__ == '__main__':\n get_html()\n\n","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"334992314","text":"from math import log10\ndef sot(n):\n sum = 0\n for i in range(1, int(n**0.5)+1):\n if n%i == 0:\n\n sum += i\n if i != n/i and n/i != n:\n\n sum += n/i\n\n return int(sum)\n\nl = [i for i in range(1, 100000)]\n\nt = int(input())\nna = []\nfor _ in range(t):\n na = int(input())\n l1 = []\n for e in l[:]:\n if e>na:\n break\n\n if sot(sot(e)) == e and sot(e) != e:\n l1.append(e)\n else:\n l.remove(e)\n\n\n print(sum(l1))","sub_path":"problem021.py","file_name":"problem021.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"215244290","text":"import numpy as np\nfrom numpy.linalg import solve \nimport itertools #重複組合せを求める\n\nclass CloseQueue_lib:\n\n def __init__(self, N, K, p, mu, m):\n self.N = N #網内の拠点数(プログラム内部で指定する場合は1少なくしている)\n self.K = K #網内の客数\n self.p = p\n self.alpha = np.array([])#ノード到着率\n self.mu = mu\n self.rho = np.array([])\n self.pi = np.zeros((len(p),len(p)))\n self.m = m\n self.comb = self.fact(N + K -1) // (self.fact(N + K -1 - (N -1)) * self.fact(N -1))\n self.L = np.zeros(self.N)\n self.R = np.zeros(self.N)\n self.lmd = np.zeros(self.N)\n \n #閉鎖型ネットワークのノード到着率αを求める\n #https://mizunolab.sist.ac.jp/2019/09/bcmp-network1.html\n def getCloseTraffic(self):\n e = np.eye(len(self.p)-1) #次元を1つ小さくする\n pe = self.p[1:len(self.p), 1:len(self.p)].T - e #行と列を指定して次元を小さくする\n lmd = self.p[0, 1:len(self.p)] #0行1列からの値を右辺に用いる\n slv = solve(pe, lmd * (-1))\n self.alpha = np.insert(slv, 0, 1.0) #α1=1を追加\n return self.alpha\n\n #畳み込みで求める\n #http://www.ocw.titech.ac.jp/index.php?module=General&action=DownLoad&file=201316812-17-0-1.pdf&type=cal&JWC=201316812\n def calcConvolution(self, n, k, rho): #メモ化利用なし\n #rho = alpha / mu\n if k == 0: #Gj(0) = 1 (j = 1,...,N)\n g = 1\n elif n == 0:#G(0,k) = f0(k)\n g = np.power(rho[n], k)\n else : \n g = self.calcConvolution(n-1, k,rho) + rho[n] * self.calcConvolution(n, k-1,rho)\n return g\n\n def initMemo(self, rho, memo):\n for i in range(self.N):\n memo[i][0] = 1\n for i in range(self.K+1): #(k = 0,1,2,...,K)\n memo[0][i] = np.power(rho[0], i)\n return memo\n \n #メモ化を利用して計算を早くする(畳み込みのインデックスを再度確認)\n def calcConvolution_memo(self, n, k, rho, memo):\n if memo[n][k] >= 0:\n g = memo[n][k]\n else : \n memo[n][k] = self.calcConvolution_memo(n-1, k,rho,memo) + rho[n] * self.calcConvolution_memo(n, k-1,rho,memo)\n g = memo[n][k]\n return g\n \n # Closed Queueで窓口数が複数の場合の対応 : QN&MC P289 式(7.62) 2021/06/03追加したかったけどやめた\n \n def getGNK(self, rho):#メモ化利用なし\n self.g = self.calcConvolution(self.N-1, self.K, rho) #ノード番号は1小さくしている\n self.gg = self.calcConvolution(self.N-1, self.K-1, rho) #ノード番号は1小さくしている\n \n def getGNK_memo(self, rho):\n #メモ化の準備\n memo = np.ones((self.N, self.K+1))#メモ化で利用(n = 0,1,...,N-1, k = 0,1,2,...,K)\n memo *= -1\n memo = self.initMemo(rho, memo)\n self.g = self.calcConvolution_memo(self.N-1, self.K, rho, memo) #ノード番号は1小さくしている\n self.gg = self.calcConvolution_memo(self.N-1, self.K-1, rho, memo) #ノード番号は1小さくしている\n \n def getThroughput(self):\n throughput = self.alpha * self.gg / self.g\n return throughput\n\n def getAvailability(self):\n avail = self.alpha / self.mu * self.gg / self.g\n return avail\n\n #http://www.ieice-hbkb.org/files/05/05gun_01hen_05.pdf\n #畳み込みを利用する場合、周辺分布までしか算出できない\n def getStationary_memo(self, p, rho, memo): #memoを追加\n pi = []\n for i in range(self.K+1):\n pi.append(np.power(rho[self.N-1], i) * self.calcConvolution_memo(self.N-2,self.K-i, rho, memo) / self.calcConvolution_memo(self.N-1, self.K, rho, memo))\n return pi\n \n def getStationary(self, p, rho): #メモ化なし\n pi = []\n for i in range(self.K+1):\n pi.append(np.power(rho[self.N-1], i) * self.calcConvolution(self.N-2,self.K-i, rho) / self.calcConvolution(self.N-1, self.K, rho))\n return pi\n\n def getLength(self, pi):\n l = np.zeros(self.N)\n for i in range(self.N):\n for j in range(self.K+1):\n l[i] += j * pi[i][j]\n return l \n\n def getStationaryDistribution(self, memo_flag):#メモ化を追加\n #定常分布を求めたいノードをノードN(最後のノード)に持ってくる\n #推移確率、α、μの順番を変更\n pi_all = np.zeros((self.N, self.K+1)) #全状態確率を入れるリスト\n for i in range(self.N):\n p = self.p.copy() #copyがないとobjectそのものになってしまう\n alpha = self.alpha.copy()\n mu = self.mu.copy()\n\n #行の交換\n p[len(p)-1] = self.p[i]\n p[i] = self.p[len(self.p)-1]\n pp = p.copy()\n #列の交換\n p[:,len(p)-1] = pp[:,i]\n p[:,i] = pp[:,len(self.p)-1]\n\n #αの交換\n alpha[len(p)-1] = self.alpha[i]\n alpha[i] = self.alpha[len(self.p)-1]\n\n #μの交換\n mu[len(p)-1] = self.mu[i]\n mu[i] = self.mu[len(self.p)-1]\n\n rho = alpha / mu\n \n if memo_flag == 1:#メモ化実施\n #メモ化の準備\n memo = np.ones((self.N, self.K+1))#メモ化で利用(n = 0,1,...,N-1, k = 0,1,2,...,K)\n memo *= -1\n memo = self.initMemo(rho, memo)\n pi = self.getStationary_memo(p, rho, memo) #memoを追加\n else:\n pi = self.getStationary(p, rho) #memoなし\n \n pi_all[i] = pi \n \n return pi_all\n \n def getPi(self, k, rho):#定常分布pi(k1,k2,k3,...)を返す\n rho_p = 1\n for i in range(self.N):\n rho_p *= rho[i]**k[i]\n pi = rho_p / self.g\n return pi\n \n def calcMVA(self):\n k = 0\n while(k < self.K):\n k += 1\n #Step3 Rの更新\n for i in range(self.N):\n self.R[i] = (self.L[i] + 1)/self.mu[i]\n #Step4 Lambdaの更新\n for i in range(self.N):\n sum = 0\n for j in range(self.N):\n sum += self.alpha[j]*self.R[j] \n if(i == 0):\n self.lmd[i] = k/sum\n else: \n self.lmd[i] = self.alpha[i]*self.lmd[0]\n #Step5 Lの更新\n for i in range(self.N):\n self.L[i] = self.lmd[i]*self.R[i]\n return self.L, self.R, self.lmd\n \n def fact(self, n):\n if n == 1:\n return 1\n return n * self.fact(n-1)\n \n def getCombi(self,N,K):\n #s = combinations_count(N, K)#重複組み合わせ\n l = [i for i in range(N)]\n p_list = list(itertools.combinations_with_replacement(l, K))\n combi = [[0 for i in range(N)] for j in range(len(p_list))]\n for ind, p in enumerate(p_list):\n for k in range(K):\n combi[ind][p[k]] += 1\n return combi\n\n def getMemo(self):\n print(self.memo)\n \n def getG(self):\n print('G = {}'.format(self.g))\n \n def getGG(self):\n print('GG = {}'.format(self.gg))","sub_path":"CloseQueue_lib.py","file_name":"CloseQueue_lib.py","file_ext":"py","file_size_in_byte":7404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"387141429","text":"import psi4\nimport numpy as np\n\n# Initial setup\npsi4.set_memory('2 GB')\npsi4.set_num_threads(2)\n\nfile_prefix = 'methane_HF-DZ'\n\nch4 = psi4.geometry(\"\"\"\nsymmetry c1\n0 1\n C -0.85972 2.41258 0.00000\n H 0.21028 2.41258 0.00000\n H -1.21638 2.69390 -0.96879\n H -1.21639 3.11091 0.72802\n H -1.21639 1.43293 0.24076\n\"\"\")\n\n\n# Geometry optimization\npsi4.set_output_file(file_prefix + '_geomopt.dat', False)\npsi4.set_options({'g_convergence': 'gau_tight'})\npsi4.optimize('scf/cc-pVDZ', molecule=ch4)\n\n\n# Run vibrational frequency analysis\npsi4.set_output_file(file_prefix + '_vibfreq.dat', False)\nscf_energy, scf_wfn = psi4.frequency('scf/cc-pVDZ', molecule=ch4, return_wfn=True, dertype='gradient')\n\n# Save \"raw\" frequencies into a variable\nprint(scf_wfn.frequency_analysis) # this command is just to get you started!\n\n# Eliminate imaginary parts of frequencies,\nprint(scf_wfn.frequency_analysis['omega'])\nprint(scf_wfn.frequency_analysis['omega'][2])\nfreqs = scf_wfn.frequency_analysis['omega'][2]\n\nnp.real(freqs)\nrealfreq = np.real(freqs)\n\n# round the frequencies (to the nearest whole number),\nnp.round(realfreq)\n\n# and extract only the *non-zero* frequencies\nnp.round(realfreq[6:])\nprint (np.round(realfreq[6:]))\nroundfreq = np.round(realfreq[6:])\n\n# Determine the unique non-zero frequencies and \n# the number of times each such frequency occurs;\nunique,counts=np.unique(roundfreq,return_counts=True)\nprint(unique)\nprint(counts)\nx=np.transpose(np.vstack((unique,counts)))\nprint(x)\n\n# store these in a NumPy array in the format: \nnp.savetxt(fname='CH4-frequencylist.dat', X=x, fmt='%.1f %d', delimiter=',', header='Freq Degen, **Kimberly Jarquin**' )\n# {frequency, count} (i.e, one line per freq.)\n\n\n# Save the NumPy array with frequency and count data\n# to a text file\n\n\n","sub_path":"Methane-VibFreqAnalysis.py","file_name":"Methane-VibFreqAnalysis.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"537990508","text":"from Spielfeld import Spielfeld\nfrom Spielerfarbe import Spielerfarbe as sf\nimport UserInterfaceConsole as ui\nimport ControlsConsole\nfrom Network import EnhancedNetwork\nimport ControlsConsole as cc\nfrom Network import EnhancedNetwork\n\nclass GameLogic:\n\n __matchfield = Spielfeld\n __connection = EnhancedNetwork\n\n def __init__(self):\n self.__matchfield = Spielfeld(sf.gelb)\n self.__connection = EnhancedNetwork()\n self.data=[]\n\n def game(self):\n while(True):\n\n ui.PrintConnectionInfo()\n key = cc.GetUserInputChar()\n if key == 'c':\n beServer = False\n break\n if key =='s':\n beServer = True\n break\n ui.PrintError('not a valid input')\n\n self.__startConnection(beServer)\n #übergeben ob erster oder zweiter\n self.__startGame()#connInfo gleich als indikator für ersten und zweiten?\n \n def __startGame(self, first):\n gameOver = False\n self.__matchfield.newField()\n if (not first):\n pass\n #auf move von anderem warten\n\n while(not gameOver):\n self.gameMove()\n #Spielablauf\n return\n\n def gameMove(self):\n #getinput\n \n return\n\n def __startConnection(self, asServer):\n\n #wenn asServer true, dann \n #waitfor connection\n #if not self.__connection.waitForConnection():\n #ui.PrintError('connection error')\n #else\n #connect to\n #ui.PrintGetIPInfo()\n #ip = cc.GetUserInputString()\n #if not self.__connection.connectToOther(ip):\n #ui.PrintError('connection error')\n \n #verbunden, jetzt Spiel starten\n #herausfinden wer beginnt\n #startgame\n \n \n while(True):\n inp = cc.GetUserInputChar()\n if inp == 'c':\n ui.PrintGetIPInfo()\n ip = cc.GetUserInputString()\n if not self.__connection.connectToOther(ip):\n ui.PrintError('connection error')\n\n if inp == 'g':\n if not self.__connection.waitForConnection():\n ui.PrintError('connection error')\n\n if inp == 's':\n ui.Print('input message:')\n message = cc.GetUserInputString()\n self.__connection.sendMessage(message)\n\n if inp == 'r':\n print(self.__connection.receiveMessage())\n if inp == 'e':\n self.__connection.endConnection()\n break","sub_path":"GameLogic.py","file_name":"GameLogic.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"309218902","text":"# Change the socket program so that it only shows data after the headers\n# and a blank line have been received.\n#\n# Remember that recv is receiving characters (newlines and all), not lines.\n#\n# 0. read individual characters with for loop as usual\n# 1. add all characters to a single page\n# 2. split at '\\r\\n\\r\\n'\n\nimport socket\n\nHOST = 'data.pr4e.org'\nPORT = 80\nGET = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\\r\\n\\r\\n'.encode()\n\na_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\na_socket.connect( (HOST, PORT) )\na_socket.send(GET)\n\na_page = b\"\" # is there a less ugly way to declare?\n\nwhile True:\n new_data_chunk = a_socket.recv(20)\n if (len(new_data_chunk) < 1) :\n break\n a_page = a_page + new_data_chunk\na_socket.close()\n\nsplit_page = a_page.decode().split('\\r\\n\\r\\n')\nprint('\\n' + str(split_page[1]))\n","sub_path":"src/3_html_char_retrieve.py","file_name":"3_html_char_retrieve.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"321233270","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.modules.utils import _pair\n\nfrom mmdet.core import (auto_fp16, bbox_target, delta2bbox, force_fp32,\n multiclass_nms)\nfrom ..builder import build_loss\nfrom ..losses import accuracy\nfrom ..registry import HEADS\nfrom ..utils import ConvModule, GradientScalarLayer\nfrom icecream import ic\n\n@HEADS.register_module\nclass DAInsHead(nn.Module):\n \"\"\"instance level domain classifier\"\"\"\n\n def __init__(self,\n in_channels=25088,\n feat_channels=1024,\n grl_weight=-0.1,\n loss_cls=dict(\n type='CrossEntropyLoss',\n use_sigmoid=True,\n loss_weight=0.1),):\n super(DAInsHead, self).__init__()\n self.da_fc1 = nn.Linear(in_channels, feat_channels)\n self.da_fc2 = nn.Linear(feat_channels, feat_channels)\n self.da_cls = nn.Linear(feat_channels, 1)\n self.loss_cls = build_loss(loss_cls)\n self.grl_img = GradientScalarLayer(grl_weight)\n self.init_weights()\n\n def init_weights(self):\n for l in [self.da_fc1, self.da_fc2]:\n nn.init.normal_(l.weight, std=0.01)\n nn.init.constant_(l.bias, 0)\n nn.init.normal_(self.da_cls.weight, std=0.05)\n nn.init.constant_(self.da_cls.bias, 0)\n\n @auto_fp16()\n def forward(self, x):\n x = self.grl_img(x)\n x = x.view(x.shape[0], -1)\n x = F.relu(self.da_fc1(x))\n # x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu(self.da_fc2(x))\n # x = F.dropout(x, p=0.5, training=self.training)\n x = self.da_cls(x)\n return x\n\n @force_fp32(apply_to='cls_score')\n def loss(self,\n cls_score,\n source,\n reduction_override=None):\n losses = dict()\n N = cls_score.shape\n domain_label = 0 if source else 1\n labels = torch.zeros_like(cls_score, dtype=torch.float32)\n labels[:, :] = domain_label\n cls_score = cls_score.view(N, -1)\n labels = labels.view(N, -1)\n losses['loss_dc_ins'] = self.loss_cls(\n cls_score,\n labels,\n reduction_override=reduction_override)\n return losses\n","sub_path":"mmdet/models/domain_classifier/dc_ins.py","file_name":"dc_ins.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"342115645","text":"from django.core.mail import send_mail\nfrom celery_tasks.main import celery_app\n\nimport logging\nlogger = logging.getLogger('django')\n# @celery_app.task\n# def send_verify_email(subject,message,from_email,recipient_list,html_message):\n#\n# send_mail(\n# subject=subject,\n# message=message,\n# from_email=from_email,\n# recipient_list=recipient_list,\n# html_message=html_message\n# )\nfrom meiduo_mall02 import settings\n\n\n@celery_app.task(bind=True, name='send_verify_email', retry_backoff=3)\ndef send_verify_email(self, email, verify_url):\n \"\"\"\n 发送验证邮箱邮件\n :param to_email: 收件人邮箱\n :param verify_url: 验证链接\n :return: None\n \"\"\"\n subject = \"美多商城邮箱验证\"\n html_message = '

尊敬的用户您好!

' \\\n '

感谢您使用美多商城。

' \\\n '

您的邮箱为:%s 。请点击此链接激活您的邮箱:

' \\\n '

%s

' % (email, verify_url, verify_url)\n try:\n send_mail(subject, \"\", settings.EMAIL_FROM, [email], html_message=html_message)\n except Exception as e:\n logger.error(e)\n # 有异常自动重试三次\n raise self.retry(exc=e, max_retries=3)\n","sub_path":"meiduo_mall02/celery_tasks/email/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"146608314","text":"'''\nProblem Statement\n\nYou have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th\nbarrel contains ai liters of water.\nYou can pour water from one barrel to another. In one act of pouring, you can choose two\ndifferent barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of\nwater from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite\ncapacity, so you can pour any amount of water in each of them.\nCalculate the maximum possible difference between the maximum and the minimum amount\nof water in the barrels, if you can pour water at most k times.\n\nInput Format\n\nThe first line contains one integer t— the number of test cases.\nThe first line of each test case contains two integers n and k — the number of barrels and the\nnumber of pourings you can make.\nThe second line contains n integers a1,a2,…,an , where ai is the initial amount of water the i-th\nbarrel has.\nIt's guaranteed that the total sum of n over test cases doesn't exceed\n\nConstraints\n\n(1≤t≤1000)\n(1≤k\n(0≤ai≤10^9)\n2⋅(10^5).\n\nOutput Format\n\nFor each test case, print the maximum possible difference between the maximum and the\nminimum amount of water in the barrels, if you can pour water at most k times\n\n'''\nt = int(input())\nfor i in range(t):\n n, k = map(int, input().split())\n lit = list(map(int, input().split()))\n lit.sort()\n for i in range(k):\n if(lit[-1]!=0 and lit[-2]!=0):\n res=lit[-1]+lit[-2]\n lit=lit[:-2]\n lit.append(res)\n if(k>0):\n print(lit[-1])\n else:\n print(lit[-1]-lit[0])\n","sub_path":"Fill_Barrel.py","file_name":"Fill_Barrel.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"415521915","text":"\"\"\"\nGiven two strings s and t, determine if they are isomorphic.\nTwo strings are isomorphic if the characters in s can be replaced to get t.\n\nAll occurrences of a character must be replaced with another character while preserving the order of characters.\nNo two characters may map to the same character but a character may map to itself.\n\nExample 1:\n\nInput: s = \"egg\", t = \"add\"\nOutput: true\nExample 2:\n\nInput: s = \"foo\", t = \"bar\"\nOutput: false\n\"\"\"\nclass Solution(object):\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if not s or not t:\n return True\n\n # 用来记录两个单词的字母要怎么匹配\n hashmap = {}\n if len(s) != len(t):\n return False\n\n for i in range(len(s)):\n if s[i] in hashmap:\n if hashmap[s[i]] != t[i]:\n return False\n else:\n # \"ab\"\n # \"aa\"\n # 此时a:a已经在dict里面了,但是b作为key却没在里面,但是a已经和a匹配过了,所以要返回false\n if t[i] in hashmap.values():\n return False\n else:\n hashmap[s[i]] = t[i]\n return True\n\n\"\"\"\nTime O(n) space O(n0\nhttps://www.youtube.com/watch?v=tBK5f-BJOdg\n答案:\n1.我们用hashmap(python 中的dictionary),来储存 s:t\n 例如: abb\n egg (a:e , b:g) 那么后续碰到a,b这两个字母,我们只用看看value对不对的上就可以了\n\n2.当两个string长度都不一样,肯定不是同构\n3. 假如说s[i] 在hashmap里面,那么取出s[i]的value,看和t[i]对不对的上\n4. 假如说s[i] 不在hashmap里面,就要看t[i]在不在hashmap.values()里,有的话说明错了\n 若都不在,那就把他们两加进map里\n5.经过重重考验,最后可以return True了\n\n\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"leetcode/Hashmap/205m. Isomorphic Strings(同构字符串).py","file_name":"205m. Isomorphic Strings(同构字符串).py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"542701747","text":"import numpy as np\nimport numba\nimport copy\n\n\nnp.random.seed(42)\n\n\ndef reset_seed(seed=42):\n np.random.seed(seed)\n\n\n@numba.njit(parallel=True)\ndef cross_entropy_loss(y, y_hat):\n \"\"\"Implements the cross-entropy loss.\"\"\"\n loss = -y * np.log(y_hat + 1e-8)\n for i in numba.prange(loss.shape[1]):\n loss[np.isnan(loss[:, i]), i] = 0.0\n loss[np.isinf(loss[:, i]), i] = np.finfo(loss.dtype).max\n return np.sum(loss) / y.shape[0]\n\n\n@numba.njit()\ndef softmax(x_):\n \"\"\"Implements a numerically stable softmax function.\"\"\"\n exp = np.exp(x_ - np.max(x_))\n return exp / np.sum(exp)\n\n\n@numba.njit()\ndef sigma(x_):\n \"\"\"\n Implements the logistic function.\n \"\"\"\n return 1 / (1 + np.exp(-x_))\n\n\n@numba.njit()\ndef sigma_prime(x_):\n \"\"\"\n Implements the derivative of the logistic function.\n \"\"\"\n s = sigma(x_)\n return s * (1 - s)\n\n\n@numba.njit()\ndef relu(x_):\n \"\"\"Implements the ReLU activation function. Not used.\"\"\"\n return np.maximum(x_, 0)\n\n\n@numba.njit()\ndef relu_prime(x_):\n \"\"\"Implements the ReLU derivative. Not used.\"\"\"\n return np.minimum(np.maximum(x_, 0), 1)\n\n\n@numba.njit()\ndef predict(x_, w_, b_):\n \"\"\"\n Calculates the predictions y_hat = w_ @ x_ + b.\n \"\"\"\n return x_ @ w_ + b_\n\n\ndef l1_prime(weight):\n \"\"\"Implements L1 regularisation.\"\"\"\n return np.where(weight >= 0, 1.0, -1.0)\n\n\ndef l2_prime(weight):\n \"\"\"Implements L2 regularisation.\"\"\"\n return weight\n\n\ndef forward_pass(xs, weights, return_prediction=False, activation=sigma):\n \"\"\"\n Calculates one forward pass of the model. If return_predictions=True only the predictions of the model will be\n returned.\n \"\"\"\n # First forward dict contains outputs, second forward dict contains outputs after feeding them through a logistic\n # function.\n forward_dicts = [{}, {}]\n prev_output = xs\n # Loop through layers, calculate outputs and feed them through activation functions.\n for i in range(len(weights)):\n weight, bias = weights[i]\n forward_dicts[0][i + 1] = predict(prev_output, weight, bias)\n if i == len(weights) - 1:\n prev_output = forward_dicts[1][i + 1] = np.array(\n [softmax(forward_dicts[0][i + 1][j]) for j in range(forward_dicts[0][i + 1].shape[0])])\n else:\n prev_output = forward_dicts[1][i + 1] = activation(forward_dicts[0][i + 1])\n if return_prediction:\n return prev_output\n return forward_dicts\n\n\ndef backward_pass(xs, ys, weights, forward_dicts, activation_derivative=sigma_prime, l1_reg=0.0, l2_reg=0.0):\n \"\"\"\n Calculates one backward pass of the model.\n \"\"\"\n num_layers = len(forward_dicts[0])\n gradients = []\n y_hat = forward_dicts[1][num_layers]\n ys = np.eye(y_hat.shape[1])[ys]\n # Delta for last layer.\n delta = (1.0 / ys.shape[0]) * (y_hat - ys)\n for i in range(num_layers - 1, -1, -1):\n # Loop through the layers and calculate the gradients for each weight/bias vector.\n prev_output = forward_dicts[1][i] if i >= 1 else xs\n weight_gradient = prev_output.T @ delta + l1_reg * l1_prime(weights[i][0]) + l2_reg * l2_prime(weights[i][0])\n bias_gradient = np.sum(delta, axis=0)\n gradients.append((weight_gradient, bias_gradient))\n if i != 0:\n delta = (delta @ weights[i][0].T) * activation_derivative(forward_dicts[0][i])\n return gradients\n\n\ndef initialise_weights(layers):\n \"\"\"\n Randomly initialise the weights specified by layers.\n \"\"\"\n weights = []\n for i in range(len(layers)):\n input_dim, output_dim = layers[i]\n weight = np.random.randn(input_dim, output_dim) / 100\n bias = np.random.randn(output_dim) / 100\n weights.append((weight, bias))\n return weights\n\n\ndef analytical_gradients(xs, ys, weights, activation=sigma, activation_derivative=sigma_prime, l1_reg=0.0, l2_reg=0.0):\n \"\"\"\n Calculate the analytical gradients of the model.\n \"\"\"\n forward_dict = forward_pass(xs, weights, activation=activation)\n gradients = backward_pass(xs, ys, weights, forward_dict, activation_derivative=activation_derivative, l1_reg=l1_reg,\n l2_reg=l2_reg)\n return gradients, forward_dict\n\n\ndef calculate_error_loss(xs, weights, true):\n \"\"\"\n Calculate the error as well as the loss for a given dataset (xs, true) and weights.\n \"\"\"\n predictions = forward_pass(xs, weights, return_prediction=True)\n ys = np.eye(predictions.shape[1])[true]\n loss = cross_entropy_loss(ys, predictions) / predictions.shape[0]\n error = (predictions.argmax(axis=1) != true).sum() / true.size * 100.0\n return loss, error\n\n\ndef update_weights(weights, gradients, learning_rate, layer_count, momentum, prev_gradients):\n \"\"\"\n Updates the weights of all of the layers for given gradients.\n :param weights: The weights to be updated.\n :param gradients: The gradients w.r.t. the error.\n :param learning_rate: The learning rate.\n :param layer_count: The number of layers in the model.\n :param momentum: The momentum coefficient. Set to 0 to disable momentum.\n :param prev_gradients: The previous gradients (used for momentum).\n :return: The updated weights.\n \"\"\"\n for i in range(len(gradients)):\n weight_gradient, bias_gradient = gradients[i]\n prev_weight_gradient, prev_bias_gradient = prev_gradients[i]\n weight, bias = weights[layer_count - i - 1]\n weight -= learning_rate * weight_gradient + momentum * prev_weight_gradient\n bias -= learning_rate * bias_gradient + momentum * prev_bias_gradient\n weights[layer_count - i - 1] = (weight, bias)\n return weights\n\n\ndef train_mlp(xs, ys, epochs, learning_rate, layers, optimizer=update_weights, batching=\"Full\", batch_size=0,\n momentum=0.0, l1_reg=0.0, l2_reg=0.0, return_metrics=False, return_best_weights=False, print_metrics=True,\n test_xs=None, test_ys=None):\n \"\"\"\n Trains a multi-layer perceptron. The training is performed by gradient descent and backpropagation. The training\n supports different batch modes ('Full', 'Mini', and 'SGD'). The parameter batch_size specifies the size of a single\n batch for the batch mode 'Mini' (otherwise the parameter is ignored). The momentum parameter specifies the momentum\n coefficient. To disable momentum the parameter can be set to 0.0 (default). The parameters l1_reg and l2_reg control\n the regularisation coefficients. To disable regularisation set the parameters to 0.0 (default).\n :param xs: Training data.\n :param ys: Training targets.\n :param epochs: The number of epochs the training should be run for.\n :param learning_rate: The learning rate for the weight updates.\n :param layers: The specification of the layers. An iterable containing tuples of (input_dimension, output_dimension)\n are expected. Each tuple specifies a single layer in the network.\n :param optimizer: Function to perform the weight update.\n :param batching: Batch mode. Either 'Full' (default), 'Mini', or SGD.\n :param batch_size: The size of a single batch. Only relevant for batch mode 'Mini'.\n :param momentum: The momentum coefficient. Set to 0 to disable momentum (default).\n :param l1_reg: L1 regularisation coefficient.\n :param l2_reg: L2 regularisation coefficient.\n :param return_metrics: Returns a dictionary containing all the training/validation accuracies and losses per epoch.\n :param return_best_weights: Return the best weights (defined by the highest validation accuracy).\n :param print_metrics: Print the metrics during training.\n :param test_xs: Test data.\n :param test_ys: Test labels.\n :return: weights [list], (metrics [dict])\n \"\"\"\n weights = initialise_weights(layers)\n best_weights, best_error = weights, 100.0\n y_hat_alias, layer_count = f\"h{len(layers)}_sigma\", len(layers)\n metrics = {\"train_loss\": np.zeros(epochs), \"train_err\": np.zeros(epochs), \"test_loss\": np.zeros(epochs),\n \"test_err\": np.zeros(epochs)}\n prev_gradients = [(np.zeros_like(weight[0]), np.zeros_like(weight[1])) for weight in weights]\n # Reverse order of initial prev_gradients (based on weight shapes) as the gradients start from the last layer.\n prev_gradients.reverse()\n # Split the training data into full/mini/SGD batches.\n if batching != \"Full\":\n if batching == \"Mini\" and batch_size > 0:\n # Split into batches of size batch_size with the remainder being omitted.\n x_batches = np.array_split(xs, np.arange(batch_size, xs.shape[0], batch_size))\n y_batches = np.array_split(ys, np.arange(batch_size, ys.shape[0], batch_size))\n elif batching == \"SGD\":\n # Split into batches of size 1. This allows reusing the same training code for mini-batches.\n x_batches = np.hsplit(xs, xs.shape[1])\n y_batches = np.hsplit(ys, ys.shape[1])\n else:\n raise ValueError(\"Parameter batching must be one either 'Full', 'Mini' or 'SGD'.\")\n # Training\n for epoch in range(epochs):\n if batching != \"Full\":\n for i in range(len(x_batches)):\n # Train on mini-batches. prev_gradients is only used if momentum > 0.0.\n gradients, forward_dict = analytical_gradients(x_batches[i], y_batches[i], weights, l1_reg=l1_reg,\n l2_reg=l2_reg)\n weights = optimizer(weights, gradients, learning_rate, layer_count, momentum, prev_gradients)\n prev_gradients = gradients\n else:\n # Train on full batch. prev_gradients is only used if momentum > 0.0.\n gradients, forward_dict = analytical_gradients(xs, ys, weights)\n weights = optimizer(weights, gradients, learning_rate, layer_count, momentum, prev_gradients)\n prev_gradients = gradients\n # Calculate error and loss on the training and test (if present) sets.\n train_loss, train_error = calculate_error_loss(xs, weights, ys)\n metrics[\"train_err\"][epoch] = train_error\n metrics[\"train_loss\"][epoch] = train_loss\n if train_error < best_error:\n # Save best weights.\n best_weights = copy.deepcopy(weights)\n best_error = train_error\n if test_xs is not None and test_ys is not None:\n test_loss, test_error = calculate_error_loss(test_xs, weights, test_ys)\n metrics[\"test_err\"][epoch] = test_error\n metrics[\"test_loss\"][epoch] = test_loss\n if print_metrics:\n print(\n f\"Epoch {epoch} - Training loss {train_loss} - Training error {train_error} - Test loss {test_loss}\"\n f\" - Test error {test_error}\")\n reset_seed()\n if return_best_weights:\n weights = best_weights\n if return_metrics:\n return weights, metrics\n return weights\n","sub_path":"digit_classification/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":10933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"598431431","text":"#! /usr/bin/env python\n\nimport re\n\nclass MarkdownHelper(object):\n\n\trulesRegex = [\n\t\t# tables\n\t\t(r'((?:([^\\r\\n|]*)\\|)+(?:([^\\r\\n|]*)))\\r?\\n(?:( ?:?-+:? ?)\\|)+(?:( ?:?-+:? ?))\\r?\\n(((?:([^\\r\\n|]*)\\|)+(?:([^\\r\\n|]*))\\r?\\n)+)', \"\\n
\\n \\n \\n
{{{{TH}}}}\\g<1>{{{{TH}}}}
{{{{TD}}}}\\g<6>{{{{TD}}}}
\\n
\\n\", re.MULTILINE),\n\t\t(r'(\\|(?:([^\\r\\n|]*)\\|)+)\\r?\\n\\|(?:( ?:?-+:? ?)\\|)+\\r?\\n((\\|(?:([^\\r\\n|]*)\\|)+\\r?\\n)+)', \"\\n\\n \\n \\n
{{{{TH}}}}\\g<1>{{{{TH}}}}
{{{{TD}}}}\\g<4>{{{{TD}}}}
\\n
\\n\", re.MULTILINE),\n\t\t# manage titles\n\t\t(r'^[#]{6}\\s*(.+)$', '
\\g<1>
\\n', re.MULTILINE),\n\t\t(r'^[#]{5}\\s*(.+)$', '
\\g<1>
\\n', re.MULTILINE),\n\t\t(r'^[#]{4}\\s*(.+)$', '

\\g<1>

\\n', re.MULTILINE),\n\t\t(r'^[#]{3}\\s*(.+)$', '

\\g<1>

\\n', re.MULTILINE),\n\t\t(r'^[#]{2}\\s*(.+)$', '

\\g<1>

\\n', re.MULTILINE),\n\t\t(r'^[#]{1}\\s*(.+)$', '

\\g<1>

\\n', re.MULTILINE),\n\t\t# specific titles\n\t\t(r'^(.*)\\n[=]+.*$', '

\\g<1>

\\n', re.MULTILINE),\n\t\t(r'^(.*)\\n[-][-]+.*\\n$', '

\\g<1>

\\n', re.MULTILINE),\n\t\t(r'[\\']{3}((.|\\n)+)[\\']{3}', '\\g<1>', re.MULTILINE), # code bloc\n\t\t# lines break\n\t\t(r'\\n([- * _]{3,})\\n', '
', 0),\n\t\t# manage caracters\n\t\t(r'\\s\\*{3}(.+)\\*{3}\\s', '\\g<1>', 0), # bolt && italic\n\t\t(r'\\s\\*{2}(.+)\\*{2}\\s', '\\g<1>', 0), # bolt\n\t\t(r'\\s\\*{1}(.+)\\*{1}\\s', '\\g<1>', 0), # italic\n\t\t(r'\\s_(.+)_\\s', '\\g<1>', 0), # underline\n\t\t# manage lists\n\t\t(r'^[ \\t]*(\\w|\\d)\\.[ \\t]+(.+)$\\n\\n', \"
  • \\g<2>
  • \\n\\n\", re.MULTILINE), # end of number\n\t\t(r'\\n\\n^[ \\t]*([\\w\\d])\\.[ \\t]+(.+)$', \"\\n\\n
      \\\" start=\\\"\\g<1>\\\">
    1. \\g<2>
    2. \\n\", re.MULTILINE), # start of number\n\t\t(r'^[ \\t]*[-\\*][ \\t]+(.+)\\n$', \"
    3. \\g<1>
    4. \\n\\n\", re.MULTILINE), # end of list\n\t\t(r'\\n\\n^[ \\t]*[-\\*][ \\t]+(.+)$', \"\\n\\n
      • \\g<1>
      • \\n\", re.MULTILINE), # start of list\n\t\t(r'^[ \\t]*(([\\d\\w]\\.)|([-\\*]))[ \\t]+(.+)$', \"
      • \\g<4>
      • \\n\", re.MULTILINE), # content of list\n\n\t\t(r'/^\\r?\\n$/', \"
        \\n\", re.MULTILINE), # new line\n\t\t# paragraph\n\t\t#'/<.*>((.|\\n)*)<\\/.*>/', '

        ${1}

        ',\n\t\t# links\n\t\t(r'\\s\\[(.*)\\]\\((.*)\\)\\s', \"
        \\\" target=\\\"_blank\\\">\\g<1>\", re.MULTILINE),\n\t\t# images\n\t\t(r'\\s!\\[(.*)\\]\\((.*)\\)\\s', \"\\\" alt=\\\"\\g<1>\\\" />\", re.MULTILINE),\n\t\t# videos\n\t]\n\n\t@staticmethod\n\tdef transformMdToHtml(fullText):\n\t\n\t\tfor (patternReg, replacStr, flagsPat) in MarkdownHelper.rulesRegex:\n\t\t\tfullText = re.sub(patternReg, replacStr, fullText, flags=flagsPat)\n\n\t\t# Table treatment\n\n\t\t# define TH part Table\n\t\treplaceTH = lambda matchobj: matchobj.group(1).replace('|',\"\")\n\t\t# treatment on TH part Table\n\t\tfullText = re.sub(r'{{{{TH}}}}\\s?[|]?(.*?)[|]?\\s?{{{{TH}}}}', replaceTH, fullText, flags=re.MULTILINE)\n\n\t\t# define TD part Table\n\t\treplaceTD = lambda matchobj: re.sub(r'\\|?\\r?\\n\\|?','\\n ', matchobj.group(1), flags=re.MULTILINE).replace('|', \"\")\n\t\t# treatment on TD part Table\n\t\tfullText = re.sub(r'{{{{TD}}}}\\s*[|]?((.|\\n)*?)\\n?[|]?\\s*{{{{TD}}}}', replaceTD, fullText, flags=re.MULTILINE)\n\t\n\t\treturn fullText\n\n\n#Do for tests\nif __name__ == '__main__':\n\n\ttest = \"\"\"\n\t\t\nThis is a simple test for MardownHelper\n\n***\n\n# Title1\n\nunder the title 1\n\n## Title 2\n\nunder thte title 2\n\n\nList:\n\n- l1\n- l2\n- l3\n- l4\n\n\n\"\"\"\n\n\t# historic calling\n\t#with open('../tests.md', 'r') as myfile:\n\t#\ttest = myfile.read()\n\tfrom pathlib import Path\n\ttxt = Path('../tests.md').read_text()\n\n\ttransformedText = MarkdownHelper.transformMdToHtml(txt)\n\tprint(transformedText)","sub_path":"python/MarkdownHelper.py","file_name":"MarkdownHelper.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"312198016","text":"###\n# PASA Confidentiality Notice:\n# This source code and information contained herewith may be legally privileged and confidential\n# Any dissemination, distribution or copy of this source code is strictly prohibited.\n#\n# Copyright (C) 2019, Panasonic Automotive Systems Company of America\n# All Rights Reserved\n#\n#\n# @file: email_test.py\n#\n# @author: Panasonic, developer\n#\n##\n\nimport unittest\n\nfrom unittest.mock import patch, MagicMock\n\nfrom sns2email.email import EmailSender, CHARSET\n\n\nclass TestEmailSender(unittest.TestCase):\n @patch(\"sns2email.email.os\")\n def test_email_create(self, os):\n sender = \"test_sender\"\n recipient = \"test_recipient\"\n os.getenv.side_effect = [sender, recipient]\n\n email = EmailSender()\n\n self.assertEqual(email.sender, sender)\n self.assertEqual(email.recipient, recipient)\n\n @patch(\"sns2email.email.boto3\")\n @patch(\"sns2email.email.os\")\n def test_email_send(self, os, boto3):\n subject = \"test_subject\"\n body = \"test_body\"\n sender = \"test_sender\"\n recipient = \"test_recipient\"\n os.getenv.side_effect = [sender, recipient]\n ses_client_mock = MagicMock()\n boto3.client.side_effect = [ses_client_mock]\n\n email = EmailSender().send(subject=subject, body=body)\n\n ses_client_mock.send_email.assert_called_once_with(Destination={'ToAddresses': [recipient]}, Message={'Body': {'Text': {'Charset': 'UTF-8', 'Data': body}}, 'Subject': {'Charset': 'UTF-8', 'Data': subject}}, Source=sender)\n","sub_path":"lambda/sns2email/tests/email_test.py","file_name":"email_test.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"146387472","text":"# -*- coding: utf-8 -*-\n#this is a module containing all the relationship-related functions.\nimport hashlib\nimport re\nimport configparser\nimport json\nimport os\n\nhash = hashlib.md5()\n\nconfig = configparser.ConfigParser()\nconfigPath = './config/graph.cfg'\nconfig.read(configPath)\n\nunwantedWords = config['relationship']['unwanted'].split(',')\n#print(unwantedWords)\n\nconfigPath = './config/data.cfg'\nconfig.read(configPath)\ndataDir = config['data']['dataDir']\n\nif os.path.isfile(dataDir + 'graph/relationships/relationships.txt'):\n with open(dataDir + 'graph/relationships/relationships.txt', 'r') as g:\n data = [item.strip() for item in g.readlines()]\nelse:\n data = []\n\n\n#print(data)\n\ndef formatRel(rel, unwantedWords):\n for word in unwantedWords:\n rel = re.sub(word + ' ','',rel)\n return rel\n\n\ndef createRelationshipFromDict(dictionary):\n start = dictionary['start']\n end = dictionary['end']\n relationship = formatRel(dictionary['relationship'], unwantedWords)\n \n sentence = start + '---' + relationship +'---' + end\n sentence = sentence.replace('/','-')\n# hash.update(sentence.encode('utf-8'))\n# h = hash.hexdigest()\n \n with open(dataDir + 'graph/relationships/relationships.txt', 'a') as f:\n js = json.dumps(dictionary)\n if js in data:\n print('Relationship already existed: ', start , ' -[', relationship, ']-> ', end)\n return None\n print(js, file=f)\n print('Relationship created: ', start , ' -[', relationship, ']-> ', end)\n\n\ndef createRelationshipFromCategoryBox(catbox):\n #catbox['main'] is a child node of categories.\n main = catbox['main']\n categories = catbox['categories']\n\n relationships = [{'start': category['name'], 'end': main, 'relationship': 'subcategory', 'source':'catbox'} for category in categories]\n [createRelationshipFromDict(relationship) for relationship in relationships]\n \ndef createRelationshipFromCategoryPage(catPage):\n try:\n main = catPage['main']['name']\n children = catPage['child']\n relationships = [{'start':main, 'end':child['name'], 'relationship':'subcategory','source':'catpage'} for child in children]\n [createRelationshipFromDict(relationship) for relationship in relationships]\n except TypeError:\n pass\n\ndef createRelationshipFromNavbox(table):\n tb = table['navbox']\n mainNode = table['main']\n relationships = []\n name = mainNode['name']\n try:\n links = mainNode['links']\n except (KeyError, AttributeError):\n links = None\n \n def createRelationship(layer, rel = '', z=''):\n if type(layer) == list:\n for item in layer:\n R = rel\n Z = z\n Z = Z.split('---')\n #Z is now an array\n #Remove empty elem\n Arr = []\n for e in Z:\n if e != '':\n Arr.append(formatRel(e, unwantedWords))\n \n relationship = {'start': name, 'end':item['name'], 'relationship': formatRel(R, unwantedWords), 'source':'navbox', 'relLabel': Arr}\n relationships.append(relationship)\n #createSimpleNode(item['name'])\n else:\n for key in layer:\n #print([key, rel])\n if key != rel:\n R = key\n Z = z + '---' + key\n else:\n R = rel\n Z = z\n createRelationship(layer[key], R, Z)\n #print('Created nodes from navbox layer: ', layer)\n \n createRelationship(tb)\n \n if links:\n if len(links) > 1:\n mainLinkRelationships = []\n mainLinkRelationships = []\n for link in links:\n #create relationships between links and childNodes\n linkChildRelationships = []\n mainLinkRelationship = {'start': name, 'end':link['name'], 'relationship': 'related concept', 'source':'navtitle'}\n mainLinkRelationships.append(mainLinkRelationship)\n for relationship in relationships:\n linkChildRelationship = {'start': link['name'], 'end':relationship['end'], 'relationship': relationship['relationship'], 'source':'navtitle'}\n linkChildRelationships.append(linkChildRelationship)\n #create relationships between mainNode and links\n \n \n \n relationships = relationships + linkChildRelationships + mainLinkRelationships\n print('Created relationships from navbox') \n [createRelationshipFromDict(relationship) for relationship in relationships]\n return relationships\n \n#createRelationshipFromCategoryBox(catbox)\n#createRelationshipFromCategoryPage(categoryPage)\n#rel = createRelationshipFromNavbox(tables[2])\n#print(rel)","sub_path":"graph/relationship.py","file_name":"relationship.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"353456049","text":"# encoding: UTF-8\n\nfrom __future__ import print_function\nimport json\nimport requests\nfrom socketIO_client import SocketIO\nfrom threading import Thread\nfrom queue import Queue, Empty\n\n\n########################################################################\nclass FxcmApi(object):\n \"\"\"FXCM\"\"\"\n API_URL = 'https://api-demo.fxcm.com:443'\n WEBSOCKET_PORT = 443\n METHOD_GET = 'get'\n METHOD_POST = 'post'\n \n MODEL_OFFER = 'Offer'\n MODEL_ACCOUNT = 'Account'\n MODEL_ORDER = 'Order'\n MODEL_OPENPOSITION = 'OpenPosition'\n MODEL_SUMMARY = 'Summary'\n MODEL_PROPERTIES = 'Properties'\n MODEL_CLOSEDPOSITION = 'ClosedPosition'\n\n #----------------------------------------------------------------------\n def __init__(self):\n \"\"\"Constructor\"\"\"\n self.url = ''\n self.port = ''\n self.token = ''\n self.proxy = ''\n \n self.sio = None\n self.bearer = ''\n self.headers = None\n \n self.queue = Queue()\n self.reqid = 0\n self.active = False\n self.reqThread = None\n self.sioThread = None\n \n #----------------------------------------------------------------------\n def connect(self, url, port, token, proxy=''):\n \"\"\"连接\"\"\"\n self.url = url\n self.port = port\n self.token = token\n self.proxy = proxy\n \n self.active = True\n \n self.reqThread = Thread(target=self.runReq)\n self.reqThread.start()\n \n self.sioThread = Thread(target=self.runSio)\n self.sioThread.start()\n \n #----------------------------------------------------------------------\n def stop(self):\n \"\"\"停止\"\"\"\n if self.active:\n self.active = False\n self.reqThread.join()\n \n self.sio._close()\n self.sioThread.join()\n \n #----------------------------------------------------------------------\n def initSocketIO(self):\n \"\"\"初始化SocketIO客户端\"\"\"\n params = {\n 'access_token': self.token, \n 'agent': \"leiwang-rest-api\"\n }\n \n proxy = {}\n if self.proxy:\n proxy['https'] = self.proxy \n \n self.sio = SocketIO(self.url, self.port, params=params, proxies=proxy)\n \n self.sio.on('connect', self.onConnect)\n self.sio.on('disconnect', self.onDisconnect)\n \n #----------------------------------------------------------------------\n def generateBearer(self):\n \"\"\"创建通讯授权码\"\"\"\n self.bearer = \"Bearer \" + self.sio._engineIO_session.id + self.token\n \n #----------------------------------------------------------------------\n def generateHeaders(self):\n \"\"\"生成通讯头部\"\"\"\n self.headers = {\n 'User-Agent': 'request',\n 'Authorization': self.bearer,\n 'Accept': 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n \n #----------------------------------------------------------------------\n def runReq(self):\n \"\"\"处理主动请求\"\"\"\n while self.active:\n try:\n d = self.queue.get(timeout=1)\n self.processReq(d)\n except Empty:\n pass\n \n #----------------------------------------------------------------------\n def runSio(self):\n \"\"\"处理回调数据\"\"\"\n self.initSocketIO()\n self.generateBearer()\n self.generateHeaders() \n self.sio.wait()\n \n #----------------------------------------------------------------------\n def sendReq(self, method, uri, params, callback):\n \"\"\"发出请求\"\"\"\n self.reqid += 1\n \n d = {\n 'method': method,\n 'uri': uri,\n 'params': params,\n 'callback': callback,\n 'reqid': self.reqid\n }\n \n self.queue.put(d)\n \n return self.reqid\n \n #----------------------------------------------------------------------\n def processReq(self, d):\n \"\"\"处理请求\"\"\"\n method = d['method']\n uri = d['uri']\n params = d['params']\n callback = d['callback']\n reqid = d['reqid']\n \n url = self.url + uri\n \n proxy = {}\n if self.proxy:\n proxy['https'] = self.proxy\n \n if method == self.METHOD_GET:\n resp = requests.get(url, headers=self.headers, params=params, proxies=proxy)\n elif method == self.METHOD_POST:\n resp = requests.post(url, headers=self.headers, data=params, proxies=proxy)\n \n if resp.status_code == 200:\n data = resp.json()\n if data[\"response\"][\"executed\"] is True:\n callback(data, reqid)\n return\n if 'response' in data:\n self.onError(data[\"response\"][\"error\"], reqid)\n else:\n self.onError(u'HTTP请求失败,错误代码%s' %resp.status_code)\n \n #----------------------------------------------------------------------\n def getInstruments(self):\n \"\"\"查询合约代码\"\"\"\n uri = '/trading/get_instruments'\n reqid = self.sendReq(self.METHOD_GET, uri, {}, self.onGetInstruments)\n return reqid\n \n #----------------------------------------------------------------------\n def getModel(self, model):\n \"\"\"查询表\"\"\"\n uri = '/trading/get_model'\n params = {'models': model}\n reqid = self.sendReq(self.METHOD_GET, uri, params, self.onGetModel)\n return reqid \n \n #----------------------------------------------------------------------\n def subscribe(self, symbol):\n \"\"\"订阅行情\"\"\"\n uri = '/subscribe'\n params = {'pairs': symbol}\n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onSubscribe)\n self.sio.on(symbol, self.processPriceUpdate)\n return reqid\n \n #----------------------------------------------------------------------\n def unsubscribe(self, symbol):\n \"\"\"退订行情\"\"\"\n uri = '/unsubscribe'\n params = {'pairs': symbol}\n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onUnsubscribe)\n return reqid \n \n #----------------------------------------------------------------------\n def subscribeModel(self, model):\n \"\"\"订阅表\"\"\"\n uri = '/trading/subscribe'\n params = {'models': model}\n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onSubscribeModel)\n self.sio.on(model, self.processModelUpdate)\n return reqid\n \n #----------------------------------------------------------------------\n def unsubscribeModel(self, model):\n \"\"\"退订表\"\"\"\n uri = '/trading/unsubscribe'\n params = {'models': model}\n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onUnsubscribeModel)\n return reqid \n \n #----------------------------------------------------------------------\n def updateSubscriptions(self, symbol):\n \"\"\"订阅报价表\"\"\"\n uri = '/trading/update_subscriptions'\n params = {\n 'symbol': symbol,\n 'visible': 'true'\n }\n #params = {'symbol': symbol} \n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onUpdateSubscriptions)\n return reqid \n \n #----------------------------------------------------------------------\n def openTrade(self, accountID, symbol, isBuy, amount,\n atMarket, orderType, timeInForce,\n rate=0, limit=0, stop=0, \n trailingStep=0, isInPips=False):\n \"\"\"市价开仓交易\"\"\"\n uri = '/trading/open_trade'\n params = {\n 'account_id': accountID,\n 'symbol': symbol,\n 'is_buy': isBuy,\n 'amount': amount,\n 'at_market': atMarket,\n 'order_type': orderType,\n 'time_in_force': timeInForce,\n 'is_in_pips': isInPips\n }\n \n if rate:\n params['rate'] = rate\n \n if rate:\n params['limit'] = limit\n \n if stop:\n params['stop'] = stop\n \n if trailingStep:\n params['trailing_step'] = trailingStep\n \n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onOpenTrade)\n return reqid \n \n #----------------------------------------------------------------------\n def createEntryOrder(self, accountID, symbol, isBuy, rate, \n amount, orderType, timeInForce,\n limit=0, stop=0, trailingStep=0, isInPips=False):\n \"\"\"限价开仓交易\"\"\"\n uri = '/trading/create_entry_order'\n \n params = {\n 'account_id': accountID,\n 'symbol': symbol,\n 'is_buy': isBuy,\n 'rate': rate,\n 'amount': amount,\n 'order_type': orderType,\n 'time_in_force': timeInForce,\n 'is_in_pips': isInPips\n }\n \n if rate:\n params['limit'] = limit\n \n if stop:\n params['stop'] = stop\n \n if trailingStep:\n params['trailing_step'] = trailingStep\n \n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onOpenTrade)\n return reqid\n \n #----------------------------------------------------------------------\n def closeTrade(self, tradeID, amount, atMarket, orderType, timeInForce, rate=0):\n \"\"\"平仓交易\"\"\"\n uri = '/trading/close_trade'\n params = {\n 'trade_id': tradeID,\n 'amount': amount,\n 'at_market': atMarket,\n 'order_type': orderType,\n 'time_in_force': timeInForce\n }\n \n if rate:\n params['rate'] = rate\n\n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onCloseTrade)\n return reqid \n \n #----------------------------------------------------------------------\n def changeOrder(self, orderID, rate, range_, amount, trailingStep=0):\n \"\"\"修改委托\"\"\"\n uri = '/trading/change_order'\n params = {\n 'order_id': orderID,\n 'rate': rate,\n 'range': range_,\n 'amount': amount\n }\n \n if trailingStep:\n params['trailing_step'] = trailingStep\n \n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onChangeOrder)\n return reqid \n \n #----------------------------------------------------------------------\n def deleteOrder(self, orderID):\n \"\"\"撤销委托\"\"\"\n uri = '/trading/delete_order'\n params = {'order_id': orderID}\n reqid = self.sendReq(self.METHOD_POST, uri, params, self.onDeleteOrder)\n return reqid \n \n #----------------------------------------------------------------------\n def onConnect(self):\n \"\"\"连接回调\"\"\"\n print('onConnect')\n \n #----------------------------------------------------------------------\n def onDisconnect(self):\n \"\"\"断开回调\"\"\"\n print('onClose')\n \n #----------------------------------------------------------------------\n def onError(self, error, reqid):\n \"\"\"错误回调\"\"\"\n print('onError', error)\n \n #----------------------------------------------------------------------\n def onGetInstruments(self, data, reqid):\n \"\"\"查询合约代码回调\"\"\"\n print(data, reqid)\n \n #----------------------------------------------------------------------\n def onGetModel(self, data, reqid):\n \"\"\"查询表回调\"\"\"\n print('*' * 30)\n print(data)\n for d in data['offers']:\n #if str(d['currency']) == 'EUR/USD':\n # print d\n print(d['currency'])#, d['visible']\n #print len(data['summary'])\n #print data\n \n \n #----------------------------------------------------------------------\n def onSubscribe(self, data, reqid):\t\n \"\"\"订阅行情回调\"\"\"\n print(data, reqid) \n \n #----------------------------------------------------------------------\n def onUnsubscribe(self, data, reqid):\n \"\"\"退订行情回调\"\"\"\n print(data, reqid) \n \n #----------------------------------------------------------------------\n def onSubscribeModel(self, data, reqid):\n \"\"\"订阅表回调\"\"\"\n print(data, reqid) \n \n #----------------------------------------------------------------------\n def onUnsubscribeModel(self, data, reqid):\n \"\"\"退订表回调\"\"\"\n print(data, reqid) \n \n #----------------------------------------------------------------------\n def onUpdateSubscriptions(self, data, reqid):\n \"\"\"订阅报价表回调\"\"\"\n print(data, reqid)\n \n #----------------------------------------------------------------------\n def onOpenTrade(self, data, reqid):\n \"\"\"开仓回调\"\"\"\n print(data, reqid)\n \n #----------------------------------------------------------------------\n def onCloseTrade(self, data, reqid):\n \"\"\"平仓回调\"\"\"\n print(data, reqid) \n \n #----------------------------------------------------------------------\n def onChangeOrder(self, data, reqid):\n \"\"\"改单回调\"\"\"\n print(data, reqid) \n\n #----------------------------------------------------------------------\n def onDeleteOrder(self, data, reqid):\n \"\"\"撤单回调\"\"\"\n print(data, reqid) \n \n #----------------------------------------------------------------------\n def processPriceUpdate(self, msg):\n \"\"\"行情推送\"\"\"\n data = json.loads(msg)\n self.onPriceUpdate(data)\n \n #----------------------------------------------------------------------\n def processModelUpdate(self, msg):\n \"\"\"表推送\"\"\"\n print(msg)\n data = json.loads(msg)\n self.onModelUpdate(data)\n \n #----------------------------------------------------------------------\n def onPriceUpdate(self, data):\n \"\"\"行情推送\"\"\"\n print(data)\n \n #----------------------------------------------------------------------\n def onModelUpdate(self, data):\n \"\"\"表推送\"\"\"\n print(data)\n #print '*' * 30\n #fsubscribeModel\n #print len(data), data.get('isTotal', None), data\n #print '*' * 30\n #for d in data:\n # print d\n\n ","sub_path":"vnpy/api/fxcm/vnfxcm.py","file_name":"vnfxcm.py","file_ext":"py","file_size_in_byte":14802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"560443627","text":"def isIn(c, temp):\n for i in range(0, len(temp)):\n if c == temp[i]:\n return True\n return False\n\n\ndef removeRepeat(s):\n rmv = []\n for i in range(0, len(s)):\n if isIn(s[i], rmv):\n continue\n else:\n rmv.append(s[i])\n return rmv\n\n\ndef checkIsogram(s):\n rmv = removeRepeat(s)\n if len(rmv) == len(s):\n return True\n else:\n return False\n\n\nt = int(input())\nfor i in range(0, t):\n inp = str(input())\n s = inp\n if checkIsogram(s):\n print(1)\n else:\n print(0)","sub_path":"Code/CodeRecords/2559/60673/300507.py","file_name":"300507.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"69703121","text":"# SPDX-FileCopyrightText: 2021 Kevin Matocha\n#\n# SPDX-License-Identifier: MIT\n\n\"\"\"\n`Animation`\n================================================================================\nCircuitPython Animation Class to make it easy to move around displayio and\nvectorio graphical elements.\n\n* Author(s): Kevin Matocha\n\nImplementation Notes\n--------------------\n\n**Hardware:**\n\n**Software and Dependencies:**\n\n* Adafruit CircuitPython firmware for the supported boards:\n https://github.com/adafruit/circuitpython/releases\n\n\"\"\"\n\n# Animation class for use with displayio Groups\n\nfrom adafruit_displayio_layout.widgets.easing import linear_interpolation\n\n\n# pylint: disable=too-many-arguments, anomalous-backslash-in-string, invalid-name\n# pylint: disable=unused-argument, too-few-public-methods, useless-super-delegation\n\n\nclass Animation(list):\n \"\"\"An Animation class to make it easy to making moving animations with CircuitPython's\n displayio and vectorio graphical elements.\n\n After instancing an `Animation()` object, use `Animation.add_entry()` to add\n frame animation sections. Once all your animation entries are added, then perform\n the frame animation using `Animation.execute_frame()`.\n\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def add_entry(self, group, frame_start, frame_end, function, **kwargs):\n \"\"\"Adds an animation entry into the Animation list.\n\n :param displayio.Group group: the displayio Group that will be animated\n within this frame range\n :param float frame_start: the starting frame position for this animation\n :param float frame_end: the ending frame position for this animation\n :param function: the name of the function to be called to mutate\n the ``group`` during the frame range\n :param \\*\\*kwargs: the additional arguments that should be passed to\n `function` when `Animation.execute_frame()` is called to trigger the\n animation to execute\n\n Note: See the definition of `Animation.execute_frame()` to understand\n what other parameters are sent to `function` during animations.\n\n \"\"\"\n\n myentry = Entry(\n group,\n frame_start,\n frame_end,\n function, # will be called function(position=position, arguments...)\n kwargs,\n )\n\n self.append(myentry)\n\n def execute_frame(self, frame):\n \"\"\"The function that performs the actual frame animation execution.\n\n This function searches through all ``Entry`` items that have been added to\n the Animation instance to determine if this frame is within the window of\n ``frame_start`` to ``frame_end``. If the requested frame is within the window,\n this calls the ``Entry.function`` with several \"internal\" parameters along\n with the additional \"user\" parameters that were input as additional arguments\n in the ``Animation.add_entry()`` function.\n\n The parameters that are sent to ``Entry.function()`` are:\n - float position: a value between 0.0 and 1.0 representing the current ``frame``\n distance within the window of ``frame_start`` and ``frame_end``. For example, if\n the current ``frame`` is equal to ``frame_start``, then ``position`` is 0.0.\n - displayio.Group group: the group to be animated using ``function``\n - int x0: the x-position of the group at ``frame_start``\n - int y0: the y-position of the group at ``frame_start``\n - float frame: the current frame that is being executed\n - float frame_start: the starting frame for this frame window\n - float frame_end: the ending frame for this frame window\n - \\*\\*kwargs: any other parameters that were defined in the Entry\n\n The ``function`` should be designed to ignore any unneeded input parameters by\n including ``**kwargs`` as one of the input parameters. This will cause the\n function to ignore excess arguments.\n\n Note: If a function requires the (x0,y0) values, you **must** initally perform\n ``Animation.execute_frame()`` at frame == frame_start. The ``Animation.execute_frame()``\n initializes the (x0, y0) values only when called with the value of ``frame_start``.\n\n Other Note: The frame window is \"exclusive\", so no animation is performed when\n ``frame == frame_end``.\n\n :param float frame: The frame to be displayed. Note: This is a float, so subframes\n can be animated.\n \"\"\"\n for entry in self:\n\n if frame == entry.frame_start: # initialize startx, starty\n entry.startx = entry.group.x\n entry.starty = entry.group.y\n\n if entry.frame_start <= frame < entry.frame_end:\n # This frame is within the entry frame range, so animate it\n\n # calculate a value between 0.0 and 1.0 to show the current frame's\n # position within this entry's frame range\n\n if (\n entry.frame_end - 1 - entry.frame_start\n ) <= 0: # prevent divide by zero\n position = 1.0\n else:\n position = (frame - entry.frame_start) / (\n entry.frame_end - 1 - entry.frame_start\n )\n entry.function(\n position=position,\n group=entry.group,\n x0=entry.startx,\n y0=entry.starty,\n frame=frame,\n frame_start=entry.frame_start,\n frame_end=entry.frame_end,\n **entry.kwargs,\n )\n\n\nclass Entry:\n \"\"\"This `Entry` class is a holder for the conditions that define an animated\n frame range. This holds the group, the \"augmentation\" function and arguments\n that are run at each call of `Animation.execute_frame`.\n\n Before running your loop with `Animation.execute_frame`, add all of your\n entries to the Animation object using `Animation.add_entry()`. Any excess\n arguments that are not handled by `Animation.execute_frame` will be passed\n to the `function` parameter (see notes on using the ``kwargs`` notation).\n\n Here is a code example. Append some display elements into ``group1``, create\n an Animation instance and then add an animation entry:\n\n .. code-block:: python\n\n group1=displayio.Group(max_size=1)\n\n animation=Animation()\n\n animation.add_entry(group=group1,\n frame_start=5, frame_end=20,\n function=translate,\n x1=50, y1=20, x2=50, y2=50,\n easing_function_x=quadratic_easeinout,\n easing_function_y=quadratic_easeinout)\n\n :param displayio.Group group: the group that is animated in this set of frames\n :param float frame_start: the starting frame for this animation\n :param float frame_end: the ending frame for this animation\n :param function: the function that mutates the group to cause the animation\n :param kwargs: a set of additional arguments that will be passed to the\n ``function`` during the animation\n \"\"\"\n\n def __init__(\n self,\n group,\n frame_start,\n frame_end,\n function,\n kwargs,\n ):\n self.group = group\n self.frame_start = frame_start\n self.frame_end = frame_end\n self.function = function\n self.kwargs = kwargs\n\n # Create placeholder instance variables, to store the initial\n # group's (x,y) position at the initial action frame\n self.startx = None\n self.starty = None\n\n\n#####################\n# Animation functions\n#####################\n# This is a starter set of functions that can be used with the Animation class\n#\n# The function can ignore some parameters that the ``execute_frame`` function sends.\n# Be sure to include ``**kwargs`` to the function input parameters\n# so the function will ignore all unused input parameters.\n#\n# Here are the parameters that ``execute_frame`` always sends to the function:\n# float position: a linear interpolation of the current frame's position between ``frame_start``\n# and ``frame_end``\n# displayio.Group group: the group in the Entry\n# int x0: initial x-position at the starting frame\n# int y0: initial y-position at the starting frame\n# float frame: the current frame\n# float frame_start: the starting frame of this animation entry\n# float frame_end: the ending frame of this animation entry (should be used as exclusive)\n# Other arguments that are defined in the `add_entry` call.\n\n\ndef translate(\n *,\n x1,\n y1,\n x2,\n y2,\n easing_function_x=linear_interpolation,\n easing_function_y=linear_interpolation,\n group,\n position,\n **kwargs\n):\n \"\"\"Performs a translation animation between two endpoints. Use two different\n easing functions to get all kinds of variety of cool motion.\n\n :param int x1: initial x-position of ``group``\n :param int y1: initial y-position of ``group``\n :param int x2: final x-position of ``group``\n :param int y2: final y-position of ``group``\n\n :param function easing_function_x: easing function that modifies the ``position`` value\n for the x-motion (default: linear_interpolation)\n :param function easing_function_y: easing function that modifies the ``position`` value\n for the y-motion (default: linear_interpolation)\n\n :param displayio.Group group: the display group that is sent to the ``function``. If using\n `Animation.execute_frame()` the group input parameter will be included automatically\n from the Entry.\n :param float position: float position: a linear interpolation of the current frame's\n position between ``frame_start`` and ``frame_end``. If using\n `Animation.execute_frame()` the ``position`` parameter will be included automatically.\n \"\"\"\n # including kwargs here is necessary to ignore excess arguments\n # user parameters: x1, y1, x2, y2, easing_function_x, easing_function_y\n # parameters handled from `execute_frame`: group, position\n\n group.x = round((x2 - x1) * easing_function_x(position)) + x1\n group.y = round((y2 - y1) * easing_function_y(position)) + y1\n\n\ndef translate_relative(\n *,\n delta_x,\n delta_y,\n easing_function_x,\n easing_function_y,\n group,\n x0,\n y0,\n position,\n **kwargs\n):\n \"\"\"Performs a relative translation animation between two endpoints. Use two different\n easing functions to get all kinds of variety of cool motion.\n\n Note: To use relative translations, be sure to run `execute_frame` at ``frame_start`` first\n so the initial (x0, y0) position is stored. For example, if you run the frames in reverse,\n you must run `execute_frame` at ``frame_start`` at least once initialize the initial (x0, y0)\n position.\n\n Special note: Relative translations can get complicated. If you want to tightly control\n predefined positions, then `translate` is the best approach. By combining overlapping\n relative translations, you can probably come up with all kinds of clever and confusing\n animations. Perhaps the `translate_relative` function is an avenue to create animated\n \"generative art\" projects.\n\n :param int x2: final x-position of ``group``\n :param int y2: final y-position of ``group``\n\n :param function easing_function_x: easing function that modifies the ``position`` value\n for the x-motion (default: linear_interpolation)\n :param function easing_function_y: easing function that modifies the ``position`` value\n for the y-motion (default: linear_interpolation)\n\n :param displayio.Group group: the display group that is sent to the ``function``. If using\n `Animation.execute_frame()` the ``group`` input parameter will be included automatically\n from the Entry.\n :param int x0: initial x-position of ``group``. If using `Animation.execute_frame()`\n the ``x0`` input parameter will be included automatically from the Entry.\n :param int y0: initial y-position of ``group``. If using `Animation.execute_frame()`\n the ``y0`` input parameter will be included automatically from the Entry.\n :param float position: float position: a linear interpolation of the current frame's\n position between ``frame_start`` and ``frame_end``. If using\n `Animation.execute_frame()` the ``position`` parameter will be included automatically.\n \"\"\"\n # including kwargs here is necessary to ignore excess arguments\n # user parameters: x2, y2, easing_function_x, easing_function_y\n # parameters handled from `execute_frame`: group, x0, y0, position\n group.x = round((delta_x) * easing_function_x(position)) + x0\n group.y = round((delta_y) * easing_function_y(position)) + y0\n\n\ndef wiggle(\n *,\n delta_x=0,\n delta_y=0,\n xsteps=None,\n ysteps=None,\n group,\n x0,\n y0,\n frame_start,\n frame,\n **kwargs\n):\n \"\"\"Performs a nervous wiggling animation around the starting point. To achieve a random-looking\n wiggle, set ``xsteps`` and ``ysteps`` to two different prime numbers.\n\n Note: To use `wiggle`, be sure to run `execute_frame` at ``frame_start`` first\n so the initial (x0, y0) position is stored. For example, if you run the frames in reverse,\n you must run `execute_frame` at ``frame_start`` at least once initialize the initial (x0, y0)\n position.\n\n :param int delta_x: amount of x-movement, in pixels (default = 0)\n :param int delta_y: amount of y-movement, in pixels (default = 0)\n :param int xsteps: number of frame steps it takes to make a full x-direction wiggle\n :param int ysteps: number of frame steps it takes to make a full y-direction wiggle\n :param displayio.Group group: the display group that is sent to the ``function``. If using\n `Animation.execute_frame()` the ``group`` input parameter will be included automatically\n from the Entry.\n :param int x0: initial x-position of ``group``. If using `Animation.execute_frame()`\n the ``x0`` input parameter will be included automatically from the Entry.\n :param int y0: initial y-position of ``group``. If using `Animation.execute_frame()`\n the ``y0`` input parameter will be included automatically from the Entry.\n :param float frame_start: the starting frame of this animation entry. If using\n `Animation.execute_frame()` the ``frame_start`` parameter will be included automatically\n from the Entry.\n :param float frame: the current frame being animated. If using\n `Animation.execute_frame()` the ``frame`` parameter will be included automatically.\n \"\"\"\n\n # including kwargs here is necessary to ignore excess arguments\n # user parameters: delta_x, delta_y, xsteps, ysteps\n # parameters handled from `execute_frame`: group, x0, y0, position, frame_start, frame\n\n if (xsteps is not None) and (delta_x != 0):\n xpositions = (\n list(range(xsteps // 2))\n + list(range(xsteps // 2 - 2, -1 * xsteps // 2, -1))\n + list(range(-1 * xsteps // 2 + 2, 0))\n )\n group.x = x0 + round(\n delta_x / xsteps * xpositions[int((frame - frame_start) % len(xpositions))]\n )\n\n if (ysteps is not None) and (delta_y != 0):\n ypositions = (\n list(range(ysteps // 2))\n + list(range(ysteps // 2 - 2, -1 * ysteps // 2, -1))\n + list(range(-1 * ysteps // 2 + 2, 0))\n )\n group.y = y0 + round(\n delta_y / ysteps * ypositions[int((frame - frame_start) % len(ypositions))]\n )\n","sub_path":"displayio_animation.py","file_name":"displayio_animation.py","file_ext":"py","file_size_in_byte":15621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"372515421","text":"from Graph import Graph\nimport random\n\n# Recursive function to calculate the ordering of the vertices\ndef recursive_DFS(G,vertex):\n stack = []\n G.mark_visited(vertex)\n # For every unvisited neighbour of the chosen vertex, DFS is run on\n # them\n for neighbour in G.unvisited_neighbours(vertex):\n dict = G.get_unvisited_dict()\n if neighbour in dict.keys():\n stack.extend(recursive_DFS(G,neighbour))\n stack.append(vertex)\n return stack\n\n# Function to calculate the component sizes by going through the given graph \n# in the order of the stack\ndef DFS_reversed(G,stack):\n component_sizes = []\n num_of_vertices = len(G.all_vertices())\n # Starting from the last vertex in the stack, we use DFS to find the strongly\n # connected components of the graph and append the size of the component to \n # the list of component sizes\n while(len(G.unvisited_vertices()) != 0):\n vertex = stack.pop()\n if vertex in G.unvisited_vertices():\n component_sizes.append(len(recursive_DFS(G,vertex)))\n return component_sizes\n\n# Function to compute the component sizes of the strongly connected \n# components of the given graph\ndef SCC(G,G_rev):\n # We choose a start vertex randomly and use DFS to order the vertices in\n # the first pass\n start_vertex = random.choice(G.unvisited_vertices())\n stack = recursive_DFS(G,start_vertex)\n while(len(G.unvisited_vertices()) != 0):\n stack.extend(recursive_DFS(G,random.choice(G.unvisited_vertices())))\n component_sizes = []\n # Using the ordering given by the algorithm in the first pass, we use \n # reversed DFS to find the component sizes\n component_sizes = DFS_reversed(G_rev,stack)\n return component_sizes","sub_path":"StronglyConnectedComponents/SCC.py","file_name":"SCC.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"111286347","text":"'''\nCreated on Apr 2, 2016\n\n@author: Edielson\n'''\n\nimport csv\nimport numpy as np\nimport struct \n\ndef LoadCSV(fileName,numFeatures):\n \n with open(fileName, 'rb') as csvfile:\n dataReader = csv.reader(csvfile, delimiter=',', quotechar='|')\n if numFeatures > 1:\n dataTrain=np.empty(shape=[0, numFeatures])\n for row in dataReader:\n listAux=[]\n for column in row:\n listAux.append(float(column))\n dataTrain = np.append(dataTrain, [listAux], axis=0)\n else:\n dataTrain=[]\n for row in dataReader:\n for column in row:\n dataTrain.append(float(column))\n \n return dataTrain \n\ndef LoadMel(fileName,numFeatures):\n with open(fileName, mode='rb') as file: # b is important -> binary\n fileContent = file.read(12*8)\n Mel=np.empty(shape=[0, numFeatures])\n while fileContent:\n out = struct.unpack('12d',fileContent[0:8*12])\n Mel = np.append(Mel, [out], axis=0)\n fileContent = file.read(12*8)\n return Mel\n return ","sub_path":"python/SurfaceRoughness/Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"569767726","text":"# -*- coding: utf-8 -*-\n# @time :21-1-13 下午3:55\nfrom argparse import ArgumentParser\nimport cv2\nimport numpy as np\nimport os\nimport json\nfrom mmdet.apis import inference_detector, init_detector, show_result_pyplot\n\n\n\njson_file = '/swdata/df/cz_data/data/tile_round1_train_20201231/test.json'\npath = '/swdata/df/cz_data/data/tile_round1_testA_20201231/testA_imgs'\nconfig = '/swdata/df/cz_data/mmdetection/df_use/retain/retain_net.py'\ncheckpoint = '/swdata/df/cz_data/mmdetection/df_use/log/epoch_12.pth'\n\nwith open(json_file, 'r') as d:\n data = json.load(d)\n\ncategories = data['categories']\nlabels = {}\nfor categorie in categories:\n id = categorie['id']\n name = categorie['name']\n labels[id] = int(name)\nmin_score = 1.\nout = []\nfiles = os.listdir(path)\n\ndone_files = []\nmodel = init_detector(config, checkpoint, device='cuda:0')\nfor file in files:\n done_files.append(file)\n print((len(done_files)*1.)/len(files))\n file_path = os.path.join(path, file)\n results = inference_detector(model, file_path)\n for result_inx in range(len(results)):\n out_single = {}\n name = file\n # print(name)\n result = results[result_inx]\n if len(result) == 0:\n continue\n categorie = labels[result_inx+1]\n # label_id = labels[result_inx]\n for bboxes in result:\n bbox = bboxes[:4]\n score = bboxes[4]\n if score < min_score:\n min_score = score\n print(min_score)\n if score < 0.01:\n continue\n # bbox = bbox.astype(np.int)\n bbox_single = []\n for bb in bbox:\n bbox_single.append(int(bb))\n # print(name)\n out_single['name'] = name\n out_single['category'] = categorie\n out_single['bbox'] = bbox_single\n out_single['score'] = np.float(score)\n out.append(out_single)\n\nprint(min_score)\nresult_out = json.dumps(out, ensure_ascii=False, indent=4)\nwith open('result1.json', 'w+', encoding='utf-8') as f:\n f.write(result_out)\n\n","sub_path":"df_use/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"227634271","text":"\n# coding=utf-8\nimport ujson as json\nimport redis, time, random\nfrom datetime import datetime\nfrom django.contrib.auth.models import User\nfrom location import REDLOC4\nfrom score import BAN_REASON, RATELIMIT_TTL, SUPER_FLOODING_THRESHOLD, FLOODING_THRESHOLD, LAZY_FLOODING_THRESHOLD, SHORT_MESSAGES_ALWD, \\\nSHARED_PHOTOS_CEILING, PHOTO_DELETION_BUFFER\nfrom models import UserProfile, Photo\n\n'''\n##########Redis Namespace##########\n\ncity_shops = \"city_shops\"\n\"historical_calcs\"\nlip: 'stores latest ip of a user for up to 5 mins'\nlogged_users = \"logged_users\"\nsorted_set = \"online_users\"\nuser_ban = \"ub:\"+str(user_id)\nuser_times = \"user_times:\"+str(user_id)\n\npusk:: # photo_upload_secret_key\ntisk::: # text input secret_key\n\nrlfh: - rate limited from home (e.g. because of abusive reasons)\nrlfpg: - rate limited from public group (e.g. because of spammy behavior)\nrlfpvg: - rate limited from private group (e.g. because of spammy behavior)\nrlfpc: - rate limited from photo comments (e.g. because of spammy behavior)\nrlfhr: - rate limited from home replies (e.g. because of spammy behavior)\n\nhir: - home input rate (list holding times of posting on home for a specific user)\npgir: - public group input rate (list holding times of posting in public group for a specific user)\npvgir: - private group input rate (list holding times of posting in public group for a specific user)\npcir: - photo comment input rate (list holding times of posting on photo comments for a specific user)\nhrir: - home reply input rate (list holding times of posting in home replies)\n\nhit: - home input text (list holding previous text of home posting for a specific user)\npgit: - public group input text (list holding text of public group posting for a specific user in a specific group)\npvgit: - private group input rate (list holding times of posting in private group for a specific user)\npcit: - photo comment input text (list holding text of photo comments for a specific user and a specific photo)\nhrit: - home reply input text (list holding text of home replies for a specific user under a specific home sentence)\n\nsm::
        : - counter to count short messages sent on home objects\n\nuser_id: is a key containing user_ids of certain usernames\nuname: is a hash containing username and avatar_url data of a user\npht: is a hash containing image_url and caption data of a photo posted by user\nphd: contains cached photo sharing data for a specific user_id (cached for 20 mins)\naurl: is 'avatar_uploading_rate_limit', and is used to rate limit how frequently a user can change their avatar\n\nvb:: 'visited_by' key that stores which star_id was visited by which visitor_id\n\n------------ Personal Group Metrics ------------\n\nlig_pm: contains user_id that performed latest interaction in private mehfil with id group_id\nlig_pg: contains user_id that performed latest interaction in private chat with id group_id\npm_ch contains list of private mehfil IDs alongwith number of chats occuring in those private mehfils\npm_sw contains list of private mehfil IDs alongwith number of switchovers occuring in those private mehfils\npg_ch contains list of private chat IDs alongwith number of chats occuring in those private chats\npg_sw contains list of private chat IDs alongwith number of switchovers occuring in those private chats\n\ngs_pm:: contains a 'session key' that idenitifies whether a new session has started for a user visiting a particular private mehfil\ngs_pg:: contains a 'session key' that idenitifies whether a new session has started for a user visiting a particular private chat\npm_sess contains : pairs alongwith number of 24 hour sessions for that pair\npg_sess contains : pairs alongwith number of 24 hour sessions for that pair\n\np2p_sms is a list of :: tuples, tracking SMSes in private chat\nrc: sets a key as a \"red carpet\" for sent_to_id (waits for them to return to Damadam as a result of an SMS sent by a friend)\nsms_eft tracks sms effectiveness. It contains : pairs for users who returned to Damadam after being sent an SMS\n\nexits contains : pairs alongwith times of exiting a private chat. Useful for charting average life of a private chat.\ndel_after_exit contains groups and exit times for groups that were deleted due to exiting\ndel_after_idle contains groups and exit times for groups that were deleted due to idleness\n\n------------ Social Sharing ------------\n\nas:: key to check whether a photo was already shared by a certain user (in whatsapp)\n\npdim: key that temporarily caches a shared photo's width and height\n\n\"sp: is a sorted set containing information about photos shared of each user\n\n###########\n'''\n\nPOOL = redis.ConnectionPool(connection_class=redis.UnixDomainSocketConnection, path=REDLOC4, db=0)\n\nTWO_WEEKS = 60*60*24*7*2\nTHREE_DAYS = 60*60*24*3\nONE_DAY = 60*60*24\nONE_HOUR = 60*60\nTWELVE_HOURS = 60*60*12\nTHIRTY_MINS = 30*60\nTWENTY_MINS = 20*60\nTEN_MINS = 10*60\nSEVEN_MINS = 7*60\nFIVE_MINS = 5*60\nTHREE_MINS = 3*60\nONE_MIN = 60\n\n\ndef convert_to_epoch(time):\n\treturn (time-datetime(1970,1,1)).total_seconds()\n\n\ndef save_deprecated_photo_ids_and_filenames(deprecated_photos):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tfinal_list = []\n\tfor filename, photo_id in deprecated_photos:\n\t\tfilename = filename.split('photos/')[1]\n\t\tfinal_list.append(filename)\n\t\tfinal_list.append(photo_id)\n\tmy_server.zadd(\"deprecated_photos\",*final_list)\n\n\n# def log_pic_uploader_status(user_id, is_verified):\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tverified = '1' if is_verified else '0'\n# \tmy_server.lpush('uploaded_pics',verified+\":\"+str(user_id))\n\n# def save_user_choice(user_id, choice):\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tmy_server.lpush(\"new_user_choice\",{'user_id':user_id,'user_choice':choice})\n\n# def log_referrer(referrer, loc, user_id):\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tmy_server.lpush(\"referrer\",{'referrer':referrer,'origin':loc, 'user_id':user_id, 'time_stamp':time.time()})\n\ndef return_referrer_logs(log_name):\n\treturn redis.Redis(connection_pool=POOL).lrange(log_name,0,-1)\n\n\n# def error_logger(obj_creator_reported_id, object_creator_actual_id,actual_object_attributes, reported_link_attributes, from_loc, is_post_request,referrer):\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tmy_server.lpush(\"block_error\",{'obj_creator_reported_id':obj_creator_reported_id,'object_creator_actual_id':object_creator_actual_id,\\\n# \t\t'actual_object_attributes':actual_object_attributes, 'reported_link_attributes':reported_link_attributes,'where_from':from_loc, \\\n# \t\t'is_post_request':is_post_request,'referrer':referrer})\n\n\n# def log_html_error(obj_list, forms, page, nickname, referrer):\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tmy_server.lpush(\"matka_error\",{'obj_list':obj_list,'forms':forms, 'page':page, 'username':nickname,'referrer':referrer ,'time':time.time()})\n\n# def log_button_error(target_user_id, id_type,target_username,own_id, object_id,referrer):\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tmy_server.lpush(\"button_error\",{'target_user_id':target_user_id,'id_type':id_type, 'target_username':target_username,'own_id':own_id, \\\n# \t\t'object_id':object_id,'referrer':referrer,'time':time.time()})\n\n\n# def save_number_verification_error_data(user_id, err_data, err_type=None, on_fbs=None, is_auth=None, which_flow=None):\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tif which_flow == 'consumer':\n# \t\terr_data[\"user_id\"], err_data[\"err_type\"], err_data[\"on_fbs\"], err_data[\"is_auth\"] = user_id, err_type, on_fbs, is_auth\n# \t\tmy_server.lpush(\"consumer_number_errors\",err_data)\n# \telse:\n# \t\terr_data[\"user_id\"], err_data[\"err_type\"], err_data[\"on_fbs\"], err_data[\"is_auth\"] = user_id, err_type, on_fbs, is_auth\n# \t\tmy_server.lpush(\"seller_number_errors\",err_data)\n\n#######################Ecomm Metrics######################\n\ndef log_ecomm_user_visit(user_id):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tmy_server.lpush(\"ecomm_visits\",user_id)\n\ndef get_and_reset_daily_ecomm_visits():\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tall_visits = my_server.lrange(\"ecomm_visits\",0,-1)\n\tpipeline1 = my_server.pipeline()\n\tpipeline1.lpush(\"weekly_ecomm_visits\",all_visits)\n\tpipeline1.delete(\"ecomm_visits\")\n\tpipeline1.execute()\n\treturn all_visits, my_server.llen(\"weekly_ecomm_visits\")\n\ndef get_and_reset_weekly_ecomm_visits():\n\timport ast\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tweekly_visits = my_server.lrange(\"weekly_ecomm_visits\",0,-1)\n\tweekly_gross_visits = []\n\tfor daily_visits in weekly_visits:\n\t\tweekly_gross_visits += ast.literal_eval(daily_visits)\n\tmy_server.delete(\"weekly_ecomm_visits\")\n\treturn weekly_gross_visits\n\n\ndef insert_metrics(ecomm_metrics, reporting_time, period=None):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tif period == 'daily':\n\t\tmapping = {'entry_time':reporting_time, 'unique_clicks_per_unique_visitor':ecomm_metrics[0], 'unique_clicks_per_unique_clicker':ecomm_metrics[1], \\\n\t\t'proportion_of_clickers_to_visitors':ecomm_metrics[2], 'unique_new_clickers_per_unique_new_visitors':ecomm_metrics[3], \\\n\t\t'unique_new_clicks_per_unique_new_visitor':ecomm_metrics[4], 'total_unique_visitors':ecomm_metrics[5], 'total_unique_clicks':ecomm_metrics[6]}\n\t\tmy_server.lpush(\"ecomm_metrics\",mapping)\n\tif period == 'weekly':\n\t\tmapping = {'entry_time':reporting_time, 'weekly_unique_clicks_per_unique_visitor':ecomm_metrics[0], 'weekly_unique_clicks_per_unique_clicker':ecomm_metrics[1], \\\n\t\t'weekly_proportion_of_clickers_to_visitors':ecomm_metrics[2], 'weekly_unique_visitors':ecomm_metrics[3], \\\n\t\t'weekly_unique_clicks':ecomm_metrics[4]}\n\t\tmy_server.lpush(\"weekly_ecomm_metrics\",mapping)\n\n\n\ndef return_all_metrics_data():\n\tmy_server = redis.Redis(connection_pool=POOL)\n\treturn my_server.lrange(\"ecomm_metrics\", 0, -1), my_server.lrange(\"weekly_ecomm_metrics\", 0, -1)\n\n#######################Photo Secret Key######################\n\ndef set_photo_upload_key(user_id, secret_key, group_id=None):\n\t\"\"\"\n\tUsed to prevent double form submission when uploading photos (public photos or personal group photos)\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tsec_key = \"pusk:\"+str(user_id)+\":\"+group_id if group_id else \"pusk:\"+str(user_id)\n\tmy_server.setex(sec_key,secret_key,TWENTY_MINS)\n\n\ndef get_and_delete_photo_upload_key(user_id, group_id=None):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tuser_id = str(user_id)\n\tsec_key = \"pusk:\"+user_id+\":\"+group_id if group_id else \"pusk:\"+user_id\n\tsecret_key = my_server.get(sec_key)\n\tif secret_key:\n\t\tmy_server.delete(sec_key)\n\t\treturn secret_key\n\telse:\n\t\treturn '1'\n\n\ndef set_text_input_key(user_id, obj_id, obj_type, secret_key):\n\t\"\"\"\n\tUsed to prevent double form submission\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tsec_key = \"tisk:\"+str(user_id)+\":\"+obj_type+\":\"+str(obj_id)\n\tmy_server.setex(sec_key,secret_key,TWENTY_MINS)\n\n\ndef get_and_delete_text_input_key(user_id, obj_id, obj_type):\n\t\"\"\"\n\tChecks if secret key exists and returns an appropriate response\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tsec_key = \"tisk:\"+str(user_id)+\":\"+obj_type+\":\"+str(obj_id)\n\tsecret_key = my_server.get(sec_key)\n\tif secret_key:\n\t\tmy_server.delete(sec_key)\n\t\treturn secret_key\n\telse:\n\t\treturn '1'\n\n\n######################## Shared urls caching (for private chat) ########################\n\ndef cache_meta_data(url, mapping, time_timen_to_sniff, time_taken_to_parse, is_youtube, deg_of_comp):\n\t\"\"\"\n\tCache shared url's meta_data for upto a day\n\t\"\"\"\n\tpipeline1 = redis.Redis(connection_pool=POOL).pipeline()\n\tpipeline1.hmset(url,mapping)\n\tpipeline1.expire(url,ONE_DAY)\n\tpipeline1.lpush(\"shared_urls\",url+\":\"+is_youtube+\":\"+\"{0:.2f}\".format(time_taken_to_parse)+\":\"+\"{0:.2f}\".format(time_timen_to_sniff)+\":\"+\"{0:.2f}\".format(time.time())+\":\"+deg_of_comp)\n\tpipeline1.ltrim(\"shared_urls\",0,999)#saving up to 1000 hits\n\tpipeline1.execute()\n\ndef get_cached_meta_data(url):\n\t\"\"\"\n\tReturns cached meta data, and extends life of cache by 3 days if it's a successful hit\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tmeta_data = my_server.hgetall(url)\n\tif meta_data:\n\t\tmy_server.expire(url,THREE_DAYS)\n\t\treturn meta_data\n\telse:\n\t\treturn {}\n\n\n###################### Photo dimensions and data caching ######################\n\ndef get_cached_photo_dim(photo_id):\n\t\"\"\"\n\tReturn photo with photo_id's height and width\n\t\"\"\"\n\tkey = 'pdim:'+photo_id\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tmy_server.expire(key,THREE_DAYS)#extending life of cache\n\treturn my_server.hmget(key,'h','w')\n\n\ndef cache_photo_dim(photo_id,img_height,img_width):\n\t\"\"\"\n\tCache photo dimensions for use in photo sharing to personal groups\n\t\"\"\"\n\tmapping, key = {'h':img_height,'w':img_width}, 'pdim:'+photo_id\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tmy_server.hmset(key,mapping)\n\tmy_server.expire(key,THREE_DAYS)\n\n\ndef retrieve_photo_data(photo_ids, owner_id):\n\t\"\"\"\n\tRetrieves photo data (caption and url)\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tphoto_data, missing_photos = {}, []\n\tfor photo_id in photo_ids:\n\t\tcaption, image_url, upload_time = my_server.hmget('pht:'+photo_id,'caption','image_url','upload_time')\n\t\tif caption and image_url and upload_time:\n\t\t\tphoto_data[photo_id] = {'caption':caption.decode('utf-8'),'image_url':image_url,'id':photo_id,'upload_time':upload_time}\n\t\telse:\n\t\t\tmissing_photos.append(photo_id)\n\tif missing_photos:\n\t\tmissing_data = Photo.objects.filter(id__in=missing_photos).values('id','image_file','caption','upload_time')\n\t\tfor data in missing_data:\n\t\t\tphoto_id = str(data['id'])\n\t\t\tkey = 'pht:'+photo_id\n\t\t\tupload_time = str(convert_to_epoch(data['upload_time']))\n\t\t\tphoto_data[photo_id] = {'caption':data['caption'],'image_url':data['image_file'],'id':photo_id,'upload_time':upload_time}\n\t\t\tmy_server.hmset(key,{'caption':data['caption'],'image_url':data['image_file'],'upload_time':upload_time})\n\t\t\tmy_server.expire(key,THREE_DAYS)\n\treturn photo_data\n\n###################### User credentials caching ######################\n\n\ndef retrieve_bulk_credentials(user_ids, decode_unames=False):\n\t\"\"\"\n\tReturns usernames and avatars if fed a list of user_ids\n\n\tAlso caches the data for up to TWO days\n\tIf avatar was never uploaded, 'empty' string is returned instead\n\tReturned format is dictionary of dictionaries, where int(user_ids) serve as keys. This ensures O(1) lookup down the road\n\t\"\"\"\n\tif not user_ids:\n\t\treturn {}\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\tfor user_id in user_ids:\n\t\tpipeline1.hmget('uname:'+str(user_id),'uname','avurl')\n\tcredentials_wip = pipeline1.execute() #credentials_wip is a list of lists\n\tcounter = 0\n\tcredentials = {}#list of dictionaries\n\tuncollected_unames, uncollected_avurls = [], []\n\tfor uname,avurl in credentials_wip:\n\t\tcurrent_uid = int(user_ids[counter])\n\t\tuname = '' if not uname else uname\n\t\tavurl = '' if not avurl else avurl\n\t\tif decode_unames:\n\t\t\tcredentials[current_uid] = {'uname':uname.decode('utf-8'),'avurl':avurl}\n\t\telse:\n\t\t\tcredentials[current_uid] = {'uname':uname,'avurl':avurl}\n\t\tif uname and avurl:\n\t\t\tpass\n\t\telif avurl:\n\t\t\t# log that this user's uname has to be retrieved\n\t\t\tuncollected_unames.append(current_uid)\n\t\telif uname:\n\t\t\t# log that this user's avurl has to be retrieved\n\t\t\tuncollected_avurls.append(current_uid)\n\t\telse:\n\t\t\t# log that this user's both credential have to be retrieved\n\t\t\tuncollected_unames.append(current_uid)\n\t\t\tuncollected_avurls.append(current_uid)\n\t\tcounter += 1\n\tcollected_unames, collected_avurls = [], []\n\tif uncollected_unames:\n\t\tcollected_unames = User.objects.filter(id__in=uncollected_unames).values('id','username')\n\t\tpipeline2 = my_server.pipeline()\n\t\tfor uname in collected_unames:\n\t\t\tuser_id = uname['id']\n\t\t\thash_name = 'uname:'+str(user_id)\n\t\t\tcredentials[user_id]['uname'] = uname['username']\n\t\t\tpipeline2.hset(hash_name, 'uname', uname['username'])\n\t\t\tpipeline2.expire(hash_name,ONE_DAY)\n\t\tpipeline2.execute()\n\tif uncollected_avurls:\n\t\tcollected_avurls = UserProfile.objects.filter(user_id__in=uncollected_avurls).values('user_id','avatar')\n\t\tpipeline3 = my_server.pipeline()\n\t\tfor avurl in collected_avurls:\n\t\t\tuser_id = avurl['user_id']\n\t\t\thash_name = 'uname:'+str(user_id)\n\t\t\tif not avurl['avatar']:\n\t\t\t\tavurl['avatar'] = 'empty'\n\t\t\tcredentials[user_id]['avurl'] = avurl['avatar']\n\t\t\tpipeline3.hset(hash_name, 'avurl', avurl['avatar'])\n\t\t\tpipeline3.expire(hash_name,ONE_DAY)\n\t\tpipeline3.execute()\n\treturn credentials\n\n\ndef retrieve_bulk_avurls(user_ids):\n\t\"\"\"\n\tRetrieves avatar_urls in bulk for a given list of user_ids\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\tfor user_id in user_ids:\n\t\tpipeline1.hget('uname:'+str(user_id),'avurl')\n\tavatars_wip = pipeline1.execute()\n\tcounter = 0\n\tavatars, uncollected_avurls = {}, []\n\tfor avatar in avatars_wip:\n\t\tuser_id = int(user_ids[counter])\n\t\tif avatar:\n\t\t\tavatars[user_id] = avatar\n\t\telse:\n\t\t\tuncollected_avurls.append(user_id)\n\t\tcounter += 1\n\tif uncollected_avurls:\n\t\tcollected_avurls = UserProfile.objects.filter(user_id__in=uncollected_avurls).values('user_id','avatar')\n\t\tpipeline2 = my_server.pipeline()\n\t\tfor avurl in collected_avurls:\n\t\t\tuser_id = avurl['user_id']\n\t\t\thash_name = 'uname:'+str(user_id)\n\t\t\tif not avurl['avatar']:\n\t\t\t\tavurl['avatar'] = 'empty'\n\t\t\tavatars[user_id] = avurl['avatar']\n\t\t\tpipeline2.hset(hash_name,'avurl',avurl['avatar'])\n\t\t\tpipeline2.expire(hash_name,ONE_DAY)\n\t\tpipeline2.execute()\n\treturn avatars\n\n\ndef retrieve_bulk_unames(user_ids, decode=False):\n\t\"\"\"\n\tReturns usernames in bulk, in id-username dictionary format\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\tfor user_id in user_ids:\n\t\tpipeline1.hget('uname:'+str(user_id),'uname')\n\tusernames_wip = pipeline1.execute()\n\tcounter = 0\n\tusernames, uncollected_uname_ids = {}, []\n\tfor username in usernames_wip:\n\t\tid_ = int(user_ids[counter])\n\t\tif username:\n\t\t\tif decode:\n\t\t\t\tusernames[id_] = username.decode('utf-8')\n\t\t\telse:\n\t\t\t\tusernames[id_] = username\n\t\telse:\n\t\t\tusernames[id_] = ''\n\t\t\tuncollected_uname_ids.append(id_)\n\t\tcounter += 1\n\tif uncollected_uname_ids:\n\t\tresidual_unames = dict(User.objects.filter(id__in=uncollected_uname_ids).values_list('id','username'))\n\t\tpipeline2 = my_server.pipeline()\n\t\tfor key in residual_unames:\n\t\t\tusernames[key], hash_name = residual_unames[key], 'uname:'+str(key)\n\t\t\tpipeline2.hset(hash_name,'uname',residual_unames[key])\n\t\t\tpipeline2.expire(hash_name,ONE_DAY)\n\t\tpipeline2.execute()\n\treturn usernames\n\n\n\ndef retrieve_uname(user_id,decode=False):\n\t\"\"\"\n\tReturns user's nickname\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\thash_name = 'uname:'+str(user_id)\n\tusername = my_server.hget(hash_name,'uname')\n\tif username:\n\t\tif decode:\n\t\t\treturn username.decode('utf-8')\n\t\telse:\n\t\t\treturn username\n\telse:\n\t\tusername = User.objects.filter(id=user_id).values_list('username',flat=True)[0]\n\t\tpipeline1 = my_server.pipeline()\n\t\tpipeline1.hset(hash_name,'uname',username)\n\t\tpipeline1.expire(hash_name,ONE_DAY)\n\t\tpipeline1.execute()\n\t\treturn username\n\n\ndef retrieve_credentials(user_id,decode_uname=False):\n\t\"\"\"\n\tReturns username and avatar_url for given user_id\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\thash_name = 'uname:'+str(user_id)\n\tusername, avurl = my_server.hmget(hash_name,'uname','avurl')\n\tif username and avurl:\n\t\tif decode_uname:\n\t\t\treturn username.decode('utf-8'),avurl\n\t\telse:\n\t\t\treturn username, avurl\n\telif username:\n\t\tavurl = UserProfile.objects.filter(user_id=user_id).values_list('avatar',flat=True)[0]\n\t\tif not avurl:\n\t\t\tavurl = 'empty'\n\t\tpipeline1 = my_server.pipeline()\n\t\tpipeline1.hset(hash_name,'avurl',avurl)\n\t\tpipeline1.expire(hash_name,ONE_DAY)\n\t\tpipeline1.execute()\n\t\tif decode_uname:\n\t\t\treturn username.decode('utf-8'),avurl\n\t\telse:\n\t\t\treturn username, avurl\n\telif avurl:\n\t\tusername = User.objects.filter(id=user_id).values_list('username',flat=True)[0]\n\t\tpipeline1 = my_server.pipeline()\n\t\tpipeline1.hset(hash_name,'uname',username)\n\t\tpipeline1.expire(hash_name,ONE_DAY)\n\t\tpipeline1.execute()\n\t\treturn username, avurl\n\telse:\n\t\tusername = User.objects.filter(id=user_id).values_list('username',flat=True)[0]\n\t\tavurl = UserProfile.objects.filter(user_id=user_id).values_list('avatar',flat=True)[0]\n\t\tif not avurl:\n\t\t\tavurl = 'empty'\n\t\tmapping = {'uname':username,'avurl':avurl}\n\t\tpipeline1 = my_server.pipeline()\n\t\tpipeline1.hmset(hash_name,mapping)\n\t\tpipeline1.expire(hash_name,ONE_DAY)\n\t\tpipeline1.execute()\n\t\treturn username, avurl\n\n\ndef retrieve_user_id(username):\n\t\"\"\"\n\tReturns user's user_id (for a given username)\n\t\"\"\"\n\tkey = 'user_id:'+username\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tuser_id = my_server.get(key)\n\tif user_id:\n\t\tmy_server.expire(key,THREE_DAYS)# extend lease for 3 days\n\t\treturn user_id\n\telse:\n\t\ttry:\n\t\t\tuser_id = User.objects.filter(username=username).values_list('id',flat=True)[0]\n\t\texcept IndexError:\n\t\t\treturn None\n\t\tmy_server.setex(key,user_id,ONE_DAY)\n\t\treturn str(user_id)\n\n\ndef retrieve_avurl(user_id):\n\t\"\"\"\n\tReturns user's avatar_url\n\t\"\"\"\n\thash_name = 'uname:'+str(user_id)\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tavurl = my_server.hget(hash_name,'avurl')\n\tif not avurl:\n\t\tavurl = UserProfile.objects.filter(user_id=user_id).values_list('avatar',flat=True)[0]\n\t\tif not avurl:\n\t\t\tavurl = 'empty'\n\t\tpipeline1 = my_server.pipeline()\n\t\tpipeline1.hset(hash_name,'avurl',avurl)\n\t\tpipeline1.expire(hash_name,ONE_DAY)\n\t\tpipeline1.execute()\n\treturn avurl\n\n\ndef invalidate_avurl(user_id,set_rate_limit=None):\n\t\"\"\"\n\tInvalidate cached avatar_url if user uploads new avatar\n\n\tIf set_rate_limit is True, a rate limit is imposed on uploading a new avatar\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tuser_id = str(user_id)\n\tmy_server.hdel('uname:'+user_id,'avurl')\n\tif set_rate_limit:\n\t\tmy_server.setex('aurl:'+user_id,1,THREE_MINS)\n\n\ndef get_aurl(user_id):\n\t\"\"\"\n\tRetrieves the status of avatar uploading rate limit\n\t\"\"\"\n\treturn redis.Redis(connection_pool=POOL).ttl('aurl:'+str(user_id))\n\n\n#####################Retention Logger#####################\ndef log_retention(server_instance, user_id):\n\ttime_now = time.time()\n\tif server_instance.exists(\"user_times:\"+user_id):\n\t\tif time_now - float(server_instance.lrange(\"user_times:\"+user_id,0,0)[0]) > TEN_MINS:\n\t\t\tserver_instance.lpush(\"user_times:\"+user_id,time_now)\n\t\t\tserver_instance.sadd(\"logged_users\",user_id)\n\telse:\n\t\t# contains a user's times of browsing Damadam\n\t\tserver_instance.lpush(\"user_times:\"+user_id,time_now)\n\t\t# contains all user_ids that have ever been logged\n\t\tserver_instance.sadd(\"logged_users\",user_id)\n\ndef retrieve_retention_ids():\n\tmy_server = redis.Redis(connection_pool=POOL)\n\treturn my_server.smembers(\"logged_users\")\n\ndef retrieve_retention_data(user_ids):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\tfor id_ in user_ids:\n\t\tpipeline1.lrange(\"user_times:\"+id_,0,-1)\n\tresult1 = pipeline1.execute()\n\tuser_times = []\n\tcounter = 0\n\tfor id_ in user_ids:\n\t\tuser_times.append((id_,result1[counter]))\n\t\tcounter += 1\n\treturn user_times\n\n# def reduce_retention_data():\n\t\"\"\"\n\tto delete, get ids of really old \"last_active\"\n\tdates from session table in DB (to ensure it's \n\tan old user). Then delete those \"user_times\"+str(user_id)\n\t\"\"\"\n\n#######################Whose Online#######################\n\n\ndef expire_online_users():\n\t\"\"\"\n\tExpires online_users from tasks.py\n\t\"\"\"\n\tredis.Redis(connection_pool=POOL).zremrangebyscore(\"online_users\",'-inf','('+str(time.time()-TEN_MINS))\n\n\n\ndef set_online_users(user_id,user_ip):\n\t\"\"\"\n\tInvoked from WhoseOnline.py middleware\n\t\"\"\"\n\tpipeline1 = redis.Redis(connection_pool=POOL).pipeline()\n\tpipeline1.zadd(\"online_users\",user_id+\":\"+user_ip,time.time())\n\tpipeline1.setex(\"lip:\"+user_id,user_ip,FIVE_MINS)\n\tpipeline1.execute()\n\t############ logging user retention ############\n\t# if random.random() < 0.45:\n\t# \tlog_retention(my_server,user_id)\n\n\ndef get_recent_online():\n\t\"\"\"\n\tInvoked by tasks.py to show whoever is online in OnlineKon\n\t\"\"\"\n\tsorted_set = \"online_users\"\n\tten_mins_ago = time.time() - TEN_MINS\n\tonline_users = redis.Redis(connection_pool=POOL).zrangebyscore(sorted_set,ten_mins_ago,'+inf')\n\tonline_ids = []\n\tfor user in online_users:\n\t\tonline_ids.append(user.split(\":\",1)[0])\n\treturn online_ids\n\n\n######################################## Detect Clones of User ID ########################################\n\n\ndef get_clones(user_id):\n\t\"\"\"\n\tInvoked in views.py to show possible clones of users\n\t\"\"\"\n\tlatest_user_ip = \"lip:\"+str(user_id) #latest ip of user with 'user_id'\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tuser_ip = my_server.get(latest_user_ip)\n\tif user_ip:\n\t\tclones = []\n\t\tfive_mins_ago = time.time() - FIVE_MINS\n\t\tonline_users = my_server.zrangebyscore(\"online_users\",five_mins_ago,'+inf')\n\t\tfor user in online_users:\n\t\t\tif user_ip == user.split(\":\",1)[1]:\n\t\t\t\tclones.append(user.split(\":\",1)[0])\n\t\treturn clones\n\telse:\n\t\treturn None\n\n# def set_site_ban(user_id):\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tuser_ban = \"ub:\"+str(user_id) # banning user's ip from logging into website\n# \tmy_server.set(user_ban,1)\n# \tmy_server.expire(user_ban,ONE_HOUR)\n\n\n#########################################################\n\n#calculating installment amount for mobile devices\ndef get_historical_calcs(base_price=None, time_period_in_months=None, monthly_installment=None, ending_value=None):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\tif base_price is None:\n\t\tid_ = my_server.get(\"historical_calcs\")\n\t\tif id_ is not None:\n\t\t\tfor x in range(1,(int(id_)+1)):\n\t\t\t\tpipeline1.hgetall(\"cd:\"+str(x))\n\t\t\treturn pipeline1.execute()\n\t\telse:\n\t\t\treturn None\n\telse:\n\t\tid_ = my_server.incr(\"historical_calcs\")\n\t\tcalc_details = \"cd:\"+str(id_)\n\t\tmapping = {'id':id_,'bp':base_price,'tpim':time_period_in_months,'mi':monthly_installment,'ev':ending_value, 't':time.time()}\n\t\tmy_server.hmset(calc_details,mapping)\n\t\tfor x in range(1,(id_+1)):\n\t\t\tpipeline1.hgetall(\"cd:\"+str(x))\n\t\treturn pipeline1.execute()\n\n#########################################################\n\ndef save_ad_desc(text, price, user_id,username):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tmapping = {'uid':user_id, 'nick':username, 'desc':text,'price':price}\n\tmy_server.lpush(\"ad_desc\",mapping)\n\n#########################################################\n\ndef save_careem_data(careem_data):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tif my_server.zscore(\"careem_applicant_nums\",careem_data[\"phonenumber\"]):\n\t\t# it already exists\n\t\treturn False\n\telse:\n\t\t# it does not exist\n\t\tpipeline1 = my_server.pipeline()\n\t\tpipeline1.hmset(\"cad:\"+str(careem_data['phonenumber']),careem_data)\n\t\tpipeline1.zadd('careem_applicant_nums',careem_data['phonenumber'],time.time())\n\t\tpipeline1.zadd('careem_applicant_nums_live',careem_data['phonenumber'],time.time())\n\t\tpipeline1.execute()\n\n\t\treturn True\n\ndef export_careem_data():\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\tuser = my_server.zcard(\"careem_applicant_nums_live\")\n\tif user == 0:\n\t\treturn False\n\telse:\n\t\tnums = my_server.zrange(\"careem_applicant_nums_live\",0,-1)\n\t\tpipeline1 = my_server.pipeline()\n\t\tfor num in nums:\n\t\t\tpipeline1.hgetall('cad:'+num)\n\t\tresult1 = pipeline1.execute()\n\t\treturn result1\n\ndef del_careem_data():\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tmy_server.delete(\"careem_applicant_nums_live\")\n\n\n##################################################Mobile_Shop\n\n\ndef log_buyer_form_err(error_data):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\terror_id = get_error_id()\n\tkey_name = \"error_data:\"+str(error_id)\n\tpipeline1 = my_server.pipeline()\n\tpipeline1.hmset(key_name,error_data)\n\t#pipeline1.expire(key_name,TWELVE_HOURS)\n\tpipeline1.execute()\n\treturn True\n\ndef get_error_id():\n\tmy_server = redis.Redis(connection_pool=POOL)\n\treturn my_server.incr(\"ms_error_id\")\n\ndef save_order_data(order_data):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tkey_name = \"order_data:\"+str(order_data['user_id'])\n\tpipeline1 = my_server.pipeline()\n\tpipeline1.hmset(key_name,order_data)\n\tpipeline1.expire(key_name,TWELVE_HOURS)\n\tpipeline1.execute()\n\treturn True\n\ndef save_query_data(query_data):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tkey_name = \"querydata:\"+str(query_data['user_id'])\n\tpipeline1 = my_server.pipeline()\n\tpipeline1.hmset(key_name,query_data)\n\tpipeline1.sadd('queryusers',query_data['user_id'])\n#\tpipeline1.expire(key_name,TWELVE_HOURS)\n\tpipeline1.execute()\n\treturn True\n\ndef delete_query(user_id):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\tmy_server.srem(\"queryusers\",user_id)\n\tmy_server.delete(\"querydata:\"+str(user_id))\n\tpipeline1.execute()\n\treturn {}\n\n\ndef place_order(user_id):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\torder_data = False\n\torder_data = get_temp_order_data(user_id)\n\torder_id = get_order_id()\n\torder_data['order_id'] = order_id\n\tpipeline1.zadd('ordersinprocess',user_id,order_id)\n\t# after a few months, export this to excel and clean the list (it takes up needless space)\n\tpipeline1.hmset(\"placedorders:\"+str(order_id),order_data)\n\tpipeline1.execute()\n\treturn order_data\n\ndef delete_order(order_id,user_id):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\t# after a few months, export this to excel and clean the list (it takes up needless space)\n\tmy_server.zrem(\"ordersinprocess\",user_id)\n\tmy_server.delete(\"placedorders:\"+str(order_id))\n\tpipeline1.execute()\n\treturn {}\n\n\n\n\n\ndef get_temp_order_data(user_id):\n\tmy_server = redis.Redis(connection_pool=POOL)\n\ttemp_storage = \"order_data:\"+str(user_id)\n\tif my_server.exists(temp_storage):\n\t\torder_details = my_server.hgetall(\"order_data:\"+str(user_id))\n#\t\tmy_server.delete(\"order_data:\"+str(user_id))\n\t\treturn order_details\n\telse:\n\t\treturn {}\n\ndef check_orders_processing(user_id):\n\tuser = redis.Redis(connection_pool=POOL).zscore('ordersinprocess',user_id)\n\tif user == None:\n\t\treturn False\n\telse:\n\t\treturn True\n\ndef get_order_id():\n\treturn redis.Redis(connection_pool=POOL).incr(\"order_id\")\n\ndef get_total_orders():\n\treturn redis.Redis(connection_pool=POOL).get(\"order_id\")\n\ndef show_new_orders():\n\ttotal_orders = get_total_orders()\n\tif total_orders <1:\n\t\treturn False\n\telse:\n\t\tmy_server = redis.Redis(connection_pool=POOL)\n\t\tpipeline1 = my_server.pipeline()\n\t\tnum = 0\n\t\t\n\t\twhile num <= int(total_orders):\n\t\t\ttemp_storage = \"placedorders:\"+str(num)\n\t\t\tif my_server.exists(temp_storage):\n\t\t\t\tpipeline1.hgetall('placedorders:'+str(num))\n\t\t\tnum = num + 1\n\t\torders = pipeline1.execute()\n\t\treturn orders\n\n\ndef show_new_queries():\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\tusers = my_server.smembers(\"queryusers\")\n\tif users == 0:\n\t\treturn []\n\telse:\n\t\tpipeline1 = my_server.pipeline()\n\t\tfor obj in users:\n\t\t\tpipeline1.hgetall('querydata:'+obj)\n\t\tresult1 = pipeline1.execute()\n\t\treturn result1\n\n\n\n'''\n####################\nM_S Deprecated Key Names\nquery_data now querydata\nquery_users now queryusers\norders_in_process now ordersinprocess\nplaced_orders now placedorders\n\n####################\n'''\n\n############ Rate limiting flooding and spamming ############\n\ndef is_limited(user_id, section, with_reason = False):\n\t\"\"\"\n\t\"\"\"\n\tif section == 'home':\n\t\tkey = \"rlfh:\"+str(user_id)\n\telif section == 'pub_grp':\n\t\tkey = \"rlfpg:\"+str(user_id)\n\telif section == 'prv_grp':\n\t\tkey = \"rlfpvg:\"+str(user_id)\n\telif section == 'pht_comm':\n\t\tkey = \"rlfpc:\"+str(user_id)\n\telif section == 'home_rep':\n\t\tkey = \"rlfhr:\"+str(user_id)\n\telse:\n\t\treturn False\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tif with_reason:\n\t\tttl = my_server.ttl(key)\n\t\tif ttl > 0:\n\t\t\treason = my_server.get(key)\n\t\t\treturn ttl, reason\n\t\telse:\n\t\t\treturn 0, None\n\telse:\n\t\treturn my_server.ttl(key)\n\ndef rate_limit_user(user_id,section,level,ban_reason,my_server=None):\n\t\"\"\"\n\tSetting blocking rate limits on abusive users on a section of the website\n\n\tLevel relates to severity of block limit\n\t1 - lowest (7 mins)\n\t2 - low (30 mins)\n\t3 - medium (2 hours)\n\t4 - med-high (8 hours)\n\t5 - high (24 hours)\n\t6 - severe (3 days)\n\t7 - hardcore (7 days)\n\t8 - jackpot (30 days)\n\t\"\"\"\n\tif section == 'home':\n\t\trate_limit_key = \"rlfh:\"+str(user_id)\n\telif section == 'pub_grp':\n\t\trate_limit_key = \"rlfpg:\"+str(user_id)\n\telif section == 'prv_grp':\n\t\trate_limit_key = \"rlfpvg:\"+str(user_id)\n\telif section == 'pht_comm':\n\t\trate_limit_key = \"rlfpc:\"+str(user_id)\n\telif section == 'home_rep':\n\t\trate_limit_key = \"rlfhr:\"+str(user_id)\n\tif not my_server:\n\t\tmy_server = redis.Redis(connection_pool=POOL)\n\ttry:\n\t\tmy_server.setex(rate_limit_key,ban_reason,RATELIMIT_TTL[level])\n\t\treturn True\n\texcept KeyError:\n\t\tmy_server.setex(rate_limit_key,ban_reason,TWENTY_MINS)\n\t\treturn False\n\n# 1) revert log_input_rate in tasks.py (done)\n# 2) revert function definition of log_input_rate in redis4 (done)\n# 3) remove pipeline1.execute(key+\":logger\",text) from log_input_rate (done)\n# 4) remove log_rate_limited_conversation() from log_input_rate (done)\n# 5) remove function for log_rate_limited_conversation() in redis4 (done)\n# 6) remove function called report_rate_limited_conversation() in redis4 (done)\n# 7) remove logger url (and view import) from urls_maint.py (done)\n# 8) remove reporting view (called rate_limit_logging_report) from end of maint_views (done)\n# 9) remove the import for report_rate_limited_conversation() from maint_views (done)\n# 10) remove get_section_string() from redis4 (done)\n\n# def report_rate_limited_conversation():\n# \t\"\"\"\n# \tExtracts all rate limited conversations\n# \t\"\"\"\n# \timport csv,ast\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tsuper_ = my_server.lrange(\"rate_limited_convos:super\",0,-1)\n# \tnormal_ = my_server.lrange(\"rate_limited_convos:normal\",0,-1)\n# \tlazy_ = my_server.lrange(\"rate_limited_convos:lazy\",0,-1)\n# \tresult = [(super_,'super_'),(normal_,'normal_'),(lazy_,'lazy_')]\n# \tfor logs,log_type in result:\n# \t\tfilename = 'ratelimited_convos_'+log_type+str(int(time.time()))+'.csv'\n# \t\twith open(filename,'wb') as f:\n# \t\t\twtr = csv.writer(f)\n# \t\t\tcolumns = [\"Type\",\"Section\",\"#\",\"Conversation\"]\n# \t\t\twtr.writerow(columns) # writing the columns\n# \t\t\tnum = 0\n# \t\t\tfor payload in logs:\n# \t\t\t\tnum += 1\n# \t\t\t\tpayload = ast.literal_eval(payload)\n# \t\t\t\twhich_section = payload[0]\n# \t\t\t\tfor string in payload[1]:\n# \t\t\t\t\ttype_=log_type\n# \t\t\t\t\tsec=which_section\n# \t\t\t\t\tconv_num=num\n# \t\t\t\t\tconversation=string\n# \t\t\t\t\tto_write = [type_,sec,conv_num,conversation]\t\n# \t\t\t\t\twtr.writerows([to_write])\n\n\n# def get_section_string(key):\n# \ttry:\n# \t\tstring = key[:2]\n# \texcept TypeError:\n# \t\tstring = 'undef'\n# \tif string == 'hi':\n# \t\treturn 'home_post'\n# \telif string == 'pg':\n# \t\treturn 'public_group'\n# \telif string == 'pv':\n# \t\treturn 'private_group'\n# \telif string == 'pc':\n# \t\treturn 'photo_comment'\n# \telif string == 'hr':\n# \t\treturn 'home_reply'\n# \telse:\n# \t\treturn 'undefined'\t\n\n# def log_rate_limited_conversation(convo_key, severity):\n# \t\"\"\"\n# \tlogger for rate limited conversation strings\n# \t\"\"\"\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \twhich_section = get_section_string(convo_key)\n# \tif severity == 'super':\n# \t\tmy_server.lpush(\"rate_limited_convos:super\",[which_section,my_server.lrange(convo_key,0,-1)])\n# \telif severity == 'normal':\n# \t\tmy_server.lpush(\"rate_limited_convos:normal\",[which_section,my_server.lrange(convo_key,0,-1)])\n# \telse:\n# \t\tmy_server.lpush(\"rate_limited_convos:lazy\",[which_section,my_server.lrange(convo_key,0,-1)])\n\n\n# def log_input_rate(section,user_id,time_now):\ndef log_input_rate(section,user_id,time_now,text=None):\n\t\"\"\"\n\tKeeps check of writing rates to rate limit abusive users\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tif section == 'home':\n\t\tkey = \"hir:\"+str(user_id)\n\telif section == 'pub_grp':\n\t\tkey = \"pgir:\"+str(user_id)\t\n\telif section == 'prv_grp':\n\t\tkey = \"pvgir:\"+str(user_id)\n\telif section == 'pht_comm':\n\t\tkey = \"pcir:\"+str(user_id)\n\telif section == 'home_rep':\n\t\tkey = \"hrir:\"+str(user_id)\t\n\tpipeline1 = my_server.pipeline()\n\tpipeline1.lpush(key,time_now)\n\tpipeline1.expire(key,ONE_MIN)\n\t#### remove ####\n\t# pipeline1.lpush(key+\":logger\",text)\n\t# pipeline1.expire(key+\":logger\",ONE_MIN)\n\t#### remove ####\n\tpipeline1.execute()\n\t####################################\n\tall_str_values = my_server.lrange(key,0,-1)\n\ttotal_inputs = len(all_str_values)\n\tif total_inputs > 7:\n\t\tall_values = map(float, all_str_values)\n\t\tsum_of_differences = 0\n\t\tfor s, t in zip(all_values, all_values[1:]):\n\t\t\tsum_of_differences += t - s\n\t\tavg_time_taken_between_sentences = abs(sum_of_differences)/(total_inputs-1)\n\t\tif avg_time_taken_between_sentences < SUPER_FLOODING_THRESHOLD:\n\t\t\trate_limit_user(user_id=user_id,section=section,level='2',ban_reason=BAN_REASON['flooding'],my_server=my_server)\n\t\t\t# log_rate_limited_conversation(key+\":logger\",'super')\n\t\telif avg_time_taken_between_sentences < FLOODING_THRESHOLD:\n\t\t\trate_limit_user(user_id=user_id,section=section,level='1',ban_reason=BAN_REASON['flooding'],my_server=my_server)\n\t\t\t# log_rate_limited_conversation(key+\":logger\",'normal')\n\t\telif avg_time_taken_between_sentences < LAZY_FLOODING_THRESHOLD:\n\t\t\trate_limit_user(user_id=user_id,section=section,level='0',ban_reason=BAN_REASON['flooding'],my_server=my_server)\n\t\t\t# log_rate_limited_conversation(key+\":logger\",'lazy')\n\t\telse:\n\t\t\tmy_server.ltrim(key,0,6)\n\t\t\t#### remove ####\n\t\t\t# my_server.ltrim(key+\":logger\",0,6)\n\ndef log_input_text(section, section_id,text,user_id):\n\t\"\"\"\n\tLogs previous 4 sentences of each section\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tif section == 'home':\n\t\tkey = \"hit:\"+str(user_id)+\":\"+str(section_id)\n\telif section == 'pub_grp':\n\t\tkey = \"pgit:\"+str(user_id)+\":\"+str(section_id)\t\n\telif section == 'prv_grp':\n\t\tkey = \"pvgit:\"+str(user_id)+\":\"+str(section_id)\t\n\telif section == 'pht_comm':\n\t\tkey = \"pcit:\"+str(user_id)+\":\"+str(section_id)\n\telif section == 'home_rep':\n\t\tkey = \"hrit:\"+str(user_id)+\":\"+str(section_id)\n\tmy_server.lpush(key,text)\n\tmy_server.ltrim(key,0,3) # keeping previous 4 sentences\n\tmy_server.expire(key,TEN_MINS)\n\n\ndef retrieve_previous_msgs(section, section_id,user_id):\n\t\"\"\"\n\tretrieve previous messages stored for a certain section_id\n\t\"\"\"\t\n\tif section == 'home':\n\t\tkey = \"hit:\"+str(user_id)+\":\"+str(section_id)\n\telif section == 'pub_grp':\n\t\tkey = \"pgit:\"+str(user_id)+\":\"+str(section_id)\t\n\telif section == 'prv_grp':\n\t\tkey = \"pvgit:\"+str(user_id)+\":\"+str(section_id)\t\n\telif section == 'pht_comm':\n\t\tkey = \"pcit:\"+str(user_id)+\":\"+str(section_id)\n\telif section == 'home_rep':\n\t\tkey = \"hrit:\"+str(user_id)+\":\"+str(section_id)\n\treturn redis.Redis(connection_pool=POOL).lrange(key,0,-1)\n\n\n############################ Ratelimiting short messages ###############################\n\ndef log_short_message(user_id,section,obj_id):\n\tshort_message = \"sm:\"+str(user_id)+\":\"+section+\":\"+str(obj_id)\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tmy_server.incr(short_message)\n\tmy_server.expire(short_message,THREE_MINS)\n\ndef many_short_messages(user_id,section,obj_id):\n\t\"\"\"\n\tConfirms if trail of short messages have already been left by the user on the given object\n\t\"\"\"\n\tshort_message = \"sm:\"+str(user_id)+\":\"+section+\":\"+str(obj_id)\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tshort_messages_so_far = my_server.get(short_message)\n\tif short_messages_so_far:\n\t\tif int(short_messages_so_far) > SHORT_MESSAGES_ALWD:\n\t\t\tmy_server.expire(short_message,SEVEN_MINS) #renew block short messages for 7 mins\n\t\t\treturn True\n\t\telse:\n\t\t\tFalse\n\telse:\n\t\treturn False\n\n################################################# Logging Sharing in Photos #################################################\n\n\ndef log_share(photo_id, photo_owner_id, sharer_id, share_type='undefined', origin=None):\n\t\"\"\"\n\tLogs image sharing attempts (via Whatsapp)\n\t\n\t1) If origin is 'user_albums', user is originating from user profiles\n\t1) If origin is 'fresh_photos', user is originating from fresh photos\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tif origin == 'user_albums':\n\t\t# log shared profiles\n\t\tif not my_server.get('as:'+photo_id+\":\"+str(sharer_id)):\n\t\t\t# this sharer hasn't shared this photo in the last 20 mins\n\t\t\tadded = my_server.sadd('shared_user_albums_set',photo_id)\n\t\t\tif added == 1:\n\t\t\t\tmy_server.lpush('shared_user_albums_list',photo_id)\n\t\t\t\tif my_server.llen('shared_user_albums_list') > SHARED_PHOTOS_CEILING:\n\t\t\t\t\texpiring_photo_ids = my_server.lrange('shared_user_albums_list', (SHARED_PHOTOS_CEILING-PHOTO_DELETION_BUFFER), -1)\n\t\t\t\t\tpipeline1 = my_server.pipeline()\n\t\t\t\t\tpipeline1.ltrim('shared_user_albums_list',0,(SHARED_PHOTOS_CEILING-PHOTO_DELETION_BUFFER-1))\t\n\t\t\t\t\tpipeline1.zrem('sorted_user_albums_photos',*expiring_photo_ids)\n\t\t\t\t\tpipeline1.srem('shared_user_albums_set',*expiring_photo_ids)\n\t\t\t\t\tpipeline1.execute()\n\t\t\tmy_server.zincrby('sorted_user_albums_photos',photo_id,amount=1)# query this when getting report of which photos were shared the most\n\t\t\tmy_server.setex('as:'+photo_id+\":\"+str(sharer_id),'1',TWENTY_MINS)\n\telif origin == 'fresh_photos':\n\t\t# log shared photos\n\t\tif not my_server.get('as:'+photo_id+\":\"+str(sharer_id)):\n\t\t\t# this sharer hasn't shared this photo in the last 20 mins\n\t\t\tadded = my_server.sadd('shared_public_photos_set',photo_id)\n\t\t\tif added == 1:\n\t\t\t\tmy_server.lpush('shared_public_photos_list',photo_id)\n\t\t\t\tif my_server.llen('shared_public_photos_list') > SHARED_PHOTOS_CEILING:\n\t\t\t\t\texpiring_photo_ids = my_server.lrange('shared_public_photos_list', (SHARED_PHOTOS_CEILING-PHOTO_DELETION_BUFFER), -1)\n\t\t\t\t\tpipeline1 = my_server.pipeline()\n\t\t\t\t\tpipeline1.ltrim('shared_public_photos_list',0,(SHARED_PHOTOS_CEILING-PHOTO_DELETION_BUFFER-1))\n\t\t\t\t\tpipeline1.zrem('sorted_shared_public_photos',*expiring_photo_ids)\n\t\t\t\t\tpipeline1.srem('shared_public_photos_set',*expiring_photo_ids)\n\t\t\t\t\tpipeline1.execute()\n\t\t\tmy_server.zincrby('sorted_shared_public_photos',photo_id,amount=1)# query this when getting report of which photos were shared the most\n\t\t\tmy_server.setex('as:'+photo_id+\":\"+str(sharer_id),'1',TWENTY_MINS)\n\telse:\n\t\tpass\n\n\n\ndef logging_sharing_metrics(sharer_id, photo_id, photo_owner_id, num_shares, sharing_time, group_ids):\n\t\"\"\"\n\tLogs metrics for photos shared internally (from public albums to personal groups)\n\n\tThis is a separate functionality from sharing via Whatsapp\n\t\"\"\"\n\tsharer_id, num_shares, sharing_time = str(sharer_id), str(num_shares), str(sharing_time)\n\tkey = \"sp:\"+photo_owner_id\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpipeline1 = my_server.pipeline()\n\t\n\t# use this to calculate total shares in the last week, also total all_time shares (list resets if user inactive for two weeks)\n\tpipeline1.zadd(key,photo_id+\":\"+num_shares+\":\"+sharer_id+\":\"+sharing_time,sharing_time)\n\tpipeline1.expire(key,TWO_WEEKS)\n\t# can also give to each user: latest shared photo, most highly shared photo, and all other shared photos (alongwith num shares)\n\n\t# save the act of sharing in a global list as well, for our viewing\n\tpipeline1.lpush('shared_photos',photo_id+\":\"+num_shares+\":\"+photo_owner_id+\":\"+sharing_time)\n\tpipeline1.ltrim('shared_photos',0,500)\n\n\tpipeline1.execute()\n\t##################################### SHARER METRICS #####################################\n\t# one_month_ago = sharing_time - (60*60*24*30)\n\t# most proflific sharers of own content (remove those inactive for a month)\n\t# if photo_owner_id == sharer_id:\n\t# \tmy_server.zadd('ocst',sharer_id,sharing_time)#'own content sharing time'\n\t# \tmy_server.zincrby('ocsv',sharer_id,amount=num_shares)#'own content sharing volume'\n\t# \texpired_sharer_ids = my_server.zrangebyscore(\"ocst\",'-inf',one_month_ago)\n\t# \tif expired_sharer_ids:\n\t# \t\tmy_server.zrem('ocst',*expired_sharer_ids)\n\t# \t\tmy_server.zrem('ocsv',*expired_sharer_ids)\n\t\n\t# most prolific sharers of others' content (remove those inactive for a month)\n\t# else:\n\t# \tmy_server.zadd('cst',sharer_id,sharing_time)#'content sharing time'\n\t# \tmy_server.zincrby('csv',sharer_id,amount=num_shares)#'content sharing volume'\n\t# \texpired_sharer_ids = my_server.zrangebyscore(\"cst\",'-inf',one_month_ago)\n\t# \tif expired_sharer_ids:\n\t# \t\tmy_server.zrem('cst',*expired_sharer_ids)\n\t# \t\tmy_server.zrem('csv',*expired_sharer_ids)\n\t\n\t# most prolific sharers who influence the most number of people. Can use formula volume_shared^(simpson_diversity_index) to calculate 'influencer score'\n\t# volume_shared is simply total number of shares (it counts each individual share as 1)\n\t# simpson_diversity_index is here: https://www.youtube.com/watch?v=zxzwvWDeTT8\n\t\n\n# def log_photo_attention_from_fresh(photo_id, att_giver, photo_owner_id, action, vote_value):\n# \t\"\"\"\n# \tMaintains list of photos that are 'trending' via actvity from fresh photos\n\t\n# \tNote: 'action' may be 'photo_vote' or 'photo_comment'\n# \t\"\"\"\n# \tmy_server = redis.Redis(connection_pool=POOL)\n# \tif action == 'photo_vote':\n# \t\tif vote_value == '1':\n# \t\t\tpass\n# \t\telif vote_value == '-1':\n# \t\t\tpass\n# \t\telse:\n# \t\t\tpass\n\ndef cache_photo_share_data(json_data,user_id):\n\t\"\"\"\n\tCaches photo sharing data of given user_id for twenty mins\n\t\"\"\"\n\tredis.Redis(connection_pool=POOL).setex('phd:'+user_id,json_data,TWENTY_MINS)\n\n\ndef retrieve_fresh_photo_shares_or_cached_data(user_id):\n\t\"\"\"\n\tReturns shared photos of user_id\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tcached_photo_data = my_server.get('phd:'+user_id)\n\tif cached_photo_data:\n\t\treturn json.loads(cached_photo_data), True\n\telse:\n\t\treturn my_server.zrange(\"sp:\"+user_id,0,-1), False\n\n\ndef logging_profile_view(visitor_id,star_id,viewing_time):\n\t\"\"\"\n\tLogs profile view if a visitor visits\n\n\tOnly last 24 hours are preserved\n\tEnsures self visits don't count\n\tEnsures repeat visits don't count\n\t\"\"\"\n\tstar_id = str(star_id)\n\tone_day_ago = viewing_time - ONE_DAY\n\tviewing_time = str(viewing_time)\n\tvisitor_id = str(visitor_id)\n\tkey = \"vb:\"+star_id+\":\"+visitor_id\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tif not my_server.get(key):\n\t\t# can log visit\n\t\tsorted_set = 'pf:'+star_id\n\t\tmy_server.zremrangebyscore(sorted_set,'-inf',one_day_ago)#purging old data\n\t\tmy_server.zadd(sorted_set,visitor_id+\":\"+viewing_time,viewing_time)\n\t\tmy_server.expire(sorted_set,ONE_DAY)#this expires if no new views appear for 24 hours\n\t\tmy_server.setex(key,'1',THIRTY_MINS)\n\n########################################### Gathering Metrics for Personal Groups ###########################################\n\ndef increment_convo_counter(group_id, writer_id, group_type=None):\n\t\"\"\"\n\tLogs conversation quantity in personal groups and private mehfils\n\n\tHelps answer questions such as:\n\t1) What are avg number of chats produced per type of chat?\n\t2) What are avg number of switchovers produced per type of chat?\n\t\"\"\"\n\tif group_type:\n\t\tlast_interaction_in_group = \"lig_\"+group_type+\":\"+group_id\n\t\tmy_server = redis.Redis(connection_pool=POOL)\n\t\tlwid = my_server.getset(last_interaction_in_group,writer_id)\n\t\tif lwid:\n\t\t\tinteraction_type = 'ch' if lwid == str(writer_id) else 'both'\n\t\telse:\n\t\t\tinteraction_type = 'ch'\n\t\tif interaction_type == 'ch':\n\t\t\t# this logs normal chat\n\t\t\tmy_server.zincrby(group_type+\"_ch\",group_id,amount=1)\n\t\telif interaction_type == 'both':\n\t\t\t# this logs switchover, and normal chat\n\t\t\tmy_server.zincrby(group_type+\"_sw\",group_id,amount=1)\n\t\t\tmy_server.zincrby(group_type+\"_ch\",group_id,amount=1)\n\t\tmy_server.expire(last_interaction_in_group,ONE_DAY)\n\n\ndef increment_session(group_id, user_id, group_type=None):\n\t\"\"\"\n\tIncrements unique sessions per group per user\n\n\tHelps answer questions such as:\n\t1) What are avg number of sessions per type of chat\n\t2) What are median number of sessions per type of chat\n\t3) Calculate correlation between number of sessions and number of switchovers\n\t4) Calculate coorelation between number of sessions and number of chats\n\t\"\"\"\n\tmy_server, user_id = redis.Redis(connection_pool=POOL), str(user_id)\n\tif not my_server.get(\"gs_\"+group_type+\":\"+group_id+\":\"+user_id):\n\t\t# create new session key for the user for this group\n\t\tnow = datetime.now()\n\t\tsecs_till_midnight = ((24 - now.hour - 1) * 60 * 60) + ((60 - now.minute - 1) * 60) + (60 - now.second)\n\t\tmy_server.setex(\"gs_\"+group_type+\":\"+group_id+\":\"+user_id,group_id,secs_till_midnight)\n\t\t# increment session counter\n\t\tmy_server.zincrby(group_type+\"_sess\",group_id+\":\"+user_id,amount=1)\n\n\ndef track_p2p_sms(sent_by_id, sent_to_id, sending_time):\n\t\"\"\"\n\tLog which user sent whom an SMS at what time (to entice them to come to Damadam)\n\t\n\tHelps answer questions such as:\n\t1) Number of SMSes generated per chat/per day/per user\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tmy_server.lpush(\"p2p_sms\",str(sent_by_id)+\":\"+sent_to_id+\":\"+str(sending_time))#llen of list reveals number of SMSes sent\n\t# create 'red carpet' for target user\n\tmy_server.setex(\"rc:\"+sent_to_id,sending_time,ONE_DAY)\n\n\ndef check_p2p_sms(user_id):\n\t\"\"\"\n\tLogs data in case you were sent an SMS by a friend (asking you to return to Damadam)\n\t\n\tHelps answer questions such as:\n\t1) Number of people responding to SMSes\n\t2) How soon does an average responder take to return to the chat from which SMS was sent?\n\t\"\"\"\n\tmy_server, user_id = redis.Redis(connection_pool=POOL), str(user_id)\n\tsms_sent_at = my_server.get(\"rc:\"+user_id)\n\tif sms_sent_at:\n\t\tmy_server.delete(\"rc:\"+user_id)\n\t\ttime_passed_since_sms = time.time() - float(sms_sent_at)\n\t\t# log returned user and time taken since sending of SMS\n\t\tmy_server.lpush(\"sms_eft\",user_id+\":\"+str(time_passed_since_sms))\n\n\ndef log_personal_group_exit_or_delete(group_id, exit_by_id=None, action_type=None):\n\t\"\"\"\n\tLogging time of personal group exit or deletion\n\n\tHelps answer questions such as:\n\t1) How many private chats are create (net basis) week-over-week?\n\t2) What is the average life-time of a private chat?\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tif action_type == 'exit':\n\t\tmy_server.zadd(\"exits\",group_id+\":\"+exit_by_id,time.time())\n\telse:\n\t\t# group_id is a list of group_ids\n\t\ttime_now = time.time()\n\t\tgroups = []\n\t\tfor gid in group_id:\n\t\t\tgroups.append(gid)\n\t\t\tgroups.append(time_now)\n\t\tif groups:\n\t\t\tif action_type == 'del_exit':\n\t\t\t\tmy_server.zadd(\"del_after_exit\",*groups)\n\t\t\telif action_type == 'del_idle':\n\t\t\t\tmy_server.zadd(\"del_after_idle\",*groups)\n\n\ndef purge_exit_list(group_id, user_id):\n\t\"\"\"\n\tPurge a value from 'exits' (called when a user rejoins a group after exiting it)\n\t\"\"\"\n\tredis.Redis(connection_pool=POOL).zrem(\"exits\",group_id+\":\"+str(user_id))\n\n\n########################################### Reporting Metrics for Personal Groups ###########################################\n\ndef avg_sessions_per_type():\n\t\"\"\"\n\tRetrieves session information for personal groups\n\n\t1) What are avg number of sessions per type of chat\n\t2) What are median number of sessions per type of chat\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\tpgs_sampled = my_server.get('pgs_sampled_for_sess')\n\tif pgs_sampled:\n\t\tresults = my_server.mget(['pms_sampled_for_sess','med_sess_per_user_per_pg','med_sess_per_user_per_pm','avg_sess_per_user_per_pg',\\\n\t\t\t'avg_sess_per_user_per_pm','avg_users_per_pm','med_users_per_pm','avg_users_per_pg','med_users_per_pg','avg_sess_per_user_per_two_user_pm',\\\n\t\t\t'med_sess_per_user_per_two_user_pm','total_two_user_pms','avg_users_per_two_user_pm','med_users_per_two_user_pm'])\n\t\treturn pgs_sampled, results[0], results[1], results[2], results[3], results[4], results[5], results[6], results[7], results[8], results[9],\\\n\t\tresults[10],results[11], results[12], results[13]\n\telse:\n\t\tpg_data = my_server.zrange('pg_sess',0,-1,withscores=True)\n\t\tpg_sample_size = len(pg_data)\n\t\tpg_med_idx = int(pg_sample_size/2)\n\n\t\tpm_data = my_server.zrange('pm_sess',0,-1,withscores=True)\n\t\tpm_sample_size = len(pm_data)\n\t\tpm_med_idx = int(pm_sample_size/2)\n\n\t\t# data contains : tuples\n\t\tpg_sessions, all_pgs, all_pg_users = 0, set(), {}\n\t\tfor tup in pg_data:\n\t\t\tpg_sessions += int(tup[1])\n\t\t\tpayload = tup[0].split(\":\")\n\t\t\tgroup_id, user_id = payload[0], payload[1]\n\t\t\tall_pgs.add(group_id)\n\t\t\tall_pg_users[group_id] = {}\n\t\tpgs_sampled = len(all_pgs)\n\t\tfor tup in pg_data:\n\t\t\tpayload = tup[0].split(\":\")\n\t\t\tgroup_id, user_id = payload[0], payload[1]\n\t\t\tall_pg_users[group_id].update({user_id:'user_id'})\n\t\ttotal_pg_users, pg_users_set = 0, []\n\t\tfor key, value in all_pg_users.iteritems():\n\t\t\tnum_users_in_group = len(value)\n\t\t\tpg_users_set.append(num_users_in_group)\n\t\t\ttotal_pg_users += num_users_in_group\n\t\t# finding median\n\t\tarray_pg = sorted(pg_users_set)\n\t\thalf, odd = divmod(len(array_pg), 2)\n\t\tif odd:\n\t\t\tmed_users_per_pg = array_pg[half]\n\t\telse:\n\t\t\tmed_users_per_pg = (array_pg[half - 1] + array_pg[half]) / 2.0\n\n\t\t# calculating pm data\n\t\tpm_sessions, all_pms, all_pm_users = 0, set(), {}\n\t\tfor tup in pm_data:\n\t\t\tpm_sessions += int(tup[1])\n\t\t\tpayload = tup[0].split(\":\")\n\t\t\tgroup_id, user_id = payload[0], payload[1]\n\t\t\tall_pms.add(group_id)\n\t\t\tall_pm_users[group_id] = {}\n\t\tpms_sampled = len(all_pms)\n\t\tfor tup in pm_data:\n\t\t\tpayload = tup[0].split(\":\")\n\t\t\tgroup_id, user_id = payload[0], payload[1]\n\t\t\tall_pm_users[group_id].update({user_id:'user_id'})\n\t\ttotal_pm_users, pm_users_set, two_user_pms = 0, [], {}\n\t\tfor key, value in all_pm_users.iteritems():\n\t\t\tnum_users_in_group = len(value)\n\t\t\tpm_users_set.append(num_users_in_group)\n\t\t\tif num_users_in_group < 3:\n\t\t\t\t# retriving 2 user pms\n\t\t\t\ttwo_user_pms[key] = num_users_in_group\n\t\t\ttotal_pm_users += num_users_in_group\n\t\t\n\t\t# retrieving sessions for 2 user pms in {gid:num_sess} form\n\t\ttwo_user_pm_sess = {}\n\t\tfor tup in pm_data:\n\t\t\tpayload = tup[0].split(\":\")\n\t\t\tgroup_id, user_id = payload[0], payload[1]\n\t\t\tif group_id in two_user_pms:\n\t\t\t\t# it's a two person pm\n\t\t\t\tif group_id in two_user_pm_sess:\n\t\t\t\t\t# already entered data for 1 user\n\t\t\t\t\tnum_sess = two_user_pm_sess[group_id]\n\t\t\t\t\ttwo_user_pm_sess[group_id] = num_sess + int(tup[1])\n\t\t\t\telse:\n\t\t\t\t\ttwo_user_pm_sess[group_id] = int(tup[1])\n\n\t\t# we now have two_user_pms {gid:num_users} and two_user_pm_sess {gid:num_sess}\n\t\ttotal_two_user_pm_sess, all_two_user_pm_sess = 0, []\n\t\tfor key,value in two_user_pm_sess.iteritems():\n\t\t\ttotal_two_user_pm_sess += int(value)\n\t\t\tall_two_user_pm_sess.append(value)\n\t\ttotal_two_user_pm_users, all_two_user_pm_users = 0, []\n\t\tfor key,value in two_user_pms.iteritems():\n\t\t\ttotal_two_user_pm_users += int(value)\n\t\t\tall_two_user_pm_users.append(value)\n\t\tavg_sess_per_user_per_two_user_pm = \"{0:.2f}\".format(float(total_two_user_pm_sess)/total_two_user_pm_users)\n\t\tsorted_sess = sorted(all_two_user_pm_sess)\n\t\thalved, is_odd = divmod(len(sorted_sess), 2)\n\t\tif is_odd:\n\t\t\tmed_sess_per_user_per_two_user_pm = sorted_sess[halved]\n\t\telse:\n\t\t\tmed_sess_per_user_per_two_user_pm = int(sorted_sess[halved - 1] + sorted_sess[halved]) / 2.0\n\t\ttotal_two_user_pms = len(two_user_pms)\n\t\tavg_users_per_two_user_pm = \"{0:.2f}\".format(float(total_two_user_pm_users)/total_two_user_pms)\n\t\tsorted_users = sorted(all_two_user_pm_users)\n\t\tbisect, isodd = divmod(len(sorted_users), 2)\n\t\tif isodd:\n\t\t\tmed_users_per_two_user_pm = sorted_users[bisect]\n\t\telse:\n\t\t\tmed_users_per_two_user_pm = int(sorted_users[bisect - 1] + sorted_users[bisect]) / 2.0\n\t\t# we now have avg and median sessions per user per two user pm\n\n\t\t# finding overall median\n\t\tarray_pm = sorted(pm_users_set)\n\t\thalf, odd = divmod(len(array_pm), 2)\n\t\tif odd:\n\t\t\tmed_users_per_pm = array_pm[half]\n\t\telse:\n\t\t\tmed_users_per_pm = (array_pm[half - 1] + array_pm[half]) / 2.0\n\t\tavg_sess_per_user_per_pg = \"{0:.2f}\".format(float(pg_sessions)/pg_sample_size)\n\t\tavg_sess_per_user_per_pm = \"{0:.2f}\".format(float(pm_sessions)/pm_sample_size)\n\t\tavg_users_per_pg = \"{0:.2f}\".format(float(total_pg_users)/pgs_sampled)\n\t\tavg_users_per_pm = \"{0:.2f}\".format(float(total_pm_users)/pms_sampled)\n\t\tmed_sess_per_user_per_pg = my_server.zrange('pg_sess',pg_med_idx,pg_med_idx+1,withscores=True)[0]\n\t\tmed_sess_per_user_per_pm = my_server.zrange('pm_sess',pm_med_idx,pm_med_idx+1,withscores=True)[0]\n\n\t\t# caching the results\n\t\tpipeline1 = my_server.pipeline()\n\t\tpipeline1.setex('pgs_sampled_for_sess',pgs_sampled,TEN_MINS)\n\t\tpipeline1.setex('pms_sampled_for_sess',pms_sampled,TEN_MINS)\n\t\tpipeline1.setex('avg_users_per_pm',avg_users_per_pm,TEN_MINS)\n\t\tpipeline1.setex('avg_users_per_pg',avg_users_per_pg,TEN_MINS)\n\t\tpipeline1.setex('med_users_per_pm',med_users_per_pm,TEN_MINS)\n\t\tpipeline1.setex('med_users_per_pg',med_users_per_pg,TEN_MINS)\n\t\tpipeline1.setex('total_two_user_pms',total_two_user_pms,TEN_MINS)\n\t\tpipeline1.setex('avg_sess_per_user_per_pg',avg_sess_per_user_per_pg,TEN_MINS)\n\t\tpipeline1.setex('avg_sess_per_user_per_pm',avg_sess_per_user_per_pm,TEN_MINS)\n\t\tpipeline1.setex('med_sess_per_user_per_pg',med_sess_per_user_per_pg,TEN_MINS)\n\t\tpipeline1.setex('med_sess_per_user_per_pm',med_sess_per_user_per_pm,TEN_MINS)\n\t\tpipeline1.setex('med_sess_per_user_per_pm',med_sess_per_user_per_pm,TEN_MINS)\n\t\tpipeline1.setex('avg_users_per_two_user_pm',avg_users_per_two_user_pm,TEN_MINS)\n\t\tpipeline1.setex('med_users_per_two_user_pm',med_users_per_two_user_pm,TEN_MINS)\n\t\tpipeline1.setex('avg_sess_per_user_per_two_user_pm',avg_sess_per_user_per_two_user_pm,TEN_MINS)\n\t\tpipeline1.setex('med_sess_per_user_per_two_user_pm',med_sess_per_user_per_two_user_pm,TEN_MINS)\n\t\tpipeline1.execute()\n\t\treturn pgs_sampled, pms_sampled, med_sess_per_user_per_pg, med_sess_per_user_per_pm, avg_sess_per_user_per_pg, avg_sess_per_user_per_pm,\\\n\t\tavg_users_per_pm, med_users_per_pm, avg_users_per_pg, med_users_per_pg, avg_sess_per_user_per_two_user_pm, med_sess_per_user_per_two_user_pm,\\\n\t\ttotal_two_user_pms, avg_users_per_two_user_pm, med_users_per_two_user_pm\n\t\"\"\"\n\tMeasure 2-user pms vs 2-user pgs\n\tGet 2-user pms and 2-user pgs from pm_sess and pg_sess (i.e. where sessions for 2 participants were logged)\n\n\tGet rid of less than 2 user cases to make it like for like\n\t\"\"\"\n\ndef avg_num_of_switchovers_per_type():\n\t\"\"\"\n\tWhat are avg number of chats produced per type of chat?\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\ttotal_pms = my_server.get('total_pms_sw')\n\tif total_pms:\n\t\tresults = my_server.mget(['median_pm_idx_sw','median_pm_tuple_sw','aggregate_pm_sws','avg_sw_per_pm','total_pgs_sw','median_pg_idx_sw',\\\n\t\t\t'median_pg_tuple_sw','aggregate_pg_sws','avg_sw_per_pg'])\n\t\treturn total_pms, results[0], results[1], results[2], results[3], results[4], results[5], results[6], results[7], results[8]\n\telse:\n\t\tpm_data = my_server.zrange('pm_sw',0,-1,withscores=True)\n\t\ttotal_pms = len(pm_data)\n\t\tmedian_pm_idx = int(total_pms/2)\n\t\tmedian_pm_tuple = my_server.zrange('pm_sw',median_pm_idx,median_pm_idx+1,withscores=True)[0]\n\n\t\tpg_data = my_server.zrange('pg_sw',0,-1,withscores=True)\t\n\t\ttotal_pgs = len(pg_data)\n\t\tmedian_pg_idx = int(total_pgs/2)\n\t\tmedian_pg_tuple = my_server.zrange('pg_sw',median_pg_idx,median_pg_idx+1,withscores=True)[0]\n\n\t\t# data is list of (group_id,chat_num) type tuples\n\t\taggregate_pm_sws, aggregate_pg_sws = 0, 0\n\t\tfor tup in pm_data:\n\t\t\taggregate_pm_sws += int(tup[1])\n\t\tfor tup in pg_data:\n\t\t\taggregate_pg_sws += int(tup[1])\n\t\tavg_sw_per_pm = \"{0:.2f}\".format(aggregate_pm_sws/float(total_pms))\n\t\tavg_sw_per_pg = \"{0:.2f}\".format(aggregate_pg_sws/float(total_pgs))\n\n\t\t# caching the results\n\t\tpipeline1 = my_server.pipeline()\n\t\tpipeline1.setex('total_pms_sw',total_pms,TEN_MINS)\n\t\tpipeline1.setex('median_pm_idx_sw',median_pm_idx,TEN_MINS)\n\t\tpipeline1.setex('median_pm_tuple_sw',median_pm_tuple,TEN_MINS)\n\t\tpipeline1.setex('aggregate_pm_sws',aggregate_pm_sws,TEN_MINS)\n\t\tpipeline1.setex('avg_sw_per_pm',avg_sw_per_pm,TEN_MINS)\n\t\tpipeline1.setex('total_pgs_sw',total_pgs,TEN_MINS)\n\t\tpipeline1.setex('median_pg_idx_sw',median_pg_idx,TEN_MINS)\n\t\tpipeline1.setex('median_pg_tuple_sw',median_pg_tuple,TEN_MINS)\n\t\tpipeline1.setex('aggregate_pg_sws',aggregate_pg_sws,TEN_MINS)\n\t\tpipeline1.setex('avg_sw_per_pg',avg_sw_per_pg,TEN_MINS)\n\t\tpipeline1.execute()\n\t\treturn total_pms, median_pm_idx, median_pm_tuple, aggregate_pm_sws, avg_sw_per_pm, total_pgs, median_pg_idx, median_pg_tuple, \\\n\t\t\taggregate_pg_sws, avg_sw_per_pg\n\n\t\"\"\"\n\tDivide green mehfils into 2 person and 2+ person groups. Only 2 person green groups can be compared to private chat\n\t\"\"\"\n\n\ndef avg_num_of_chats_per_type():\n\t\"\"\"\n\tWhat are avg number of chats produced per type of chat?\n\t\"\"\"\n\tmy_server = redis.Redis(connection_pool=POOL)\n\ttotal_pms = my_server.get('total_pms')\n\tif total_pms:\n\t\tresults = my_server.mget(['median_pm_idx','median_pm_tuple','aggregate_pm_chats','avg_chat_per_pm','total_pgs','median_pg_idx','median_pg_tuple',\\\n\t\t\t'aggregate_pg_chats','avg_chat_per_pg','pms_with_sws','pgs_with_sws'])\n\t\treturn total_pms, results[0], results[1], results[2], results[3], results[4], results[5], results[6], results[7], results[8], results[9], results[10]\n\telse:\n\t\tpm_data = my_server.zrange('pm_ch',0,-1,withscores=True)\n\t\ttotal_pms = len(pm_data)\n\t\tmedian_pm_idx = int(total_pms/2)\n\t\tmedian_pm_tuple = my_server.zrange('pm_ch',median_pm_idx,median_pm_idx+1,withscores=True)[0]\n\n\t\tpg_data = my_server.zrange('pg_ch',0,-1,withscores=True)\n\t\ttotal_pgs = len(pg_data)\n\t\tmedian_pg_idx = int(total_pgs/2)\n\t\tmedian_pg_tuple = my_server.zrange('pg_ch',median_pg_idx,median_pg_idx+1,withscores=True)[0]\n\n\t\t# data is list of (group_id,chat_num) type tuples\n\t\taggregate_pm_chats, aggregate_pg_chats = 0, 0\n\t\tfor tup in pm_data:\n\t\t\taggregate_pm_chats += int(tup[1])\n\t\tfor tup in pg_data:\n\t\t\taggregate_pg_chats += int(tup[1])\n\t\tavg_chat_per_pm = \"{0:.2f}\".format(aggregate_pm_chats/float(total_pms))\n\t\tavg_chat_per_pg = \"{0:.2f}\".format(aggregate_pg_chats/float(total_pgs))\n\n\t\tpms_with_sws = \"{0:.2f}\".format(my_server.zcard('pm_sw')/float(total_pms)*100)\n\t\tpgs_with_sws = \"{0:.2f}\".format(my_server.zcard('pg_sw')/float(total_pgs)*100)\n\n\t\t# caching the results\n\t\tpipeline1 = my_server.pipeline()\n\t\tpipeline1.setex('total_pms',total_pms,TEN_MINS)\n\t\tpipeline1.setex('median_pm_idx',median_pm_idx,TEN_MINS)\n\t\tpipeline1.setex('median_pm_tuple',median_pm_tuple,TEN_MINS)\n\t\tpipeline1.setex('aggregate_pm_chats',aggregate_pm_chats,TEN_MINS)\n\t\tpipeline1.setex('avg_chat_per_pm',avg_chat_per_pm,TEN_MINS)\n\t\tpipeline1.setex('total_pgs',total_pgs,TEN_MINS)\n\t\tpipeline1.setex('median_pg_idx',median_pg_idx,TEN_MINS)\n\t\tpipeline1.setex('median_pg_tuple',median_pg_tuple,TEN_MINS)\n\t\tpipeline1.setex('aggregate_pg_chats',aggregate_pg_chats,TEN_MINS)\n\t\tpipeline1.setex('avg_chat_per_pg',avg_chat_per_pg,TEN_MINS)\n\t\tpipeline1.setex('pms_with_sws',pms_with_sws,TEN_MINS)\n\t\tpipeline1.setex('pgs_with_sws',pgs_with_sws,TEN_MINS)\n\t\tpipeline1.execute()\n\t\treturn total_pms, median_pm_idx, median_pm_tuple, aggregate_pm_chats, avg_chat_per_pm, total_pgs, median_pg_idx, median_pg_tuple, \\\n\t\taggregate_pg_chats, avg_chat_per_pg, pms_with_sws, pgs_with_sws","sub_path":"links/redis4.py","file_name":"redis4.py","file_ext":"py","file_size_in_byte":62779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"387776652","text":"import pandas as pd\nimport os\n\nfiles = []\n\nfor dirpath, dirnames, files in os.walk('channeltranscripts'):\n for name in files:\n if name.lower().endswith('.csv'):\n print('reading', name)\n data = pd.read_csv(os.path.join(dirpath, name))\n\n","sub_path":".history/dataformatter_20210412131615.py","file_name":"dataformatter_20210412131615.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"629169777","text":"#1723682\n#David van Vliet\n\ngetallen = [] #nieuwe list maken van de inputs\ninp = (int(input(\"Geef een getal: \")))\nwhile inp != 0:\n getallen.append(inp) #inputs in de list zetten\n inp = (int(input(\"Geef een getal: \")))\n\nx = len(getallen)\ny = sum(getallen)\nprint(\"Er zijn\", x, \"getallen ingevoerd, de som is: \", y)\n","sub_path":"Python/les7/pe7_1.py","file_name":"pe7_1.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"179688283","text":"from alphavantage import Alphavantage\nfrom newsapi import Newsapi\nimport json\nfrom twilio.rest import Client\nSTOCK = \"TSLA\"\nCOMPANY_NAME = \"Tesla Inc\"\nDOWN_ICON = \"🔻\"\nUP_ICON = \"🔺\"\n\nwith open(\"../cred.json\") as f:\n api_json = f.read()\ntwilio_cred = json.loads(api_json)[\"twilio\"]\naccount_sid = twilio_cred['TWILIO_ACCOUNT_SID']\nauth_token = twilio_cred['TWILIO_AUTH_TOKEN']\n\ntesla_obj = Alphavantage()\ntesla_data = tesla_obj.time_series_daily_adjusted(STOCK)\n\ndiff_per = tesla_obj.prev_diff_percentage(tesla_data)\n\nif diff_per > 5 or diff_per < -5:\n if diff_per < 0:\n icon = DOWN_ICON\n else:\n icon = UP_ICON\n newsapi = Newsapi()\n tesla_news = newsapi.get_news(keyword=COMPANY_NAME,page_size=3)\n message_body = f\"{STOCK}: {icon}{abs(diff_per)}%\\n\"\n for n in tesla_news:\n message_body += f\"\\nHeadline: {n['title']}\\nBrief: {n['description']}\\n\"\n client = Client(account_sid, auth_token)\n\n message = client.messages \\\n .create(\n body=f\"{message_body}\",\n from_=f'{twilio_cred[\"from_number\"]}',\n to=f'{twilio_cred[\"to_number\"]}'\n )\n\n print(message.status)\n","sub_path":"day-36/stock-news/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"158228009","text":"#codeing=utf-8\n# @Time : 2017-10-12\n# @Author : J.sky\n# @Mail : bosichong@qq.com\n# @Site : www.17python.com\n# @Title : Python中创建TCP服务器与客户端进行通信(中)Tk、thread与socket组合。\n# @Url : http://www.17python.com/blog/41\n# @Details : Python中创建TCP服务器与客户端进行通信(中)Tk、thread与socket组合。\n# @Other : OS X 10.11.6 \n# Python 3.6.1\n# VSCode 1.15.1\n###################################\n# Python中创建TCP服务器与客户端进行通信(中)Tk、thread与socket组合。\n###################################\n#coding=utf-8\nimport threading, socket, time\nimport tkinter as tk\n\n\nclass TcpClient(threading.Thread):\n def __init__(self, addr, port):\n threading.Thread.__init__(self)\n self.addr = addr\n self.port = port\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.s.connect((self.addr, self.port))\n self.stop_flag = False\n self.name = ''\n\n def run(self):\n self.sendName()#发送昵称验证\n t1 = threading.Thread(target=self.recvMsgThread)\n t2 = threading.Thread(target=self.sendMsgThread)\n t1.start()\n t2.start()\n t1.join()\n t2.join()\n\n#发送客户端用户名,保存在服务器端列表中\n def sendName(self):\n\n while True:\n self.name = input('请输出昵称:')\n self.s.send(self.name.encode()) # 发送到服务器\n msg = self.s.recv(1024)\n if msg.decode('utf-8') == '用户名已经存在':\n print(msg.decode('utf-8'),'请重新输入昵称!')\n else:\n break\n\n\n\n # 发送消息线程方法\n def sendMsgThread(self):\n print('发消息线程启动------------', self.stop_flag)\n while not self.stop_flag:\n data = input('>>>')\n if data == 'exit':#输入exit退出客户端\n msg = self.name + '好象有什么急事!一路小跑的离开了聊天室'\n self.s.send(msg.encode())\n time.sleep(1)\n self.stop() # 中止线程\n print('发消息线程已关闭')\n \n elif data:\n data = '[{0}]说道:{1}'.format(self.name,data)\n self.s.send(data.encode())\n\n\n # 接收消息线程方法\n def recvMsgThread(self):\n print('收消息线程启动-------------', self.stop_flag)\n while not self.stop_flag:\n try:\n msg = self.s.recv(1024)\n if msg: print(msg.decode())\n\n except Exception as e:\n print('收消息线程已关闭')\n\n def stop(self):\n self.s.close()\n self.stop_flag = True\n\n\ndef main():\n ip = '192.168.0.88'\n port = 18888\n t3 = TcpClient(ip, port)\n print('正在进入聊天室,请先起个牛逼的名字!')\n t3.start()\n t3.join()\n\n\nif __name__ == '__main__':\n main()\n print('客户端退出')\n\n","sub_path":"TCP/GUISocket/GUI_Clisock.py","file_name":"GUI_Clisock.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"474601663","text":"from PIL import ImageGrab, Image, ImageChops\nimport time\nimport cv2\nimport os\nimport shutil\nimport sys\nimport pickle\nimport time\nfrom scipy.misc import imread\nfrom scipy.linalg import norm\nfrom scipy import sum, average\nfrom skimage import color\nfrom skimage import io\nfrom sklearn.decomposition import PCA\nimport numpy as np\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# caputure image\n# ----------------------------------------------------------------------------------------------------------------------\n# for i in range(1000):\n# time.sleep(0.5)\n# im = ImageGrab.grab(bbox=(0,280,405,820))\n# #im = ImageGrab.grab() full screen\n# im.save('screen_shots/screenshot-{}.png'.format(i))\n# ----------------------------------------------------------------------------------------------------------------------\n\nclass GameFb:\n def __init__(self):\n self.pic_uuid = 0\n self.run_bbox = (748, 175, 1140, 705)\n self.end_bbox = (830, 525, 1065, 560)\n\n def _grab_save_img(self, path, bbox):\n im = ImageGrab.grab(bbox=bbox)\n im.save(path)\n self.pic_uuid += 1\n\n def get_img_feature(self, thin_factor = 1):\n im = ImageGrab.grab(bbox=self.run_bbox).convert('1')\n arr = np.array(im)\n arr = 1 * arr.flatten()\n im.save('test.png')\n #arr = arr[::thin_factor]\n pca_path = 'fb_PCA'\n pca = pickle.load(open(pca_path, \"rb\"))\n pca_arr = pca.transform(arr)[0]\n return pca_arr\n\n # path = 'running_screen_shots/{}.png'.format(self.pic_uuid)\n # self._grab_save_img(path, self.run_bbox)\n # img_vector = color.rgb2gray(io.imread(path))\n # print (\"img_vector: \".format(img_vector))\n # sys.exit()\n\n def clear_screen_shots(self):\n self.pic_uuid = 0\n clear_folder = 'running_screen_shots'\n file_list = os.listdir(clear_folder)\n for file in file_list:\n file_path = os.path.join(clear_folder, file)\n os.remove(file_path)\n\n @property\n def is_game_start(self):\n #\n GAME_START_THRESHOLD = 1.0\n #\n start_pics_folder_path = 'start_end_shots'\n start_pic_path = 'start.png'\n start_pic_path = os.path.join(start_pics_folder_path, start_pic_path)\n #\n path = 'running_screen_shots/{}.png'.format(self.pic_uuid)\n self._grab_save_img(path, self.run_bbox)\n #\n\n n_m = self._compare_images(start_pic_path, path)\n #print(\"n_m: {}\".format(n_m))\n\n if n_m <= GAME_START_THRESHOLD:\n return True\n else:\n\n return False\n\n @property\n def is_game_end(self):\n\n #\n GAME_END_THRESHOLD = 1.0\n #\n end_pics_folder_path = 'start_end_shots'\n end_pic_path = 'end.png'\n end_pic_path = os.path.join(end_pics_folder_path, end_pic_path)\n #\n path = 'running_screen_shots/{}.png'.format(self.pic_uuid)\n self._grab_save_img(path, self.end_bbox)\n #\n\n n_m = self._compare_images(end_pic_path, path)\n #print(\"n_m: {}\".format(n_m))\n\n if n_m <= GAME_END_THRESHOLD:\n return True\n else:\n\n return False\n\n\n def _compare_images(self,img1_path, img2_path):\n\n def _to_grayscale(arr):\n \"If arr is a color image (3D array), convert it to grayscale (2D array).\"\n if len(arr.shape) == 3:\n return average(arr, -1) # average over the last axis (color channels)\n else:\n return arr\n\n def _normalize(arr):\n rng = arr.max() - arr.min()\n amin = arr.min()\n return (arr - amin) * 255 / rng\n\n img1 = _to_grayscale(imread(img1_path).astype(float))\n img2 = _to_grayscale(imread(img2_path).astype(float))\n\n # normalize to compensate for exposure difference\n img1 = _normalize(img1)\n img2 = _normalize(img2)\n # calculate the difference and its norms\n diff = img1 - img2 # elementwise for scipy arrays\n m_norm = sum(abs(diff)) # Manhattan norm\n #z_norm = norm(diff.ravel(), 0) # Zero norm\n\n img_size = img1.size\n n_m = m_norm / img_size\n return n_m\n\n# ----------------------------------------------------------------------------------------------------------------------\n# compare image\n# ----------------------------------------------------------------------------------------------------------------------\n\n\n\n# bbox = (748, 175, 1140, 705)\n# im = ImageGrab.grab(bbox=bbox)\n# for i in range(1000):\n# img_path = 'running_screen_shots/{}.png'.format(i)\n# path = 'running_screen_shots/{}.txt'.format(i)\n# time.sleep(0.5)\n# im = ImageGrab.grab(bbox=bbox).convert('1')\n# im.save(img_path)\n# arr = np.array(im)\n# arr = 1 * arr.flatten()\n# arr = [str(x) for x in arr]\n# arr_str = ','.join(arr)\n# with open (path, 'w') as f:\n# f.write(arr_str)\n\n\n\n\n\n# file1 = \"start_shots/screenshot-20.png\"\n# file2 = \"start_shots/screenshot-21.png\"\n#\n#\n# img1 = to_grayscale(imread(file1).astype(float))\n# img2 = to_grayscale(imread(file2).astype(float))\n# # compare\n# n_m, n_0 = compare_images(img1, img2)\n# # threshold n_m: 1.6\n# print (\"n_m: {}, n_0:{}\".format(n_m/img1.size, n_0/img1.size))\n# ----------------------------------------------------------------------------------------------------------------------\n","sub_path":"screen_capturer.py","file_name":"screen_capturer.py","file_ext":"py","file_size_in_byte":5482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"595546968","text":"from banco import Banco\nfrom cliente import Cliente\nfrom conta import ContaCorrente, ContaPoupanca\n\nbanco = Banco()\n\ncliente1 = Cliente('Pedro', 28)\ncliente2 = Cliente('Maria', 18)\ncliente3 = Cliente('Juliana', 25)\n\nconta1 = ContaPoupanca(1111, 235687, 0)\nconta2 = ContaCorrente(2222, 321687, 0)\nconta3 = ContaPoupanca(1112, 2187, 0)\n\ncliente1.inserir_contar(conta1)\ncliente2.inserir_contar(conta2)\ncliente3.inserir_contar(conta3)\n\nbanco.inserir_conta(conta1)\nbanco.inserir_cliente(cliente1)\n\n\nif banco.autenticar(cliente1):\n cliente1.conta.depositar(200)\n cliente1.conta.sacar(30)\nelse:\n print('Cliente não autenticado')","sub_path":"Desafio/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"172983874","text":"def fade(st, nd, steps=10):\n st = st.strip(\"#\")\n nd = nd.strip(\"#\")\n st_rgb = hex_to_rgb(st)\n nd_rgb = hex_to_rgb(nd)\n\n to_step = [nds - sts for sts, nds in zip(st_rgb, nd_rgb)]\n\n (rstep, gstep, bstep) = [to_step[i] // steps for i in (0, 1, 2)]\n\n color_steps = []\n for i in range(steps - 1):\n color_steps.append(\n rgb_to_hex((st_rgb[0]+i*rstep, st_rgb[1]+i*gstep, st_rgb[2]+i*bstep))\n )\n color_steps.append(\"#\" + nd)\n\n return color_steps\n\n\ndef hex_to_rgb(h):\n return [int(h[i:i + 2], 16) for i in (0, 2, 4)]\n\ndef rgb_to_hex(rgb):\n _long_hex = lambda s: ('0' if len(s) == 1 else '') + s\n _hex = lambda i: _long_hex(format(i, 'x'))\n return f'#{_hex(rgb[0])}{_hex(rgb[1])}{_hex(rgb[2])}'\n\ndef long_hex(h):\n if len(h) == 3:\n return \"\".join([ch*2 for ch in h])\n return h\n \n","sub_path":"color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"403390994","text":"from __future__ import print_function\nimport requests\nimport argparse\n\n# handle ModuleNotFoundError during python3 execution\ntry:\n from cli_weather.airquality_data import *\n from cli_weather.weather_data import *\n from cli_weather.weather_forecast_data import *\n from cli_weather.airquality_forecast_data import *\nexcept ModuleNotFoundError:\n from airquality_data import *\n from weather_data import *\n from weather_forecast_data import *\n from airquality_forecast_data import *\n\ndef get_by_city_args(subparsers):\n \"\"\"\n add positinal argument 'city' to argparser\n \"\"\"\n city_parser = subparsers.add_parser('city',\n formatter_class=argparse.RawTextHelpFormatter\n )\n city_parser.add_argument(\n \"city\",\n help=\"get weather by city name\"\n )\n city_parser.add_argument(\n \"-a\",\"--airquality\",\n action=\"store_true\",\n help=\"current air quality observations\"\n )\n city_parser.add_argument(\n \"-d\",\"--detailed\",\n help=\"display detailed data [not applicable for forecast]\",\n action=\"store_true\"\n )\n city_parser.add_argument(\n \"-f\",\"--forecast\",\n action=\"store_true\",\n help=\"forecast on weather or airquality\"\n )\n city_parser.add_argument(\n \"-c\", \"--country\",\n help=\"country of entered area\",\n default=\"\"\n )\n city_parser.add_argument(\n \"-u\", \"--units\",\n choices=['M','S','I'],\n help=\"M - Metric (Celcius, m/s, mm) [DEFAULT]\\nS - Scientific (Kelvin, m/s, mm)\\nI - Imperial (F, mph, in)\",\n default=\"M\"\n )\n\n\ndef city_parse(args):\n \"\"\"\n Send API request to WeatherBIT for city based input\n and call respective methods based on optional arguments\n \"\"\"\n city = args.city\n country = \"&\" + args.country\n units = args.units\n API_KEY = \"2a7db0585e7541018229c17efb2efa94\"\n\n\n if args.airquality is True and args.forecast is False:\n if args.country == \"\":\n API_URL = \"https://api.weatherbit.io/v2.0/current/airquality?city=\"+city+\"&key=\"\n else:\n API_URL = \"https://api.weatherbit.io/v2.0/current/airquality?city=\"+city+country+\"&key=\"\n\n elif args.airquality is False and args.forecast is True:\n if args.country == \"\":\n API_URL = \"https://api.weatherbit.io/v2.0/forecast/daily?city=\"+city+\"&key=\"\n else:\n API_URL = \"https://api.weatherbit.io/v2.0/forecast/daily?city=\"+city+country+\"&key=\"\n\n elif args.airquality is True and args.forecast is True:\n if args.country == \"\":\n API_URL = \"https://api.weatherbit.io/v2.0/forecast/airquality?city=\"+city+\"&key=\"\n else:\n API_URL = \"https://api.weatherbit.io/v2.0/forecast/airquality?city=\"+city+country+\"&key=\"\n\n elif args.airquality is False:\n if args.country == \"\":\n API_URL = \"https://api.weatherbit.io/v2.0/current?city=\"+city+\"&key=\"\n else:\n API_URL = \"https://api.weatherbit.io/v2.0/current?city=\"+city+country+\"&key=\"\n\n url = API_URL + API_KEY\n\n querystring = {\n \"lang\":\"en\",\n \"units\":units\n }\n\n response = requests.request(\"GET\", url, params=querystring)\n\n try:\n main_data = response.json()\n # ValueError-unable to decode json, UnboundLocalError-used var before declaring\n except (ValueError,UnboundLocalError) as err:\n print(\"Invalid city\")\n print(\"Please use format ex: $ cli-weather bengaluru [-c country_name][-a][-u M/S/I][-d]\")\n return\n\n # defalut metric values\n degree = \"celcius\"\n speed = \"m/s\"\n distance = \"mm\"\n\n if args.units == \"S\":\n degree = \"kelvin\"\n elif args.units == \"I\":\n degree = \"Fahrenheit\"\n speed = \"mph\"\n distance = \"in\"\n\n choice = [True, False]\n if args.airquality is False and args.detailed in choice and args.forecast is True:\n get_weather_forecast(main_data, degree, speed, distance)\n return\n elif args.airquality is True and args.detailed in choice and args.forecast is True:\n get_airquality_forecast(main_data)\n return\n\n # call respective methods based on selected combination of optional arguments in cli-weather\n if args.detailed is False and args.airquality is False:\n get_basic_temparature(main_data, degree)\n\n elif args.detailed is True and args.airquality is False:\n get_detailed_weather(main_data, degree, speed, distance)\n\n elif args.detailed is False and args.airquality is True:\n get_basic_airquality(main_data)\n\n elif args.detailed is True and args.airquality is True:\n get_detailed_airquality(main_data)\n","sub_path":"venv/Lib/site-packages/cli_weather/get_by_city.py","file_name":"get_by_city.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"200851098","text":"\"\"\"\nWhat is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n\"\"\"\n\n\n# Primeros 4 numeros primos\nprimes = [2,3,5,7]\n\n# Obtiene una lista con los factores de un numero\ndef get_factors(n):\n if n in primes:\n return [int(n)]\n else:\n #print(f'Calling with n={n}')\n for i in range (2,int(n)):\n if int(n)%i == 0:\n #print(f'Factor found: {i}')\n resto = get_factors(int(n)/i)\n return [*resto, *[int(i)]]\n return[int(n)]\n\n# Devuelve un diccionario con el numer de ocurrencias de cada factor\ndef dict_factor(factores):\n dic = {}\n for i in factores:\n if i in dic.keys():\n dic[i] += 1\n else:\n dic[i] = 1\n return dic\n\n# A partir de un diccionario factor/ocurrencias, saca en mcm\ndef get_mcm(factores: dict):\n resultado = 1\n for i in factores.keys():\n n = i**factores[i]\n resultado = resultado * n\n return resultado\n\n\n\nall_divisors = {}\n\nfor n in range(2,21):\n factores = dict_factor(get_factors(n))\n for f in factores.keys():\n if f in all_divisors:\n if all_divisors[f] < factores[f]:\n all_divisors[f] = factores[f]\n else:\n all_divisors[f] = factores[f]\n\n\nprint(f'All divisors: {all_divisors}')\nmcm = get_mcm(all_divisors)\n\nprint(f'The mcm is: {mcm}')\n\n","sub_path":"Problem_005/problem_5.py","file_name":"problem_5.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"586164884","text":"# System imports\nimport os\nimport sys\nfrom pprint import pprint as pp\nfrom time import time as tt\nimport inspect\n\n# External imports\nimport matplotlib.pyplot as plt\nimport matplotlib.colors\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import auc\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport torch\nfrom torch_geometric.data import Data\nfrom torch_geometric.data import DataLoader\nfrom mpl_toolkits.mplot3d import Axes3D\nimport argparse\nfrom itertools import permutations\n\nfrom itertools import chain\nimport trackml.dataset\n\nimport ipywidgets as widgets\nfrom ipywidgets import interact, interact_manual\n\n# Pick up local packages\nsys.path.append(\"..\")\n\n# Local imports\nfrom prepare import select_hits\nfrom toy_utils import *\nfrom models import *\nfrom trainers import *\n\n# Get rid of RuntimeWarnings, gross\nimport warnings\n\nwarnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n\nimport wandb\n\n\ndef parse_args():\n \"\"\"Parse command line arguments.\"\"\"\n parser = argparse.ArgumentParser(\"train.py\")\n add_arg = parser.add_argument\n\n add_arg(\"--hidden-dim\", type=int, default=None, help=\"Hidden layer dimension size\")\n add_arg(\n \"--n-graph-iters\", type=int, default=None, help=\"Number of graph iterations\"\n )\n add_arg(\n \"--emb-dim\",\n type=int,\n default=None,\n help=\"Number of spatial embedding dimensions\",\n )\n add_arg(\n \"--emb-hidden\",\n type=int,\n default=None,\n help=\"Number of embedding hidden dimensions\",\n )\n add_arg(\"--nb-layer\", type=int, default=None, help=\"Number of embedding layers\")\n add_arg(\"--r-val\", type=float, default=None, help=\"Radius of graph construction\")\n add_arg(\"--r-train\", type=float, default=None, help=\"Radius of embedding training\")\n add_arg(\"--margin\", type=float, default=None, help=\"Radius of hinge loss\")\n add_arg(\"--lr-1\", type=float, default=None, help=\"Embedding loss learning rate\")\n add_arg(\"--lr-2\", type=float, default=None, help=\"AGNN loss learning rate\")\n add_arg(\"--lr-3\", type=float, default=None, help=\"Weight balance learning rate\")\n add_arg(\"--weight\", type=float, default=None, help=\"Positive weight in AGNN\")\n add_arg(\"--train-size\", type=int, default=None, help=\"Number of train population\")\n add_arg(\"--val-size\", type=int, default=None, help=\"Number of validate population\")\n add_arg(\"--pt-cut\", type=float, default=None, help=\"Cutoff for momentum\")\n add_arg(\"--adjacent\", type=bool, default=False, help=\"Enforce adjacent layers?\")\n add_arg(\"--pretrain-epochs\", type=int, default=5)\n\n return parser.parse_args()\n\n\ndef build_event(event_file, pt_min, feature_scale, adjacent):\n hits, particles, truth = trackml.dataset.load_event(\n event_file, parts=[\"hits\", \"particles\", \"truth\"]\n )\n hits = select_hits(hits, truth, particles, pt_min=pt_min).assign(\n evtid=int(event_file[-9:])\n )\n layers = hits.layer.to_numpy()\n\n # Get true edge list\n records_array = hits.particle_id.to_numpy()\n idx_sort = np.argsort(records_array)\n sorted_records_array = records_array[idx_sort]\n _, idx_start, _ = np.unique(\n sorted_records_array, return_counts=True, return_index=True\n )\n # sets of indices\n res = np.split(idx_sort, idx_start[1:])\n true_edges = np.concatenate(\n [list(permutations(i, r=2)) for i in res if len(list(permutations(i, r=2))) > 0]\n )\n if adjacent:\n true_edges = true_edges[\n (layers[true_edges.T[1]] - layers[true_edges.T[0]] == 1)\n ]\n\n return (\n hits[[\"r\", \"phi\", \"z\"]].to_numpy() / feature_scale,\n hits.particle_id.to_numpy(),\n layers,\n true_edges,\n )\n\n\ndef prepare_event(event_file, pt_min, feature_scale, adjacent=True):\n # print(\"Preparing\",event_file)\n X, pid, layers, true_edges = build_event(\n event_file, pt_min, feature_scale, adjacent\n )\n data = Data(\n x=torch.from_numpy(X).float(),\n pid=torch.from_numpy(pid),\n layers=torch.from_numpy(layers),\n true_edges=torch.from_numpy(true_edges),\n )\n return data\n\n\ndef save_model(epoch, model, optimizer, scheduler, running_loss, config, PATH):\n torch.save(\n {\n \"epoch\": epoch,\n \"model_state_dict\": model.state_dict(),\n \"optimizer_state_dict\": optimizer.state_dict(),\n \"scheduler_state_dict\": scheduler.state_dict(),\n \"loss\": running_loss,\n \"config\": config,\n },\n os.path.join(\"model_comparisons/\", PATH),\n )\n\n\ndef main(args):\n # print(args)\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n # Dataset processing\n\n input_dir = \"/global/cscratch1/sd/danieltm/ExaTrkX/trackml/train_all/\"\n all_events = os.listdir(input_dir)\n all_events = [input_dir + event[:14] for event in all_events]\n np.random.shuffle(all_events)\n\n train_dataset = [\n prepare_event(event_file, args.pt_cut, [1000, np.pi, 1000], args.adjacent)\n for event_file in all_events[:4000]\n ]\n test_dataset = [\n prepare_event(event_file, args.pt_cut, [1000, np.pi, 1000], args.adjacent)\n for event_file in all_events[-args.val_size :]\n ]\n train_loader = DataLoader(train_dataset, batch_size=1, shuffle=True)\n test_loader = DataLoader(test_dataset, batch_size=1, shuffle=True)\n\n # Model config\n e_configs = {\n \"in_channels\": 3,\n \"emb_hidden\": args.emb_hidden,\n \"nb_layer\": args.nb_layer,\n \"emb_dim\": args.emb_dim,\n }\n m_configs = {\n \"in_channels\": 3,\n \"emb_hidden\": args.emb_hidden,\n \"nb_layer\": args.nb_layer,\n \"emb_dim\": args.emb_dim,\n \"r\": args.r_val,\n \"hidden_dim\": args.hidden_dim,\n \"n_graph_iters\": args.n_graph_iters,\n }\n other_configs = {\n \"weight\": args.weight,\n \"r_train\": args.r_train,\n \"r_val\": args.r_val,\n \"margin\": args.margin,\n \"reduction\": \"mean\",\n }\n\n # Create and pretrain embedding\n embedding_model = Embedding(**e_configs).to(device)\n wandb.init(group=\"EmbeddingToAGNN_PurTimesEff\", config=m_configs)\n embedding_optimizer = torch.optim.Adam(\n embedding_model.parameters(), lr=0.0005, weight_decay=1e-3, amsgrad=True\n )\n\n for epoch in range(args.pretrain_epochs):\n tic = tt()\n embedding_model.train()\n cluster_pur, train_loss = train_emb(\n embedding_model, train_loader, embedding_optimizer, other_configs\n )\n\n embedding_model.eval()\n with torch.no_grad():\n cluster_pur, cluster_eff, val_loss, av_nhood_size = evaluate_emb(\n embedding_model, test_loader, other_configs\n )\n wandb.log(\n {\n \"val_loss\": val_loss,\n \"train_loss\": train_loss,\n \"cluster_pur\": cluster_pur,\n \"cluster_eff\": cluster_eff,\n \"av_nhood_size\": av_nhood_size,\n }\n )\n\n # Create and train main model\n model = EmbeddingToAGNNPretrained(**m_configs, pretrained_model=embedding_model).to(\n device\n )\n multi_loss = MultiNoiseLoss(n_losses=2).to(device)\n m_configs.update(other_configs)\n wandb.run.save()\n print(wandb.run.name)\n model_name = wandb.run.name\n wandb.watch(model, log=\"all\")\n\n # Optimizer config\n\n optimizer = torch.optim.AdamW(\n [\n {\"params\": model.emb_network.parameters()},\n {\n \"params\": chain(\n model.node_network.parameters(),\n model.edge_network.parameters(),\n model.input_network.parameters(),\n )\n },\n {\"params\": multi_loss.noise_params},\n ],\n lr=0.001,\n weight_decay=1e-3,\n amsgrad=True,\n )\n\n # Scheduler config\n\n lambda1 = lambda ep: 1 / (args.lr_1 ** (ep // 10))\n lambda2 = lambda ep: 1 / (args.lr_2 ** (ep // 30))\n lambda3 = lambda ep: 1 / (args.lr_3 ** (ep // 10))\n scheduler = torch.optim.lr_scheduler.LambdaLR(\n optimizer, lr_lambda=[lambda1, lambda2, lambda3]\n )\n\n # Training loop\n\n for epoch in range(50):\n tic = tt()\n model.train()\n if args.adjacent:\n edge_acc, cluster_pur, train_loss = balanced_adjacent_train(\n model, train_loader, optimizer, multi_loss, m_configs\n )\n else:\n edge_acc, cluster_pur, train_loss = balanced_train(\n model, train_loader, optimizer, multi_loss, m_configs\n )\n # print(\"Training loss:\", train_loss)\n\n model.eval()\n if args.adjacent:\n with torch.no_grad():\n (\n edge_acc,\n edge_pur,\n edge_eff,\n cluster_pur,\n cluster_eff,\n val_loss,\n av_nhood_size,\n ) = evaluate_adjacent(model, test_loader, multi_loss, m_configs)\n else:\n with torch.no_grad():\n (\n edge_acc,\n edge_pur,\n edge_eff,\n cluster_pur,\n cluster_eff,\n val_loss,\n av_nhood_size,\n ) = evaluate(model, test_loader, multi_loss, m_configs)\n scheduler.step()\n wandb.log(\n {\n \"val_loss\": val_loss,\n \"train_loss\": train_loss,\n \"edge_acc\": edge_acc,\n \"edge_pur\": edge_pur,\n \"edge_eff\": edge_eff,\n \"cluster_pur\": cluster_pur,\n \"cluster_eff\": cluster_eff,\n \"lr\": scheduler._last_lr[0],\n \"combined_performance\": edge_eff * cluster_eff * edge_pur + cluster_pur,\n \"combined_efficiency\": edge_eff * cluster_eff * edge_pur,\n \"noise_1\": multi_loss.noise_params[0].item(),\n \"noise_2\": multi_loss.noise_params[1].item(),\n \"av_nhood_size\": av_nhood_size,\n }\n )\n\n save_model(\n epoch,\n model,\n optimizer,\n scheduler,\n cluster_eff,\n m_configs,\n \"EmbeddingToAGNN/\" + model_name + \".tar\",\n )\n\n\n# print('Epoch: {}, Edge Accuracy: {:.4f}, Edge Purity: {:.4f}, Edge Efficiency: {:.4f}, Cluster Purity: {:.4f}, Cluster Efficiency: {:.4f}, Loss: {:.4f}, LR: {} in time {}'.format(epoch, edge_acc, edge_pur, edge_eff, cluster_pur, cluster_eff, val_loss, scheduler._last_lr, tt()-tic))\n\nif __name__ == \"__main__\":\n\n # Parse the command line\n args = parse_args()\n # print(args)\n\n main(args)\n","sub_path":"pretrain.py","file_name":"pretrain.py","file_ext":"py","file_size_in_byte":10789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"29470928","text":"import re\nimport math\nfrom collections import Counter\nfrom Project import db\nfrom flask_restful import Resource,reqparse,fields,marshal\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom Project.views import userbase,extra,home\nfrom flask import url_for,request\nfrom Project.models import User\nfrom werkzeug.urls import url_parse\nfrom Project.models import UserProfile\nfrom Project.models import Student\nfrom flask_cors import CORS,cross_origin\nfrom flask import jsonify\n\nheaders ={\"Content-Type\": \"application/json\"}\n\nclass SkillRecommender(Resource):\n\tdecorators= [login_required]\n\t@cross_origin()\n\tdef get(self,username):\n\t\t#u = User.query.filter_by(username=username).first()\n\t\t\t\t\n\t\tif username is None:\n\t\t\treturn jsonify({\"description\" : \"The username is NULL\"}),200,headers\n\t\tu = User.query.filter_by(username=username).first()\n\t\t\t\t\n\t\tu = UserProfile.query.filter_by(id=u.id).first()\n\t\t#text1 is the list of skills of the user\n\t\tprint(u)\n\t\tif u is None:\n\t\t\treturn jsonify({\"description\" : \"The username does not exist.Please enter a valid username\"}),200,headers\n\t\t\t\t\n\t\ttext1=u.skills\n\t\t#text2 is the list of skills from the group table\n\t\t#It is in the form of group_id,skills\n\t\ttext2=[[1,\"Java, C programming, R programming\"],[3,\"NodeJs, HTML, CSS\"],[5,\"C programming, Java, Python\"],[8,\"NodeJs, Java\"]]\n\t\ttext3=[[1,\"SE Project\"],[2,\"Chatbot App\"],[3,\"Proveit\"],[5,\"NGO Website\"],[8,\"Brownie\"]]\n\t\t\n\t\tWORD = re.compile(r'\\w+')\n\n\t\tdef get_cosine(vec1, vec2):\n\t\t intersection = set(vec1.keys()) & set(vec2.keys())\n\t\t numerator = sum([vec1[x] * vec2[x] for x in intersection])\n\n\t\t sum1 = sum([vec1[x]**2 for x in vec1.keys()])\n\t\t sum2 = sum([vec2[x]**2 for x in vec2.keys()])\n\t\t denominator = math.sqrt(sum1) * math.sqrt(sum2)\n\t\t if not denominator:\n\t\t return (0)\n\t\t else:\n\t\t return float(numerator) / denominator\n\n\t\tdef text_to_vector(text):\n\t\t words = WORD.findall(text)\n\t\t return Counter(words)\n\n\n\t\tvector1 = text_to_vector(text1)\n\t\tl=[]\n\t\tval=-11111\n\t\tfor i in range(len(text2)):\n\t\t\tvector2 = text_to_vector(text2[i][1])\n\t\t\tcosine = get_cosine(vector1, vector2)\n\t\t\tl.append(cosine)\n\t\t\t#print 'Project id: ',text2[i][0],'Cosine:', cosine\n\t\t\tif(cosine>val):\n\t\t\t\tval=cosine\n\t\t\t\tprojid=text2[i][0]\n\t\tfor i in range(len(text3)):\n\t\t\tif(text3[i][0]==projid):\n\t\t\t\tprojname=text3[i][1]\n\t\t\t\t#max=val\n\t\t#print 'Max Project id', projid, 'Similarity: ',val\n\t\t#print 'Recommendation for user: See project_id ', projid #Return the projid of max similarity between text1 and text2\n\t\t#projid_list=[]\n\t\t#projid_list.append(projid)\t\t\n\t\t#projid_returned = jsonify(projid_list)\n\n\t\treturn jsonify({ 'Projects recommended based on skills are' : projname}),200,headers\n\n","sub_path":"Project/Project/resources/skills.py","file_name":"skills.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"458148997","text":"# Даны два вектора в трехмерном пространстве: (10,10,10) и (0,0,-10)\n# Напишите код на Python, реализующий расчет длины вектора, заданного его координатами.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\na = np.array([10, 10, 10])\nb = np.array([0, 0, -10])\nc = a + b\n\nprint(math.sqrt(c[0]**2 + c[1]**2 + c[2]**2))\n\n# 3. Задание Напишите код на Python, реализующий построение графиков:\n# окружности,\n# эллипса,\n# гиперболы.\n\n# окружность\nx = []\ny1 = []\ny2 = []\nR = 2\nfor i in range(500*2*R+1):\n x1 = -R + i/500\n x.append(x1)\n y1.append(math.sqrt(R**2 - x1**2))\n y2.append(-math.sqrt(R**2 - x1**2))\nplt.plot(x,y1)\nplt.plot(x,y2)\nplt.xlabel(\"Ось x\")\nplt.ylabel(\"Ось y\")\nplt.ylim(-3,3)\nplt.xlim(-4.3,4.3)\nplt.grid(True)\n\nplt.show()\n\n# Эллипс\nx = []\ny1 = []\ny2 = []\na = 4\nb = 7\nfor i in range(500*2*a+1):\n x1 = -a + i/500\n x.append(x1)\n y1.append(math.sqrt(1 - x1**2/a**2) * b)\n y2.append(-math.sqrt(1 - x1**2/a**2) * b)\nplt.plot(x,y1)\nplt.plot(x,y2)\nplt.xlabel(\"Ось x\")\nplt.ylabel(\"Ось y\")\nplt.ylim(-10,10)\nplt.xlim(-4.3,4.3)\nplt.grid(True)\n\nplt.show()\n\n# Гипербола\nx = []\ny1 = []\ny2 = []\na = 1\nb = 3\nfor i in range(5000*2*a):\n x1 = a + i/500\n x.append(x1)\n y1.append(math.sqrt(x1**2/a**2 - 1) * b)\n y2.append(-math.sqrt(x1**2/a**2 - 1) * b)\nplt.plot(x,y1)\nplt.plot(x,y2)\nplt.xlabel(\"Ось x\")\nplt.ylabel(\"Ось y\")\nplt.ylim(-5,5)\nplt.xlim(-5,5)\nplt.grid(True)\nplt.show()\n\n# Нарисуйте трехмерный график двух параллельных плоскостей.\nfrom pylab import *\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = figure()\nax = Axes3D(fig)\nX = np.arange(-10, 10, 1)\nY = np.arange(-10, 10, 1)\nX, Y = np.meshgrid(X, Y)\nZ = X + 2*Y\nZ1 = X + 2*Y + 40\nax.plot_surface(X, Y, Z)\nax.plot_surface(X, Y, Z1)\nshow()\n\n#Нарисуйте трехмерный график двух любых поверхностей второго порядка.\n\nfrom pylab import *\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = figure()\nax = Axes3D(fig)\nX = np.arange(-10, 10, 1)\nY = np.arange(-10, 10, 1)\nX, Y = np.meshgrid(X, Y)\nZ = - np.sqrt(X**2 + Y**2)\nZ1 = X**2/10 + Y**2/10\nax.plot_surface(X, Y, Z)\nax.plot_surface(X, Y, Z1)\nshow()","sub_path":"lesson 3.py","file_name":"lesson 3.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"379303599","text":"# -*- encoding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\nversion = '1.0.1'\n\nsetup(name='sumdir',\n version=version,\n description=\"Display sizes of the current subdirectories\",\n long_description=\"\"\"\\\nDisplay sizes of the current subdirectories\"\"\",\n # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Intended Audience :: Developers\",\n \"Environment :: Console\",\n \"Development Status :: 5 - Production/Stable\",\n \"Programming Language :: Python\",\n \"Topic :: Utilities\",\n \"License :: OSI Approved :: MIT License\",\n ],\n keywords='',\n author='Ginés Martínez Sánchez',\n author_email='ginsmar@gmail.com',\n license='MIT',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n # -*- Extra requirements: -*-\n ],\n entry_points=\"\"\"\n [console_scripts]\n sumdir = sumdir:main\n \"\"\",\n)\n","sub_path":"pypi_install_script/sumdir-1.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"226479544","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.tree import DecisionTreeClassifier\r\ndef open_files(): #Функция открывает файл tokens, groups, docs, записывает каждый размеченный текстб добавляет в общий список. На выходе размеченные тексты такие: [текст1][текст2] и тд., а каждый текст [элемент1][элемент2] и т.д.\r\n with open('Documents.txt', 'r', encoding='utf-8') as documents:\r\n docs = []\r\n for line in documents:\r\n docs.append(line.split('\\t')[:2])\r\n with open('Tokens.txt', 'r', encoding='utf-8') as tokens_file:\r\n tokens = []\r\n for line in tokens_file:\r\n line = line[:-1]\r\n tokens.append(line.split('\\t'))\r\n for t in tokens:\r\n if len(t)==1:\r\n del t\r\n del t[4]\r\n with open('Groups.txt', 'r', encoding='utf-8') as groups_file:\r\n groups = []\r\n for line in groups_file:\r\n line = line[:-2]\r\n groups.append(line.split('\\t'))\r\n for g in groups:\r\n if len(g)==1:\r\n del g\r\n del g[1]\r\n parsed_t = []\r\n for d in docs[1:]:\r\n filepath = d[1].replace('/', '\\\\')\r\n filepath = filepath.replace('txt', 'conll')\r\n try:\r\n with open('parsed_testset\\\\{0}'.format(filepath), 'r', encoding='utf-8') as parsed_texts:\r\n a = []\r\n a.append(int(d[0]))\r\n\r\n for line in parsed_texts:\r\n line = line[:-2]\r\n a.append(line.split('\\t'))\r\n parsed_t.append(a)\r\n except:\r\n pass\r\n parsed_t.insert(0, ['id', 'word', 'lemma', 'part', 'part', 'gram','to_head', 'role', ' ', ' '])\r\n #Текст распарсенный [[file1], [file2], [[el1], [el2]]]\r\n return parsed_t, tokens, groups\r\nparsed_t, tokens, groups = open_files()\r\n\r\ndef unite_info(parsed_t): #Функция добавляет к каждому элементу из parsed_t id документа в начало\r\n parsed_t[0].insert(0, 'doc_id')\r\n for p in parsed_t[1:]:\r\n for element in p[1:]:\r\n element.insert(0, p[0])\r\n return parsed_t\r\nparsed_t = unite_info(parsed_t)\r\n\r\ndef clean_info(parsed_t): #очищает лишний данные (последние две колонки, повтор части речи)\r\n del parsed_t[0][-1]\r\n del parsed_t[0][-1]\r\n del parsed_t[0][5]\r\n for p in parsed_t[1:]:\r\n del p[0]\r\n for element in p:\r\n try:\r\n del element[-1]\r\n del element[-1]\r\n del element[5]\r\n except:\r\n pass\r\n return parsed_t\r\nparsed_t = clean_info(parsed_t)\r\n#print(parsed_t[:5])\r\n\r\ndef split_on(parsed_t): #Делит parsed_t на предложения, получаем в итоге список файлов, в каждом файле список предложений, в каждом предложении список элементов.\r\n full_split = []\r\n for p in parsed_t[1:]:\r\n splitted = [[]]\r\n for item in p:\r\n if item == [' '] or len(item)==0:\r\n splitted.append([])\r\n else:\r\n splitted[-1].append(item)\r\n full_split.append(splitted)\r\n return full_split\r\nfull_split = split_on(parsed_t)\r\n\r\ndef group_NP(NP, sent):\r\n to_head_id = NP[6]\r\n head = sent[int(to_head_id)-1]\r\n new_NP = []\r\n if ((head[4] == 'N' and head[5].startswith('Np')) or head[4] == 'S') and (head[5]!= 'SENT' and head[4]!='PUNC'): #условие проверяет, явл. ли именем собственным\r\n #doc id, NP, veersh, len в символах, rolev, gramv, id\r\n new_NP.append(NP[0])\r\n new_NP.append(head[2]+' '+NP[2])\r\n if head[4]=='S':\r\n new_NP.append(NP[3])\r\n else:\r\n new_NP.append(head[3])\r\n new_NP.append(2)\r\n new_NP.append(head[-1])\r\n if head[4] == 'S':\r\n new_NP.append(NP[5])\r\n else:\r\n new_NP.append(head[5])\r\n else:\r\n new_NP.append(NP[0])\r\n new_NP.append(NP[2])\r\n new_NP.append(NP[3])\r\n new_NP.append(1)\r\n new_NP.append(NP[-1])\r\n new_NP.append(NP[5])\r\n new_NP.append(NP[1])\r\n return new_NP\r\ndef find_NP(sent): #ищет ИГ в предложениях.\r\n NPs = []\r\n for element in sent:\r\n if (element[4] == 'N' or element[4]=='P') and element[-1]!='ROOT':\r\n NPs.append(element)\r\n return NPs\r\ndef groupall(NP, sent): #добавлять зависимые и смотреть кол-во cлов в группе\r\n id = NP[-1]\r\n for element in sent:\r\n if int(element[-2])==int(id) and(element[-1]=='опред'):\r\n NP[3]+=1\r\n else:\r\n pass\r\n return NP\r\nfinal = []\r\nfor text in full_split:\r\n for sent in text:\r\n new_NPs = []\r\n NPs = find_NP(sent)\r\n for NP in NPs:\r\n new_NP = group_NP(NP, sent)\r\n new_NPs.append(new_NP)\r\n\r\n for NP in new_NPs:\r\n new_NP = groupall(NP, sent)\r\n final.append(new_NP)\r\nfind_NP(full_split)\r\ndef process_NP(final):\r\n for NP in final:\r\n del NP[-1]\r\n return final\r\nfinal = process_NP(final)\r\ndef base(final): #Если иг или вершина повторяетя - 1, если нет - 0\r\n have = []\r\n for element in final:\r\n new = []\r\n new.append(element[1])\r\n new.append(element[0])\r\n new2 = []\r\n new2.append(element[1])\r\n new2.append(element[0])\r\n if (new2 in have ) or (new in have):\r\n element.append(1)\r\n else:\r\n have.append(new)\r\n have.append(new2)\r\n element.append(0)\r\n return final\r\nfinal=base(final) #doc id, content. lemma head, len in words, role, gram, base\r\ndef part(final):\r\n for element in final:\r\n if element[-2][0]=='N':\r\n element.append(1)\r\n elif element[-2][0]=='P':\r\n element.append(2)\r\n return final\r\nfinal = part(final)#doc id, content, lemma head, len in words, role, gram, base, part\r\ndef pr_com(final):#proper - 1, common - 2\r\n for element in final:\r\n if element[-3][1]=='p':\r\n element.append(1)\r\n else:\r\n element.append(2)\r\n return final\r\nfinal = pr_com(final) #doc id, content, lemma, len(words), role, gram, base, part, proper or common\r\ndef groups_pro(groups):\r\n new_groups = []\r\n for g in groups:\r\n group = []\r\n id = g[0]\r\n cont = g[6]\r\n group.append(id)\r\n group.append(cont)\r\n new_groups.append(group)\r\n return new_groups\r\ngroups = groups_pro(groups)\r\ndef groups_check(final, groups): #1 - singlton, 0-not\r\n for f in final:\r\n id = str(f[0])\r\n cont = f[1]\r\n for g in groups[1:]:\r\n if id ==g[0] and (cont in g[1]):\r\n f.append(0)\r\n break\r\n else:\r\n pass\r\n if len(f)==9:\r\n f.append(1)\r\n return final\r\nfinal = groups_check(final, groups)\r\ndef dele(final):\r\n for f in final:\r\n del f[2]\r\n del f[-5]\r\n return final\r\nfinal = dele(final) # doc id, cont, len in words, role, base, part, proper or common, singleton or not\r\ndef del_role(final):\r\n for f in final:\r\n del f[3]\r\n return final\r\nfinal = del_role(final) #doc id, cont, len in words, base, part, proper or common, singleton or not\r\n\r\ndef group_list(lists):#группирует списки по документам, чтобы делить на обучающую и тестовую тексты, а не ИГ.\r\n finals = []\r\n d = []\r\n for e in lists:\r\n if e[0] in d:\r\n pass\r\n else:\r\n d.append(e[0])\r\n for id in d:\r\n to_final = []\r\n for el in lists:\r\n if el[0]==id:\r\n to_final.append(el)\r\n else:\r\n pass\r\n finals.append(to_final)\r\n return finals\r\nfinal = group_list(final)\r\nfinal_train, final_test = train_test_split(final, test_size = 0.3, random_state = 10)\r\ndef for_pand(final):\r\n Y = []\r\n Xs = []\r\n name = []\r\n for text in final:\r\n for element in text:\r\n Y.append(element[-1])\r\n name.append(element[1])\r\n X = element[2:-1]\r\n Xs.append(X)\r\n return Y, Xs, name\r\ny_train, X_train, name_train = for_pand(final_train)\r\ny_test, X_test, name_test = for_pand(final_test)\r\n\r\ndata = pd.DataFrame(X_train + X_test)\r\ndata.columns = ['len'] + ['base:0-n,1-y'] + ['(Noun-1/Pr-2)'] + ['Pr-1/com-2']\r\ndata.index = name_train+name_test\r\nprint(data[-5:])\r\nprint(data.shape)\r\n\r\nfrom sklearn import ensemble\r\nimport sklearn\r\nrf = ensemble.RandomForestClassifier(n_estimators=100, random_state=20) #Baseline признаки\r\nrf.fit(X_train, y_train)\r\n\r\nerr_train = np.mean(y_train != rf.predict(X_train))\r\nerr_test = np.mean(y_test != rf.predict(X_test))\r\nprint(err_train, err_test)\r\nreport = sklearn.metrics.classification_report(y_test, rf.predict(X_test), target_names=['NoSingl', 'Singleton'])\r\nprint(report)\r\nprint(sklearn.metrics.confusion_matrix(y_test, rf.predict(X_test)))\r\n\r\ndef singletones(X_test, name_test): #Вершины синглтонов в отдельный файл.\r\n m = rf.predict(X_test)\r\n Singletones = []\r\n with open('Singletones.txt', 'a', encoding='utf-8') as file:\r\n for i in range(len(m)-1):\r\n if m[i]==1:\r\n file.write(name_test[i])\r\n file.write('\\n')\r\n Singletones.append(name_test[i])\r\n return Singletones\r\nSingletones = singletones(X_test, name_test)\r\n","sub_path":"Singletones.py","file_name":"Singletones.py","file_ext":"py","file_size_in_byte":9899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"575613539","text":"#!/bin/env python\n# This script lets you ACK a Nagios alert \n# by replying to an email with the word \"ACK\". \n\n# Crudely read the email line by line from stdin and send an \n# acknowledgement command to Nagios if appropriate.\n# Requires a procmail recipe to feed it.\n\nimport os, re, sys, time\n\nack = None\ncmd_fifo = \"/var/lib/nagios3/rw/nagios.cmd\"\n\nfor line in sys.stdin:\n if line.startswith('Subject'):\n subject = line.strip()\n elif re.match('ack', line, re.IGNORECASE):\n ack = 'True'\n elif line.startswith('From:'):\n from_addr = line.strip()\n\nif ack is None:\n exit()\n\nmylist = subject.split(\" \")\nnow = int(time.time())\n\nif 'Host' in mylist: # Host down alerts.\n cmd = (\"[%s] ACKNOWLEDGE_HOST_PROBLEM;%s;1;1;1;email;%s;ack'd by email\" % (now, mylist[2], from_addr))\nelse:\t # Service Alerts.\n cmd = (\"[%s] ACKNOWLEDGE_SVC_PROBLEM;%s;%s;1;1;1;%s;ack'd by email\" % (now, mylist[2], mylist[3], from_addr))\n\nf = open(cmd_fifo, \"w\")\nf.write(cmd)\nf.close()\n","sub_path":"nagios/parsemail.py","file_name":"parsemail.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"588333929","text":"import os\nimport shutil\ndef rename(path):\n i=1\n for file in os.listdir(path):\n filedir=path+'\\\\'+ file\n for files in os.listdir(filedir):\n filesdir=filedir+'\\\\'+files\n print(filesdir)\n if os.path.isdir(filesdir):\n for video in os.listdir(filesdir):\n if video[-3:]=='blv':\n videodir = filesdir + '\\\\' + video\n os.rename(videodir,str(i)+'.blv')\n i+=1\n os.system('rd /s /q filedir')\nrename(r'C:\\Users\\lsjsg\\Desktop\\download\\test')","sub_path":"python/others/get_video_from_bilibili_file.py","file_name":"get_video_from_bilibili_file.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"649804042","text":"# July 2020\r\n#Take two lists, say for example these two:\r\n#and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.\r\n\r\na = [5, 6, 5, 20, 20, 20, 3,3]\r\nb = [20, 5, 3, 4, 5, 6]\r\nc=[]\r\nfor i,vi in enumerate(a):\r\n #print(i,vi)\r\n for j,vj in enumerate(b):\r\n #print(j,vj)\r\n if vi==vj:\r\n c.append(vi)\r\nprint(c)\r\ncclean=[]\r\nfor k in c:\r\n if k not in cclean:\r\n cclean.append(k)\r\nprint(cclean)\r\n","sub_path":"PythonExercise/Ex21E.py","file_name":"Ex21E.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"423472505","text":"\"\"\"\nThe core Dshell library\n\nThis library contains the base level plugins that all others will inherit.\n\nPacketPlugin contains attributes and functions for plugins that work with\nindividual packets.\n\nConnectionPlugin inherits from PacketPlugin and includes additional functions\nfor handling reassembled connections.\n\nIt also contains class definitions used by the plugins, including definitions\nfor Blob, Connection, and Packet.\n\n\"\"\"\n\n# standard Python imports\nimport datetime\nimport inspect\nimport ipaddress\nimport logging\nimport os\n#import pprint\nimport struct\nfrom collections import defaultdict\nfrom multiprocessing import Value\n\n# Dshell imports\nfrom dshell.output.output import Output\nfrom dshell.dshellgeoip import DshellGeoIP, DshellFailedGeoIP\n\n# third-party imports\nimport pcapy\nfrom pypacker.layer12 import can, ethernet, ieee80211, linuxcc, ppp, pppoe, radiotap\nfrom pypacker.layer3 import ip, ip6, icmp, icmp6\nfrom pypacker.layer4 import tcp, udp\n\nlogging.basicConfig(format=\"%(levelname)s (%(name)s) - %(message)s\")\nlogger = logging.getLogger(\"dshell.core\")\n\n__version__ = \"3.1.3\"\n\nclass SequenceNumberError(Exception):\n \"\"\"\n Raised when reassembling connections and data is missing or overlapping.\n See Blob.reassemble function\n \"\"\"\n pass\n\nclass DataError(Exception):\n \"\"\"\n Raised when any data being handled just isn't right.\n For example, invalid headers in httpplugin.py\n \"\"\"\n pass\n\n\n# Create GeoIP refrence object\ntry:\n geoip = DshellGeoIP(logger=logging.getLogger(\"dshellgeoip.py\"))\nexcept FileNotFoundError:\n logger.error(\"Could not find GeoIP data files! Country and ASN lookups will not be possible. Check README for instructions on where to find and install necessary data files.\")\n geoip = DshellFailedGeoIP()\n\n\ndef print_handler_exception(e, plugin, handler):\n \"\"\"\n A convenience function to display an error message when a handler raises\n an exception.\n\n If using --debug, it will print a full traceback.\n\n Args:\n e: the exception object\n plugin: the plugin object\n handler: name of the handler function\n \"\"\"\n etype = e.__class__.__name__\n if logger.isEnabledFor(logging.DEBUG):\n logger.error(\"The {!s} for the {!r} plugin raised an exception and failed! ({}: {!s})\".format(handler, plugin.name, etype, e))\n logger.exception(e)\n else:\n logger.error(\"The {!s} for the {!r} plugin raised an exception and failed! ({}: {!s}) Use --debug for more details.\".format(handler, plugin.name, etype, e))\n\n\nclass PacketPlugin(object):\n \"\"\"\n Base level class that plugins will inherit.\n\n This plugin handles individual packets. To handle reconstructed\n connections, use the ConnectionPlugin.\n\n Attributes:\n name: the name of the plugin\n description: short description of the plugin (used with decode -l)\n longdescription: verbose description of the plugin (used with -h)\n bpf: default BPF to apply to traffic entering plugin\n compiled_bpf: a compiled BPF for pcapy, usually created in decode.py\n vlan_bpf: boolean that tells whether BPF should be compiled with\n VLAN support\n author: preferably, the initials of the plugin's author\n seen_packet_count: number of packets this plugin has seen\n handled_packet_count: number of packets this plugin has passed\n through a handler function\n seen_conn_count: number of connections this plugin has seen\n handled_conn_count: number of connections this plugin has passed\n through a handler function\n out: output module instance\n raw_decoder: pypacker module to use for unpacking packet\n link_layer_type: numeric label for link layer\n striplayers: number of layers to automatically strip before handling\n (such as PPPoE, IP-over-IP, etc.)\n defrag_ip: rebuild fragmented IP packets (default: True)\n \"\"\"\n\n IP_PROTOCOL_MAP = dict((v, k[9:]) for k, v in ip.__dict__.items() if type(v) == int and k.startswith('IP_PROTO_') and k != 'IP_PROTO_HOPOPTS')\n\n def __init__(self, **kwargs):\n self.name = kwargs.get('name', __name__)\n self.description = kwargs.get('description', '')\n self.longdescription = kwargs.get('longdescription', self.description)\n self.bpf = kwargs.get('bpf', '')\n self.compiled_bpf = kwargs.get('compiled_bpf', None)\n self.vlan_bpf = kwargs.get(\"vlan_bpf\", True)\n self.author = kwargs.get('author', '')\n # define overall counts as multiprocessing Values for --parallel\n self.seen_packet_count = Value('i', 0)\n self.handled_packet_count = Value('i', 0)\n self.seen_conn_count = Value('i', 0)\n self.handled_conn_count = Value('i', 0)\n # dict of options specific to this plugin in format\n # 'optname':{configdict} translates to --pluginname_optname\n self.optiondict = kwargs.get('optiondict', {})\n\n # queues used by decode.py\n # if a handler decides a packet is worth keeping, it is placed in a\n # queue and later grabbed by decode.py to pass to subplugins\n self.raw_packet_queue = []\n self.packet_queue = []\n\n # self.out holds the output plugin instance\n # can be overwritten in decode.py by user selection\n self.out = kwargs.get('output', Output(label=__name__))\n\n # capture options\n # these can be updated with set_link_layer_type function\n self.raw_decoder = ethernet.Ethernet # assumed link-layer type\n self.link_layer_type = 1 # assume Ethernet\n # strip extra layers before IP/IPv6? (such as PPPoE, IP-over-IP, etc..)\n self.striplayers = 0\n # rebuild fragmented IP packets\n self.defrag_ip = True\n\n # holder for the pcap file being processing\n self.current_pcap_file = None\n\n # get the list of functions for this plugin\n # this is used in decode.py\n self.members = tuple([x[0] for x in inspect.getmembers(self, inspect.ismethod)])\n\n # a holder for IP packet fragments when attempting to reassemble them\n self.packet_fragments = defaultdict(dict)\n\n def write(self, *args, **kwargs):\n \"\"\"\n Sends information to the output formatter, after adding some\n additional fields.\n \"\"\"\n if 'plugin' not in kwargs:\n kwargs['plugin'] = self.name\n if 'pcapfile' not in kwargs:\n kwargs['pcapfile'] = self.current_pcap_file\n self.out.write(*args, **kwargs)\n\n def log(self, msg, level=logging.INFO):\n '''\n logs msg argument at specified level\n (default of INFO is for -v/--verbose output)\n\n Arguments:\n msg: text string to log\n level: logging level (default: logging.INFO)\n '''\n self.out.log(msg, level=level)\n\n def debug(self, msg):\n '''logs msg argument at debug level'''\n self.log(msg, level=logging.DEBUG)\n\n def warn(self, msg):\n '''logs msg argument at warning level'''\n self.log(msg, level=logging.WARN)\n\n def error(self, msg):\n '''logs msg argument at error level'''\n self.log(msg, level=logging.ERROR)\n\n def __str__(self):\n return \"<{}: {}>\".format(\"Plugin\", self.name)\n\n def __repr__(self):\n return '<{}: {}/{}/{}>'.format(\"Plugin\", self.name, self.bpf,\n ','.join([('%s=%s' % (x, str(self.__dict__.get(x)))) for x in self.optiondict]))\n\n def set_link_layer_type(self, datalink):\n \"\"\"\n Attempts to set the raw_decoder attribute based on the capture file's\n datalink type, which is fetched by pcapy when used in decode.py. It\n takes one argument: the numeric value of the link layer.\n\n http://www.tcpdump.org/linktypes.html\n \"\"\"\n # NOTE: Not all of these have been tested\n # TODO add some more of these\n self.link_layer_type = datalink\n if datalink == 1:\n self.raw_decoder = ethernet.Ethernet\n elif datalink == 9:\n self.raw_decoder = ppp.PPP\n elif datalink == 51:\n self.raw_decoder = pppoe.PPPoE\n elif datalink == 105:\n self.raw_decoder = ieee80211.IEEE80211\n elif datalink == 113:\n self.raw_decoder = linuxcc.LinuxCC\n elif datalink == 127:\n self.raw_decoder = radiotap.Radiotap\n elif datalink == 204:\n self.raw_decoder = ppp.PPP\n elif datalink == 227:\n self.raw_decoder = can.CAN\n elif datalink == 228:\n self.raw_decoder = ip.IP\n elif datalink == 229:\n self.raw_decoder = ip6.IP6\n else:\n # by default, assume Ethernet and hope for the best\n self.link_layer_type = 1\n self.raw_decoder = ethernet.Ethernet\n self.debug(\"Datalink input: {!s}. Setting raw_decoder to {!r}, link_layer_type to {!s}\".format(datalink, self.raw_decoder, self.link_layer_type))\n\n def recompile_bpf(self):\n \"Compile the BPF stored in the .bpf attribute\"\n # This function is normally only called by the decode.py script,\n # but can also be called by plugins that need to dynamically update\n # their filter.\n if not self.bpf:\n logger.debug(\"Cannot compile BPF: .bpf attribute not set for plugin {!r}.\".format(self.name))\n self.compiled_bpf = None\n return\n\n # Add VLAN wrapper, if necessary\n if self.vlan_bpf:\n bpf = \"({0}) or (vlan and {0})\".format(self.bpf)\n else:\n bpf = self.bpf\n self.debug(\"Compiling BPF as {!r}\".format(bpf))\n\n # Compile BPF and handle any expected errors\n try:\n self.compiled_bpf = pcapy.compile(\n self.link_layer_type, 65536, bpf, True, 0xffffffff\n )\n except pcapy.PcapError as e:\n if str(e).startswith(\"no VLAN support for data link type\"):\n logger.error(\"Cannot use VLAN filters for {!r} plugin. Recommend running with --no-vlan argument.\".format(self.name))\n elif str(e) == \"syntax error\":\n logger.error(\"Fatal error when compiling BPF: {!r}\".format(bpf))\n sys.exit(1)\n else:\n raise e\n\n def ipdefrag(self, pkt):\n \"IP fragment reassembly\"\n if isinstance(pkt, ip.IP): # IPv4\n f = self.packet_fragments[(pkt.src, pkt.dst, pkt.id)]\n f[pkt.offset] = pkt\n\n if not pkt.flags & 0x1:\n data = b''\n for key in sorted(f.keys()):\n data += f[key].body_bytes\n del self.packet_fragments[(pkt.src, pkt.dst, pkt.id)]\n newpkt = ip.IP(pkt.header_bytes + data)\n newpkt.bin(update_auto_fields=True) # refresh checksum\n return newpkt\n\n elif isinstance(pkt, ip6.IP6): # IPv6\n # TODO handle IPv6 offsets https://en.wikipedia.org/wiki/IPv6_packet#Fragment\n return pkt\n\n def handle_plugin_options(self):\n \"\"\"\n A placeholder.\n\n This function is called immediately after plugin args are processed\n and set in decode.py. A plugin can overwrite this function to perform\n actions based on the arg values as soon as they are set, before\n decoder.py does any further processing (e.g. updating a BPF based on\n provided arguments before handling --ebpf and --bpf flags).\n \"\"\"\n pass\n\n def _premodule(self):\n \"\"\"\n _premodule is called before capture starts or files are read. It will\n attempt to call the child plugin's premodule function.\n \"\"\"\n self.premodule()\n self.out.setup()\n# self.debug('{}'.format(pprint.pformat(self.__dict__)))\n self.debug(str(self.__dict__))\n\n def premodule(self):\n \"\"\"\n A placeholder.\n\n A plugin can overwrite this function to perform an action before\n capture starts or files are read.\n \"\"\"\n pass\n\n def _postmodule(self):\n \"\"\"\n _postmodule is called when capture ends. It will attempt to call the\n child plugin's postmodule function. It will also print stats if in\n debug mode.\n \"\"\"\n self.postmodule()\n self.out.close()\n self.log(\"{} seen packets, {} handled packets, {} seen connections, {} handled connections\".format(self.seen_packet_count.value, self.handled_packet_count.value, self.seen_conn_count.value, self.handled_conn_count.value))\n\n def postmodule(self):\n \"\"\"\n A placeholder.\n\n A plugin can overwrite this function to perform an action after\n capture ends or all files are processed.\n \"\"\"\n pass\n\n def _prefile(self, infile=None):\n \"\"\"\n _prefile is called just before an individual file is processed.\n Stores the current pcap file string and calls the child plugin's\n prefile function.\n \"\"\"\n self.current_pcap_file = infile\n self.prefile(infile)\n self.log('working on file \"{}\"'.format(infile))\n\n def prefile(self, infile=None):\n \"\"\"\n A placeholder.\n\n A plugin will be able to overwrite this function to perform an action\n before an individual file is processed.\n\n Arguments:\n infile: filepath or interface that will be processed\n \"\"\"\n pass\n\n def _postfile(self):\n \"\"\"\n _postfile is called just after an individual file is processed.\n It may expand some day, but for now it just calls a child's postfile\n function.\n \"\"\"\n self.postfile()\n\n def postfile(self):\n \"\"\"\n A placeholder.\n\n A plugin will be able to overwrite this function to perform an action\n after an individual file is processed.\n \"\"\"\n pass\n\n def _raw_handler(self, pktlen, pkt, ts):\n \"\"\"\n Accepts raw packet data (pktlen, pkt, ts), and handles decapsulation\n and layer stripping.\n\n Then, it passes the massaged data to the child's raw_handler function,\n if additional custom handling is necessary. The raw_handler function\n should return (pktlen, pkt, ts) if it wishes to continue with the call\n chain. Otherwise, return None.\n \"\"\"\n# with self.seen_packet_count.get_lock():\n# self.seen_packet_count.value += 1\n#\n# # call raw_handler and check its output\n# # decode.py will continue down the chain if it returns proper output or\n# # display a warning if it doesn't return the correct things\n# try:\n# raw_handler_out = self.raw_handler(pktlen, pkt, ts)\n# except Exception as e:\n# print_handler_exception(e, self, 'raw_handler')\n# return\n#\n# failed_msg = \"The output of {} raw_handler must be (pktlen, pkt, ts) or a list of such lists! Further packet refinement and plugin chaining will not be possible\".format(self.name)\n# if raw_handler_out and isinstance(raw_handler_out, (list, tuple)):\n# self.warn(failed_msg)\n# return\n\n with self.seen_packet_count.get_lock():\n self.seen_packet_count.value += 1\n # decode with the raw decoder (probably ethernet.Ethernet)\n pkt = self.raw_decoder(pkt)\n\n # strip any intermediate layers (e.g. PPPoE, etc.)\n # NOTE: make sure only the first plugin in a chain has striplayers set\n for _ in range(self.striplayers):\n try:\n pkt = pkt.upper_layer\n except AttributeError:\n # No more layers to strip\n break\n\n # call raw_handler and check its output\n # decode.py will continue down the chain if it returns proper output or\n # display a warning if it doesn't return the correct things\n try:\n raw_handler_out = self.raw_handler(pktlen, pkt, ts)\n except Exception as e:\n print_handler_exception(e, self, 'raw_handler')\n return\n failed_msg = \"The output of {} raw_handler must be (pktlen, pkt, ts) or a list of such lists! Further packet refinement and plugin chaining will not be possible\".format(self.name)\n if isinstance(raw_handler_out, (list, tuple)):\n if len(raw_handler_out) == 3 and (\n isinstance(raw_handler_out[0], type(pktlen)) and\n isinstance(raw_handler_out[1], type(pkt)) and\n isinstance(raw_handler_out[2], type(ts))):\n # If it returns one properly formed response, queue and continue\n self.raw_packet_queue.append(raw_handler_out)\n else:\n # If it returns several responses, check them individually\n for rhout in raw_handler_out:\n if isinstance(rhout, (list, tuple)) and \\\n len(rhout) == 3 and \\\n isinstance(rhout[0], type(pktlen)) and \\\n isinstance(rhout[1], type(pkt)) and \\\n isinstance(rhout[2], type(ts)):\n self.raw_packet_queue.append(rhout)\n elif rhout:\n self.warn(failed_msg)\n elif raw_handler_out:\n self.warn(failed_msg)\n\n\n def raw_handler(self, pktlen, pkt, ts):\n \"\"\"\n A placeholder.\n\n Plugins will be able to overwrite this to perform custom activites on\n raw packet data, such as decapsulation or decryption, before it\n becomes further refined down the chain. It should return the same\n arguments: pktlen, pkt, ts\n\n Generally speaking, however, this should never be overwritten unless\n there is a very, very good reason for it.\n\n Arguments:\n pktlen: length of packet\n pkt: raw bytes of the packet\n ts: timestamp of packet\n \"\"\"\n return pktlen, pkt, ts\n\n def _packet_handler(self, pktlen, pkt, ts):\n \"\"\"\n Accepts the output of raw_handler, pulls out addresses, and converts\n it all into a dshell.Packet object before calling the child's\n packet_handler function.\n \"\"\"\n # Attempt to perform defragmentation\n if isinstance(pkt.upper_layer, (ip.IP, ip6.IP6)):\n ipp = pkt.upper_layer\n if self.defrag_ip:\n ipp = self.ipdefrag(ipp)\n if not ipp:\n # we do not yet have all of the packet fragments, so move\n # on to next packet for now\n return\n else:\n pkt.upper_layer = ipp\n\n # Initialize a Packet object\n # This will be populated with values as we continue through\n # the function and eventually be passed to packet_handler\n packet = Packet(self, pktlen, pkt, ts)\n\n # call packet_handler and return its output\n # decode.py will continue down the chain if it returns anything\n try:\n packet_handler_out = self.packet_handler(packet)\n except Exception as e:\n print_handler_exception(e, self, 'packet_handler')\n return\n failed_msg = \"The output from {} packet_handler must be of type dshell.Packet or a list of such objects! Handling connections or chaining from this plugin may not be possible.\".format(self.name)\n if isinstance(packet_handler_out, (list, tuple)):\n for phout in packet_handler_out:\n if isinstance(phout, Packet):\n self.packet_queue.append(phout)\n with self.handled_packet_count.get_lock():\n self.handled_packet_count.value += 1\n elif phout:\n self.warn(failed_msg)\n elif isinstance(packet_handler_out, Packet):\n self.packet_queue.append(packet_handler_out)\n with self.handled_packet_count.get_lock():\n self.handled_packet_count.value += 1\n elif packet_handler_out:\n self.warn(failed_msg)\n\n\n def packet_handler(self, pkt):\n \"\"\"\n A placeholder.\n\n Plugins will be able to overwrite this to perform custom activites on\n Packet data.\n\n It should return a Packet object for functions further down the chain\n (i.e. connection_handler and/or blob_handler)\n\n Arguments:\n pkt: a Packet object\n \"\"\"\n return pkt\n\n\n\nclass ConnectionPlugin(PacketPlugin):\n \"\"\"\n Base level class that plugins will inherit.\n\n This plugin reassembles connections from packets.\n \"\"\"\n\n def __init__(self, **kwargs):\n PacketPlugin.__init__(self, **kwargs)\n\n # similar to packet_queue and raw_packet_queue in superclass\n self.connection_queue = []\n\n # dictionary to store packets for connections according to addr()\n self.connection_tracker = {}\n # maximum number of blobs a connection will store before calling\n # connection_handler\n # it defaults to infinite, but this should be lowered for huge datasets\n self.maxblobs = float(\"inf\") # infinite\n # how long do we wait before deciding a connection is \"finished\"\n # time is checked by iterating over cached connections and checking if\n # the timestamp of the connection's last packet is older than the\n # timestamp of the current packet, minus this value\n self.connection_timeout = datetime.timedelta(hours=1)\n\n def _connection_handler(self, pkt):\n \"\"\"\n Accepts a single Packet object and tracks the connection it belongs to.\n\n If it is the first packet in a connection, it creates a new Connection\n object and passes it to connection_init_handler. Otherwise, it will\n find the existing Connection in self.connection_tracker.\n\n The Connection will then be passed to connection_handler.\n\n If a connection changes direction with this packet, blob_handler will\n be called.\n\n Finally, if this packet is a FIN or RST, it will determine if the\n connection should close.\n \"\"\"\n # Sort the addr value for consistent dictionary key purposes\n addr = tuple(sorted(pkt.addr))\n\n # If this is a new connection, initialize it and call the init handler\n if addr not in self.connection_tracker:\n conn = Connection(self, pkt)\n self.connection_tracker[addr] = conn\n try:\n self.connection_init_handler(conn)\n except Exception as e:\n print_handler_exception(e, self, 'connection_init_handler')\n return\n with self.seen_conn_count.get_lock():\n self.seen_conn_count.value += 1\n else:\n conn = self.connection_tracker[addr]\n\n if conn.stop:\n # This connection was flagged to not be tracked\n return\n\n # If connection data is about to change, we set it to a \"dirty\" state\n # for future calls to connection_handler\n if pkt.data:\n conn.handled = False\n\n # Check and update the connection's current state\n if pkt.tcp_flags in (tcp.TH_SYN, tcp.TH_ACK, tcp.TH_SYN|tcp.TH_ACK, tcp.TH_SYN|tcp.TH_ACK|tcp.TH_ECE):\n # if new connection and a handshake is taking place, set to \"init\"\n if not conn.client_state:\n conn.client_state = \"init\"\n if not conn.server_state:\n conn.server_state = \"init\"\n else:\n # otherwise, if the connection isn't closed, set to \"established\"\n # TODO do we care about \"listen\", \"syn-sent\", and other in-between states?\n if conn.client_state not in ('finishing', 'closed'):\n conn.client_state = \"established\"\n if conn.server_state not in ('finishing', 'closed'):\n conn.server_state = \"established\"\n\n # Add the packet to the connection\n # If the direction changed, a Blob will be returned for handling\n # Note: The Blob will not be reassembled ahead of time. reassemble()\n # must be run inside the blob_handler to catch any unwanted exceptions.\n previous_blob = conn.add_packet(pkt)\n if previous_blob:\n try:\n blob_handler_out = self._blob_handler(conn, previous_blob)\n except Exception as e:\n print_handler_exception(e, self, 'blob_handler')\n return\n if (blob_handler_out\n and not isinstance(blob_handler_out[0], Connection)\n and not isinstance(blob_handler_out[1], Blob)):\n self.warn(\"The output from {} blob_handler must be of type (dshell.Connection, dshell.Blob)! Chaining plugins from here may not be possible.\".format(self.name))\n blob_handler_out = None\n # If the blob_handler decides this Blob isn't interesting, it sets\n # the hidden flag, which excludes it and its packets from further\n # processing along the plugin chain\n if not blob_handler_out:\n conn.blobs[-2].hidden = True\n\n # Check if a side of the connection is attempting to close the\n # connection using a FIN or RST packet. Once both sides make a\n # closing gesture, the connection is considered closed and handled\n if pkt.tcp_flags and pkt.tcp_flags & (tcp.TH_RST | tcp.TH_FIN):\n if pkt.sip == conn.clientip:\n conn.client_state = \"closed\"\n else:\n conn.server_state = \"closed\"\n\n if conn.connection_closed:\n # Both sides have closed the connection\n self._close_connection(conn, full=True)\n\n elif len(conn.blobs) > self.maxblobs:\n # Max blobs hit, so we will run connection_handler and decode.py\n # will clear the connection's blob cache\n self._close_connection(conn)\n\n # The current connection is done processing. Now, look over existing\n # connections and look for any that have timed out.\n # This is based on comparing the time of the current packet, minus\n # self.connection_timeout, to each connection's current endtime value.\n for addr, conn in self.connection_tracker.items():\n if conn.handled:\n continue\n if conn.endtime < (pkt.dt - self.connection_timeout):\n self._close_connection(conn)\n\n\n def _close_connection(self, conn, full=False):\n \"\"\"\n Runs through some standard actions to close a connection\n \"\"\"\n try:\n connection_handler_out = self.connection_handler(conn)\n except Exception as e:\n print_handler_exception(e, self, 'connection_handler')\n return None\n conn.handled = True\n if connection_handler_out and not isinstance(connection_handler_out, Connection):\n self.warn(\"The output from {} connection_handler must be of type dshell.Connection! Chaining plugins from here may not be possible.\".format(self.name))\n connection_handler_out = None\n if connection_handler_out:\n self.connection_queue.append(connection_handler_out)\n with self.handled_conn_count.get_lock():\n self.handled_conn_count.value += 1\n if full:\n try:\n self.connection_close_handler(conn)\n except Exception as e:\n print_handler_exception(e, self, 'connection_close_handler')\n return connection_handler_out\n\n\n def _cleanup_connections(self):\n \"\"\"\n decode.py will often reach the end of packet capture before all of the\n connections are closed properly. This function is called at the end\n of things to process those dangling connections.\n\n NOTE: Because the connections did not close cleanly,\n connection_close_handler will not be called.\n \"\"\"\n for addr, conn in self.connection_tracker.items():\n if not conn.stop and not conn.handled:\n # try to process the final blob in the connection\n try:\n blob_handler_out = self._blob_handler(conn, conn.blobs[-1])\n except Exception as e:\n print_handler_exception(e, self, 'blob_handler')\n blob_handler_out = None\n if (blob_handler_out\n and not isinstance(blob_handler_out[0], Connection)\n and not isinstance(blob_handler_out[1], Blob)):\n self.warn(\"The output from {} blob_handler must be of type (dshell.Connection, dshell.Blob)! Chaining plugins from here may not be possible.\".format(self.name))\n blob_handler_out = None\n if not blob_handler_out:\n conn.blobs[-1].hidden = True\n\n # then, handle the connection itself\n connection_handler_out = self._close_connection(conn)\n yield connection_handler_out\n\n def _purge_connections(self):\n \"\"\"\n When finished with handling a pcap file, calling this will clear all\n caches in preparation for next file.\n \"\"\"\n self.connection_queue = []\n self.connection_tracker = {}\n\n def _blob_handler(self, conn, blob):\n \"\"\"\n Accepts a Connection and a Blob.\n\n It doesn't really do anything except call the blob_handler and is only\n here for consistency and possible future features.\n \"\"\"\n return self.blob_handler(conn, blob)\n\n def blob_handler(self, conn, blob):\n \"\"\"\n A placeholder.\n\n Plugins will be able to overwrite this to perform custom activites on\n Blob data.\n\n It should return a Connection object and a Blob object for functions\n further down the chain.\n\n Args:\n conn: Connection object\n blob: Blob object\n \"\"\"\n return conn, blob\n\n def connection_init_handler(self, conn):\n \"\"\"\n A placeholder.\n\n Plugins will be able to overwrite this to perform custom activites on\n a connection it is first seen.\n\n Args:\n conn: Connection object\n \"\"\"\n return\n\n def connection_handler(self, conn):\n \"\"\"\n A placeholder.\n\n Plugins will be able to overwrite this to perform custom activites on\n Connection data.\n\n It should return a Connection object for functions further down the chain\n\n Args:\n conn: Connection object\n \"\"\"\n return conn\n\n def connection_close_handler(self, conn):\n \"\"\"\n A placeholder.\n\n Plugins will be able to overwrite this to perform custom activites on\n a TCP connection when it is cleanly closed with RST or FIN.\n\n Args:\n conn: Connection object\n \"\"\"\n return\n\nclass Packet(object):\n \"\"\"\n Class for holding data of individual packets\n\n def __init__(self, plugin, pktlen, pkt, ts):\n\n Args:\n plugin: an instance of the plugin creating this packet\n pktlen: length of packet\n pkt: pypacker object for the packet\n ts: timestamp of packet\n\n Attributes:\n plugin: name of plugin creating Packet\n ts: timestamp of packet\n dt: datetime of packet\n pkt: pypacker object for the packet\n rawpkt: raw bytestring of the packet\n pktlen: length of packet\n byte_count: length of packet body\n sip: source IP\n dip: destination IP\n sip_bytes: source IP as bytes\n dip_bytes: destination IP as bytes\n sport: source port\n dport: destination port\n smac: source MAC\n dmac: destination MAC\n sipcc: source IP country code\n dipcc: dest IP country code\n siplat: source IP latitude\n diplat: dest IP latitude\n siplon: source IP longitude\n diplon: dest IP longitude\n sipasn: source IP ASN\n dipasn: dest IP ASN\n protocol: text version of protocol in layer-3 header\n protocol_num: numeric version of protocol in layer-3 header\n data: data of the packet after TCP layer, or highest layer\n sequence_number: TCP sequence number, or None\n ack_number: TCP ACK number, or None\n tcp_flags: TCP header flags, or None\n \"\"\"\n\n def __init__(self, plugin, pktlen, pkt, ts):\n self.plugin = plugin.name\n self.ts = ts\n self.dt = datetime.datetime.fromtimestamp(ts)\n self.pkt = pkt\n self.rawpkt = pkt.bin()\n self.pktlen = pktlen\n self.byte_count = None\n self.sip = None\n self.dip = None\n self.sport = None\n self.dport = None\n self.smac = None\n self.dmac = None\n self.sipcc = None\n self.dipcc = None\n self.siplat = None\n self.diplat = None\n self.siplon = None\n self.diplon = None\n self.sipasn = None\n self.dipasn = None\n self.protocol = None\n self.protocol_num = None\n self.data = b''\n self.sequence_number = None\n self.ack_number = None\n self.tcp_flags = None\n\n # these are the layers Dshell will help parse\n # try to find them in the packet and eventually pull out useful data\n ethernet_p = None\n ieee80211_p = None\n ip_p = None\n tcp_p = None\n udp_p = None\n current_layer = pkt\n while current_layer:\n if isinstance(current_layer, ethernet.Ethernet) and not ethernet_p:\n ethernet_p = current_layer\n elif isinstance(current_layer, ieee80211.IEEE80211) and not ieee80211_p:\n ieee80211_p = current_layer\n elif isinstance(current_layer, (ip.IP, ip6.IP6)) and not ip_p:\n ip_p = current_layer\n elif isinstance(current_layer, tcp.TCP) and not tcp_p:\n tcp_p = current_layer\n elif isinstance(current_layer, udp.UDP) and not udp_p:\n udp_p = current_layer\n try:\n current_layer = current_layer.upper_layer\n except AttributeError:\n break\n\n # attempt to grab MAC addresses\n if ethernet_p:\n # from Ethernet\n self.smac = ethernet_p.src_s\n self.dmac = ethernet_p.dst_s\n elif ieee80211_p:\n # from 802.11\n try:\n if ieee80211_p.subtype == ieee80211.M_BEACON:\n ieee80211_p2 = ieee80211_p.beacon\n elif ieee80211_p.subtype == ieee80211.M_DISASSOC:\n ieee80211_p2 = ieee80211_p.disassoc\n elif ieee80211_p.subtype == ieee80211.M_AUTH:\n ieee80211_p2 = ieee80211_p.auth\n elif ieee80211_p.subtype == ieee80211.M_DEAUTH:\n ieee80211_p2 = ieee80211_p.deauth\n elif ieee80211_p.subtype == ieee80211.M_ACTION:\n ieee80211_p2 = ieee80211_p.action\n else:\n # can't figure out how pypacker stores the other subtypes\n raise AttributeError\n self.smac = ieee80211_p2.src_s\n self.dmac = ieee80211_p2.dst_s\n except AttributeError as e:\n pass\n\n # process IP addresses and associated metadata (if applicable)\n if ip_p:\n # get IP addresses\n sip = ipaddress.ip_address(ip_p.src)\n dip = ipaddress.ip_address(ip_p.dst)\n self.sip = sip.compressed\n self.dip = dip.compressed\n self.sip_bytes = sip.packed\n self.dip_bytes = dip.packed\n\n # get protocols, country codes, and ASNs\n self.protocol_num = ip_p.p if isinstance(ip_p, ip.IP) else ip_p.nxt\n self.protocol = PacketPlugin.IP_PROTOCOL_MAP.get(self.protocol_num, str(self.protocol_num))\n self.sipcc, self.siplat, self.siplon = geoip.geoip_location_lookup(self.sip)\n self.sipasn = geoip.geoip_asn_lookup(self.sip)\n self.dipcc, self.diplat, self.diplon = geoip.geoip_location_lookup(self.dip)\n self.dipasn = geoip.geoip_asn_lookup(self.dip)\n\n if tcp_p:\n self.sport = tcp_p.sport\n self.dport = tcp_p.dport\n self.sequence_number = tcp_p.seq\n self.ack_number = tcp_p.ack\n self.tcp_flags = tcp_p.flags\n self.data = tcp_p.body_bytes\n\n elif udp_p:\n self.sport = udp_p.sport\n self.dport = udp_p.dport\n self.data = udp_p.body_bytes\n\n else:\n self.data = pkt.highest_layer.body_bytes\n\n self.byte_count = len(self.data)\n\n\n\n @property\n def addr(self):\n \"\"\"\n A standard representation of the address:\n ((self.sip, self.sport), (self.dip, self.dport))\n or\n ((self.smac, self.sport), (self.dmac, self.dport))\n \"\"\"\n # try using IP addresses first\n if self.sip or self.dip:\n return ((self.sip, self.sport), (self.dip, self.dport))\n # then try MAC addresses\n elif self.smac or self.dmac:\n return ((self.smac, self.sport), (self.dmac, self.dport))\n # if all else fails, return Nones\n else:\n return ((None, None), (None, None))\n\n @property\n def packet_tuple(self):\n \"\"\"\n A standard representation of the raw packet tuple:\n (self.pktlen, self.rawpkt, self.ts)\n \"\"\"\n return (self.pktlen, self.rawpkt, self.ts)\n\n def __repr__(self):\n return \"%s %16s :%-5s -> %5s :%-5s (%s -> %s)\" % (self.dt, self.sip, self.sport, self.dip, self.dport, self.sipcc, self.dipcc)\n\n def info(self):\n \"\"\"\n Provides a dictionary with information about a packet. Useful for\n calls to a plugin's write() function, e.g. self.write(\\\\*\\\\*pkt.info())\n \"\"\"\n d = dict(self.__dict__)\n del d['pkt']\n del d['rawpkt']\n del d['data']\n return d\n\n\nclass Connection(object):\n \"\"\"\n Class for holding data about connections\n\n def __init__(self, plugin, first_packet)\n\n Args:\n plugin: an instance of the plugin creating this connection\n first_packet: the first Packet object to initialize connection\n\n Attributes:\n plugin: name of the plugin that created object\n addr: .addr attribute of first packet\n sip: source IP\n smac: source MAC address\n sport: source port\n sipcc: country code of source IP\n siplat: latitude of source IP\n siplon: longitude of source IP\n sipasn: ASN of source IP\n clientip: same as sip\n clientmac: same as smac\n clientport: same as sport\n clientcc: same as sipcc\n clientlat: same as siplat\n clientlon: same as siplon\n clientasn: same as sipasn\n dip: dest IP\n dmac: dest MAC address\n dport: dest port\n dipcc: country code of dest IP\n diplat: latitude of dest IP\n diplon: longitude of dest IP\n dipasn: ASN of dest IP\n serverip: same as dip\n servermac: same as dmac\n serverport: same as dport\n servercc: same as dipcc\n serverlat: same as diplat\n serverlon: same as diplon\n serverasn: same as dipasn\n protocol: text version of protocol in layer-3 header\n clientpackets: counts of packets from client side\n clientbytes: total bytes transferred from client side\n serverpackets: counts of packets from server side\n serverbytes: total bytes transferred from server side\n ts: timestamp of first packet\n dt: datetime of first packet\n starttime: datetime of first packet\n endtime: datetime of last packet\n client_state: the TCP state on the client side (\"init\",\n \"established\", \"closed\", etc.)\n server_state: the TCP state on server side\n blobs: list of reassembled half-stream Blobs\n stop: if True, stop following connection\n handled: used to indicate if a connection was already passed through\n a plugin's connection_handler function. Resets when new\n data for a connection comes in.\n\n \"\"\"\n\n def __init__(self, plugin, first_packet):\n \"\"\"\n Initializes Connection object\n\n Args:\n plugin: an instance of the plugin creating this connection\n first_packet: the first Packet object to initialize connection\n \"\"\"\n self.plugin = plugin.name\n self.addr = first_packet.addr\n self.sip = first_packet.sip\n self.smac = first_packet.smac\n self.sport = first_packet.sport\n self.sipcc = first_packet.sipcc\n self.siplat = first_packet.siplat\n self.siplon = first_packet.siplon\n self.sipasn = first_packet.sipasn\n self.clientip = first_packet.sip\n self.clientmac = first_packet.smac\n self.clientport = first_packet.sport\n self.clientcc = first_packet.sipcc\n self.clientlat = first_packet.siplat\n self.clientlon = first_packet.siplon\n self.clientasn = first_packet.sipasn\n self.dip = first_packet.dip\n self.dmac = first_packet.dmac\n self.dport = first_packet.dport\n self.dipcc = first_packet.dipcc\n self.diplat = first_packet.diplat\n self.diplon = first_packet.diplon\n self.dipasn = first_packet.dipasn\n self.serverip = first_packet.dip\n self.servermac = first_packet.dmac\n self.serverport = first_packet.dport\n self.servercc = first_packet.dipcc\n self.serverlat = first_packet.diplat\n self.serverlon = first_packet.diplon\n self.serverasn = first_packet.dipasn\n self.protocol = first_packet.protocol\n self.clientpackets = 0\n self.clientbytes = 0\n self.serverpackets = 0\n self.serverbytes = 0\n self.ts = first_packet.ts\n self.dt = first_packet.dt\n self.starttime = first_packet.dt\n self.endtime = first_packet.dt\n self.client_state = None\n self.server_state = None\n self.blobs = []\n self.stop = False\n self.handled = False\n # used to determine if direction changes\n self._current_addr_pair = None\n\n @property\n def duration(self):\n \"total seconds from starttime to endtime\"\n tdelta = self.endtime - self.starttime\n return tdelta.total_seconds()\n\n @property\n def connection_closed(self):\n return self.client_state == \"closed\" and self.server_state == \"closed\"\n\n def add_packet(self, packet):\n \"\"\"\n Accepts a Packet object and attempts to push it into the current Blob.\n If the direction changes, it creates a new Blob and returns the old one\n to the caller.\n\n Args:\n packet: a Packet object to add to the connection\n\n Returns:\n Previous Blob if direction has changed\n \"\"\"\n if packet.sip == self.clientip and (not packet.sport or packet.sport == self.clientport):\n # packet moving from client to server\n direction = 'cs'\n else:\n # packet moving from server to client\n direction = 'sc'\n\n if (packet.addr != self._current_addr_pair and packet.data) or len(self.blobs) == 0:\n try:\n old_blob = self.blobs[-1]\n except IndexError:\n old_blob = None\n self.blobs.append(Blob(packet, direction))\n self._current_addr_pair = packet.addr\n else:\n old_blob = None\n\n blob = self.blobs[-1]\n blob.add_packet(packet)\n\n # Only count packets if they have data (i.e. ignore SYNs, ACKs, etc.)\n if packet.data:\n if packet.addr == self.addr:\n self.clientpackets += 1\n self.clientbytes += packet.byte_count\n else:\n self.serverpackets += 1\n self.serverbytes += packet.byte_count\n\n if packet.dt > self.endtime:\n self.endtime = packet.dt\n\n if old_blob:\n return old_blob\n\n def info(self):\n \"\"\"\n Provides a dictionary with information about a connection. Useful for\n calls to a plugin's write() function, e.g. self.write(\\\\*\\\\*conn.info())\n\n Returns:\n Dictionary with information\n \"\"\"\n d = dict(self.__dict__)\n d['duration'] = self.duration\n del d['blobs']\n del d['stop']\n del d['_current_addr_pair']\n del d['handled']\n return d\n\n def __repr__(self):\n return '%s %16s -> %16s (%s -> %s) %6s %6s %5d %5d %7d %7d %-.4fs' % (\n self.starttime,\n self.clientip,\n self.serverip,\n self.clientcc,\n self.servercc,\n self.clientport,\n self.serverport,\n self.clientpackets,\n self.serverpackets,\n self.clientbytes,\n self.serverbytes,\n self.duration,\n )\n\nclass Blob(object):\n \"\"\"\n Class for holding and reassembling pieces of a connection.\n\n A Blob holds the packets and reassembled data for traffic moving in one\n direction in a connection, before direction changes.\n\n def __init__(self, first_packet, direction)\n\n Args:\n first_packet: the first Packet object to initialize Blob\n direction: direction of blob -\n 'cs' for client-to-server, 'sc' for sever-to-client\n\n Attributes:\n addr: .addr attribute of the first packet\n ts: timestamp of the first packet\n starttime: datetime for first packet\n endtime: datetime of last packet\n sip: source IP\n smac: source MAC address\n sport: source port\n sipcc: country code of source IP\n sipasn: ASN of source IP\n dip: dest IP\n dmac: dest MAC address\n dport: dest port\n dipcc: country code of dest IP\n dipasn: ASN of dest IP\n protocol: text version of protocol in layer-3 header\n direction: direction of the blob -\n 'cs' for client-to-server, 'sc' for sever-to-client\n ack_sequence_numbers: set of ACK numbers from the receiver for ####################################\n collected data packets\n all_packets: list of all packets in the blob\n hidden (bool): Used to indicate that a Blob should not be passed to\n next plugin. Can theoretically be overruled in, say, a\n connection_handler to force a Blob to be passed to next\n plugin.\n \"\"\"\n\n # max offset before wrap, default is MAXINT32 for TCP sequence numbers\n MAX_OFFSET = 0xffffffff\n\n def __init__(self, first_packet, direction):\n self.addr = first_packet.addr\n self.ts = first_packet.ts\n self.starttime = first_packet.dt\n self.endtime = first_packet.dt\n self.sip = first_packet.sip\n self.smac = first_packet.smac\n self.sport = first_packet.sport\n self.sipcc = first_packet.sipcc\n self.sipasn = first_packet.sipasn\n self.dip = first_packet.dip\n self.dmac = first_packet.dmac\n self.dport = first_packet.dport\n self.dipcc = first_packet.dipcc\n self.dipasn = first_packet.dipasn\n self.protocol = first_packet.protocol\n self.direction = direction\n# self.ack_sequence_numbers = {}\n self.all_packets = []\n# self.data_packets = []\n self.__data_bytes = b''\n\n # Used to indicate that a Blob should not be passed to next plugin.\n # Can theoretically be overruled in, say, a connection_handler to\n # force a Blob to be passed to next plugin.\n self.hidden = False\n\n @property\n def data(self):\n \"\"\"\n Returns the reassembled byte string.\n\n If it was not already reassembled, reassemble is called with default\n arguments.\n \"\"\"\n if not self.__data_bytes:\n self.reassemble()\n return self.__data_bytes\n\n def reassemble(self, allow_padding=True, allow_overlap=True, padding=b'\\x00'):\n \"\"\"\n Rebuild the data string from the current list of data packets\n For each packet, the TCP sequence number is checked.\n\n If overlapping or padding is disallowed, it will raise a\n SequenceNumberError exception if a respective event occurs.\n\n Args:\n allow_padding (bool): If data is missing and allow_padding = True\n (default: True), then the padding argument\n will be used to fill the gaps.\n allow_overlap (bool): If data is overlapping, the new data is\n used if the allow_overlap argument is True\n (default). Otherwise, the earliest data is\n kept.\n padding: Byte character(s) to use to fill in missing data. Used\n in conjunction with allow_padding (default: b'\\\\\\\\x00')\n \"\"\"\n data = b\"\"\n unacknowledged_data = []\n acknowledged_data = {}\n for pkt in self.all_packets:\n if not pkt.sequence_number:\n # if there are no sequence numbers (i.e. not TCP), just rebuild\n # in chronological order\n data += pkt.data\n continue\n\n if pkt.data:\n if pkt.sequence_number in acknowledged_data:\n continue\n unacknowledged_data.append(pkt)\n\n elif pkt.tcp_flags and pkt.tcp_flags & tcp.TH_ACK:\n ackpkt = pkt\n for i, datapkt in enumerate(unacknowledged_data):\n if (datapkt.ack_number == ackpkt.sequence_number\n and ackpkt.ack_number == (datapkt.sequence_number + len(datapkt.data))):\n # if the seq/ack numbers align, this is the data packet\n # we want\n # TODO confirm this logic is correct\n acknowledged_data[datapkt.sequence_number] = datapkt.data\n unacknowledged_data.pop(i)\n break\n\n if not acknowledged_data and not unacknowledged_data:\n # For non-sequential protocols, just return what we have\n self.__data_bytes = data\n\n else:\n # Create a list of each segment of the complete data. Use\n # acknowledged data first, and then try to fill in the blanks with\n # unacknowledged data.\n segments = acknowledged_data.copy()\n for pkt in reversed(unacknowledged_data):\n if pkt.sequence_number in segments: continue\n segments[pkt.sequence_number] = pkt.data\n\n offsets = sorted(segments.keys())\n # iterate over the segments and try to piece them together\n # handle any instances of missing or overlapping segments\n nextoffset = offsets[0]\n startoffset = offsets[0]\n for offset in offsets:\n if offset > nextoffset:\n # data is missing\n if allow_padding:\n data += padding * (offset - nextoffset)\n else:\n raise SequenceNumberError(\"Missing data for sequence number %d %s\" % (nextoffset, self.addr))\n elif offset < nextoffset:\n # data is overlapping\n if not allow_overlap:\n raise SequenceNumberError(\"Overlapping data for sequence number %d %s\" % (nextoffset, self.addr))\n\n nextoffset = (offset + len(segments[offset])) & self.MAX_OFFSET\n data = data[:offset - startoffset] + \\\n segments[offset] + \\\n data[nextoffset - startoffset:]\n self.__data_bytes = data\n\n return data\n\n\n\n\n# segments = {}\n# for pkt in self.data_packets:\n# if pkt.sequence_number:\n# segments.setdefault(pkt.sequence_number, []).append(pkt.data)\n# else:\n# # if there are no sequence numbers (i.e. not TCP), just rebuild\n# # in chronological order\n# data += pkt.data\n#\n# if not segments:\n# # For non-sequential protocols, just return what we have\n# self.__data_bytes = data\n# return data\n#\n# offsets = sorted(segments.keys())\n#\n# # iterate over the segments and try to piece them together\n# # handle any instances of missing or overlapping segments\n# nextoffset = offsets[0]\n# startoffset = offsets[0]\n# for offset in offsets:\n# # TODO do we still want to implement custom error handling?\n# if offset > nextoffset:\n# # data is missing\n# if allow_padding:\n# data += padding * (offset - nextoffset)\n# else:\n# raise SequenceNumberError(\"Missing data for sequence number %d %s\" % (nextoffset, self.addr))\n# elif offset < nextoffset:\n# # data is overlapping\n# if not allow_overlap:\n# raise SequenceNumberError(\"Overlapping data for sequence number %d %s\" % (nextoffset, self.addr))\n## nextoffset = (offset + len(segments[offset][dup])) & self.MAX_OFFSET\n## if nextoffset in self.ack_sequence_numbers:\n# if offset in self.ack_sequence_numbers:\n# # If the data packet was acknowledged by the receiver,\n# # we use the first packet received.\n# dup = 0\n# else:\n# # If it went unacknowledged, we use the last packet and hope\n# # for the best.\n# dup = -1\n# print(dup)\n# print(offset)\n# print(nextoffset)\n# print(str(self.ack_sequence_numbers))\n# nextoffset = (offset + len(segments[offset][dup])) & self.MAX_OFFSET\n# data = data[:offset - startoffset] + \\\n# segments[offset][dup] + \\\n# data[nextoffset - startoffset:]\n# self.__data_bytes = data\n# return data\n\n def info(self):\n \"\"\"\n Provides a dictionary with information about a blob. Useful for\n calls to a plugin's write() function, e.g. self.write(\\\\*\\\\*conn.info())\n\n Returns:\n Dictionary with information\n \"\"\"\n d = dict(self.__dict__)\n del d['hidden']\n del d['_Blob__data_bytes']\n del d['all_packets']\n return d\n\n def add_packet(self, packet):\n \"\"\"\n Accepts a Packet object and stores it.\n\n Args:\n packet: a Packet object\n \"\"\"\n self.all_packets.append(packet)\n\n if packet.dt > self.endtime:\n self.endtime = packet.dt\n","sub_path":"dshell/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":55911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"402264731","text":"import pandas as pd\nfrom tqdm import tqdm, trange\nimport tables\nfrom sklearn.linear_model import LinearRegression, SGDRegressor\nfrom sklearn import cross_validation\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom clean_training_set import load_clean_training_set\nfrom featurizer import *\nfrom pandas.tseries.offsets import *\nfrom learn_structure import load_structure\nimport math\nimport os, pickle\n\n\ndef update_data(df, sums, numbers):\n for index, row in df.iterrows():\n triplet = (row.DAY_WE_DS, row.ASS_ASSIGNMENT, row.DATE.time())\n if triplet not in sums:\n sums[triplet] = 0\n numbers[triplet] = 0\n sums[triplet] += row.CSPL_RECEIVED_CALLS\n numbers[triplet] += 1\n\n\ndef load_data(df):\n sums = {}\n numbers = {}\n\n update_data(df, sums, numbers)\n\n pickle.dump((sums, numbers), open(\"files/time_series_data.pkl\", \"wb\"))\n return sums, numbers\n\n\ntraining_df = load_clean_training_set(\"files/train_clean.pkl\")\n\nsubmission_df = load_submission(\"files/submission_test.txt\")\n\ny_true = np.copy(submission_df['prediction'].as_matrix())\ny_pred = np.zeros(len(y_true))\n\nmin_date = submission_df['DATE'].min()\nmax_date = submission_df['DATE'].max()\n\nold_df = training_df[training_df.DATE < min_date - DateOffset(days=3)]\n\nsums, numbers = load_data(old_df)\n\nprev_date = min_date\ncurrent_date = min_date + DateOffset(days=7)\n\nn = 0\nwith tqdm(total=((max_date - min_date).days / 7) + 1) as pbar:\n while prev_date < max_date:\n sub_df = submission_df[(submission_df.DATE >= prev_date) & (submission_df.DATE < current_date)]\n for index, row in sub_df.iterrows():\n triplet = (row.DAY_WE_DS, row.ASS_ASSIGNMENT, row.DATE.time())\n if triplet in sums:\n y_pred[index] = float(sums[triplet]) / numbers[triplet]\n\n old_df = training_df[(training_df.DATE >= prev_date - DateOffset(days=3)) &\n (training_df.DATE < current_date - DateOffset(days=3))]\n update_data(old_df, sums, numbers)\n prev_date = current_date\n current_date = prev_date + DateOffset(days=7)\n pbar.update(1)\n\nprint(n)\ny_pred_round = [int(math.ceil(x)) if x > 0 else 0 for x in y_pred]\nsubmission_df.prediction = y_pred_round\nprint(submission_df)\nsubmission_df.DATE = submission_df.DATE.apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])\nsubmission_df[['DATE', 'ASS_ASSIGNMENT', 'prediction']].to_csv('results/submission_real.txt', sep='\\t', index=False)\n#\nprint('MSE round: '),\nprint(mean_squared_error(y_true, y_pred_round))\n#\nprint('MSE not round: '),\nprint(mean_squared_error(y_true, y_pred))\n","sub_path":"classifier_time_series_optimized.py","file_name":"classifier_time_series_optimized.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33915077","text":"\"\"\"The Vulcan component.\"\"\"\nimport asyncio\nimport logging\n\nfrom aiohttp import ClientConnectorError\nfrom homeassistant.exceptions import ConfigEntryNotReady\nfrom homeassistant.helpers.entity import Entity\nfrom homeassistant.helpers.typing import ConfigType\nfrom vulcan import Account, Keystore, Vulcan\nfrom vulcan._utils import VulcanAPIException\n\nfrom .const import DOMAIN\n\n_LOGGER = logging.getLogger(__name__)\n\nPLATFORMS = [\"sensor\", \"calendar\"]\n\n\nasync def async_setup(hass, config) -> bool:\n hass.data.setdefault(DOMAIN, {})\n\n return True\n\n\nasync def async_setup_entry(hass, config_entry):\n try:\n with open(f\".vulcan/keystore-{config_entry.data.get('login')}.json\") as f:\n keystore = Keystore.load(f)\n with open(f\".vulcan/account-{config_entry.data.get('login')}.json\") as f:\n account = Account.load(f)\n client = Vulcan(keystore, account)\n await client.select_student()\n students = await client.get_students()\n for student in students:\n if str(student.pupil.id) == str(config_entry.data.get(\"student_id\")):\n client.student = student\n break\n except VulcanAPIException as err:\n if str(err) == \"The certificate is not authorized.\":\n _LOGGER.error(\n \"The certificate is not authorized, please authorize integration again.\"\n )\n hass.async_create_task(\n hass.config_entries.flow.async_init(\n DOMAIN,\n context={\"source\": \"reauth\"},\n )\n )\n else:\n _LOGGER.error(\"Vulcan API error: %s\", err)\n return False\n except FileNotFoundError as err:\n _LOGGER.error(\n \"The certificate is not authorized, please authorize integration again.\"\n )\n hass.async_create_task(\n hass.config_entries.flow.async_init(\n DOMAIN,\n context={\"source\": \"reauth\"},\n )\n )\n return False\n except ClientConnectorError as err:\n if \"connection_error\" not in hass.data[DOMAIN]:\n _LOGGER.error(\n \"Connection error - please check your internet connection: %s\", err\n )\n hass.data[DOMAIN][\"connection_error\"] = True\n await client.close()\n raise ConfigEntryNotReady\n num = 0\n for _ in hass.config_entries.async_entries(DOMAIN):\n num += 1\n hass.data[DOMAIN][\"students_number\"] = num\n hass.data[DOMAIN][config_entry.entry_id] = client\n\n if not config_entry.update_listeners:\n update_listener = config_entry.add_update_listener(_async_update_options)\n\n for platform in PLATFORMS:\n hass.async_create_task(\n hass.config_entries.async_forward_entry_setup(config_entry, platform)\n )\n\n return True\n\n\nasync def async_unload_entry(hass, entry):\n \"\"\"Unload a config entry.\"\"\"\n for platform in PLATFORMS:\n await hass.config_entries.async_forward_entry_unload(entry, platform)\n\n return True\n\n\nasync def _async_update_options(hass, entry):\n \"\"\"Update options.\"\"\"\n await hass.config_entries.async_reload(entry.entry_id)\n\n\nclass VulcanEntity(Entity):\n @property\n def name(self):\n return self._name\n\n @property\n def icon(self):\n return self._icon\n\n @property\n def unique_id(self):\n return self._unique_id\n\n @property\n def state(self):\n return self._state\n","sub_path":"custom_components/vulcan/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"23797646","text":"# coding: utf-8\n\nfrom io import BytesIO\nimport uuid\n\nfrom base64 import b64encode, b64decode\nfrom flask import request, jsonify\n\nimport config\nfrom main import conn\nfrom common import verify_helper\nfrom libs.image_storage import bucket\nfrom . import api\n\n@api.route('/api/profile', methods=['GET'])\ndef profile():\n\tsess = request.cookies.get('s_', '')\n\tsessionid = b64decode(sess)\n\tuser_mobile = conn.hget('login:', sessionid)\n\tif not user_mobile:\n\t\tdata = {'errno': -1, 'errmsg': '获取用户失败'}\n\t\treturn jsonify(data)\n\n\tuser = conn.hgetall('user:' + user_mobile)\n\tif user:\n\t\tuser_info = {}\n\t\tuser_info['name'] = user.get('uname', '')\n\t\tuser_info['mobile'] = user.get('phone', '')\n\t\tavatar_ = user.get('avatar', '')\n\t\tuser_info['avatar'] = config.OSS_PREFIX + str(avatar_) if avatar_ else ''\n\t\tdata = {'errno': 0, 'errmsg': '获取用户信息成功', 'data': user_info}\n\telse:\n\t\tdata = {'errno': 0, 'errmsg': '获取用户信息失败'}\n\treturn jsonify(data)\n\n\n@api.route('/api/profile/avatar', methods=['POST'])\ndef avatar():\n\tsess = request.cookies.get('s_', '')\n\tsessionid = b64decode(sess)\n\tuser_mobile = conn.hget('login:', sessionid)\n\tif not user_mobile:\n\t\tdata = {'errno': -1, 'errmsg': '获取用户失败'}\n\t\treturn jsonify(data)\n\n\n\t# print dir(request.files)\n\t# print type(request.files)\n\t# print request.files\n\tfile = request.files.get('avatar')\n\t# print file \n\t# print dir(file)\n\t# print file.stream\n\t# # print dir(file)\n\tsuffix = '.' + file.filename.rpartition('.')[-1]\n\t# print name\n\tfilename = 'img_' + str(uuid.uuid4()) + suffix\n\tbuffer = BytesIO()\n\tfile.save(buffer)\n\tfile.close()\n\t# print buffer.getvalue()\n\t# filename有些多余,真正文件名由bucket产生\n\tf = bucket.upload(filename, buffer.getvalue())\n\t# file.save('./html/static/images/' + name)\n\t# print filename\n\t\n\n\ttry:\n\t\tavatar = conn.hset('user:' + user_mobile, 'avatar', f)\n\t\tdata = {'errno': 0, 'errmsg': '上传图像成功', 'data': config.OSS_PREFIX + f}\n\texcept:\n\t\tdata = {'errno': 0, 'errmsg': '上传图像失败'}\n\treturn jsonify(data)\n\n\t\n\n@api.route('/api/profile/name', methods=['POST'])\ndef profile_name():\n\tname = request.json.get('name', '')\n\tsess = request.cookies.get('s_', '')\n\tsessionid = b64decode(sess)\n\tuser_mobile = conn.hget('login:', sessionid)\n\tif not user_mobile:\n\t\tdata = {'errno': -1, 'errmsg': '获取用户失败'}\n\t\treturn jsonify(data)\n\t# 比较是否与前一次名字相同和直接修改一次名字,操作量一样 因此,不作比较\n\ttry:\n\t\tconn.hset('user:' + user_mobile, 'uname', name)\n\t\tdata = {'errno': 0, 'msg': '重设用户名成功'}\n\texcept:\n\t\tdata = {'errno': -1, 'msg': '重设用户名失败'}\n\t\n\treturn jsonify(data)\n\n\n@api.route('/api/profile/auth', methods=['GET'])\ndef get_auth():\n\tsess = request.cookies.get('s_', '')\n\tsessionid = b64decode(sess)\n\tuser_mobile = conn.hget('login:', sessionid)\n\tif not user_mobile:\n\t\tdata = {'errno': -1, 'errmsg': '获取用户失败'}\n\t\treturn jsonify(data)\n\tuser_info = conn.hgetall('user:' + user_mobile)\n\treal_name = user_info.get('real_name', '')\n\tid_card = user_info.get('id_card', '')\n\tdata = {'errno': 0, 'errmsg': '获取信息成功', \n\t\t'data': {'real_name': real_name, 'id_card': id_card}}\n\treturn jsonify(data)\n\n\n@api.route('/api/profile/auth', methods=['POST'])\ndef post_auth():\n\tsess = request.cookies.get('s_', '')\n\tsessionid = b64decode(sess)\n\tuser_mobile = conn.hget('login:', sessionid)\n\tif not user_mobile:\n\t\tdata = {'errno': -1, 'errmsg': '获取用户失败'}\n\t\treturn jsonify(data)\n\n\tdata = request.json\n\t# real_name = data.get('real_name', '')\n\t# id_card = data.get('id_card', '')\n\tuser_info = {}\n\tuser_info['real_name'] = data.get('real_name', '')\n\tuser_info['id_card'] = data.get('id_card', '')\n\n\tconn.hmset('user:' + user_mobile, user_info)\n\t\t\n\tres = {'errno': 0, 'errmsg': '获取信息成功', \n\t\t'data': {'real_name': user_info['real_name'], 'id_card': user_info['id_card']}}\n\treturn jsonify(res)\n\n\n","sub_path":"api/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"520547623","text":"#!/usr/bin/env python3\n#\n# A script that scrapes a web page for a blog post etc, then uses AWS Polly to\n# convert the content text to an audio file suitable for a private podcast.\n#\n# Usage:\n# as_audio.py \n\nimport os\nimport sys\nimport re\nimport requests\nimport argparse\nimport boto3\nimport html2text\nfrom markdown import markdown\nfrom bs4 import BeautifulSoup\nfrom readability import Document\nimport pydub\n\ndef extract_doi_from_string(s):\n \"\"\"\n Extract the DOI from a string.\n \"\"\"\n doi = re.search(r'(10\\.\\d{4,9}/[-._;()/:A-Za-z0-9]+|10.1002/[^\\s]+|10.\\d{4}/\\d+-\\d+X?(\\d+)\\d+<[\\d\\w]+:[\\d\\w]*>\\d+.\\d+.\\w+;\\d|10.1021/\\w\\w\\d+|10.1207/[\\w\\d]+\\&\\d+_\\d+)', s)\n if doi:\n return doi.group()\n else:\n return None\n\ndef extract_isbn_from_string(s):\n \"\"\"\n Extract the ISBN from a string.\n \"\"\"\n isbn = re.search(r'(?=(?:\\D*\\d){10}(?:(?:\\D*\\d){3})?$)[\\d-]+', s)\n if isbn:\n return str(isbn.group()).replace('-',\"\")\n else:\n return None\n\ndef get_article_doc(url: str) -> Document:\n \"\"\"\n Get the Document version of the article from the given URL.\n \"\"\"\n response = requests.get(url)\n if response.status_code != 200:\n print(\"Error: {}\".format(response.status_code))\n raise Exception(\"Failed to get article text from URL: {}\".format(url))\n html = response.text\n doc = Document(html)\n return doc\n\ndef convert_doc_to_dict(doc: Document, strip_html=True) -> dict:\n \"\"\"\n Convert the Document to a dictionary of the article's text and title.\n \"\"\"\n if strip_html:\n h = html2text.HTML2Text()\n # ignore links\n h.ignore_links = True\n text = h.handle(doc.summary())\n else:\n text = doc.summary()\n return {\n \"title\": doc.title(),\n \"text\": text\n }\n\ndef split_article_text(text: str, max_length=3000) -> list:\n \"\"\"\n Split the article text into paragraphs as best as possible.\n \"\"\"\n if '\\n\\n' in text:\n split_text = text.split('\\n\\n')\n split_text = [p.replace('\\n', ' ').strip() for p in split_text if p.strip()]\n else:\n split_text = text.split('\\n')\n clean_split_text = []\n split_text = [p.strip() for p in split_text if len(p.strip()) > 0]\n for p in split_text:\n if p.startswith('>'):\n p = p[1:].strip()\n if len(p) >= max_length:\n # find a space to split on\n sentences = p.split('.')\n parts = [\"\"]\n for s in sentences:\n latest_part = parts[-1] if len(parts) > 0 else \"\"\n if len(latest_part) + len(s) + 1 >= max_length:\n parts.append(s)\n else:\n parts[-1] = \"{}.{}\".format(latest_part, s)\n clean_split_text.extend(parts)\n else:\n clean_split_text.append(p)\n return clean_split_text\n\n\ndef strip_markdown(text: str) -> str:\n \"\"\"\n Strip out markdown from the given text snippet.\n \"\"\"\n html = markdown(text)\n soup = BeautifulSoup(html, 'html.parser')\n return soup.get_text()\n\ndef build_polly_client():\n \"\"\"\n Build a Polly client.\n \"\"\"\n return boto3.client('polly')\n\ndef generate_temp_id():\n \"\"\"\n Generate a temporary ID for a file.\n \"\"\"\n return os.urandom(16).hex()\n\ndef get_and_prep_for_polly(url: str, remove_html=True, remove_markdown=True):\n \"\"\"Take a url; prep a dict containing a list of polly-suitable texts.\"\"\"\n try:\n raw_doc = get_article_doc(url)\n clean_doc = convert_doc_to_dict(raw_doc, strip_html=remove_html)\n title = clean_doc['title']\n text = clean_doc['text']\n if remove_markdown:\n paragraphs = [strip_markdown(p) for p in split_article_text(text)]\n else:\n paragraphs = split_article_text(text)\n paragraphs = [p.strip().replace('>','').replace(' ',' ') for p in paragraphs if len(p.strip()) > 0]\n # add the title to the first paragraph\n if len(title.strip()) > 0:\n paragraphs.insert(0, title.strip())\n return {\n \"title\": title,\n \"text\": paragraphs,\n \"url\": url,\n \"id\": generate_temp_id()\n }\n except Exception as e:\n print(\"Error: {}\".format(e))\n return None\n\ndef send_and_save(text:str, polly_client, outdir, id, n, voice=\"Matthew\"):\n \"\"\"\n Send a short string to a polly client, then save the resulting file.\n \"\"\"\n response = polly_client.synthesize_speech(\n OutputFormat='mp3',\n Text=text,\n VoiceId=voice,\n TextType='text',\n Engine='neural'\n )\n if 'AudioStream' in response:\n with open(\"{}/{}-{}.mp3\".format(outdir, id, str(n).zfill(6)), 'wb') as f:\n f.write(response['AudioStream'].read())\n\ndef list_temp_audio_files(outdir, id):\n \"\"\"\n Find all the temporary audio files for a given id; return a list in order.\n \"\"\"\n files = [os.path.join(outdir, f) for f in os.listdir(outdir) if id in f]\n files.sort()\n return files\n\ndef generate_combined_audio_outpath(outdir, id):\n \"\"\"\n Generate the output path for the combined audio file.\n \"\"\"\n return os.path.join(outdir, \"{}.mp3\".format(id))\n\ndef join_audio_files(files, outdir, id, buffer_silence=1000):\n \"\"\"\n Join all the audio files into a single file.\n \"\"\"\n audio_files = [pydub.AudioSegment.from_mp3(f) for f in files]\n silence = pydub.AudioSegment.silent(duration=buffer_silence)\n joined_audio = pydub.AudioSegment.empty()\n for i, audio in enumerate(audio_files):\n joined_audio += audio\n joined_audio += silence\n combined_outpath = generate_combined_audio_outpath(outdir, id)\n joined_audio.export(combined_outpath, format=\"mp3\")\n if not os.path.exists(combined_outpath):\n print(\"Attempt to saved combined audio to {} failed for an unknown reason!\".format(combined_outpath))\n\n\ndef build_final_outpath(outdir, document_dict):\n \"\"\"\n Build the final output path for the given document.\n \"\"\"\n if 'title' in document_dict.keys() and len(document_dict['title']) > 0:\n final_name = \"{}.mp3\".format(document_dict['title'].strip())\n final_outpath = os.path.join(outdir, final_name)\n return final_outpath\n else:\n return None\n\ndef rename_combined_file(temp_outdir, id, final_outdir, document_dict):\n \"\"\"\n Rename the combined file to the final name.\n \"\"\"\n combined_outpath = generate_combined_audio_outpath(temp_outdir, id)\n final_outpath = build_final_outpath(final_outdir, document_dict)\n if final_outpath is not None:\n os.rename(src=combined_outpath, dst=final_outpath)\n else:\n final_name = \"{}.mp3\".format(id)\n final_outpath = os.path.join(final_outdir, final_name)\n os.rename(src=combined_outpath, dst=final_outpath)\n\ndef make_audible(url, temp_dir=\"/Users/g/Desktop\", final_dir=\"/Users/g/Desktop\", remove_html=True, remove_markdown=True, buffer_silence=1000, voice=\"Matthew\"):\n \"\"\"\n Take a url and generate an audio file from it.\n \"\"\"\n document = get_and_prep_for_polly(url)\n if document is not None:\n final_outpath = build_final_outpath(final_dir, document) # use to check if it already exists!\n if final_outpath is not None and os.path.exists(final_outpath):\n print(\"{} already exists! Skipping.\".format(final_outpath))\n return None\n else:\n client = build_polly_client()\n for n, text in enumerate(document['text']):\n send_and_save(text, client, temp_dir, document['id'], n, voice=voice)\n temp_files = list_temp_audio_files(temp_dir, document['id'])\n join_audio_files(temp_files, temp_dir, document['id'])\n rename_combined_file(temp_dir, document['id'], final_dir, document)\n # remove temp files\n for f in temp_files:\n os.remove(f)\n\ndef get_args(sysargs = sys.argv[1:]):\n \"\"\"\n Get the command line arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Make an audio file from a given URL.\")\n parser.add_argument(\"url\", help=\"The URL to make an audio file from.\")\n parser.add_argument(\"--temp_dir\", help=\"The temporary directory to save the in-process audio files.\", default=\"/Users/g/Desktop\")\n parser.add_argument(\"--final_dir\", help=\"The directory to save the final audio file.\", default=\"/Users/g/Desktop\")\n parser.add_argument(\"--remove_html\", help=\"Remove HTML from the text.\", action=\"store_true\", default=True)\n parser.add_argument(\"--remove_markdown\", help=\"Remove markdown from the text.\", action=\"store_true\", default=True)\n parser.add_argument(\"--buffer_silence\", help=\"The amount of silence to add between each audio file.\", default=1000, type=int)\n parser.add_argument(\"--voice\", help=\"The Polly voice to use.\", default=\"Matthew\")\n return parser.parse_args(sysargs)\n\ndef main():\n \"\"\"\n Get the arguments and make an audio file.\n \"\"\"\n args = get_args(sys.argv[1:])\n if args.url is not None and args.url != \"\":\n # make sure the link doesn't have a doi or isbn\n doi = extract_doi_from_string(args.url)\n isbn = extract_isbn_from_string(args.url)\n if doi is None and isbn is None and not str(args.url).endswith('.pdf'):\n make_audible(args.url,\n args.temp_dir,\n args.final_dir,\n args.remove_html,\n args.remove_markdown,\n args.buffer_silence,\n args.voice)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"scripts/as_audio.py","file_name":"as_audio.py","file_ext":"py","file_size_in_byte":9600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"501175939","text":"import numpy as np\n\ndef eval_perplexity(model, corpus, batch_size=10, time_size=35):\n print('=== Evaluating perplexity... ===')\n corpus_size = len(corpus)\n total_loss, loss_cnt = 0, 0\n max_iters = (corpus_size - 1) // (batch_size * time_size)\n jump = (corpus_size - 1) // batch_size\n\n for iters in range(max_iters):\n xs = np.zeros((batch_size, time_size), dtype=np.int32)\n ts = np.zeros((batch_size, time_size), dtype=np.int32)\n time_offset = iters * time_size\n offsets = [time_offset + (i * jump) for i in range(batch_size)]\n for t in range(time_size):\n for i, offset in enumerate(offsets):\n xs[i, t] = corpus[(offset + t) % corpus_size]\n ts[i, t] = corpus[(offset + t + 1) % corpus_size]\n try:\n loss = model.forward(xs, ts, train_flag=False)\n except TypeError:\n loss = model.forward(xs, ts)\n total_loss += loss\n sys.stdout.write('\\r%d / %d' % (iters, max_iters))\n sys.stdout.flush()\n print('')\n ppl = np.exp(total_loss / max_iters)\n return ppl\n","sub_path":"src/concerns/eval_perplexity.py","file_name":"eval_perplexity.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"563563308","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import NearestNeighbors\n\nfrom iccpy.gadget import load_snapshot\nfrom iccpy.gadget.labels import cecilia_labels\nfrom iccpy.gadget.subfind import SubfindCatalogue\nfrom iccpy.utils import match\n\nimport time, pickle\n\n\n################################################################################################\n################################################################################################\n\n\ndef M_vir_crit(snap, subh, layers, rmax):\n \"\"\"\n Returns M_vir, Mstar_vir, r_200_crit\n \"\"\"\n hubble0 = snap.header.hubble0[0]\n ind_gas = np.concatenate([match(subh.ids, snap['ID '][0]), match(subh.ids + 2**31, snap['ID '][0])])\n ind_gas = ind_gas[ind_gas != -1]\n ind_stars = match(subh.ids, snap['ID '][4])\n ind_stars = ind_stars[ind_stars != -1]\n ind_DM = match(subh.ids, snap['ID '][1])\n ind_DM = ind_DM[ind_DM != -1]\n\n CM = subh.pot_min\n\n pos = np.concatenate((snap['POS '][0][ind_gas] - CM, snap['POS '][4][ind_stars] - CM, snap['POS '][1][ind_DM] - CM))\n pos = pos / hubble0 * 1000\n r = np.linalg.norm(pos, axis=1)\n\n\n masses = np.concatenate((snap['MASS'][0][ind_gas], snap['MASS'][4][ind_stars], snap['MASS'][1][ind_DM])) * 1e10 / hubble0\n\n # We make a mass histogram with radial bins:\n mass, radius = np.histogram(r, bins=layers, range=(0, rmax), weights=masses)\n\n inner_mass = np.cumsum(mass)\n rho = inner_mass / (4/3 * np.pi * radius[1:]**3)\n rho_crit = 126.7 # solar masses per kpc^3, from Planck\n\n ind_200 = (np.abs(rho - 200*rho_crit)).argmin() # This gives the index of the bin where rho is closest to 200*rho_crit\n r_200 = radius[ind_200]\n print('r_200 is {}'.format(r_200))\n M_vir = np.sum(masses[r < r_200])\n\n pos = (snap['POS '][4][ind_stars] - CM) / hubble0 * 1000\n r = np.linalg.norm(pos, axis=1)\n\n star_mass = snap['MASS'][4][ind_stars] * 1e10 / hubble0\n Mstar_vir = np.sum(star_mass[r < r_200])\n\n return M_vir, Mstar_vir, r_200\n\n\n################################################################################################\n################################################################################################\n\n\ndef get_inner_inds(snap, subh, component):\n \"\"\"\n Finds the indexes of the particles of\n a given component which lie within r_200 / 10 from the subhalo CM.\n This will return the indexes for the particles of the given type so one can\n then use them with snap['XXXX'][component][indexes]\n \"\"\"\n CM = subh.pot_min\n hubble0 = snap.header.hubble0[0]\n pos = (snap['POS '][component] - CM) * 1000 / hubble0\n r = np.linalg.norm(pos, axis=1)\n r_200 = M_vir_crit(snap, subh, 5000, 300)[2]\n ind = r < r_200 / 10\n # r_half = .05\n print('r_200 is {} kpc'.format(r_200))\n \n ind = np.nonzero(ind)[0]\n\n return ind\n\n\n################################################################################################\n################################################################################################\n\n\ndef most_massives(cat, n):\n \"\"\"\n This gets the n most massive subhalos in the catalogue\n \"\"\"\n import heapq\n n_most_massive = []\n masses = []\n for subh in cat.subhalo[:]:\n masses.append(subh.mass)\n thresh = np.min(heapq.nlargest(n, masses))\n for subh in cat.subhalo[:]:\n if subh.mass >= thresh:\n n_most_massive.append(subh)\n\n return n_most_massive\n\n\n################################################################################################\n################################################################################################\n\n\ndef get_massive(snap, cat, M):\n \"\"\"\n Returns a list with subhalo objects with more mass than M (given in solar masses)\n TAKES TOO MUCH TIME TO RUN, BUT IF WE TAKE SUBFIND MASS IT'S TOO BIG\n MAYBE FILTER OUT LOW TOTAL MASSES BEFORE FILTERING BY VIRIAL MASS????\n \"\"\"\n hubble0 = snap.header.hubble0[0]\n massives = []\n i = 0\n for subh in cat.subhalo[:]:\n \tif subh.mass > M * hubble0 / 1e10:\n \t\tmassives.append(subh)\n \ti += 1\n return massives\n\n\n################################################################################################\n################################################################################################\n\n\ndef PCA_matrix(snap, subh):\n CM = subh.pot_min\n # ind = match(subh.ids, snap['ID '][4])\n # ind = ind[ind != -1]\n\n ind = get_inner_inds(snap, subh, 4)\n print('{} stars for PCA'.format(np.size(ind)))\n pos = (snap['POS '][4][ind] - CM)\n # We calculate covariance matrix and diagonalize it. The eigenvectors are the galaxy's principal axes\n covMatrix = np.cov(np.transpose(pos))\n eigenval, eigenvect = np.linalg.eig(covMatrix)\n\n # eigenvalues are not ordered; we make it so rot_matrix has eigenvectors as columns ordered from highest eigenvalue to lowest:\n eig1 = eigenval.argmax()\n eig3 = eigenval.argmin()\n eig2 = 3 - eig1 - eig3\n\n rot_matrix = np.array([eigenvect[:, eig1], eigenvect[:, eig2], eigenvect[:, eig3]])\n rot_matrix = np.transpose(rot_matrix)\n\n # Now we check if the total angular momentum is antiparallel to z; if it is we flip the galaxy\n vel = snap['VEL '][4][ind]\n V_cm = Vcm(snap, subh)\n vel = vel - V_cm\n vel = np.dot(vel, rot_matrix)\n pos = np.dot(pos, rot_matrix)\n\n pos_x = pos[:, 0]\n pos_y = pos[:, 1]\n vel_x = vel[:, 0]\n vel_y = vel[:, 1]\n\n jz = pos_x * vel_y - pos_y * vel_x\n\n if np.sum(jz) < 0:\n # We invert first and last row (x and z) from the rot_matrix which is equivalent to rotating around the y axis\n rot_matrix[:, 0] = - rot_matrix[:, 0]\n rot_matrix[:, 2] = - rot_matrix[:, 2]\n\n return rot_matrix\n\n\n################################################################################################\n################################################################################################\n\n\ndef Vcm(snap, subh):\n \"\"\"\n Computes the Vcm using only star particles\n \"\"\"\n ind = match(subh.ids, snap['ID '][4])\n ind = ind[ind != -1]\n vel = snap['VEL '][4][ind]\n masses = snap['MASS'][4][ind]\n masses_reshaped = np.transpose(np.array([masses, masses, masses]))\n\n V_cm = np.sum(vel * masses_reshaped, axis=0) / np.sum(masses)\n\n return V_cm\n\n\n################################################################################################\n################################################################################################\n\n\ndef grid_maker(snap, subh, quantity, component, axis1, axis2, length, res, use_subf_ids):\n \"\"\"\n Returns a res*res 2darray with the projected quantity (e.g. 'MASS') for the\n desired component (0 for gas, 1 for DM, 4 for stars)\n subfind: True if the subfind can be trusted, False if we want to use\n get_subh_from_CM to get all the particles inside r_200 / 10\n \"\"\"\n hubble0 = snap.header.hubble0[0]\n CM = subh.pot_min\n\n if use_subf_ids:\n if component == 0:\n \tind = np.concatenate([match(subh.ids, snap['ID '][0]), match(subh.ids + 2**31, snap['ID '][0])])\n else:\n \tind = match(subh.ids, snap['ID '][component])\n ind = ind[ind != -1]\n positions = (snap['POS '][component][ind] - CM) / hubble0\n else:\n positions = (snap['POS '][component] - CM) / hubble0\n ind = list(abs(positions[:, 0]) < length/2) and list(abs(positions[:, 1]) < length/2) and list(abs(positions[:, 2]) < length/2)\n positions = positions[ind]\n\n # We rotate the positions so that the galactic angular momentum is parallel to the z axis:\n rot_matrix = PCA_matrix(snap, subh)\n positions = np.dot(positions, rot_matrix)\n\n pos_1 = positions[:, axis1]\n pos_2 = positions[:, axis2]\n # axis3 = 3 - axis2 - axis1\n # pos_3 = (snap['POS '][component][index] - CM)[axis3] * 1000 / hubble0\n magnitude = snap[quantity][component][ind] * 1e10 / hubble0 # cambio de unidades para masa\n\n # # Here we smooth the mass distribution, averaging with 32 nearest neighbors:\n # nbrs = NearestNeighbors(n_neighbors=32, algorithm='auto').fit(positions)\n # indices = nbrs.kneighbors(positions)[1]\n # mag_smoothed = []\n #\n # for i in range(np.size(magnitude)):\n # # print(indices[i])\n # mag = np.sum(magnitude[indices[i]]) / 32\n # mag_smoothed.append(mag)\n\n # hist = np.histogram2d(pos_1, pos_2, bins=res, range=[[-length/2, length/2], [-length/2, length/2]], weights=mag_smoothed)\n hist = np.histogram2d(pos_1, pos_2, bins=res, range=[[-length/2, length/2], [-length/2, length/2]], weights=magnitude)\n\n return hist[0]\n\n\n################################################################################################\n################################################################################################\n\n\ndef grid_maker_SPH(snap, subh, quantity, component, axis1, axis2, length, res, use_subf_ids):\n \"\"\"\n Returns a res*res 2darray with the projected quantity (e.g. 'MASS') for the\n desired component (0 for gas, 1 for DM, 4 for stars)\n subfind: True if the subfind can be trusted, False if we want to use\n get_subh_from_CM to get all the particles inside r_200 / 10\n \"\"\"\n hubble0 = snap.header.hubble0[0]\n CM = subh.pot_min\n\n if use_subf_ids:\n if component == 0:\n \tind = np.concatenate([match(subh.ids, snap['ID '][0]), match(subh.ids + 2**31, snap['ID '][0])])\n else:\n \tind = match(subh.ids, snap['ID '][component])\n ind = ind[ind != -1]\n positions = (snap['POS '][component][ind] - CM) / hubble0\n else:\n positions = (snap['POS '][component] - CM) / hubble0\n\n # We rotate the positions so that the galactic angular momentum is parallel to the z axis:\n rot_matrix = PCA_matrix(snap, subh)\n positions = np.dot(positions, rot_matrix)\n\n # We exclude all the particles laying outside the box post-rotation:\n ind = np.all([[abs(positions[:, 0]) < length/2], [abs(positions[:, 1]) < length/2], [abs(positions[:, 2]) < length/2]], axis=0)[0]\n positions = positions[ind]\n print('{} particles inside the grid'.format(np.sum(ind)))\n # We take HSML from snap for gas and we calculate the mean distance of the 32 nearest neighbors for other components:\n if component == 0:\n hsml = snap['HSML'][0][ind] / hubble0\n else:\n hsml = []\n nbrs = NearestNeighbors(n_neighbors=32, algorithm='auto').fit(positions)\n distances = nbrs.kneighbors(positions)[0]\n for d in distances:\n hsml.append(d.mean())\n hsml = np.array(hsml)\n\n magnitude = snap[quantity][component][ind] * 1e10 / hubble0 # cambio de unidades para masa\n\n grid3d = np.zeros((res, res, res))\n # Here we write the hsml and positions in grid units:\n h_grid = (2 * hsml * res / length).astype(int)\n # print(np.min(h_grid))\n # print(np.max(h_grid))\n\n pos_grid = (positions * res / length + res / 2).astype(int)\n\n # We depickle the kernels previously computed:\n pickle_in = open('kernel_list', 'rb')\n kernels = pickle.load(pickle_in)\n pickle_in.close()\n\n def addAtPos(mat1, mat2, pos):\n \"\"\"\n Add two 3-arrays of different sizes in place, offset by xyz coordinates\n Usage:\n - mat1: base matrix\n - mat2: add this matrix to mat1\n - pos: [x,y,z] containing coordinates\n \"\"\"\n x, y, z = pos[0], pos[1], pos[2]\n x1, y1, z1 = mat1.shape\n if np.size(mat2) == 1:\n mat1[x, y, z] += mat2\n else:\n x2, y2, z2 = mat2.shape\n\n # get slice ranges for matrix1\n x1min = max(0, x)\n y1min = max(0, y)\n z1min = max(0, z)\n x1max = max(min(x + x2, x1), 0)\n y1max = max(min(y + y2, y1), 0)\n z1max = max(min(z + z2, z1), 0)\n\n # get slice ranges for matrix2\n x2min = max(0, -x)\n y2min = max(0, -y)\n z2min = max(0, -z)\n x2max = min(-x + x1, x2)\n y2max = min(-y + y1, y2)\n z2max = min(-z + z1, z2)\n\n mat1[x1min:x1max, y1min:y1max, z1min:z1max] += mat2[x2min:x2max, y2min:y2max, z2min:z2max]\n return mat1\n\n l = 0\n for pos, h, mag in zip(pos_grid, h_grid, magnitude):\n l += 1\n # if l%(int(np.size(hsml)/10)) == 0:\n # print('Currently {}0%'.format(int(l//(np.size(hsml)/10))))\n # We just add the contribution of the particle:\n if h < res:\n # If hsml exceeds the maximum kernel available, we take the maximum kernel instead:\n kernel = kernels[min(h, np.size(kernels) - 1)]\n # If h = 0 we just add a point to the grid:\n grid3d += addAtPos(np.zeros((res, res, res)), mag * kernel, pos - 2*h + 1)\n\n axis3 = 3 - axis2 - axis1\n grid = np.sum(grid3d, axis=axis3)\n grid = np.transpose(grid)\n print('Finished!!!!!!!!!!!!!')\n return grid\n\n\n################################################################################################\n################################################################################################\n\n\ndef V_i_grid(snap, subh, component, axis1, axis2, length, res, i):\n \"\"\"\n Returns a res*res 2darray with the mean velocity in the i direction (0 is x, 1 is y and 2 is z) for the desired matter component (0 for gas, 1 for DM, 4 for stars)\n \"\"\"\n hubble0 = snap.header.hubble0[0]\n if component == 0:\n \tind = np.concatenate([match(subh.ids, snap['ID '][0]), match(subh.ids + 2**31, snap['ID '][0])])\n else:\n \tind = match(subh.ids, snap['ID '][component])\n ind = ind[ind != -1]\n\n CM = subh.pot_min\n\n # We rotate the positions so that the galactic angular momentum is parallel to the z axis:\n positions = (snap['POS '][component][ind] - CM) / hubble0\n\n rot_matrix = PCA_matrix(snap, subh)\n positions = np.dot(positions, rot_matrix)\n\n pos_1 = positions[:, axis1]\n pos_2 = positions[:, axis2]\n # We rotate the velocities:\n vel = snap['VEL '][component][ind] - Vcm(snap, subh)\n vel = np.dot(vel, rot_matrix)\n # and take the i-th component:\n v_i = vel[:, i]\n hist = np.histogram2d(pos_1, pos_2, bins=res, range=[[-length/2, length/2], [-length/2, length/2]], weights=v_i)\n return hist[0]\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":14317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"10471611","text":"from collections import deque\nimport numpy as np\nimport random\n\nLAYERS = 4\nINSANE_MUTATIONS = False\nCELL_FUNCTIONS = [\n lambda x: x,\n lambda x: (x*2)**3,\n lambda x: 1/(10*x+1) if x >= 0 else 1/(10*x-1),\n]\n\nclass Neuron(object):\n def __init__(self):\n self.name = \"\"\n self.signal = 0\n# self.factor = random.random() * 10 - 5\n self.factor = 1\n self.rating = 1\n\n self.function = random.choice(CELL_FUNCTIONS)\n\n def set_inputs(self, inputs):\n # should be a tuple of (connection-strength, neuron, signal) items\n self.inputs = inputs\n\n def copy(self):\n result = Neuron()\n result.signal = self.signal\n result.rating = self.rating\n result.factor = self.factor\n\n def calculate(self):\n cumulative = 0\n count = 0\n for strength, neuron, signal in self.inputs:\n if signal and strength:\n cumulative += signal * strength\n count += 1\n if count:\n self.signal = cumulative / count * self.factor\n else:\n self.signal = 0\n\n def connect(self, neuron, strength):\n neuron.inputs.add((self, strength))\n self.outputs.add(neuron)\n\n def __repr__(self):\n return \"<%s signal=%f>\" % (self.name, self.signal)\n\n\nclass Sensor(Neuron):\n def __init__(self, name, function):\n Neuron.__init__(self)\n self.name = name\n self.sensor_function = function\n\n def calculate(self):\n self.signal = self.sensor_function()\n\n def copy(self):\n raise NotImplemented()\n\n\nclass Actuator(Neuron):\n def __init__(self, name, function):\n Neuron.__init__(self)\n self.name = name\n self.actuator_function = function\n\n def calculate(self):\n Neuron.calculate(self)\n self.actuator_function(self.signal)\n\n def copy(self):\n raise NotImplemented()\n\n\nclass NeuronCluster(object):\n def __init__(self, count, sensors, actuators):\n self.currentNeuron = 0\n self.sensors = [Sensor(name, function) \\\n for name, function in sensors]\n self.actuators = [Actuator(name, function) \\\n for name, function in actuators]\n self.neurons = [Neuron() for i in range(count)]\n self.sinks = self.actuators + self.neurons\n self.sources = self.sensors + self.neurons\n\n xpad = len(self.sensors)\n ypad = len(self.actuators)\n\n self.width = len(self.sources)\n self.height = len(self.sinks)\n\n perLayer = count // LAYERS\n self.connections = np.zeros([self.height, self.width])\n\n # Connect neurons in layers\n for layer in range(LAYERS):\n yStep = perLayer\n yStart = ypad + perLayer * layer\n yEnd = yStart + yStep\n xStep = (xpad if layer == 0 else perLayer)\n xStart = 0 if layer == 0 else xpad + (layer - 1) * perLayer\n xEnd = xStart + xStep\n self.connections[yStart:yEnd, xStart:xEnd] = np.random.rand(yStep, xStep)\n self.connections[0:ypad, xpad+(LAYERS-1)*perLayer:xpad+LAYERS*perLayer] = np.random.rand(ypad, perLayer)\n\n for y in range(self.connections.shape[0]):\n for x in range(self.connections.shape[1]):\n if self.connections[y][x]:\n self.connections[y][x] = self.connections[y][x] * 2 - 1\n\n# print(\"\")\n# print(self.connections)\n\n #self.connections[0:ypad, 0:xpad] = np.zeros([ypad, xpad])\n #for i in range(len(self.neurons)):\n #self.connections[ypad + i][xpad + i] = 0\n\n # Set random factors\n# for i in range(len(self.neurons)):\n# self.connections[ypad + i][xpad + i] = random.random() * 2 - 1\n\n def copy(self, neuronCluster):\n self.connections = neuronCluster.connections.copy()\n for this, other in zip(self.neurons, neuronCluster.neurons):\n this.function = other.function\n\n def sense(self):\n for i, sensor in enumerate(self.sensors):\n sensor.calculate()\n\n def step(self):\n i = self.currentNeuron\n neuron = self.sinks[i]\n# for i, neuron in enumerate(self.sinks):\n# neuron.set_inputs(tuple(zip(self.connections[i], self.sources,\n# [neuron.signal for neuron in self.sources])))\n neuron.set_inputs(tuple(zip(self.connections[i], self.sources,\n [neuron.signal for neuron in self.sources])))\n\n# xpad = len(self.sensors)\n# ypad = len(self.actuators)\n\n# for i, neuron in enumerate(self.neurons):\n# neuron.factor = self.connections[ypad + i][xpad + i]\n\n neuron.calculate()\n# for neuron in self.sinks:\n# neuron.calculate()\n\n self.currentNeuron = (self.currentNeuron + 1) % len(self.sinks)\n\n def mutate(self):\n for _ in range(20):\n y = random.randint(0, self.connections.shape[0] - 1)\n x = random.randint(0, self.connections.shape[1] - 1)\n if INSANE_MUTATIONS or self.connections[y][x]:\n self.connections[y][x] = random.random()\n break\n","sub_path":"cell.py","file_name":"cell.py","file_ext":"py","file_size_in_byte":5163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"386933329","text":"\"\"\"\nTesting for Extreme Learning Machine module (pyrcn.extreme_learning_machine)\n\"\"\"\nimport scipy\nimport numpy as np\n\nimport pytest\n\nfrom sklearn.datasets import load_iris, load_digits\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\n\nfrom pyrcn.base import InputToNode\nfrom pyrcn.linear_model import IncrementalRegression\nfrom pyrcn.extreme_learning_machine import ELMClassifier, ELMRegressor\n\n\nX_iris, y_iris = load_iris(return_X_y=True)\n\n\ndef test_elm_regressor_jobs():\n print('\\ntest_elm_regressor_jobs():')\n X = np.linspace(0, 10, 2000)\n y = np.hstack((np.sin(X).reshape(-1, 1), np.cos(X).reshape(-1, 1)))\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=10, random_state=42)\n param_grid = {\n 'input_to_node': [\n [('default', InputToNode(bias_scaling=10., hidden_layer_size=20, random_state=42))],\n [('default', InputToNode(bias_scaling=10., hidden_layer_size=50, random_state=42))]],\n 'regressor': [\n IncrementalRegression(alpha=.0001),\n IncrementalRegression(alpha=.01)],\n 'random_state': [42]\n }\n elm = GridSearchCV(ELMRegressor(), param_grid)\n elm.fit(X_train.reshape(-1, 1), y_train, n_jobs=2)\n y_elm = elm.predict(X_test.reshape(-1, 1))\n print(\"tests - elm:\\n sin | cos \\n {0}\".format(y_test-y_elm))\n print(\"best_params_: \".format(elm.best_params_))\n print(\"best_score: \".format(elm.best_score_))\n np.testing.assert_allclose(y_test, y_elm, atol=1e-1)\n\n\ndef test_elm_regressor_chunk():\n print('\\ntest_elm_regressor_chunk():')\n X = np.linspace(0, 10, 2000)\n y = np.hstack((np.sin(X).reshape(-1, 1), np.cos(X).reshape(-1, 1)))\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=10, random_state=42)\n param_grid = {\n 'input_to_node__hidden_layer_size': [20, 50],\n 'input_to_node__input_scaling': [1.],\n 'input_to_node__bias_scaling': [10.],\n 'input_to_node__activation': ['tanh'],\n 'input_to_node__random_state': [42],\n 'chunk_size': [500],\n 'regressor__alpha': [1e-2, 1e-5],\n 'random_state': [42]\n }\n elm = GridSearchCV(ELMRegressor(), param_grid)\n elm.fit(X_train.reshape(-1, 1), y_train, n_jobs=2)\n y_elm = elm.predict(X_test.reshape(-1, 1))\n print(\"tests - elm:\\n sin | cos \\n {0}\".format(y_test-y_elm))\n print(\"best_params_: \".format(elm.best_params_))\n print(\"best_score: \".format(elm.best_score_))\n np.testing.assert_allclose(y_test, y_elm, atol=1e-1)\n\n\ndef test_iris_ensemble_iterative_regression():\n print('\\ntest_iris_ensemble_iterative_regression():')\n X_train, X_test, y_train, y_test = train_test_split(X_iris, y_iris, test_size=5, random_state=42)\n cls = ELMClassifier(\n input_to_node=[\n ('tanh', InputToNode(hidden_layer_size=10, random_state=42, activation='tanh')),\n ('bounded_relu', InputToNode(hidden_layer_size=10, random_state=42, activation='bounded_relu'))],\n regressor=IncrementalRegression(alpha=.01),\n random_state=42)\n\n for samples in np.split(np.arange(0, X_train.shape[0]), 5):\n cls.partial_fit(X_train[samples, :], y_train[samples], classes=np.arange(3, dtype=int))\n y_predicted = cls.predict(X_test)\n\n for record in range(len(y_test)):\n print('predicted: {0} \\ttrue: {1}'.format(y_predicted[record], y_test[record]))\n\n print('score: {0}'.format(cls.score(X_test, y_test)))\n print('proba: {0}'.format(cls.predict_proba(X_test)))\n print('log_proba: {0}'.format(cls.predict_log_proba(X_test)))\n assert cls.score(X_test, y_test) >= 4./5.\n\n\nif __name__ == \"__main__\":\n test_elm_regressor_jobs()\n test_elm_regressor_chunk()\n test_iris_ensemble_iterative_regression()\n","sub_path":"pyrcn/extreme_learning_machine/tests/test_elm.py","file_name":"test_elm.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"581530034","text":"from EmergencyGame.models import Option, Role, Task\n\nr1 = Role(role_name=\"Room coordinator\")\nr1.save()\nr2 = Role(role_name=\"People's safety\")\nr2.save()\n\no1 = Option(option_text=\"Yes\")\no1.save()\no2 = Option(option_text=\"No\")\no2.save()\no3 = Option(option_text=\"Maybe\")\no3.save()\no4 = Option(option_text=\"Only if it is really dirty\")\no4.save()\no5 = Option(option_text=\"Run\")\no5.save()\no6 = Option(option_text=\"Walk\")\no6.save()\no7 = Option(option_text=\"Skipping\")\no7.save()\no8 = Option(option_text=\"The classroom next door \")\no8.save()\no9 = Option(option_text=\"Home\")\no9.save()\no10 = Option(option_text=\"To designated area for emergencies outside\")\no10.save()\no11 = Option(option_text=\"110\")\no11.save()\no12 = Option(option_text=\"112\")\no12.save()\no13 = Option(option_text=\"113\")\no13.save()\no14 = Option(option_text=\"Open\")\no14.save()\no15 = Option(option_text=\"Closed\")\no15.save()\no16 = Option(option_text=\"Open and go through\")\no16.save()\no17 = Option(option_text=\"Keep closed and find another exit\")\no17.save()\no18 = Option(option_text=\"Try to cool it down\")\no18.save()\no19 = Option(option_text=\"crawl out of the building\")\no19.save()\no20 = Option(option_text=\"Run to the nearest exit\")\no20.save()\no21 = Option(option_text=\"Hold your breath and keep walking\")\no21.save()\no22 = Option(option_text=\"..put books in alphabetical order\")\no22.save()\no23 = Option(option_text=\"..find a book to take home\")\no23.save()\no24 = Option(option_text=\"..just leave\")\no24.save()\no25 = Option(option_text=\"Only if really valuable\")\no25.save()\n\n\nt1 = Task(role=r1, description=\"Keep the windows open or closed?\", max_score=100, correct_option=o15)\nt1.save()\nt1.options.add(o14)\nt1.options.add(o15)\nt2 = Task(role=r1, description=\"Clean the board now?\", max_score=100, correct_option=o2)\nt2.save()\nt2.options.add(o1)\nt2.options.add(o2)\nt2.options.add(o4)\nt3 = Task(role=r2, description=\"In what manner should the children leave the room?\", max_score=100, correct_option=o6)\nt3.save()\nt3.options.add(o6)\nt3.options.add(o5)\nt3.options.add(o7)\nt4 = Task(role=r1, description=\"Do you take your things with you?\", max_score=100, correct_option=o2)\nt4.save()\nt4.options.add(o1)\nt4.options.add(o2)\nt4.options.add(o25)\nt5 = Task(role=r2, description=\"Where do you go when you leave the classroom?\", max_score=100, correct_option=o10)\nt5.save()\nt5.options.add(o8)\nt5.options.add(o9)\nt5.options.add(o10)\nt6 = Task(role=r1, description=\"Which number do you call when a fire occurs?\", max_score=100, correct_option=o11)\nt6.save()\nt6.options.add(o11)\nt6.options.add(o12)\nt6.options.add(o13)\nt7 = Task(role=r2, description=\"What do you do if you meet a closed door that is warm?\", max_score=100, correct_option=o17)\nt7.save()\nt7.options.add(o16)\nt7.options.add(o17)\nt7.options.add(o18)\nt8 = Task(role=r2, description=\"If there is smoke in the room, what do you do?\", max_score=100, correct_option=o19)\nt8.save()\nt8.options.add(o19)\nt8.options.add(o20)\nt8.options.add(o21)\nt9 = Task(role=r1, description=\"Finish your homework before reacting to the fire alarm?\", max_score=100, correct_option=o2)\nt9.save()\nt9.options.add(o1)\nt9.options.add(o2)\nt10 = Task(role=r1, description=\"Should you..?\", max_score=100, correct_option=o24)\nt10.save()\nt10.options.add(o22)\nt10.options.add(o23)\nt10.options.add(o24)\nt11 = Task(role=r2, description=\"Close the window?\", max_score=100, correct_option=o1)\nt11.save()\nt11.options.add(o1)\nt11.options.add(o2)\nt11.options.add(o16)\n","sub_path":"DjangoApp/populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"651115972","text":"import time\nimport threading\nfrom queue import Queue\nimport re\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\n# from sys import argv\n\nimport pyperclip\nimport gallery_get\n\n\ndef is_imagefap(url):\n if url.startswith(\"https://www.imagefap.com\"):\n print(\"Found url: %s\" % str(url))\n return True\n return False\n\n\nDOWNLOAD_QUEUE = Queue()\nEXTRACTION_QUEUE = Queue()\n\n\ndef sort_url(url):\n if bool(re.match(\"(?s)^https://www.imagefap.com/pictures/[0-9]+/.*\", url)):\n DOWNLOAD_QUEUE.put(url)\n if bool(re.match(\"(?s)^https://www.imagefap.com/(?:profile|organizer)/[0-9]+/.*\", url)):\n EXTRACTION_QUEUE.put(url)\n\n\nclass ClipboardWatcher(threading.Thread):\n def __init__(self, predicate, callback, pause=5.):\n super(ClipboardWatcher, self).__init__()\n self._predicate = predicate\n self._callback = callback\n self._pause = pause\n self._stopping = False\n\n def run(self):\n recent_value = \"\"\n\n while not self._stopping:\n tmp_value = pyperclip.paste()\n if tmp_value != recent_value:\n recent_value = tmp_value\n\n for url in recent_value.splitlines():\n if self._predicate(url):\n self._callback(url)\n time.sleep(self._pause)\n\n def stop(self):\n self._stopping = True\n\n\nclass LinkExtractor(threading.Thread):\n def __init__(self, pause=5.):\n super().__init__()\n self._stopping = False\n self._pause = pause\n\n @staticmethod\n def get_links(url):\n html_page = urlopen(url)\n soup = BeautifulSoup(html_page, features=\"lxml\")\n links = []\n\n for link in soup.findAll('a', attrs={'href': re.compile(\"^/gallery\")}):\n links.append(\"https://www.imagefap.com\" + link.get('href'))\n\n return links\n\n def run(self):\n while not self._stopping:\n for gallery_url in self.get_links(EXTRACTION_QUEUE.get()):\n DOWNLOAD_QUEUE.put(gallery_url)\n time.sleep(self._pause)\n\n def stop(self):\n self._stopping = True\n\n\nclass Downloader(threading.Thread):\n def __init__(self, location, pause=5.):\n super().__init__()\n self._stopping = False\n self._pause = pause\n self._location = location\n\n def run(self):\n while not self._stopping:\n try:\n gallery_url = DOWNLOAD_QUEUE.get()\n print(\"Downloading \" + gallery_url)\n gallery_get.run(gallery_url, self._location)\n except Exception as e:\n print(e)\n time.sleep(self._pause)\n\n def stop(self):\n self._stopping = True\n\n\ndef main():\n # download_location = argv[1]\n download_location = \"V:\\\\imagefap\\\\test\"\n\n downloader = Downloader(download_location, 5)\n extractor = LinkExtractor(5)\n watcher = ClipboardWatcher(\n is_imagefap,\n sort_url,\n 3.\n )\n\n downloader.start()\n extractor.start()\n watcher.start()\n\n while True:\n try:\n # print(\"Waiting for changed clipboard...\")\n time.sleep(3)\n except KeyboardInterrupt:\n watcher.stop()\n extractor.stop()\n downloader.stop()\n break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"429134069","text":"import aiohttp\nimport discord\nfrom discord.ext import commands\n\nclass Bus(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.session = aiohttp.ClientSession(loop=self.bot.loop)\n\n def cog_unload(self):\n self.bot.loop.create_task(self.session.detach())\n\n async def httpget(self, url):\n async with self.session.get(url) as response:\n return await response.json()\n\n @commands.command(aliases=[\"bus\", \"stop\"])\n async def realtime(self, message, stopnumber: int):\n body = await self.httpget(\n f\"https://data.smartdublin.ie/cgi-bin/rtpi/realtimebusinformation?stopid={stopnumber}&format=json\"\n )\n error = body[\"errormessage\"]\n response = body[\"results\"]\n departure_data = []\n\n if not error:\n for bus in response:\n departure_data.append(f\"*{bus['route']}* to {bus['destination']} - in **{bus['duetime']}** min(s). \\n\")\n\n InfoEmbed = discord.Embed(\n colour=0x36393e,\n title=f\"Departues for stop: {stopnumber}\",\n description=\"\\n\".join(departure_data),\n )\n await message.send(embed=InfoEmbed)\n else:\n await message.send(error)\n\n\ndef setup(bot):\n bot.add_cog(Bus(bot))","sub_path":"commands/bus.py","file_name":"bus.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"364408221","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nimport sys\nsys.path.append('../')\nfrom package import data as datagen\n\ndef load_train_images():\n (train_data, val_data, test_data) = datagen.get_data_web([6,7], 0, [8,8], 2, sample_size=1000)\n \n (train_images, train_labels) = train_data\n train_images = np.reshape(train_images, [1000, 1, 8, 8])\n train_images = torch.from_numpy(train_images).to(dtype=torch.float32)\n train_labels = torch.from_numpy(train_labels).to(dtype=torch.int64)\n \n (test_images, test_labels) = test_data\n test_images = np.reshape(test_images, [1000, 1, 8, 8])\n test_images = torch.from_numpy(test_images).to(dtype=torch.float32)\n test_labels = torch.from_numpy(test_labels).to(dtype=torch.int64)\n \n return (train_images, train_labels, test_images, test_labels)\n \nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 20, kernel_size=2)\n self.bn1 = nn.BatchNorm2d(20)\n self.conv1_drop = nn.Dropout2d()\n self.conv2 = nn.Conv2d(20, 40, kernel_size=2)\n self.bn2 = nn.BatchNorm2d(40)\n self.conv2_drop = nn.Dropout2d()\n self.conv3 = nn.Conv2d(40, 80, kernel_size=2) \n self.bn3 = nn.BatchNorm2d(80)\n self.conv3_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(320, 80)\n self.fc2 = nn.Linear(80, 10)\n self.fc3 = nn.Linear(10, 2)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x): #[samp, 1, 8, 8]\n x = self.conv1(x) #[samp, 20, 7, 7]\n self.bn1(x)\n self.conv1_drop(x)\n x = self.conv2(x) #[samp, 40, 6, 6]\n self.bn2(x)\n self.conv2_drop(x)\n x = F.relu(F.max_pool2d(x, 2)) #[samp, 80, 3, 3]\n x = self.conv3(x) #[samp, 80, 2, 2]\n self.bn3(x)\n self.conv3_drop(x) #[samp, 80, 2, 2]\n x = F.relu(x)\n x = x.view(-1, 320) #[samp, 320]\n x = self.fc1(x) #[samp, 80]\n x = F.dropout(x, training=self.training)\n x = F.relu(self.fc2(x)) #[samp, 10]\n x = F.dropout(x, training=self.training)\n x = self.fc3(x) #[samp, 2]\n x = self.sigmoid(x)\n return x\n\ndef train(network, optimizer, train_images, train_labels):\n network.train()\n batch_idx = 0\n batch_iter_train = datagen.batch_generator(train_images, train_labels, 100)\n for (data, target) in batch_iter_train:\n batch_idx += 1\n optimizer.zero_grad()\n output = network(data)\n loss = ((output - target)**2).mean()\n loss.backward()\n optimizer.step()\n \ndef test(network, test_images, test_labels):\n network.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n batch_iter_test = datagen.batch_generator(test_images, test_labels, 1000)\n for data, target in batch_iter_test:\n output = network(data)\n test_loss += ((output - target)**2).mean()\n correct += get_accuracy(output, target)\n\n return correct\n\ndef get_accuracy(output, target):\n output_index = np.argmax(output, axis=1)\n target_index = np.argmax(target, axis=1)\n compare = output_index - target_index\n compare = compare.numpy()\n num_correct = float(np.sum(compare == 0))\n total = float(output_index.shape[0])\n accuracy = num_correct / total\n return accuracy\n\ndef main():\n (train_images, train_labels, test_images, test_labels) = load_train_images()\n network = Net()\n optimizer = optim.Adam(network.parameters())\n \n print('Test Accuracy: %.3f'%test(network, test_images, test_labels))\n for epoch in range(1, 101):\n print('Epoch: %s'%epoch)\n train(network, optimizer, train_images, train_labels)\n print('Test Accuracy: %.3f'%test(network, test_images, test_labels))\n \n torch.save(network.state_dict(), '../trained_models/samp1000_size8_dig67.pth')\n print('Model saved')\n \nif __name__ == \"__main__\":\n main()","sub_path":"package/train_cnn_size8.py","file_name":"train_cnn_size8.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"98628304","text":"from django.shortcuts import get_object_or_404\nfrom products.models import Product\n\n\ndef get_cart_items_and_total(cart):\n total = 0\n cart_items = []\n for product_id, quantity in cart.items():\n product = get_object_or_404(Product, pk=product_id)\n item_total = quantity * product.bruto_price\n total += item_total\n cart_items.append({'product':product, 'quantity': quantity, 'total': item_total}) \n \n \n return {'cart_items' : cart_items, 'total': total}","sub_path":"cart/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"260135602","text":"#\n# API ROUTES\n#\n\nfrom flask import redirect, jsonify, request\n\nimport storage\n\nfrom main import app\nfrom main import verify_login\n\n@app.route(\"/content/\")\n@app.route(\"/content/\")\ndef get_content(search=None):\n response = verify_login(request)\n if response:\n return response\n items = storage.get_notes(search)\n data = { \"data\": items }\n return jsonify(data)\n\n@app.route(\"/remove/\")\ndef get_remove(id):\n response = verify_login(request)\n if response:\n return response\n storage.delete_note(id)\n return redirect(\"/notes\")\n","sub_path":"api_routes.py","file_name":"api_routes.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"208759228","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"ROS2 Twist to Jetbot Move.\n\nThis script subscribes to \"/cmd_vel\" topic, reads Twist message, and moves the\nJetbot.\n\nRevision History:\n 2021-08-18 (Animesh): Baseline Software.\n\nExample:\n $ colcon build && source install/setup.bash && ros2 run ros2_twist_message_to_robot_motion execute\n $ source install/setup.bash && ros2 run ros2_twist_message_to_robot_motion execute\n $ ros2 run ros2_twist_message_to_robot_motion execute\n\n\"\"\"\n\n\n#___Import Modules:\n\nimport atexit\nfrom Adafruit_MotorHAT import Adafruit_MotorHAT\nimport traitlets\nfrom traitlets.config.configurable import Configurable, SingletonConfigurable\n\nimport rclpy\nfrom rclpy.node import Node\nfrom geometry_msgs.msg import Twist\n\n\n#___Global Variables:\nSUBSCRIBE_TOPIC = '/cmd_vel'\nXCAL = 0.50 #Calibration X\nZCAL = 0.25 #Calibration Z\n\n\n#__Classes\nclass Twist_to_Motion(Node):\n \"\"\"TWIST to Jetbot Move Class.\n \n This class contains all methods to read TWIST message and move the Jetbot. \n \n \"\"\"\n\n def __init__(self):\n \n super().__init__('twist_to_motion')\n \n # initialize robot\n self.robot = Robot()\n \n # initialize subscriber\n self.subscription = self.create_subscription(\n Twist,\n SUBSCRIBE_TOPIC,\n self.listener_callback,\n 10)\n self.subscription # prevent unused variable warning\n\n\n def listener_callback(self, msg):\n \n # parses data from subscribed topic message\n x = XCAL*float(msg.linear.x)\n z = ZCAL*float(msg.angular.z)\n \n # control robot movement\n # both wheel same state\n if z == 0:\n # total stop\n if x == 0:\n self.robot.stop()\n else:\n self.robot.set_motors(-x, -x)\n \n # one wheel moving\n if x == 0:\n # rotate right\n if z > 0:\n self.robot.set_motors(0, -z)\n # rotate left\n elif z < 0:\n self.robot.set_motors(-z, 0)\n \n # moving forward\n elif x > 0:\n # rotate right\n if z > 0:\n self.robot.set_motors(-x/2, -(x+z)/2)\n # rotate left\n elif z < 0:\n self.robot.set_motors(-(x-z)/2, -x/2)\n \n # moving backward\n elif x < 0:\n # rotate right\n if z > 0:\n self.robot.set_motors(-x/2, -(x-z)/2)\n # rotate left\n elif z < 0:\n self.robot.set_motors(-(x+z)/2, -x/2)\n\n\n\n# Jetbot Motor Driver Classes From NVIDIA-AI-IOT\n# Ref: https://github.com/NVIDIA-AI-IOT/jetbot/blob/master/jetbot/motor.py\nclass Motor(Configurable):\n\n value = traitlets.Float()\n \n # config\n alpha = traitlets.Float(default_value=1.0).tag(config=True)\n beta = traitlets.Float(default_value=0.0).tag(config=True)\n\n def __init__(self, driver, channel, *args, **kwargs):\n super(Motor, self).__init__(*args, **kwargs) # initializes traitlets\n\n self._driver = driver\n self._motor = self._driver.getMotor(channel)\n if(channel == 1):\n self._ina = 1\n self._inb = 0\n else:\n self._ina = 2\n self._inb = 3\n atexit.register(self._release)\n \n @traitlets.observe('value')\n def _observe_value(self, change):\n self._write_value(change['new'])\n\n def _write_value(self, value):\n \"\"\"Sets motor value between [-1, 1]\"\"\"\n mapped_value = int(255.0 * (self.alpha * value + self.beta))\n speed = min(max(abs(mapped_value), 0), 255)\n self._motor.setSpeed(speed)\n if mapped_value < 0:\n self._motor.run(Adafruit_MotorHAT.FORWARD)\n # The two lines below are required for the Waveshare JetBot Board only\n self._driver._pwm.setPWM(self._ina,0,0)\n self._driver._pwm.setPWM(self._inb,0,speed*16)\n else:\n self._motor.run(Adafruit_MotorHAT.BACKWARD)\n # The two lines below are required for the Waveshare JetBot Board only\n self._driver._pwm.setPWM(self._ina,0,speed*16)\n self._driver._pwm.setPWM(self._inb,0,0)\n\n def _release(self):\n \"\"\"Stops motor by releasing control\"\"\"\n self._motor.run(Adafruit_MotorHAT.RELEASE)\n # The two lines below are required for the Waveshare JetBot Board only\n self._driver._pwm.setPWM(self._ina,0,0)\n self._driver._pwm.setPWM(self._inb,0,0)\n\n\n# Jetbot Robot Driver Classes From NVIDIA-AI-IOT\n# Ref: https://github.com/NVIDIA-AI-IOT/jetbot/blob/master/jetbot/robot.py\nclass Robot(SingletonConfigurable):\n \n left_motor = traitlets.Instance(Motor)\n right_motor = traitlets.Instance(Motor)\n\n # config\n i2c_bus = traitlets.Integer(default_value=1).tag(config=True)\n left_motor_channel = traitlets.Integer(default_value=1).tag(config=True)\n left_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True)\n right_motor_channel = traitlets.Integer(default_value=2).tag(config=True)\n right_motor_alpha = traitlets.Float(default_value=1.0).tag(config=True)\n \n def __init__(self, *args, **kwargs):\n super(Robot, self).__init__(*args, **kwargs)\n self.motor_driver = Adafruit_MotorHAT(i2c_bus=self.i2c_bus)\n self.left_motor = Motor(self.motor_driver, channel=self.left_motor_channel, alpha=self.left_motor_alpha)\n self.right_motor = Motor(self.motor_driver, channel=self.right_motor_channel, alpha=self.right_motor_alpha)\n \n def set_motors(self, left_speed, right_speed):\n self.left_motor.value = left_speed\n self.right_motor.value = right_speed\n \n def forward(self, speed=1.0, duration=None):\n self.left_motor.value = speed\n self.right_motor.value = speed\n\n def backward(self, speed=1.0):\n self.left_motor.value = -speed\n self.right_motor.value = -speed\n\n def left(self, speed=1.0):\n self.left_motor.value = -speed\n self.right_motor.value = speed\n\n def right(self, speed=1.0):\n self.left_motor.value = speed\n self.right_motor.value = -speed\n\n def stop(self):\n self.left_motor.value = 0\n self.right_motor.value = 0\n\n\n#___Main Method:\ndef main(args=None):\n rclpy.init(args=args)\n\n twist_to_motion = Twist_to_Motion()\n\n rclpy.spin(twist_to_motion)\n\n # Destroy the node explicitly\n # (optional - otherwise it will be done automatically\n # when the garbage collector destroys the node object)\n twist_to_motion.destroy_node()\n rclpy.shutdown()\n\n\n#___Driver Program:\nif __name__ == '__main__':\n main()\n\n\n# \n# end of file\n\"\"\"ANI717\"\"\"\n","sub_path":"robot_ws/src/ros2-twist-message-to-robot-motion/ros2_twist_message_to_robot_motion/jetbot_motion.py","file_name":"jetbot_motion.py","file_ext":"py","file_size_in_byte":6825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"636497890","text":"import pyperclip\nimport unittest\nfrom contact import Contact\n\n\nclass TestContact(unittest.TestCase):\n\n '''\n Test class that defines test cases for the contact class behaviours\n\n Args:\n unittest.TestCase: Testcase class that helps in creating test cases\n\n '''\n\n def setUp(self):\n '''\n Set up method to run before each test cases.\n '''\n self.new_contact = Contact(\"Irene\", \"Adler\", \"98378973\", \"iadler@gmail.com\")\n\n def test_init(self):\n '''\n test_init test case to test if the object is initialized properly\n '''\n\n self.assertEqual(self.new_contact.first_name, \"Irene\")\n self.assertEqual(self.new_contact.last_name, \"Adler\")\n self.assertEqual(self.new_contact.phone_number, \"98378973\")\n self.assertEqual(self.new_contact.email, \"iadler@gmail.com\")\n\n def test_save_contact(self):\n '''\n test_save_contact test case to test if the contact object is saved into\n the contact list\n '''\n self.new_contact.save_contact()\n self.assertEqual(len(Contact.contact_list), 1)\n\n def tearDown(self):\n '''\n tearDown method that does cleanup after each test case has run.\n '''\n Contact.contact_list = []\n\n def test_save_multiple_contact(self):\n '''\n test_save_multiple to check if we can save multiple contact\n objects to our contact_list\n '''\n self.new_contact.save_contact()\n test_contact = Contact(\n \"Irene\", \"Adler\", \"98378973\", \"iadler@gmail.com\")\n test_contact.save_contact()\n self.assertEqual(len(Contact.contact_list), 2)\n\n def test_delete_contact(self):\n '''\n test_delete_contact to test if we can remove a contact from our contact list\n '''\n self.new_contact.save_contact()\n test_contact = Contact(\n \"Irene\", \"Adler\", \"98378973\", \"iadler@gmail.com\")\n test_contact.save_contact()\n\n self.new_contact.delete_contact()\n\n self.assertEqual(len(Contact.contact_list), 1)\n\n def test_find_contact_by_number(self):\n '''\n test to check if we can find a contact by phone number and display information\n '''\n\n self.new_contact.save_contact()\n test_contact = Contact(\n \"Irene\", \"Adler\", \"98378973\", \"iadler@gmail.com\")\n test_contact.save_contact()\n\n found_contact = Contact.find_by_number(\"98378973\")\n\n self.assertEqual(found_contact.email, test_contact.email)\n\n def test_contact_exists(self):\n '''\n test to check if we can return a Boolean if we cannot find the contact.\n '''\n\n self.new_contact.save_contact()\n test_contact = Contact(\n \"Irene\", \"Adler\", \"98378973\", \"iadler@gmail.com\")\n test_contact.save_contact()\n\n contact_exists = Contact.contact_exists(\"98378973\")\n\n self.assertTrue(contact_exists)\n\n def test_display_all_contacts(self):\n '''\n method that returns a list of all contacts saved\n '''\n\n self.assertEqual(Contact.display_contacts(), Contact.contact_list)\n\n def test_copy_email(self):\n '''\n Test to confirm thet we are copying the email address from a found contact\n '''\n\n self.new_contact.save_contact()\n Contact.copy_email(\"98378973\")\n\n self.assertEqual(self.new_contact.email,pyperclip.paste())\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"contact_test.py","file_name":"contact_test.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"555256301","text":"import numpy as np\nimport pandas as pd\n\nfrom scipy.stats import f_oneway\n\nfrom tqdm import tqdm\n\nclass MABFramework(object):\n available_strategies = ['static-one-fits-all', 'dynamic-one-fits-all','contextual-one-fits-one']\n \n def __init__(self,strategy,n_actions,\n rstate=42,\n static_min_steps = 1,\n alphas=[],betas=[],\n modelling_approach=None,\n modelling_approach_pms=None\n ):\n if n_actions <= 0:\n raise ValueError('Invalid number of actions, it should be a positive number')\n elif strategy not in MABFramework.available_strategies:\n raise ValueError('Unrecognised MAB strategy, available strategies are {}'.format(MABFramework.available_strategies))\n elif (strategy=='dynamic-one-fits-all') and ((n_actions != len(alphas)) or (n_actions != len(betas))):\n raise ValueError('Cannot run a dynamic strategy without specified priors')\n elif (strategy=='contextual-one-fits-all') and ((modelling_approach is None) or (modelling_approach_pms is None)):\n raise ValueError('Cannot run a contextual strategy if a modelling approach and parameters are not provided') \n\n \n self.strategy = strategy\n self.n_actions = n_actions\n \n if self.strategy == 'static-one-fits-all':\n self.static_status = None\n self.static_min_steps = static_min_steps\n elif self.strategy == 'dynamic-one-fits-all':\n self.alphas = alphas\n self.betas = betas\n self.thompson_pms = pd.DataFrame(columns=['alphas','betas'])\n else: \n self.predictive_units = [modelling_approach(**modelling_approach_pms)]*self.n_actions\n \n self.current_data = pd.DataFrame()\n np.random.seed(rstate)\n \n def append_data(self, new_data_batch):\n \n if not len(self.current_data):\n self.current_data = pd.concat([self.current_data,new_data_batch])\n else:\n column_check = self.current_data.columns.intersection(new_data_batch.columns)\n if not len(column_check):\n raise ValueError('The new data batch has not the same column names as current data, stopping experiment')\n else:\n self.current_data = pd.concat([self.current_data,new_data_batch])\n \n def observe_rewards(self, new_data_batch, reward_columns):\n \n nrows=len(new_data_batch)\n new_data_batch['action_code'] = self.best_actions\n self.append_data(new_data_batch.drop(columns = reward_columns))\n \n def warm_up(self,incoming_data_batch):\n if self.strategy == 'static-one-fits-all':\n self.best_actions = np.random.choice(range(self.n_actions),size=len(incoming_data_batch))\n elif self.strategy == 'dynamic-one-fits-all':\n arms_average_rewards = np.random.beta(self.alphas,self.betas,[len(incoming_data_batch),self.n_actions])\n self.best_actions = np.argmax(arms_average_rewards,axis=1).tolist()\n elif self.strategy == 'contextual-one-fits-one':\n self.best_actions = np.random.choice(range(self.n_actions),size=len(incoming_data_batch))\n \n def apply_decision_policy(self, incoming_data_batch,step):\n \n if not(len(self.current_data)):\n self.warm_up(incoming_data_batch)\n else:\n if self.strategy == 'static-one-fits-all':\n if self.static_status != 'converged':\n self.static_one_fits_all('action_code','reward',incoming_data_batch,step)\n elif self.strategy == 'dynamic-one-fits-all':\n self.dynamic_one_fits_all('action_code','reward',incoming_data_batch,step)\n elif self.strategy == 'contextual-one-fits-one':\n self.contextual_one_fits_one('action_code','reward',incoming_data_batch,step)\n \n def static_one_fits_all(self, actions_column, reward_column, incoming_data_batch, step):\n \n n_choices = len(incoming_data_batch)\n \n grouped_dataset = self.current_data.groupby(by=[actions_column])[reward_column].agg([('n_trials','count'),('p','mean')])\n grouped_dataset['std_err'] = np.sqrt(grouped_dataset['p']*(1-grouped_dataset['p']))/np.sqrt(grouped_dataset['n_trials'])\n \n list_of_samples = []\n for idx in grouped_dataset.index:\n list_of_samples.append(np.random.normal(loc=grouped_dataset.loc[idx,'p'],scale=grouped_dataset.loc[idx,'std_err'],size=grouped_dataset.loc[idx,'n_trials']))\n \n pvalue = f_oneway(*list_of_samples)[1]\n if pvalue <= .05 and step>self.static_min_steps:\n self.static_status = 'converged'\n self.best_actions = [np.argmax(grouped_dataset['p'].values)]*n_choices\n \n def dynamic_one_fits_all(self, actions_column, reward_column, incoming_data_batch, step):\n \n n_choices = len(incoming_data_batch)\n \n grouped = self.current_data.groupby(by=[actions_column])[reward_column]\n self.alphas = grouped.sum().values.ravel()\n mask = self.alphas == 0.\n self.alphas[mask] = 1. \n self.betas = grouped.count().values.ravel()-self.alphas\n arms_average_rewards = np.random.beta(self.alphas,self.betas,[n_choices,self.n_actions])\n \n self.best_actions = np.argmax(arms_average_rewards,axis=1).tolist()\n self.thompson_pms.loc[step,'alphas'] = self.alphas\n self.thompson_pms.loc[step,'betas'] = self.betas\n \n def contextual_one_fits_one(self, actions_column, reward_column, incoming_data_batch, step):\n \n predictors = self.current_data.drop(columns=['reward','action_code']).columns\n sampled_probs = np.zeros([len(incoming_data_batch),self.n_actions])\n \n for action_id in range(self.n_actions):\n subset = self.current_data[self.current_data['action_code']==action_id]\n X = pd.get_dummies(subset[predictors],drop_first=True).values\n y = subset['reward'].values\n self.predictive_units[action_id].fit(X,y)\n \n X_in = pd.get_dummies(incoming_data_batch[predictors],drop_first=True).values\n predicted_probs = self.predictive_units[action_id].predict(X_in)\n sampling_indices = np.random.choice(range(predicted_probs.shape[1]),size=len(predicted_probs))\n sampled_probs[:,action_id] = np.array([predicted_probs[row,sampling_indices[row]] for row in range(predicted_probs.shape[0])])\n\n self.best_actions = np.argmax(sampled_probs,axis=1).tolist()\n \ndef run_experiment(experiment_data, batch_size, exp_class, exp_pms, return_exp_obj=False):\n \n n_steps = experiment_data.shape[0]//batch_size\n uneven = experiment_data.shape[0]%batch_size\n \n exp_obj = exp_class(**exp_pms)\n action_cols = [column for column in experiment_data.columns if 'action' in column]\n for step in tqdm(range(n_steps)):\n incoming_data = experiment_data[step*batch_size:(step+1)*batch_size].copy()\n exp_obj.apply_decision_policy(incoming_data,step)\n rewards = incoming_data[action_cols].values\n incoming_data['reward'] = [rewards[idx,exp_obj.best_actions[idx]] for idx in range(len(incoming_data))]\n incoming_data['action_code'] = exp_obj.best_actions\n exp_obj.append_data(incoming_data.drop(columns = action_cols))\n \n if uneven:\n incoming_data = experiment_data[(step+1)*batch_size:].copy()\n exp_obj.apply_decision_policy(incoming_data,step)\n rewards = incoming_data[action_cols].values\n incoming_data['reward'] = [rewards[idx,exp_obj.best_actions[idx]] for idx in range(len(incoming_data))]\n incoming_data['action_code'] = exp_obj.best_actions[:len(incoming_data)]\n exp_obj.append_data(incoming_data.drop(columns = action_cols))\n \n if return_exp_obj:\n return exp_obj\n else:\n return exp_obj.current_data['reward'].mean()","sub_path":"contextual_mab/experiments/framework.py","file_name":"framework.py","file_ext":"py","file_size_in_byte":8105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"149081797","text":"import datetime\nimport schema\nfrom collections import namedtuple, defaultdict\nfrom itertools import compress\nfrom dbmodel import Rss, Data, Tokenized, SQL_DB\n\nSQL_SCRIPT = 'db.sql'\nDbRow = namedtuple('DbRow', 'source_name title published data')\n\n\ndef create():\n \"\"\"Creates db from model and executes sql script to fill tables\"\"\"\n Rss.create_table()\n Data.create_table()\n Tokenized.create_table()\n with open(SQL_SCRIPT) as f:\n for line in f:\n SQL_DB.execute_sql(line.strip())\n\n\ndef get_feeds():\n \"\"\"Returns list of feeds\"\"\"\n return [i for i in Rss.select()]\n\n\ndef get_descriptions(date_point=None, date_range=None):\n \"\"\"Returns list of descriptions within given date range,\n from given date point\"\"\"\n if not date_point:\n date_point = datetime.datetime.now()\n if not date_range:\n date_range = datetime.timedelta(hours=12)\n dt = get_datetime(date_point, date_range)\n rows = Tokenized.select().join(Data).where(\n (Data.published <= date_point) &\n (Data.published >= dt)).order_by(Tokenized.data_id.desc())\n result = QueryResult('data_id', 'name', 'title', 'published', 'data')\n for row in rows:\n result.add_bunch(data_id=row.data_id.data_id,\n name=row.data_id.rss_id.name,\n title=row.data_id.title,\n published=row.data_id.published.isoformat(),\n data=schema.deserialize_plain(str(row.tokenized_plain)))\n return result\n\n\nclass QueryResult(object):\n\n def __init__(self, *args):\n self.keys = set(args)\n self.storage = defaultdict(list)\n self.processed = None\n\n def __nonzero__(self):\n return any(self.storage.itervalues())\n\n def __getitem__(self, key):\n return self.storage[key]\n\n def add(self, key, value):\n self.storage[key].append(value)\n\n def add_bunch(self, **kwargs):\n for key, val in kwargs.iteritems():\n self.add(key, val)\n\n def process(self, process_fun, **kwargs):\n return process_fun(self.storage['data'], **kwargs)\n\n def filter(self, data, mask_fun):\n mask = mask_fun(data)\n for key, val in self.storage.iteritems():\n self.storage[key] = [item for item in compress(val, mask)]\n tmp = data[mask, :]\n return tmp[:, mask]\n\n def __repr__(self):\n return \"\".format(self.keys)\n\n\ndef get_datetime(date_point=None, time_delta=None):\n if not date_point:\n date_point = datetime.datetime.now()\n if not time_delta:\n time_delta = datetime.timedelta(hours=36)\n return date_point - time_delta\n\n\ndef insert_data(data):\n new_row = Data()\n new_row.rss_id = data['rss_id']\n new_row.identifier = data['identifier']\n new_row.published = data['published']\n new_row.last_modified = datetime.datetime.now()\n new_row.description = data['description']\n new_row.description_hash = data['description_hash']\n new_row.title = data['title']\n new_row.link = data['link']\n new_row.save()\n return new_row.data_id\n\n\ndef update_data(row, data):\n row.published = data['published']\n row.last_modified = datetime.datetime.now()\n row.description = data['description']\n row.description_hash = data['description_hash']\n row.title = data['title']\n row.save()\n return row.data_id\n\n\ndef insert_update_tokenized(data):\n \"\"\"Inserts or updates tokenized data\"\"\"\n if Tokenized.select().where(\n Tokenized.data_id == data['data_id']).exists():\n row = Tokenized.get(\n Tokenized.data_id == data['data_id'])\n row.tokenized_count = data['tokenized_count']\n row.tokenized_plain = data['tokenized_plain']\n row.save()\n result = row.tokenized_id\n else:\n new_row = Tokenized()\n new_row.data_id = data['data_id']\n new_row.tokenized_count = data['tokenized_count']\n new_row.tokenized_plain = data['tokenized_plain']\n new_row.save()\n result = new_row.tokenized_id\n return result\n\n\ndef insert_update_data(data, cache_time_delta=None):\n \"\"\"Inserts new prased feed or updates existing parsed feed\"\"\"\n dt = get_datetime(time_delta=cache_time_delta)\n if Data.select().where(\n (Data.last_modified > dt) &\n (Data.identifier == data['identifier'])).exists():\n row = Data.get(\n (Data.last_modified > dt) &\n (Data.identifier == data['identifier']))\n result = update_data(row, data)\n elif Data.select().where(\n (Data.last_modified > dt) &\n (Data.rss_id == data['rss_id']) &\n (Data.description_hash == data['description_hash'])).exists():\n row = Data.get(\n (Data.last_modified > dt) &\n (Data.rss_id == data['rss_id']) &\n (Data.description_hash == data['description_hash']))\n result = update_data(row, data)\n else:\n result = insert_data(data)\n return result\n\n\ndef insert_update_feed(data):\n \"\"\"Updates existing feed data\"\"\"\n if Rss.select().where(Rss.rss_id == data['rss_id']).exists():\n row = Rss.get(Rss.rss_id == data['rss_id'])\n row.last_access = datetime.datetime.now()\n row.etag = data['etag']\n row.modified_parsed = data['modified_parsed']\n row.save()\n","sub_path":"rss/collector/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":5335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"45252494","text":"\"\"\"\nAt the core of a rating and of Nordic Credit Rating's business model is the\nissuer. This model defines an issuer, including meta data linked to the\nissuer.\n\"\"\"\nfrom django.contrib.auth.models import User\nfrom django.core.validators import RegexValidator, validate_email\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.utils import timezone\nfrom tinymce import HTMLField\n\nfrom a_helper.static_database_table.models.gics import GICSSubIndustry\nfrom datalake.gleif.command import GLEIFEditor\nfrom a_helper.other.sql import SQL\n\nfrom simple_history.models import HistoricalRecords\n\nALLOWED_ISSUER_TYPES = (\n (1, 'Corporate'),\n (2, 'Financial institution'),\n (3, 'Real estate corporate')\n)\n\n\nclass ProcessQuerySet(models.QuerySet):\n \"\"\"ProcessQuerySet class.\"\"\"\n\n def is_live(self):\n \"\"\"Return all decisions that have not been deleted.\"\"\"\n return self.filter(inactivated__isnull=True)\n\n def list_eligible_for_assessment(self):\n \"\"\"List all issuers that are eligible for getting a credit\n assessment.\"\"\"\n\n sql = '''\n SELECT i.id\n , i.legal_name\n FROM public.issuer_issuer as i\n WHERE i.issuer_type_id IN (1, 3)\n AND i.gics_sub_industry_id IS NOT NULL\n AND i.inactivated IS NULL\n AND i.id NOT IN (SELECT issuer_id\n FROM public.rating_process_ratingdecision)\n AND i.id NOT IN (SELECT issuer_id\n FROM public.credit_assessment_assessmentjob)\n ORDER BY i.legal_name\n ''' # noqa: E501\n\n return self.raw(sql)\n\n def list_all(self):\n \"\"\"Get all companies using an optimized query.\"\"\"\n\n sql = '''\n SELECT i.id\n , gs.name as sector_name\n , country.name as country\n , i.legal_name as legal_name\n , CASE WHEN it.description = 1 THEN 'Corporate'\n WHEN it.description = 2 THEN 'Financial'\n WHEN it.description = 3 THEN 'Real estate'\n END as issuer_type_name\n , t9.first_name || ' ' || t9.last_name as p_analyst\n , t10.first_name || ' ' || t10.last_name as s_analyst\n , au.first_name || ' ' || au.last_name as c_manager\n , decision.decided_lt as current_long_term\n , decision.decided_lt_outlook as current_outlook\n , CASE WHEN iob.date_time_onboarding_completed IS NULL THEN 'Not Onboarded'\n WHEN iob.date_time_onboarding_completed IS NOT NULL AND decision_ongoing.id IS NOT NULL THEN 'Rating job in progress'\n WHEN iob.date_time_onboarding_completed IS NOT NULL AND decision.id IS NOT NULL THEN 'Ongoing surveillance'\n WHEN iob.date_time_onboarding_completed IS NOT NULL AND decision_ongoing.id IS NULL THEN 'Onboarded'\n END AS status\n , CASE WHEN decision_ongoing.process_step = 1 THEN 'Rating job started'\n WHEN decision_ongoing.process_step = 2 THEN 'Pre-committee'\n WHEN decision_ongoing.process_step = 3 THEN 'Analytical phase'\n WHEN decision_ongoing.process_step = 4 THEN 'Post committee'\n WHEN decision_ongoing.process_step = 5 THEN 'Editing'\n WHEN decision_ongoing.process_step = 6 THEN 'Issuer confirmation'\n WHEN decision_ongoing.process_step = 7 THEN 'Analyst final approval'\n WHEN decision_ongoing.process_step = 8 THEN 'Chair final approval'\n WHEN decision_ongoing.process_step = 9 THEN 'Ready to be published'\n END AS status_text\n , iob.engagement_letter_signed\n , COALESCE(class.peer_free_text, gsi.name) AS internal_peer\n\n FROM issuer_issuer as i\n INNER JOIN issuer_issuertype as it ON 1 = 1\n AND i.issuer_type_id = it.id\n INNER JOIN issuer_onboardingprocess as iob ON 1 = 1\n AND iob.issuer_id = i.id\n LEFT OUTER JOIN auth_user as au ON 1 = 1\n AND i.relationship_manager_id = au.id\n LEFT OUTER JOIN static_database_table_gicssubindustry as gsi\n ON 1 = 1\n AND i.gics_sub_industry_id = gsi.id\n LEFT OUTER JOIN static_database_table_gicsindustry as gi\n ON 1 = 1\n AND gsi.industry_id = gi.id\n LEFT OUTER JOIN static_database_table_gicsindustrygroup as gig\n ON 1 = 1\n AND gi.industry_group_id = gig.id\n LEFT OUTER JOIN static_database_table_gicssector as gs\n ON 1 = 1\n AND gig.sector_id = gs.id\n LEFT OUTER JOIN issuer_analyst as ia\n ON 1 = 1\n AND i.id = ia.issuer_id\n LEFT OUTER JOIN auth_user as t9\n ON 1 = 1\n AND ia.primary_analyst_id = t9.id\n LEFT OUTER JOIN auth_user as t10\n ON 1 = 1\n AND ia.secondary_analyst_id = t10.id\n LEFT OUTER JOIN issuer_address as iadd\n ON 1 = 1\n AND i.id = iadd.issuer_id\n LEFT OUTER JOIN static_database_table_countryregion as country\n ON 1 = 1\n AND iadd.country_id = country.id\n LEFT OUTER JOIN rating_process_ratingdecision AS decision\n ON 1 = 1\n AND i.id = decision.issuer_id\n AND decision.is_current = True\n LEFT OUTER JOIN rating_process_ratingdecision AS decision_ongoing\n ON 1 = 1\n AND i.id = decision_ongoing.issuer_id\n AND decision_ongoing.date_time_published IS NULL\n AND decision_ongoing.date_time_deleted IS NULL\n LEFT OUTER JOIN issuer_classification as class\n ON 1 = 1\n AND i.id = class.issuer_id\n ORDER BY COALESCE(class.peer_free_text, gsi.name || ': ' || CAST(gsi.code AS TEXT))\n , i.legal_name\n ''' # noqa: E501\n\n return self.raw(sql)\n\n def list_all_rating(self):\n \"\"\"Get all companies with a rating using an optimized query.\"\"\"\n\n sql = '''\n SELECT i.id\n , gs.name as sector_name\n , country.name as country\n , i.legal_name as legal_name\n , CASE WHEN it.description = 1 THEN 'Corporate'\n WHEN it.description = 2 THEN 'Financial'\n WHEN it.description = 3 THEN 'Real estate'\n END as issuer_type_name\n , t9.first_name || ' ' || t9.last_name as p_analyst\n , t10.first_name || ' ' || t10.last_name as s_analyst\n , au.first_name || ' ' || au.last_name as c_manager\n , decision.decided_lt as current_long_term\n , decision.decided_lt_outlook as current_outlook\n , CASE WHEN iob.date_time_onboarding_completed IS NULL THEN 'Not Onboarded'\n WHEN iob.date_time_onboarding_completed IS NOT NULL AND decision_ongoing.id IS NOT NULL THEN 'Rating job in progress'\n WHEN iob.date_time_onboarding_completed IS NOT NULL AND decision.id IS NOT NULL THEN 'Ongoing surveillance'\n WHEN iob.date_time_onboarding_completed IS NOT NULL AND decision_ongoing.id IS NULL THEN 'Onboarded'\n END AS status\n , CASE WHEN decision_ongoing.process_step = 1 THEN 'Rating job started'\n WHEN decision_ongoing.process_step = 2 THEN 'Pre-committee'\n WHEN decision_ongoing.process_step = 3 THEN 'Analytical phase'\n WHEN decision_ongoing.process_step = 4 THEN 'Post committee'\n WHEN decision_ongoing.process_step = 5 THEN 'Editing'\n WHEN decision_ongoing.process_step = 6 THEN 'Issuer confirmation'\n WHEN decision_ongoing.process_step = 7 THEN 'Analyst final approval'\n WHEN decision_ongoing.process_step = 8 THEN 'Chair final approval'\n WHEN decision_ongoing.process_step = 9 THEN 'Ready to be published'\n END AS status_text\n , iob.engagement_letter_signed\n , COALESCE(class.peer_free_text, gsi.name) AS internal_peer\n FROM issuer_issuer as i\n INNER JOIN issuer_issuertype as it ON 1 = 1\n AND i.issuer_type_id = it.id\n INNER JOIN issuer_onboardingprocess as iob ON 1 = 1\n AND iob.issuer_id = i.id\n LEFT OUTER JOIN auth_user as au ON 1 = 1\n AND i.relationship_manager_id = au.id\n LEFT OUTER JOIN static_database_table_gicssubindustry as gsi\n ON 1 = 1\n AND i.gics_sub_industry_id = gsi.id\n LEFT OUTER JOIN static_database_table_gicsindustry as gi\n ON 1 = 1\n AND gsi.industry_id = gi.id\n LEFT OUTER JOIN static_database_table_gicsindustrygroup as gig\n ON 1 = 1\n AND gi.industry_group_id = gig.id\n LEFT OUTER JOIN static_database_table_gicssector as gs\n ON 1 = 1\n AND gig.sector_id = gs.id\n LEFT OUTER JOIN issuer_analyst as ia\n ON 1 = 1\n AND i.id = ia.issuer_id\n LEFT OUTER JOIN auth_user as t9\n ON 1 = 1\n AND ia.primary_analyst_id = t9.id\n LEFT OUTER JOIN auth_user as t10\n ON 1 = 1\n AND ia.secondary_analyst_id = t10.id\n LEFT OUTER JOIN issuer_address as iadd\n ON 1 = 1\n AND i.id = iadd.issuer_id\n LEFT OUTER JOIN static_database_table_countryregion as country\n ON 1 = 1\n AND iadd.country_id = country.id\n LEFT OUTER JOIN rating_process_ratingdecision AS decision\n ON 1 = 1\n AND i.id = decision.issuer_id\n AND decision.is_current = True\n LEFT OUTER JOIN rating_process_ratingdecision AS decision_ongoing\n ON 1 = 1\n AND i.id = decision_ongoing.issuer_id\n AND decision_ongoing.date_time_published IS NULL\n AND decision_ongoing.date_time_deleted IS NULL\n LEFT OUTER JOIN issuer_classification as class\n ON 1 = 1\n AND i.id = class.issuer_id\n WHERE decision.is_current = True\n ORDER BY COALESCE(class.peer_free_text, gsi.name || ': ' || CAST(gsi.code AS TEXT))\n , i.legal_name\n ''' # noqa: E501\n\n return self.raw(sql)\n\n def list_all_assessment(self, issuer_id_list):\n \"\"\"Get all companies with an assessment.\"\"\"\n\n sql = '''\n WITH t1 AS (\n SELECT i.id\n , i.legal_name\n , i.issuer_type_id\n , cr.iso_31661_alpha_2 as ccy\n , COALESCE(class.peer_free_text, gsi.name) as sort_key\n FROM issuer_issuer AS i\n LEFT OUTER JOIN issuer_address AS ia\n ON 1 = 1\n AND ia.issuer_id = i.id\n LEFT OUTER JOIN static_database_table_countryregion AS cr\n ON 1 = 1\n AND cr.id = ia.country_id\n LEFT OUTER JOIN static_database_table_gicssubindustry as gsi\n ON 1 = 1\n AND i.gics_sub_industry_id = gsi.id\n LEFT OUTER JOIN issuer_classification AS class\n ON 1 = 1\n AND i.id = class.issuer_id\n WHERE i.issuer_type_id IN %s\n ORDER BY sort_key, i.legal_name\n )\n SELECT i.id\n , i.legal_name AS i_name\n , i.ccy\n , i.sort_key AS internal_peer\n , i.issuer_type_id as i_id\n , COALESCE(dec_current.date_time_published, ass_current.date_time_approval) AS current_date_time_approval\n , ass_current.id AS current_id\n\n , ass_progress.id AS progress_id\n , ass_progress.process_step AS progress_process_step\n , ass_progress.initiated_by_id AS progress_initiated_by_id\n , ass_progress.assessment_lt AS progress_assessment_lt\n\n , dec_current.id as rating_id\n\n , COALESCE(dec_current.initiated_by_id, ass_progress.initiated_by_id, ass_current.initiated_by_id) initiated_by\n FROM t1 as i\n LEFT JOIN credit_assessment_assessmentjob AS ass_current ON 1 = 1\n AND ass_current.issuer_id = i.id\n AND ass_current.is_current = True\n LEFT JOIN credit_assessment_assessmentjob AS ass_progress ON 1 = 1\n AND ass_progress.issuer_id = i.id\n AND ass_progress.is_current = False\n AND ass_progress.date_time_approval IS NULL\n LEFT JOIN rating_process_ratingdecision as dec_current ON 1 = 1\n AND dec_current.issuer_id = i.id\n AND dec_current.is_current = True\n WHERE 1 = 1\n AND (( ass_current.id IS NOT NULL\n OR ass_progress.id IS NOT NULL ) OR dec_current.id IS NOT NULL )\n ORDER BY internal_peer\n , legal_name\n ''' # noqa: E501\n\n return self.raw(sql, [tuple(issuer_id_list)])\n\n def list_onboarded(self):\n \"\"\"List issuers that are onboarded.\"\"\"\n\n return self.filter(\n onboarding_issuer_link__date_time_onboarding_completed__isnull=False) # noqa: E501\n\n\nclass ProcessManager(models.Manager):\n \"\"\"Process manager class.\"\"\"\n\n def get_queryset(self):\n \"\"\"Basic query set. Always filter out those that have been deleted.\"\"\"\n return ProcessQuerySet(self.model, using=self._db) # Important!\n\n def is_live(self):\n \"\"\"Get all companies that are live (not deleted).\"\"\"\n return self.get_queryset().is_live()\n\n def list_all(self):\n \"\"\"Get all companies using an optimized query.\"\"\"\n return self.get_queryset().list_all()\n\n def list_all_rating(self):\n \"\"\"Get all companies with a rating using an optimized query.\"\"\"\n return self.get_queryset().list_all_rating()\n\n def list_eligible_for_assessment(self):\n \"\"\"List all issuers that are eligible for getting a credit\n assessment.\"\"\"\n\n return self.get_queryset().list_eligible_for_assessment()\n\n def list_all_assessment(self, issuer_id_list):\n \"\"\"Get all companies with an assessment.\"\"\"\n\n return self.get_queryset().list_all_assessment(issuer_id_list)\n\n def list_onboarded(self):\n \"\"\"List issuers that are onboarded.\"\"\"\n return self.get_queryset().list_onboarded()\n\n\nclass IssuerType(models.Model):\n \"\"\"\n Current, Nordic Credit Rating's business model revolvers around three\n type of issuers: corporates, corporates in the real estate sector and\n financials.\n\n The ID# linked to each issuer type is used throughout the web site, in\n views as well as in templates. The order and numbering may thus not be\n changed.\n \"\"\"\n date_added = models.DateTimeField(auto_now_add=True)\n last_updated = models.DateTimeField(auto_now=True)\n\n description = models.IntegerField(\n choices=ALLOWED_ISSUER_TYPES,\n unique=True)\n\n def __str__(self):\n return '{}'.format(self.get_description_display())\n\n\n# Create your models here.\nclass Issuer(models.Model):\n \"\"\"Define an issuer. The issuer is the core object\n of the analytical toolkit.\"\"\"\n\n # Add version history to the model\n history = HistoricalRecords()\n\n objects = ProcessManager()\n\n def __str__(self):\n \"\"\"Return a human readable representation of each record.\"\"\"\n return '{}'.format(self.legal_name)\n\n class Meta:\n \"\"\"Meta class.\"\"\"\n ordering = ['legal_name']\n\n @property\n def internal_identifier(self):\n \"\"\"Internal identifier for model.\n Same as in template_tags.\"\"\"\n\n return 'I' + str(self.pk).zfill(6)\n\n @property\n def peer_sector(self):\n \"\"\"Return the NCR defined peer group.\"\"\"\n\n return self.gics_sub_industry\n\n @property\n def is_onboarded(self):\n \"\"\"Flag if the issuer has been onboarded.\"\"\"\n\n if self in Issuer.objects.list_onboarded():\n return True\n else:\n return False\n\n parent_company = models.ForeignKey(\n 'self',\n on_delete=models.PROTECT,\n null=True,\n blank=True,\n )\n\n # The system wide unique identifier for an issuer\n # https://www.leiroc.org/lei.htm\n lei = models.CharField(\n max_length=20,\n unique=True\n )\n\n # A name in the model for the issuer's legal name\n # Is populated from GLEIF repository upon insertion\n # of issuer\n short_name = models.CharField(\n db_index=True,\n max_length=128,\n null=True,\n blank=True,\n )\n\n legal_name = models.CharField(\n db_index=True,\n max_length=128,\n unique=True\n )\n\n # Provide a description of the issuer. This description\n # is for internal as well as external use.\n description = HTMLField(\n null=True,\n blank=True,\n )\n\n # The person in the Commercial team responsible for\n # managing the relationship with the issuer\n relationship_manager = models.ForeignKey(\n User,\n on_delete=models.PROTECT,\n related_name=\"relationship_manager_link\",\n null=True,\n blank=True\n )\n\n # Type of issuer. Determines which methodology is\n # used\n issuer_type = models.ForeignKey(\n IssuerType,\n on_delete=models.PROTECT,\n null=False,\n blank=False\n )\n\n # Defines what sector the issuer belongs to\n # This is based on the Global Industry Classification Standard (GICS)\n gics_sub_industry = models.ForeignKey(\n GICSSubIndustry,\n on_delete=models.PROTECT,\n related_name=\"issuer_gicssubindustry_link\",\n null=True,\n blank=True\n )\n\n # This is if we want to de-activate the entity for some reason\n # Allows us to remove the issuer without physically delete it from the\n # database tables\n inactivated = models.DateTimeField(\n null=True,\n blank=True\n )\n\n\nclass Analyst(models.Model):\n \"\"\"Define a primary and, if applicable,\n secondary analyst for the issuer.\"\"\"\n\n # Add version history to the model\n history = HistoricalRecords()\n\n def __str__(self):\n \"\"\"Return a human readable representation of each record.\"\"\"\n return 'Analysts for {}'.format(self.issuer.legal_name)\n\n issuer = models.OneToOneField(\n Issuer,\n on_delete=models.PROTECT\n )\n\n primary_analyst = models.ForeignKey(\n User,\n on_delete=models.PROTECT,\n related_name=\"primary_analyst_link\",\n null=True,\n blank=True\n )\n\n secondary_analyst = models.ForeignKey(\n User,\n on_delete=models.PROTECT,\n related_name=\"secondary_analyst_link\",\n null=True,\n blank=True\n )\n\n\nCONTACT_TYPES = (\n (1, 'Primary contact'),\n (2, 'Secondary contact'),\n)\n\n\nclass InsiderList(models.Model):\n \"\"\"InsiderList class.\"\"\"\n\n # Add version history to the model\n history = HistoricalRecords()\n\n def __str__(self):\n \"\"\"Return a human readable representation of each record.\"\"\"\n return '%s %s is on insider list for %s %s' % (\n self.first_name,\n self.last_name,\n self.issuer.legal_name,\n 'as ' + self.get_contact_type_display().lower()\n if self.get_contact_type_display() else ''\n )\n\n issuer = models.ForeignKey(\n Issuer,\n on_delete=models.PROTECT,\n related_name=\"insider_list_issuer_link\",\n )\n\n company = models.CharField(\n max_length=100,\n null=True,\n blank=True,\n help_text=\"If other company than issuer.\"\n )\n\n contact_type = models.IntegerField(\n db_index=True,\n choices=CONTACT_TYPES,\n null=True,\n blank=True,\n help_text=\"Leave as '----' if not primary or secondary contact.\"\n )\n\n first_name = models.CharField(\n db_index=True,\n max_length=100,\n blank=False\n )\n\n last_name = models.CharField(\n db_index=True,\n max_length=100,\n blank=False\n )\n\n email = models.CharField(\n max_length=100,\n blank=False,\n validators=[validate_email],\n help_text=\"Eg name@host.com\"\n )\n\n phone_regex = RegexValidator(regex=r'^\\+?1?\\d{9,15}$',\n message=\"Phone number must be \"\n \"entered in the format: \"\n \"'+999999999999'. \"\n \"Up to 15 digits allowed.\")\n # validators should be a list\n phone_number = models.CharField(validators=[phone_regex],\n max_length=17,\n help_text=\"Eg +nnnnnnnnnn\")\n\n role = models.CharField(\n db_index=True,\n max_length=100,\n blank=False,\n help_text=\"Eg 'Debt analyst' or 'Legal counsel'\"\n )\n\n date_creation = models.DateTimeField(\n auto_now_add=True,\n )\n\n date_deletion = models.DateTimeField(\n db_index=True,\n null=True,\n blank=True\n )\n\n\nclass OnboardingProcess(models.Model):\n \"\"\"Onboarding process for Issuer.\"\"\"\n\n def __str__(self):\n \"\"\"Return a human readable representation of each record.\"\"\"\n return 'Onboarding for %s' % (\n self.issuer.legal_name,\n )\n\n issuer = models.ForeignKey(\n Issuer,\n on_delete=models.PROTECT,\n related_name=\"onboarding_issuer_link\",\n )\n\n engagement_letter_signed = models.BooleanField(\n default=False\n )\n\n date_time_engagement_letter_signed = models.DateTimeField(\n blank=True,\n null=True,\n )\n\n issuer_long_term = models.BooleanField(\n default=False\n )\n\n issuer_short_term = models.BooleanField(\n default=False\n )\n\n instrument_rating = models.BooleanField(\n default=False,\n )\n\n target_delivery_date = models.DateField(\n blank=True,\n null=True,\n )\n\n date_time_onboarding_completed = models.DateTimeField(\n blank=True,\n null=True,\n )\n\n\nclass EventType(models.Model):\n \"\"\"EventType model.\"\"\"\n\n def __str__(self):\n return self.description\n\n description = models.CharField(\n max_length=255,\n null=False,\n blank=False,\n )\n\n\nclass Event(models.Model):\n \"\"\"Log event that occur on the issuer level..\"\"\"\n\n def __str__(self):\n \"\"\"Return a human readable representation of each record.\"\"\"\n return '%s: \"%s\" on %s' % (\n self.issuer.legal_name,\n self.event_type,\n self.timestamp.strftime(\"%Y-%m-%d\")\n )\n\n issuer = models.ForeignKey(\n Issuer,\n on_delete=models.PROTECT,\n related_name=\"process_issuer_link\",\n )\n\n triggered_by_user = models.ForeignKey(\n User,\n on_delete=models.PROTECT,\n related_name=\"event_user_link\",\n null=False,\n blank=False\n )\n\n event_type = models.ForeignKey(\n EventType,\n on_delete=models.PROTECT,\n null=False,\n blank=False,\n )\n\n timestamp = models.DateTimeField(\n db_index=True,\n default=timezone.now\n )\n\n\n@receiver(post_save, sender=Issuer)\ndef create_issuer(sender, instance, created, **kwargs):\n \"\"\"\n Whenever an issuer_corporate is added to the system,\n we also want a record in the table for\n Analysts\n \"\"\"\n if created:\n Analyst.objects.create(issuer=instance)\n\n OnboardingProcess.objects.create(\n issuer=instance)\n\n # create database connection and session\n db_connection = SQL('datalake')\n\n # Get data from GLEIF database\n # If LEI does not exist, it will start with LEI_\n if not instance.lei[0:4] == 'LEI_':\n GLEIFEditor(db_connection).upsert(instance.lei)\n\n\n@receiver(post_save, sender=Issuer)\ndef save_issuer(sender, instance, created, **kwargs):\n \"\"\"\n Post save signal to check if all requirements to move to the next step in\n the onboarding process have been fulfilled.\n\n This signal does the test if the Issuer-model has been updated.\n\n If they have been fulfilled, set the 'Analyst appointed'-step in the\n OnboardingProcess-model to True.\n \"\"\"\n issuer = Issuer.objects.get(id=instance.id)\n analysts = Analyst.objects.get(issuer=issuer)\n\n if issuer.issuer_type and analysts.primary_analyst:\n onboarding_obj = OnboardingProcess.objects.get(issuer=issuer)\n onboarding_obj.analysts_appointed = True\n onboarding_obj.save()\n\n\n@receiver(post_save, sender=Analyst)\ndef save_analyst(sender, instance, created, **kwargs):\n \"\"\"\n Post save signal to check if all requirements to move to the next step in\n the onboarding process have been fulfilled.\n\n This signal does the test if the Analyst-model has been updated.\n\n If they have been fulfilled, set the 'Analyst appointed'-step in the\n OnboardingProcess-model to True.\n \"\"\"\n issuer = Issuer.objects.get(id=instance.issuer_id)\n analysts = Analyst.objects.get(issuer=issuer)\n\n if issuer.issuer_type and analysts.primary_analyst:\n onboarding_obj = OnboardingProcess.objects.get(issuer=issuer)\n onboarding_obj.analysts_appointed = True\n onboarding_obj.save()\n","sub_path":"ncr_website/issuer/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":26147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"155461167","text":"import sys\n\ndef parse(adj):\n for l in sys.stdin: \n o,d,w = l.split() \n if o not in adj: \n adj[o] = [] \n if d not in adj: \n adj[d] = [] \n adj[o].append((d,int(w))) \n adj[d].append((o,int(w)))\n return adj \n\ndef dijkstra(adj,o): \n queue = [] \n parent = {} \n dist = {}\n for v in adj: \n dist[v] = float(\"inf\") \n queue.append(v) \n dist[o] = 0\n while queue: \n u = min(queue,key=lambda x : dist[x]) \n queue.remove(u)\n for (v,w) in adj[u]: \n alt = dist[u] + w \n if alt < dist[v]: \n dist[v] = alt \n parent[v] = u\n return parent,dist\n\ndef main():\n origem,destino = sys.stdin.readline().split(\" \")\n origem = origem.strip()\n destino = destino.strip()\n \n adj = {}\n grafo = parse(adj)\n travessia, pesos = dijkstra(grafo, origem)\n \n \n\n custo = pesos[destino]\n print(custo)\n\nmain()\n\n\n","sub_path":"2ºAno/2ºSemestre/LA2/grafos/voos.py","file_name":"voos.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"589833211","text":"#!/usr/bin/env python3\n#-*- coding:utf-8 -*-\n\"\"\"\nCreated on 2020/04/23\nauthor: lujie\n\"\"\"\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import Parameter\n\nfrom IPython import embed\n\nclass UncertaintyHead(nn.Module):\n ''' Evaluate the log(sigma^2) '''\n \n def __init__(self, in_feat = 512):\n\n super(UncertaintyHead, self).__init__()\n self.fc1 = Parameter(torch.Tensor(in_feat, in_feat))\n self.bn1 = nn.BatchNorm1d(in_feat, affine=True)\n self.relu = nn.ReLU(in_feat)\n self.fc2 = Parameter(torch.Tensor(in_feat, in_feat))\n self.bn2 = nn.BatchNorm1d(in_feat, affine=False)\n self.gamma = Parameter(torch.Tensor([1.0]))\n self.beta = Parameter(torch.Tensor([0.0])) # default = -7.0\n \n nn.init.kaiming_normal_(self.fc1)\n nn.init.kaiming_normal_(self.fc2)\n\n\n def forward(self, x):\n x = x.view(x.size(0), -1)\n x = self.relu(self.bn1(F.linear(x, F.normalize(self.fc1))))\n x = self.bn2(F.linear(x, F.normalize(self.fc2))) # 2*log(sigma)\n x = self.gamma * x + self.beta\n x = torch.log(1e-6 + torch.exp(x)) # log(sigma^2)\n return x\n\n\nif __name__ == \"__main__\":\n\n unh = UncertaintyHead(in_feat=3)\n \n mu_data = np.array([[-1.7847768 , -1.0991699 , 1.4248079 ],\n [ 1.0405252 , 0.35788524, 0.7338794 ],\n [ 1.0620259 , 2.1341069 , -1.0100055 ],\n [-0.00963581, 0.39570177, -1.5577421 ],\n [-1.064951 , -1.1261107 , -1.4181522 ],\n [ 1.008275 , -0.84791195, 0.3006532 ],\n [ 0.31099692, -0.32650718, -0.60247767]])\n \n muX = torch.from_numpy(mu_data).float()\n log_sigma_sq = unh(muX)\n print(log_sigma_sq)\n","sub_path":"model/uncertainty_head.py","file_name":"uncertainty_head.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"240193633","text":"#!/usr/bin/python\nimport sys\nimport os\nfrom numpy import *\nfrom mod_cond import *\n\ndef read_plot3d(filename):\n\tfp = open(filename,'r')\n\t\n\tbuf=fp.readline().split()\n\tNplane=int(buf.pop(0))\n\tnijk=[]\n\tBD=[]\n\t\n\tfor i in range(Nplane):\n\t buf=fp.readline().split()\n\t for i,var in enumerate(buf):\n\t buf[i]=int(var)\n\t nijk.append(buf)\n\t\n\tfor plane in range(Nplane):\n\t ng=1\n\t for var in nijk[plane]:\n\t ng*=var\n\t\n\t ### read data ###\n\t prearr=[]\n\t for i in range(int((ng+3)/4)):\n\t buf=fp.readline().split()\n\t for j,var in enumerate(buf):\n\t buf[j]=float(var)\n\t prearr.extend(buf)\n\t prearr = array(prearr)\n\t gridx = prearr.reshape(nijk[plane][1],nijk[plane][0]).transpose()\n\t\n\t prearr=[]\n\t for i in range(int((ng+3)/4)):\n\t buf=fp.readline().split()\n\t for j,var in enumerate(buf):\n\t buf[j]=float(var)\n\t prearr.extend(buf)\n\t prearr = array(prearr)\n\t gridy = prearr.reshape(nijk[plane][1],nijk[plane][0]).transpose()\n\t\n\t prearr=[]\n\t for i in range(int((ng+3)/4)):\n\t buf=fp.readline().split()\n\t for j,var in enumerate(buf):\n\t buf[j]=float(var)\n\t prearr.extend(buf)\n\t prearr = array(prearr)\n\t buf = prearr.reshape(nijk[plane][1],nijk[plane][0]).transpose()\n\t\n\t ### get only boundaries ###\n\t ni=nijk[plane][0]\n\t nj=nijk[plane][1]\n\t # i-plane\n\t for j in range(nijk[plane][1]):\n\t BD.append(BD_elm([gridx[ 0][j],gridy[ 0][j]],plane,0,0,j))\n\t for j in range(nijk[plane][1]):\n\t BD.append(BD_elm([gridx[ni-1][j],gridy[ni-1][j]],plane,0,1,j))\n\t\n\t # j-plane\n\t for i in range(nijk[plane][0]):\n\t BD.append(BD_elm([gridx[i][ 0],gridy[i][ 0]],plane,1,0,i))\n\t for i in range(nijk[plane][0]):\n\t BD.append(BD_elm([gridx[i][nj-1],gridy[i][nj-1]],plane,1,1,i))\n\t\n\tfp.close()\n\treturn [Nplane,nijk,BD]\n","sub_path":"store/cond/core/read_plot3d.py","file_name":"read_plot3d.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"336857338","text":"class Solution:\n def isSubtree(self, s, t):\n if s == None:\n return False\n if self.isSame(s, t):\n return True\n return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)\n\n def isSame(self, s, t):\n if s == None and t == None:\n return True\n if s == None or t == None:\n return False\n if s.val != t.val:\n return False\n return self.isSame(s.left, t.left) and self.isSame(s.right, t.right)\n","sub_path":"TOP_QUESTIONS/572.Subtree_of_Another_Tree.py","file_name":"572.Subtree_of_Another_Tree.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255516680","text":"from django.shortcuts import render_to_response, redirect\nfrom django.template import RequestContext\nfrom django.contrib import auth\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.core.context_processors import csrf\nfrom django.forms.models import model_to_dict\n\nfrom ProfileApp.forms import ProfileForm\nfrom ProfileApp.models import UserProfile\nfrom FootballApp.views import get_articles\n\n\ndef edit_profile(request):\n if request.user == AnonymousUser():\n return redirect('/')\n args = {}\n args.update(csrf(request))\n if request.POST:\n profile_form = ProfileForm(request.POST, request.FILES)\n if profile_form.is_valid():\n profile_commit = profile_form.save(commit=False)\n profile_commit.user_id = request.user.userprofile.user_id\n if not profile_commit.photo:\n profile_commit.photo = request.user.userprofile.photo\n profile_commit.save()\n return redirect('/profile/id/%s.html' % auth.get_user(request).id)\n else:\n initial = model_to_dict(request.user.userprofile)\n profile_form = ProfileForm(initial=initial)\n args['profile_form'] = profile_form\n args['articles'] = get_articles(request.user)\n args['username'] = auth.get_user(request).username\n args['user_id'] = auth.get_user(request).id\n return render_to_response(\n \"edit_profile.html\",\n args,\n context_instance=RequestContext(request)\n )\n\n\ndef profile(request, customer_id):\n return render_to_response(\n \"profile.html\",\n {\n 'user': UserProfile.objects.get(user_id=customer_id),\n 'articles': get_articles(request.user),\n 'username': auth.get_user(request).username,\n 'my': request.user.id == int(customer_id)\n }\n )\n","sub_path":"ProfileApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"585517073","text":"\"\"\"Training script for the DeepLab-ResNet network on the PASCAL VOC dataset\n for semantic image segmentation.\n\nThis script trains the model using augmented PASCAL VOC,\nwhich contains approximately 10000 images for training and 1500 images for validation.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nfrom datetime import datetime\nimport os\nimport sys\nimport time\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom deeplab_resnet import DeepLabResNetModel, ImageReader, decode_labels, inv_preprocess, prepare_label\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nn_classes = 21\n\nBATCH_SIZE = 5\nDATA_DIRECTORY = '/workspace/hzl/tensorflow-program/data/VOCdevkit/voc12'\nDATA_LIST_PATH = './dataset/train.txt'\nINPUT_SIZE = '321,321'\nLEARNING_RATE = 2.5e-4\nMOMENTUM = 0.9\nNUM_STEPS = 20001\nPOWER = 0.9\nRANDOM_SEED = 1234\nRESTORE_FROM = './deeplab_resnet.ckpt'\nSAVE_NUM_IMAGES = 2\nSAVE_PRED_EVERY = 1000\nSNAPSHOT_DIR = './snapshots/'\nWEIGHT_DECAY = 0.0005\n\n\ndef get_arguments():\n \"\"\"Parse all the arguments provided from the CLI.\n \n Returns:\n A list of parsed arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"DeepLab-ResNet Network\")\n parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE,\n help=\"Number of images sent to the network in one step.\")\n parser.add_argument(\"--data-dir\", type=str, default=DATA_DIRECTORY,\n help=\"Path to the directory containing the PASCAL VOC dataset.\")\n parser.add_argument(\"--data-list\", type=str, default=DATA_LIST_PATH,\n help=\"Path to the file listing the images in the dataset.\")\n parser.add_argument(\"--input-size\", type=str, default=INPUT_SIZE,\n help=\"Comma-separated string with height and width of images.\")\n parser.add_argument(\"--is-training\", action=\"store_true\",\n help=\"Whether to updates the running means and variances during the training.\")\n parser.add_argument(\"--learning-rate\", type=float, default=LEARNING_RATE,\n help=\"Base learning rate for training with polynomial decay.\")\n parser.add_argument(\"--momentum\", type=float, default=MOMENTUM,\n help=\"Momentum component of the optimiser.\")\n parser.add_argument(\"--num-steps\", type=int, default=NUM_STEPS,\n help=\"Number of training steps.\")\n parser.add_argument(\"--power\", type=float, default=POWER,\n help=\"Decay parameter to compute the learning rate.\")\n parser.add_argument(\"--random-mirror\", action=\"store_true\",\n help=\"Whether to randomly mirror the inputs during the training.\")\n parser.add_argument(\"--random-scale\", action=\"store_true\",\n help=\"Whether to randomly scale the inputs during the training.\")\n parser.add_argument(\"--random-seed\", type=int, default=RANDOM_SEED,\n help=\"Random seed to have reproducible results.\")\n parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM,\n help=\"Where restore model parameters from.\")\n parser.add_argument(\"--save-num-images\", type=int, default=SAVE_NUM_IMAGES,\n help=\"How many images to save.\")\n parser.add_argument(\"--save-pred-every\", type=int, default=SAVE_PRED_EVERY,\n help=\"Save summaries and checkpoint every often.\")\n parser.add_argument(\"--snapshot-dir\", type=str, default=SNAPSHOT_DIR,\n help=\"Where to save snapshots of the model.\")\n parser.add_argument(\"--weight-decay\", type=float, default=WEIGHT_DECAY,\n help=\"Regularisation parameter for L2-loss.\")\n return parser.parse_args()\n\ndef save(saver, sess, logdir, step):\n '''Save weights.\n \n Args:\n saver: TensorFlow Saver object.\n sess: TensorFlow session.\n logdir: path to the snapshots directory.\n step: current training step.\n '''\n model_name = 'model.ckpt'\n checkpoint_path = os.path.join(logdir, model_name)\n \n if not os.path.exists(logdir):\n os.makedirs(logdir)\n saver.save(sess, checkpoint_path, global_step=step)\n print('The checkpoint has been created.')\n\ndef load(saver, sess, ckpt_path):\n '''Load trained weights.\n \n Args:\n saver: TensorFlow Saver object.\n sess: TensorFlow session.\n ckpt_path: path to checkpoint file with parameters.\n ''' \n saver.restore(sess, ckpt_path)\n print(\"Restored model parameters from {}\".format(ckpt_path))\n\ndef main():\n \"\"\"Create the model and start the training.\"\"\"\n args = get_arguments()\n \n h, w = map(int, args.input_size.split(','))\n input_size = (h, w)\n \n tf.set_random_seed(args.random_seed)\n \n # Create queue coordinator.\n coord = tf.train.Coordinator()\n \n # Load reader.\n with tf.name_scope(\"create_inputs\"):\n reader = ImageReader(\n args.data_dir,\n args.data_list,\n input_size,\n args.random_scale,\n args.random_mirror,\n coord)\n image_batch, label_batch = reader.dequeue(args.batch_size)\n \n # Create network.\n net = DeepLabResNetModel({'data': image_batch}, is_training=args.is_training)\n # For a small batch size, it is better to keep \n # the statistics of the BN layers (running means and variances)\n # frozen, and to not update the values provided by the pre-trained model. \n # If is_training=True, the statistics will be updated during the training.\n # Note that is_training=False still updates BN parameters gamma (scale) and beta (offset)\n # if they are presented in var_list of the optimiser definition.\n\n # Predictions.\n raw_output = net.layers['fc1_voc12']\n # Which variables to load. Running means and variances are not trainable,\n # thus all_variables() should be restored.\n restore_var = tf.global_variables()\n all_trainable = [v for v in tf.trainable_variables() if 'beta' not in v.name and 'gamma' not in v.name]\n fc_trainable = [v for v in all_trainable if 'fc' in v.name]\n conv_trainable = [v for v in all_trainable if 'fc' not in v.name] # lr * 1.0\n fc_w_trainable = [v for v in fc_trainable if 'weights' in v.name] # lr * 10.0\n fc_b_trainable = [v for v in fc_trainable if 'biases' in v.name] # lr * 20.0\n assert(len(all_trainable) == len(fc_trainable) + len(conv_trainable))\n assert(len(fc_trainable) == len(fc_w_trainable) + len(fc_b_trainable))\n \n \n # Predictions: ignoring all predictions with labels greater or equal than n_classes\n raw_prediction = tf.reshape(raw_output, [-1, n_classes])\n label_proc = prepare_label(label_batch, tf.stack(raw_output.get_shape()[1:3]), one_hot=False) # [batch_size, h, w]\n raw_gt = tf.reshape(label_proc, [-1,])\n indices = tf.squeeze(tf.where(tf.less_equal(raw_gt, n_classes - 1)), 1)\n gt = tf.cast(tf.gather(raw_gt, indices), tf.int32)\n prediction = tf.gather(raw_prediction, indices)\n \n \n # Pixel-wise softmax loss.\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=prediction, labels=gt)\n l2_losses = [args.weight_decay * tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'weights' in v.name]\n reduced_loss = tf.reduce_mean(loss) + tf.add_n(l2_losses)\n \n # Processed predictions: for visualisation.\n raw_output_up = tf.image.resize_bilinear(raw_output, tf.shape(image_batch)[1:3,])\n raw_output_up = tf.argmax(raw_output_up, dimension=3)\n pred = tf.expand_dims(raw_output_up, dim=3)\n \n # Image summary.\n images_summary = tf.py_func(inv_preprocess, [image_batch, args.save_num_images], tf.uint8)\n labels_summary = tf.py_func(decode_labels, [label_batch, args.save_num_images], tf.uint8)\n preds_summary = tf.py_func(decode_labels, [pred, args.save_num_images], tf.uint8)\n \n total_summary = tf.summary.image('images', \n tf.concat([images_summary, labels_summary, preds_summary], 2), \n max_outputs=args.save_num_images) # Concatenate row-wise.\n summary_writer = tf.summary.FileWriter(args.snapshot_dir,\n graph=tf.get_default_graph())\n \n # Define loss and optimisation parameters.\n base_lr = tf.constant(args.learning_rate)\n step_ph = tf.placeholder(dtype=tf.float32, shape=())\n learning_rate = tf.scalar_mul(base_lr, tf.pow((1 - step_ph / args.num_steps), args.power))\n \n opt_conv = tf.train.MomentumOptimizer(learning_rate, args.momentum)\n opt_fc_w = tf.train.MomentumOptimizer(learning_rate * 10.0, args.momentum)\n opt_fc_b = tf.train.MomentumOptimizer(learning_rate * 20.0, args.momentum)\n\n grads = tf.gradients(reduced_loss, conv_trainable + fc_w_trainable + fc_b_trainable)\n grads_conv = grads[:len(conv_trainable)]\n grads_fc_w = grads[len(conv_trainable) : (len(conv_trainable) + len(fc_w_trainable))]\n grads_fc_b = grads[(len(conv_trainable) + len(fc_w_trainable)):]\n\n train_op_conv = opt_conv.apply_gradients(zip(grads_conv, conv_trainable))\n train_op_fc_w = opt_fc_w.apply_gradients(zip(grads_fc_w, fc_w_trainable))\n train_op_fc_b = opt_fc_b.apply_gradients(zip(grads_fc_b, fc_b_trainable))\n\n train_op = tf.group(train_op_conv, train_op_fc_w, train_op_fc_b)\n \n \n # Set up tf session and initialize variables. \n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n init = tf.global_variables_initializer()\n \n sess.run(init)\n \n # Saver for storing checkpoints of the model.\n saver = tf.train.Saver(var_list=restore_var, max_to_keep=10)\n \n # Load variables if the checkpoint is provided.\n if args.restore_from is not None:\n loader = tf.train.Saver(var_list=restore_var)\n load(loader, sess, args.restore_from)\n \n # Start queue threads.\n threads = tf.train.start_queue_runners(coord=coord, sess=sess)\n\n # Iterate over training steps.\n for step in range(args.num_steps):\n start_time = time.time()\n feed_dict = { step_ph : step }\n \n if step % args.save_pred_every == 0:\n loss_value, images, labels, preds, summary, _ = sess.run([reduced_loss, image_batch, label_batch, pred, total_summary, train_op], feed_dict=feed_dict)\n summary_writer.add_summary(summary, step)\n save(saver, sess, args.snapshot_dir, step)\n else:\n loss_value, _ = sess.run([reduced_loss, train_op], feed_dict=feed_dict)\n duration = time.time() - start_time\n print('step {:d} \\t loss = {:.3f}, ({:.3f} sec/step)'.format(step, loss_value, duration))\n coord.request_stop()\n coord.join(threads)\n \nif __name__ == '__main__':\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"403006073","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/7/16 10:49\n# @Author : liugang9\n# @Email : mlcc330@hotmail.com\n# @File : demoScrapBaidu.py\n# @Software: PyCharm\n# @license: Apache Licence\n# @contact: 3323202070@qq.com\n# @Description: \n# \n# \n\nimport urllib.request\nimport re\nfrom bs4 import BeautifulSoup\n\ndef make_content_to_html(scrap_data):\n f = open('scrap_result.html','a+',encoding='utf-8')\n message = '''\n \n \n \n \n \n 爬取结果
        \n
        \n \n \n \n \n \n \n '''+scrap_data+'''\n \n
        省份\n 省会城市\n
        \n \n \n '''\n f.write(message)\n f.close()\n\ndef main():\n # 定义基本信息\n urls = 'https://zhidao.baidu.com/question/120615642.html'\n UserAgent = 'Mozilla / 5.0(Windows NT 6.1; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'\n Referers = 'https://www.baidu.com/link?url=qwg78ZrrBP8P-ivzTn6uKG-rTrVY5c4aKQ2hhwcEZGZc8rkQcCwLIFn69GgbxG_Q4rx9rkRBlE0mAGL1bSyM6q&wd=&eqid=9f8961540000c365000000025b4c0796'\n headers = {'UserAgent':UserAgent,'Referer':Referers}\n\n # 爬去数据\n req = urllib.request.Request(urls,headers=headers)\n responses = urllib.request.urlopen(req)\n soup = BeautifulSoup(responses,'lxml',from_encoding='gbk')\n\n\n # print(soup.select('div[class$=\"best-text mb-10\"]')),找到位置\n results = str(soup.select('div[class$=\"best-text mb-10\"]'))\n # 正则匹配\n results = str(re.findall('

        (.*)(.*)',results))\n # 去除噪声\n results = str(results.replace('p','\"').replace('xa0','\"'))\n # 提取所需的数据,返回一个字符串\n results = re.findall('(\\w+)',results)\n\n # 将字符串转换为字典\n results_dict = {}\n for i in range(0,len(results),2):\n results_dict[results[i]] = results[i+1]\n\n # 拼接html中的内容\n resultStr = ''\n for key,value in results_dict.items():\n # (''+key+''+''+value+'')\n resultStr += ''+key+''+''+value+''\n\n # 写文件\n make_content_to_html(resultStr)\n\n pass\n\n\nif __name__ == '__main__':\n main()\n pass","sub_path":"src/reading/web_scraping/demoScrapBaidu.py","file_name":"demoScrapBaidu.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"171521439","text":"#%%\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport phd.stats\nimport phd.viz\nimport phd.thermo\nimport pickle\ncolors, color_list = phd.viz.phd_style()\nconstants = phd.thermo.load_constants()\ntitle_bbox = dict(facecolor='none', edgecolor=colors['light_grey'], lw=0.1)\n#%%\n# Define the figure generation variables. \nALL_DATA = False\nALL_PRED = True\nC_RANGE = np.logspace(-2, 4, 200)\n\n# Define the repressor colors. \nedge_reps = {22:colors['dark_purple'], 60:colors['dark_orange'], \n 124: colors['black'], 260: colors['dark_red'], \n 1220: colors['dark_blue'], 1740: colors['dark_green']}\nfill_reps = {22:colors['light_purple'], 60:colors['light_orange'], \n 124: colors['light_grey'], 260: colors['light_red'], \n 1220: colors['light_blue'], 1740: colors['light_green']}\n# %%\n# Load the summarzed fold-change data\ndata = pd.read_csv('../data/RazoMejia2018_data.csv', comment='#')\n\n# Summarize the data for display.\ndata = data[data['repressors'] > 0]\ndata['repressors'] *= 2\ndata.rename(columns={'fold_change_A':'fold_change', 'IPTG_uM': 'IPTGuM'},\n inplace=True)\n\nsummarized = data.groupby(['operator', 'repressors', \n 'IPTGuM']).agg(('mean', 'sem')).reset_index()\n\n\n# Load the MCMC samples from the induction paper for O2 R260\nwith open('../data/SI_I_O2_R260.pkl', 'rb') as f:\n out = pickle.load(f)\n fit_ka = np.exp(-out[:, 0][::10])\n fit_ki = np.exp(-out[:, 1][::10])\n# %%\n# Instantiate the figure canvas. \nfig, ax = plt.subplots(1, 3, figsize=(8, 3), sharey=True, sharex=True)\n\n# Define the operator axes\n_axes = {'O1':ax[0], 'O2':ax[1], 'O3':ax[2]}\n\n# Format the axes and add labels. \nfor a in ax:\n a.set_xscale('log')\n a.set_xlabel('IPTG [$\\mu$M]')\nax[0].set_ylabel('fold-change')\nax[0].set_title('operator O1 (high affinity)', fontsize=8, color=colors['light_grey'], y=1.03, \n bbox=title_bbox)\nax[1].set_title('operator O2 (moderate affinity)', fontsize=8, color=colors['light_grey'], y=1.03, \n bbox=title_bbox)\nax[2].set_title('operator O3 (low affinity)', fontsize=8, color=colors['light_grey'], y=1.03, \n bbox=title_bbox)\n\n# Plot the theoretical predictions\nif ALL_PRED:\n for g, d in data.groupby(['repressors', 'operator']):\n cred_region = np.zeros((2, len(C_RANGE)))\n for i, c in enumerate(C_RANGE):\n fc = phd.thermo.SimpleRepression(R=g[0], ep_r=constants[g[1]], \n ka=fit_ka, ki=fit_ki, \n ep_ai=constants['ep_AI'],\n effector_conc=c).fold_change()\n cred_region[:, i] = phd.stats.compute_hpd(fc, 0.95) \n _axes[g[1]].fill_between(C_RANGE, cred_region[0, :], cred_region[1, :],\n color=fill_reps[g[0]], alpha=0.75, label=g[0])\n\n# Add the legend now. \nleg = ax[0].legend(fontsize=6, title='repressors', loc='upper left')\n\n\n# Plot the data. \nfor g, d in summarized.groupby(['repressors', 'operator']):\n if (ALL_DATA==False):\n if (g[0] != 260) | (g[1] != 'O2'):\n pass\n else:\n _ax = _axes[g[1]]\n _ax.errorbar(d['IPTGuM'], d['fold_change']['mean'], \n d['fold_change']['sem'], capsize=1, lw=0.75, color=edge_reps[g[0]],\n fmt='.', ms=6, markerfacecolor=fill_reps[g[0]], markeredgewidth=0.75,\n label='__nolegend__')\n else:\n _ax = _axes[g[1]]\n _ax.errorbar(d['IPTGuM'], d['fold_change']['mean'], \n d['fold_change']['sem'], capsize=1, lw=0.75, color=edge_reps[g[0]],\n fmt='.', ms=6, markerfacecolor=fill_reps[g[0]], markeredgewidth=0.75,\n label='__nolegend__')\n\nleg.get_title().set_fontsize(6)\n\n\n# Save it\nfor a in ax:\n a.set_ylim([-0.05, 1.05])\n\nplt.tight_layout()\nif ALL_DATA == False:\n name = 'fit_data'\nelse:\n name = 'all_data'\n\n\nplt.savefig(f'../figs/{name}_induction_profiles.pdf', bbox_inches='tight',\n facecolor='white')\n# %%\n\n\n# %%\n\n\n# %%\n","sub_path":"talks/20191025_G7_committee_meeting/code/induction_profiles.py","file_name":"induction_profiles.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"117134642","text":"#!/usr/bin/env python3\n\"\"\"\nGiven a value N, if we want to make change for N cents, and we have infinite supply of each of\nS = { S1, S2, .. , Sm} valued coins, how many ways can we make the change?\n\nEXAMPLES:\n Input: S = {1, 2, 3}, N = 4\n Output: 4 \n Explaination: {1,1,1,1}, {1,1,2}, {2,2,}, {1,3}\n\n Input: S = {2, 5, 3, 6}, N = 10\n Output: 5\n Explaination: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}.\n\n\nHINTS:\n - Need to use a table to avoid duplications.\n - Try to build all possible combinations from bottoms up.\n\nREFERENCE:\n - https://www.geeksforgeeks.org/coin-change-dp-7/\n\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def coinChange_v1(self, coins: List[int], amount: int) -> int:\n \"\"\"Use a 2-D table to track the status -- one column for each coin.\n\n Time complexity: O(nm) and space consumption is O(nm),\n where n is the amount and m is the number of coins.\n\n Examples:\n Input: S = {1, 2, 3}, N = 4\n\n | 1 2 3\n --+--------\n 0 | 1 1 1\n 1 | 1 1 1\n 2 | 1 2 2\n 3 | 1 2 3\n 4 | 1 3 4\n\n \"\"\"\n\n # Build a table for tracking\n m = len(coins)\n table = [[0] * m for _ in range(amount+1)]\n for j in range(m):\n table[0][j] = 1\n\n # Process one coin at a time.\n for j, c in enumerate(coins):\n for i in range(1, amount+1):\n # There are two ways to reach this amount (i)\n # 1. With coin c.\n x = table[i-c][j] if i >= c else 0\n # 2. Without coin c.\n y = table[i][j-1] if j > 0 else 0\n table[i][j] = x + y\n\n return table[-1][-1]\n\n def coinChange_v2(self, coins: List[int], amount: int) -> int:\n \"\"\"Use a 1-D table to track the status. \n\n This is an improvement over v1.\n Time complexity is the same, O(nm). Yet it uses less space: O(n).\n\n Example (use a 2D table to show how the 1D table evolves with each coin).\n\n Input: S = {1, 2, 3}, N = 4\n\n | 1 2 3\n --+------------->\n 0 | 1 1 1 1\n 1 | 0 1 1 1\n 2 | 0 1 (2) 2\n 3 | 0 1 2 (3)\n 4 | 0 1 (3) 4\n V\n\n Since only one column is updated at a time, we may use only\n a 1D table to track the status.\n\n \"\"\"\n\n # Build a table for tracking\n m = len(coins)\n table = [1] + [0] * amount\n\n # Process one coin at a time\n for c in coins:\n # See if this coin can be used a build a value i <= amount,\n # where i is both an index and an amount.\n # Also note that there is an offset.\n for i in range(c, amount+1):\n # Increment the table value if this coin can contribute\n # to the current amount.\n table[i] += table[i-c]\n\n return table[-1]\n\n\ndef main():\n test_data = [\n [[1, 2, 3], 4, 4],\n [[2, 5, 3, 6], 10, 5],\n [[1, 2, 5], 100, 541],\n [[88, 227, 216, 96, 209, 172, 259], 6928, 67079],\n ]\n\n sol = Solution()\n for coins, amount, ans in test_data:\n print(\"# Input = {}, {}. Ans = {}\".format(coins, amount, ans))\n print(\" Output = {}\".format(sol.coinChange_v1(coins, amount)))\n print(\" Output = {}\".format(sol.coinChange_v2(coins, amount)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python3/dynamic_programming/coin_change.py","file_name":"coin_change.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"172000128","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom django.contrib import messages\nfrom time import gmtime, strftime\nfrom . models import User\nimport re, datetime, bcrypt, random, string\n\n\n# Create your views here.\n\ndef index(request):\n\tcontext = {}\n\tif \"userID\" not in request.session:\t\t#\tSecurity feature: This process will not execute without an authentic login.\n\t\tcontext[\"name\"] = \"Guest\"\n\telse:\n\t\tcontext[\"name\"] = User.objects.get(id=request.session[\"userID\"]).userName\n\treturn render(request, \"JazzySnek/index.html\", context)\n\ndef loginReg(request):\n\treturn render(request, \"JazzySnek/regLogin.html\")\n\ndef quickGame(request):\n\treturn render(request, \"JazzySnek/game.html\")\n\ndef howTo(request):\n\treturn render(request, \"JazzySnek/howToPlay.html\")\n\ndef storyMode(request):\n\tcontext = {}\n\tif \"userID\" not in request.session:\t\t#\tSecurity feature: This process will not execute without an authentic login.\n\t\tcontext[\"name\"] = \"Guest\"\n\telse:\n\t\tcontext[\"name\"] = User.objects.get(id=request.session[\"userID\"]).userName\n\treturn render(request, \"JazzySnek/storyMode.html\")\n\ndef highScores(request):\n\tcontext = {}\n\tif \"userID\" not in request.session:\t\t#\tSecurity feature: This process will not execute without an authentic login.\n\t\tcontext[\"name\"] = \"Guest\"\n\telse:\n\t\tcontext[\"name\"] = User.objects.get(id=request.session[\"userID\"]).userName\n\tcontext[\"users\"] = User.objects.order_by(\"-highScore\")[:10]\n\treturn render(request, \"JazzySnek/highScores.html\", context)\n\n\ndef register(request):\n\t#\tExecuted when the registration form is submitted.\n\tuserData = retrieveForms(request)\n\terrors = User.objects.validatorReg(userData)\n\t#\tIf any errors are found, store the errors as messages & redirect to root.\n\tif len(errors):\n\t\tfor key, value in errors.items():\n\t\t\tmessages.error(request, value)\n\t\treturn redirect('/login_reg')\n\t#\tIf user is not in the database & all the forms are valid, create a new user with the hashed password and store on server database.\n\telse:\n\t\tpassword = userData['password1']\n\t\thashedPW = bcrypt.hashpw(password.encode(), bcrypt.gensalt())\n\t\tsecurityKey = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(30))\n\t\tUser.objects.create(userName=userData['userName'], passwordHash=hashedPW, securityKey=securityKey)\n\t\tmessages.info(request, slangPos() + \" You have successfully registered!\")\n\t\treturn redirect('/login_reg')\n\ndef login(request):\n\tif \"userID\" in request.session:\n\t\tmessages.info(request, slangPos() + \" You are already logged in!\")\n\t\treturn redirect(\"/login_reg\")\n\terrors = User.objects.validatorLogin(request.POST)\n\t#\tIf any errors are found, store the errors as messages & redirect to root.\n\tif len(errors):\n\t\tfor key, value in errors.items():\n\t\t\tmessages.error(request, value)\n\t\treturn redirect('/login_reg')\n\telse:\n\t\t#\tIf passwords match, flash a successful login message and redirect to dashboard.\n\t\tuser = User.objects.filter(userName=request.POST[\"userName\"]).first()\n\t\t#\tConfirmation of login is the user's ID number stored in the session.\n\t\trequest.session[\"userID\"] = user.id\n\t\trequest.session[\"securityKey\"] = user.securityKey\n\t\tmessages.info(request, slangPos() + \" Welcome back, \" + user.userName + \"!\")\n\t\treturn redirect(\"/login_reg\")\n\ndef logout(request):\n\t#\tLogging out removes he user's ID from session.\n\tif \"userID\" in request.session:\n\t\trequest.session.pop(\"userID\")\n\t\trequest.session.pop(\"securityKey\")\n\t\tmessages.error(request, slangPos() + \" You have logged out.\")\n\t\treturn redirect('/')\n\telse:\n\t\treturn redirect('/')\n\ndef logScore(request):\n\tif \"userID\" in request.session:\n\t\tscore = request.POST[\"finalScore\"]\n\t\tprint(score)\n\t\tif score != \"\":\n\t\t\tscoreInt = int(score)\n\t\t\tprint(scoreInt)\n\t\t\tuser = User.objects.get(id=request.session[\"userID\"])\n\t\t\tif scoreInt > user.highScore:\n\t\t\t\tuser.highScore = scoreInt\n\t\t\t\tif (scoreInt > 50):\n\t\t\t\t\tuser.status = \"Hep Cat!\"\n\t\t\t\telif (scoreInt > 46):\n\t\t\t\t\tuser.status = \"Rug Cutter!\"\n\t\t\t\telif (scoreInt > 40):\n\t\t\t\t\tuser.status = \"Jitter Bug!\"\n\t\t\t\telif (scoreInt > 32):\n\t\t\t\t\tuser.status = \"Buddy Ghee!\"\n\t\t\t\telif (scoreInt > 24):\n\t\t\t\t\tuser.status = \"Mellow Jack!\"\n\t\t\t\telif (scoreInt > 18):\n\t\t\t\t\tuser.status = \"Basic Lane!\"\n\t\t\t\tuser.save()\n\treturn redirect('/')\n\ndef replay(request):\n\tif \"userID\" in request.session:\n\t\tscore = request.POST[\"finalScore\"]\n\t\tprint(score)\n\t\tif score != \"\":\n\t\t\tscoreInt = int(score)\n\t\t\tprint(scoreInt)\n\t\t\tuser = User.objects.get(id=request.session[\"userID\"])\n\t\t\tif scoreInt > user.highScore:\n\t\t\t\tuser.highScore = scoreInt\n\t\t\t\tif (scoreInt > 50):\n\t\t\t\t\tuser.status = \"Hep Cat!\"\n\t\t\t\telif (scoreInt > 46):\n\t\t\t\t\tuser.status = \"Rug Cutter!\"\n\t\t\t\telif (scoreInt > 40):\n\t\t\t\t\tuser.status = \"Jitter Bug!\"\n\t\t\t\telif (scoreInt > 32):\n\t\t\t\t\tuser.status = \"Buddy Ghee!\"\n\t\t\t\telif (scoreInt > 24):\n\t\t\t\t\tuser.status = \"Mellow Jack!\"\n\t\t\t\telif (scoreInt > 18):\n\t\t\t\t\tuser.status = \"Basic Lane!\"\n\t\t\t\tuser.save()\n\treturn redirect('/quick_game')\n\n\n#####\t\tHELPER FUNCTIONS\n\ndef retrieveForms(request):\n\t# Returns a dictionary of the fields' names as keys and the fields' values (from registration/login page) as values.\n\tdata = { }\n\tkeys = ['userName', 'password1', 'password2']\n\tfor key in keys:\n\t\tdata[key] = request.POST[key]\n\treturn data\n\ndef slangPos():\n\trandIndex = random.randint(0, len(positiveSlang)-1)\n\treturn positiveSlang[randIndex]\n\npositiveSlang = [ \"Breakin' it Up!\", \"Bustin' the Conk!\", \"Collarin' the Jive!\",\n\t\"Dicty Dukes!\", \"Friskin' Whiskers!\", \"Get Your Boots On!\", \"In the Groove!\",\n\t\"Swell Jam!\", \"Hittin' the Licks!\", \"Muggin' Heavy!\", \"Neigho, Pops!\", \"Ridin' the Riffs!\"\n]\n\ntitles = [ \"Square Jeff!\", \"Basic Lane!\", \"Basic Lane!\", \"Mellow Jack!\", \"Buddy Ghee!\", \"Jitter Bug!\", \"Rug Cutter!\", \"Hep Cat!\" ]\n\n\n\n\n","sub_path":"apps/JazzySnek/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"336077525","text":"import sys\nif not (sys.path[0] + '/../') in sys.path:\n sys.path.append(sys.path[0] + '/../')\n\nimport logic.db as database\nimport models.logger as log\nfrom models.basemodel import BaseModel\n\n\nclass User(BaseModel):\n\n def __init__(self, options):\n if isinstance(options, dict):\n self.id = options['id']\n self.name = options['name']\n self.location = options.get('location', '')\n self.description = options.get('description', '')\n self.gender = options.get('gender', 'n')\n self.followers_count = int(options.get('followers_count', 0))\n self.friends_count = int(options.get('friends_count', 0))\n self.statuses_count = int(options.get('statuses_count', 0))\n self.db = database.DB('tb_user_info')\n else:\n raise TypeError('options must be an instance of dict')\n\n def insert(self):\n insertobj = {\n 'id': self.id,\n 'name': self.name,\n 'location': self.location,\n 'description': self.description,\n 'gender': self.gender,\n 'followers_count': self.followers_count,\n 'friends_count': self.friends_count,\n 'statuses_count': self.statuses_count\n }\n result = self.db.insert(insertobj)\n if not result[0]:\n log.e(result[1])\n return (False, result[1])\n else:\n log.i('Inserted')\n return (True,)\n","sub_path":"src/spider/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"450712847","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('doc', '0019_documentstatus_glyphicon'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='documentstatus',\n name='minimumTimeUnit',\n field=models.IntegerField(default=1, verbose_name=b'Unidade de Tempo', choices=[(1, b'Dia(s)'), (30, b'M\\xc3\\xaas(s)'), (365, b'Ano(s)')]),\n ),\n ]\n","sub_path":"legaltec/doc/migrations/0020_auto_20160222_2346.py","file_name":"0020_auto_20160222_2346.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"364207754","text":"import cv2\nimport numpy as np\n\nimg1 = np.zeros((300,500,3), np.uint8)\nimg1 = cv2.rectangle(img1, (200,0), (300,100),(255,255,255),-1)\n# This will creating a white rectangle inside the black image we getting from the np.zeros\n# Demnesjoner og colors\nimg2 = cv2.imread(\"../images/lena.jpg\")\n\n# The image must be resized to get performed bitwise\nimg2 = cv2.resize(img2, (500,300)) \nbitand = cv2.bitwise_and(img2,img1)\n# Performing bitwise operations for both images\n# Here I do some logic operation which is and operation, Look at truth table for and gate when A and B is high we get the output high\nbit_or = cv2.bitwise_or(img2,img1)\n# # or operation\n# bit_not = cv2.bitwise_not(img2, img1)\n# # nor operation\nbit_xor = cv2.bitwise_xor(img1,img2)\n#xor operation\n\ncv2.imshow(\"image1\", img1)\ncv2.imshow(\"Lena\",img2)\ncv2.imshow(\"bitand\", bitand)\ncv2.imshow(\"bitor\", bit_or)\n# cv2.imshow(\"bitnot\", bit_not)\ncv2.imshow(\"bitxor\", bit_xor)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"openCVcode/bitwise_operators.py","file_name":"bitwise_operators.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"104651063","text":"from torch.nn import Linear, Tanh, LSTM, Embedding\nfrom torch.optim import SGD, Adam\n# from pytorch_lightning import LightningModule, EvalResult, TrainResult\nimport pytorch_lightning as pl\nfrom torchvision.models import resnet18\nfrom loss_func.simclr import SimCLR\nimport torch\nfrom torchvision import transforms \n\nclass JeopardyModel2(pl.LightningModule):\n def __init__(self, vocab_sz, config):\n # possible next step - use auto scaling of batch size on GPU\n super().__init__()\n mp = config.model_params\n self.op = config.optim_params\n self.im_vec_dim = mp.im_vec_dim\n self.ans_dim = mp.ans_dim\n self.question_dim = mp.question_dim\n self.n_hidden = mp.n_hidden\n self.n_layers = mp.n_layers # in case we want multilayer RNN\n\n self.i_h = Embedding(vocab_sz, self.n_hidden, padding_idx=0) \n self.h_o = Linear(self.n_hidden, self.question_dim)\n self.h = None \n self.ans_final = Linear(self.n_hidden, self.ans_dim)\n if self.n_layers > 1:\n self.rnn = LSTM(self.n_hidden, self.n_hidden, self.n_layers)\n else:\n self.rnn = LSTM(self.n_hidden, self.n_hidden)\n\n # for images, we use resnet18, and modify the number of output classes\n self.image_feature_extractor = resnet18(pretrained=False)\n self.image_feature_extractor.fc = Linear(512, self.im_vec_dim)\n \n def forward(self, x):\n return self.image_feature_extractor(x)\n\n def forward_question(self, x):\n # we have a question as input\n if not self.h:\n batch_size = x.shape[1]\n self.h = torch.zeros(1, batch_size, self.n_hidden, device=self.device), torch.zeros(1, batch_size, self.n_hidden, device=self.device) # h0, c0\n res, h = self.rnn(self.i_h(x), self.h)\n self.h = h[0].detach(), h[1].detach()\n return self.h_o(res)\n\n def forward_answer(self, x):\n # just a linear layer over the embeddings to begin with\n x = self.i_h(x)\n return self.ans_final(x)\n \n def training_step(self, batch, batch_idx):\n loss = self.shared_step(batch)\n self.log(\"train_loss\", loss, prog_bar=True)\n return loss \n\n def validation_step(self, batch, batch_idx):\n # what hyperparams am I varying?\n loss = self.shared_step(batch)\n self.log(\"val_loss\", loss, prog_bar=True)\n return loss \n\n def shared_step(self, batch):\n # we test a question-image vector instead - so not quite Jeopardy\n question, image, answer = batch\n question = torch.stack(question)\n f_q = self.forward_question(question)\n f_q = f_q.squeeze()[-1, :]\n f_a = self.forward_answer(answer)\n im_vector = self(image)\n question_image_vector = torch.cat((f_q, im_vector), 1)\n loss = SimCLR(question_image_vector, f_a).get_loss()\n return loss\n\n def configure_optimizers(self):\n return SGD(self.parameters(), momentum=self.op.momentum, weight_decay=self.op.weight_decay, lr=self.op.learning_rate)\n","sub_path":"project/model_im_q_a.py","file_name":"model_im_q_a.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"136945063","text":"from copy_model import copy_model\nfrom eval_sine_test import eval_sine_test\nfrom sine_generator import SinusoidGenerator \n\nfrom tensorflow import keras\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use(['dark_background'])\nimport matplotlib as mpl\n\ncolors = {0:'dodgerblue' , 1: 'tomato' , 2:'forestgreen', 3:'cyan', 4:'yellow' }\n\ndef eval_sinewave_for_test(model, sinusoid_generator=None, num_steps=(0, 1, 10), lr=0.01, plot=True):\n '''Evaluates how the sinewave addapts at dataset.\n \n The idea is to use the pretrained model as a weight initializer and\n try to fit the model on this new dataset.\n \n Args:\n model: Already trained model.\n sinusoid_generator: A sinusoidGenerator instance.\n num_steps: Number of training steps to be logged.\n lr: Learning rate used for training on the test data.\n plot: If plot is True than it plots how the curves are fitted along\n `num_steps`.\n \n Returns:\n The fit results. A list containing the loss, logits and step. For\n every step at `num_steps`.\n '''\n \n if sinusoid_generator is None:\n sinusoid_generator = SinusoidGenerator(K=10)\n \n # generate equally spaced samples for ploting\n x_test, y_test = sinusoid_generator.equally_spaced_samples(100)\n \n # batch used for training\n x, y = sinusoid_generator.batch()\n \n # copy model so we can use the same model multiple times\n copied_model = copy_model(model, x)\n \n # use SGD for this part of training as described in the paper\n optimizer = keras.optimizers.SGD(learning_rate=lr)\n \n # run training and log fit results\n fit_res, w3_copied_model, weight_gradient, loss_finetune = eval_sine_test(copied_model, optimizer, x, y, x_test, y_test, num_steps)\n \n # plot\n fig = plt.figure(figsize=(12, 5), tight_layout=True)\n ax = fig.add_subplot(1,1,1)\n train, = ax.plot(x, y, '^')\n ground_truth, = ax.plot(x_test, y_test)\n plots = [train, ground_truth]\n legend = ['Training Points', 'True Function']\n i = 0\n for n, res, loss in fit_res:\n cur, = ax.plot(x_test, res[:, 0], '--', color=colors[i] )\n plots.append(cur)\n legend.append(f'After {n} Steps')\n i +=1\n \n ax.legend(plots, legend)\n ax.set_ylim(-5, 5)\n ax.set_xlim(-6, 6)\n if plot:\n plt.show()\n \n return fit_res, w3_copied_model, weight_gradient, loss_finetune","sub_path":"maml_sin/eval_sinewave_for_test.py","file_name":"eval_sinewave_for_test.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"176085188","text":"import socket\n\n\n#非阻塞io失败的例子\n# sk=socket.socket()\n# sk.bind(('127.0.0.1',10066))\n# #设置为非阻塞 默认是阻塞\n# sk.setblocking(False)\n# sk.listen()\n# # 如果没有收到链接就一直阻塞,让出了cpu控制权\n# #sk.accept()\n# while True:\n# try:\n# #sk.setblocking(False)之后\n# #收不到链接不但阻塞并且报错\n# #recv同理\n# conn,addr=sk.accept()\n# if conn:\n# print('建立链接')\n# msg=conn.recv(1024)\n# print(msg)\n# except BlockingIOError:\n# pass\n\n\nsk=socket.socket()\nsk.bind(('127.0.0.1',10066))\n#设置为非阻塞 默认是阻塞 把socket当中需要阻塞的方法都改变成非阻塞 recv recvfrom accpet\nsk.setblocking(False)\nsk.listen()\n# 如果没有收到链接就一直阻塞,让出了cpu控制权\n#sk.accept()\ncon_lista=[]\ndel_lista=[]\nwhile True:\n try:\n #sk.setblocking(False)之后\n #收不到链接不但阻塞并且报错\n #recv同理\n conn,addr=sk.accept()\n print('建立链接',addr)\n # 要将链接存入列表,这是因为client有网络延迟\n # 本机执行代码速度远远快过网络延迟,如果recv放在这里回报错\n # 且恰好这是再有人链接server,conn会e被内存冲掉,就找不到当时和\n # server链接的通道\n con_lista.append(conn)\n except BlockingIOError:\n for a in con_lista:\n try:\n #这里为什么将recv放在这里呢\n #如果是非阻塞模式,那么收不到信息会报错\n #这是因为client端有网络延迟,但是代码在本机会执行的\n #很快所以必须要放在下边\n msg = a.recv(1024)\n if msg==b'':\n # 如果客户端断开链接那么 接到的信息是byte类型的空信息\n # 那么就将链接加入到del_lista列表中,这样就保存了准备删除的链接\n del_lista.append(a)\n continue\n print(msg)\n a.send(b'byebye')\n except BlockingIOError:\n pass\n #等待循环结束之后 由于del_lista已经储存了将要删除的链接,则就可以循环删除\n for conn in del_lista:\n conn.close()\n con_lista.remove(conn)\n #同时清空del_lista列表中的元素\n del_lista.clear()\n\n'''\n非阻塞io一般不推荐\n优点 :\n 能够在等待任务完成的时间里干其他活 (包括提交其他任务,也就是后台 可以有多个任务在同时执行)\n\n缺点:\n 1 循环调用recv()将大幅推高cpu占用率,这也是我们在代码中留一句time.sleep()的原因,否则在低配主机下极容易出现卡机情况\n 2 任务完成的响应延迟增大了,因为每过一段时间才去轮训一次read操作,而任务可能在两次轮询之间的任意时间完成,这回导致整体\n 数据吞吐量的降低\n\n此外 在这个方案占用recv()更多的是起到检测 操作是否完成 的作用,实际操作系统提供了更为高效的检测 操作是否完成 作用的接口\n例如select()多路复用模式,可以一次检测多个链接是否活跃\n\n'''","sub_path":"day41/非阻塞io/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"54787626","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\noveralls = []\nsingle_grammars = []\nlabels = []\n\ndef add(name, overall, single):\n labels.append(name)\n overalls.append(overall)\n single_grammars.append(single)\n\n# 1. time ./compile.sh rlmeta.py > /dev/null\n# 2. python -m cProfile -s tottime rlmeta.py < parser.rlmeta\n\nadd('vm\\noriginal', 0.254, 0.104)\nadd('vm\\nmemo failures', 0.241, 0.087)\nadd('vm\\nposter', 0.212, 0.084)\n\nind = np.arange(len(overalls)) # the x locations for the groups\nwidth = 0.35 # the width of the bars\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(ind - width/2, overalls, width, label='Overall')\nrects2 = ax.bar(ind + width/2, single_grammars, width, label='Single grammar')\n\nax.set_ylabel('Compilation time (s)')\nax.set_xticks(ind)\nax.set_xticklabels(labels)\nax.legend()\n\nplt.xticks(rotation=70)\n\nfig.tight_layout()\n\nplt.show()\n","sub_path":"writing/creating-rlmeta-poster/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"79110819","text":"def mediana(tab):\r\n sorted_tab = sorted(tab)\r\n n = len(sorted_tab)\r\n if n % 2 == 0:\r\n return (sorted_tab[n // 2] + sorted_tab[n // 2 - 1]) / 2\r\n else:\r\n return sorted_tab[n // 2]\r\n\r\n\r\n# dominanta to element wystepujacy w tablicy najczesciej\r\n# jesli takich elementow jest kilka, to wszystkie sa dominantami (dlatego funkcja zwraca tablice)\r\ndef dominanta(tab):\r\n num_count = {}\r\n \r\n for n in tab:\r\n if n not in num_count:\r\n num_count[n] = tab.count(n)\r\n\r\n highest_counter = max(num_count.values())\r\n return [n for n in num_count if num_count[n] == highest_counter]\r\n\r\n\r\ntab = [2, 3, 5, 2, 9, 8, 1, 3, 9, 1, 1, 4, 7, 7, 1, 4]\r\n\r\nprint(f'Mediana: {mediana(tab)}')\r\nprint(f'Dominanta: {dominanta(tab)}')","sub_path":"04-Subroutines/zad29.py","file_name":"zad29.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"368591287","text":"\"\"\"\n랜선 자르기 https://www.acmicpc.net/problem/1654\n\"\"\"\n\n\ndef fn(param):\n return sum([i // param for i in data])\n\n\ndef search():\n lo = 0\n hi = data[-1] + 1\n while lo + 1 < hi:\n mid = (lo + hi) // 2\n temp = fn(mid)\n print(f\"lo={lo} mid={mid} hi={hi} temp={temp}\")\n if temp >= n:\n lo = mid\n else:\n hi = mid\n return lo\n\n\nk, n = map(int, input().split())\ndata = [int(input()) for _ in range(k)]\ndata.sort()\nprint(search())\n","sub_path":"7주차 이분탐색,그래프/백준/랜선자르기/하현준.py","file_name":"하현준.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"269254427","text":"from views import success, index, submit_survey, engine\nfrom models import Survey, Base\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom bottle.ext import sqlalchemy\n\n\nfrom bottle import Bottle, run, debug\n\napp = Bottle()\n\nBase.metadata.create_all(engine)\n\n\nplugin = sqlalchemy.Plugin(\n engine,\n Base.metadata,\n keyword='db',\n create=True,\n commit=True,\n use_kwargs=False\n)\n\napp.install(plugin)\n\n\nif __name__=='__main__':\n debug(True)\n run()","sub_path":"SurveryApp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"569272547","text":"from django.db import models\n\n# Create your models here.\nclass blog(models.Model):\n\ttitle = models.CharField(max_length=200)\n\t#Slug is a way of generating a valid URL, generally using data already obtained.\n\t# For instance, using the title of an article to generate a URL\n\tslug = models .SlugField(max_length=200,unique=True)\n\tpublish = models.BooleanField(default=True)\n\tpost_date= models.DateTimeField(auto_now_add=True,auto_now=False)\n\tmodified = models.DateTimeField(auto_now_add=False,auto_now=True)\n\n\tdef __str__(self):\n\t\treturn self.title\n\tclass Meta:\n\t\tverbose_name=\"Blog Entry\"\n\t\tverbose_name_plural=\"Blog Entries\"\n\t\tordering = [\"-post_date\"]\n","sub_path":"samurai/home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"514046405","text":"from torchvision.datasets import ImageFolder\nimport os\nimport shutil\nimport torch\nimport torch.nn as nn\nfrom torch.utils.model_zoo import load_url as load_state_dict_from_url\nfrom torch.autograd import Function\nimport logging\nimport numpy as np\nimport torch.optim as optim\nfrom torch.utils.data import Subset, DataLoader\nfrom torch.backends import cudnn\nimport torchvision\nfrom torchvision import transforms\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom torchvision.datasets import VisionDataset\nimport os.path\nimport sys\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms.functional import pad\nimport numbers\nimport torch.nn.functional as F\nfrom torchvision import models\nimport types\n\n\ndef pil_loader(path):\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('RGB')\n\ndef zoom_img(img, zoom_perc):\n \"\"\"\n img: PIL image\n zoom_perc: [0, 100]\n Return cropped_img\n \"\"\"\n zoom_perc /= 100\n # images given to this method are already transformed to square images by the pre zoom transform\n # to avoid inconsistencies, the min(width, height) is taken as resize shape. THis is the value that is used to\n # decide the size of the zoom reduction\n width, height = img.size\n resize_shape = min(width, height)\n\n crop_size = int(resize_shape * (1-zoom_perc))\n\n transformer = transforms.Compose([\n transforms.CenterCrop(crop_size)\n ])\n return transformer(img)\n\ndef uniform_difference_couple(max_val):\n \"\"\"\n Returns 0 and an integer uniformly asmpled in the interval [0, max_val].\n 0 is randomly assigned to int1 or int2.\n Return int1, int2, diff\n \"\"\"\n diff = np.random.randint(0, max_val + 1)\n b = np.random.binomial(n=1, p=0.5)\n if b:\n return 0, diff, diff\n return diff, 0, diff\n\ndef zoom_task_extractor(rgb_image, depth_image, label, parameters_dict):\n MAX_ZOOM_PERCENTAGE = parameters_dict[\"MAX_ZOOM_PERCENTAGE\"]\n PRE_ZOOM_TRANSFORM = parameters_dict[\"PRE_ZOOM_TRANSFORM\"] # Preprocessing before zoom. Same for RGB and D\n MAIN_RGB_TRANSFORM = parameters_dict[\"MAIN_RGB_TRANSFORM\"] # Preprocessing for original RGB image\n MAIN_DEPTH_TRANSFORM = parameters_dict[\"MAIN_DEPTH_TRANSFORM\"] # Preprocessing for original D image\n POST_ZOOM_RGB_TRANSFORM = parameters_dict[\"POST_ZOOM_RGB_TRANSFORM\"] # Preprocessing for zoomed RGB image\n POST_ZOOM_DEPTH_TRANSFORM = parameters_dict[\"POST_ZOOM_DEPTH_TRANSFORM\"] # Preprocessing for zoomed D image\n\n zoom_perc1, zoom_perc2, pretext_task_label = uniform_difference_couple(MAX_ZOOM_PERCENTAGE)\n\n preprocessed_rgb_image = PRE_ZOOM_TRANSFORM(rgb_image)\n preprocessed_depth_image = PRE_ZOOM_TRANSFORM(depth_image)\n\n if zoom_perc1 > 0:\n zoomed_rgb_image = zoom_img(preprocessed_rgb_image, zoom_perc1)\n else:\n zoomed_rgb_image = preprocessed_rgb_image\n \n if zoom_perc2 > 0:\n zoomed_depth_image = zoom_img(preprocessed_depth_image, zoom_perc2)\n else:\n zoomed_depth_image = preprocessed_depth_image\n\n if MAIN_RGB_TRANSFORM is not None and MAIN_DEPTH_TRANSFORM is not None:\n rgb_image = MAIN_RGB_TRANSFORM(rgb_image)\n depth_image = MAIN_DEPTH_TRANSFORM(depth_image)\n if POST_ZOOM_DEPTH_TRANSFORM is not None and POST_ZOOM_RGB_TRANSFORM is not None:\n zoomed_rgb_image = POST_ZOOM_RGB_TRANSFORM(zoomed_rgb_image)\n zoomed_depth_image = POST_ZOOM_DEPTH_TRANSFORM(zoomed_depth_image)\n return (rgb_image, depth_image, label), (zoomed_rgb_image, zoomed_depth_image, pretext_task_label)\n\ndef decentralized_zoom_task_extractor(rgb_image, depth_image, label, parameters_dict):\n MAX_ZOOM_PERCENTAGE = parameters_dict[\"MAX_ZOOM_PERCENTAGE\"]\n PRE_ZOOM_TRANSFORM = parameters_dict[\"PRE_ZOOM_TRANSFORM\"] # Preprocessing before zoom. Same for RGB and D\n MAIN_RGB_TRANSFORM = parameters_dict[\"MAIN_RGB_TRANSFORM\"] # Preprocessing for original RGB image\n MAIN_DEPTH_TRANSFORM = parameters_dict[\"MAIN_DEPTH_TRANSFORM\"] # Preprocessing for original D image\n POST_ZOOM_RGB_TRANSFORM = parameters_dict[\"POST_ZOOM_RGB_TRANSFORM\"] # Preprocessing for zoomed RGB image\n POST_ZOOM_DEPTH_TRANSFORM = parameters_dict[\"POST_ZOOM_DEPTH_TRANSFORM\"] # Preprocessing for zoomed D image\n \n # Preprocessing\n preprocessed_rgb_image = PRE_ZOOM_TRANSFORM(rgb_image)\n preprocessed_depth_image = PRE_ZOOM_TRANSFORM(depth_image)\n \n pretext_task_label = np.random.randint(0, MAX_ZOOM_PERCENTAGE + 1)\n choose_crop = np.random.randint(0, 5) # top-left, top-right, center...\n b = np.random.binomial(n=1, p=0.5) # who crop? toss coin...\n \n crop_size = int(224 * (1-pretext_task_label/100))\n five_crop = transforms.FiveCrop(crop_size)\n if b:\n # zoomed_rgb_image\n top_left, top_right, bottom_left, bottom_right, center = five_crop(preprocessed_rgb_image)\n crops = [top_left, top_right, bottom_left, bottom_right, center]\n zoomed_rgb_image = crops[choose_crop]\n # zoomed_depth_image\n zoomed_depth_image = preprocessed_depth_image\n else:\n # zoomed_rgb_image\n zoomed_rgb_image = preprocessed_rgb_image\n # zoomed_depth_image\n top_left, top_right, bottom_left, bottom_right, center = five_crop(preprocessed_depth_image)\n crops = [top_left, top_right, bottom_left, bottom_right, center]\n zoomed_depth_image = crops[choose_crop]\n \n # Postprocessing\n if MAIN_RGB_TRANSFORM is not None and MAIN_DEPTH_TRANSFORM is not None:\n rgb_image = MAIN_RGB_TRANSFORM(rgb_image)\n depth_image = MAIN_DEPTH_TRANSFORM(depth_image)\n if POST_ZOOM_DEPTH_TRANSFORM is not None and POST_ZOOM_RGB_TRANSFORM is not None:\n zoomed_rgb_image = POST_ZOOM_RGB_TRANSFORM(zoomed_rgb_image)\n zoomed_depth_image = POST_ZOOM_DEPTH_TRANSFORM(zoomed_depth_image)\n return (rgb_image, depth_image, label), (zoomed_rgb_image, zoomed_depth_image, pretext_task_label)\n \n \ndef relative_rot_task_extractor(rgb_image, depth_image, label, parameters_dict):\n MAIN_RGB_TRANSFORM = parameters_dict[\"MAIN_RGB_TRANSFORM\"] # Preprocessing for original RGB image\n MAIN_DEPTH_TRANSFORM = parameters_dict[\"MAIN_DEPTH_TRANSFORM\"] # Preprocessing for original RGB image\n PRETEXT_RGB_TRANSFORM = parameters_dict[\"PRETEXT_RGB_TRANSFORM\"] # Preprocessing for rotated RGB image\n PRETEXT_DEPTH_TRANSFORM = parameters_dict[\"PRETEXT_DEPTH_TRANSFORM\"] # Preprocessing for rotated D image\n\n j, k = np.random.randint(0, 4, 2)\n #j is the rotation index for rgb image\n #k is the rotation index for depth image\n z_encoding = (k-j) % 4\n # j k\n rgb_rot, depth_rot = j, k\n\n rotated_rgb_image = rgb_image.rotate(rgb_rot*(-90))\n rotated_depth_image = depth_image.rotate(depth_rot*(-90))\n\n if MAIN_RGB_TRANSFORM is not None and MAIN_DEPTH_TRANSFORM is not None :\n rgb_image = MAIN_RGB_TRANSFORM(rgb_image)\n depth_image = MAIN_DEPTH_TRANSFORM(depth_image)\n if PRETEXT_RGB_TRANSFORM is not None and PRETEXT_DEPTH_TRANSFORM is not None:\n rotated_rgb_image = PRETEXT_RGB_TRANSFORM(rotated_rgb_image)\n rotated_depth_image = PRETEXT_DEPTH_TRANSFORM(rotated_depth_image)\n return (rgb_image, depth_image, label), (rotated_rgb_image, rotated_depth_image, z_encoding)\n","sub_path":"Base models/dataset/rod_utils.py","file_name":"rod_utils.py","file_ext":"py","file_size_in_byte":7610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"314311240","text":"\"\"\"index file for RMSE, MAE, MAPE error creator\n\"\"\"\nimport datetime as dt\nfrom typing import List, Tuple\nfrom src.revisionwiseErrorStorage.actualDemandFetch import ActualDemandFetchRepo\nfrom src.revisionwiseErrorStorage.forecastedDemandFetch import ForecastedDemandFetchRepo\nfrom src.revisionwiseErrorStorage.revisionwiseVariousErrorCalculation import calculateRevisionwiseErrors\nfrom src.revisionwiseErrorStorage.revisionwiseErrorInsertion import RevisionwiseErrorInsertion\n\n\ndef createRevisionwiseError(startDate: dt.datetime, endDate: dt.datetime, configDict: dict) -> bool:\n \"\"\"create revisionwise mean abs error, RMSE, MAE, MAPE between start and end dates\n\n Args:\n startDate (dt.datetime): start date\n endDate (dt.datetime): end date\n \n configDict (dict): application configuration\n Returns:\n bool: returns true if errror storage is successfull, else false\n \"\"\" \n\n con_string = configDict['con_string_mis_warehouse']\n obj_actualDemandFetchRepo = ActualDemandFetchRepo(con_string)\n obj_forecastedDemandFetchRepo = ForecastedDemandFetchRepo(con_string)\n obj_revisionwiseErrorInsertion = RevisionwiseErrorInsertion(con_string)\n\n currDate = startDate\n insertSuccessCount = 0\n revisionList = ['R0A', 'R0B', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15', 'R16']\n # revisionList = ['R0A']\n\n while currDate <= endDate:\n for revisionNo in revisionList:\n #fetch actual demand\n actualDemandDf = obj_actualDemandFetchRepo.fetchActualDemand(currDate, currDate)\n \n #fetch forecasted demand\n forecastedDemandDf = obj_forecastedDemandFetchRepo.fetchForecastedDemand(currDate, currDate, revisionNo)\n \n #calculate RMSE, MAE, MAPE\n data:List[Tuple] = calculateRevisionwiseErrors(actualDemandDf, forecastedDemandDf, revisionNo, currDate.date())\n #push errors to db\n isInsertionSuccess = obj_revisionwiseErrorInsertion.insertRevisionwiseError(data)\n\n if isInsertionSuccess:\n insertSuccessCount = insertSuccessCount + 1\n\n\n # update currDate\n currDate += dt.timedelta(days=1)\n\n numOfDays = (endDate-startDate).days\n if insertSuccessCount == 18*(numOfDays +1) :\n return True\n else:\n return False","sub_path":"src/revisionwiseErrorStorage/revisionwiseErrorCreator.py","file_name":"revisionwiseErrorCreator.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"200906782","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def averageOfLevels(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[float]\n \"\"\"\n if not root:\n return 0\n node_list = [root]\n res = []\n num = 1\n while len(node_list) > 0:\n avg = 0\n count = num\n num = 0\n for i in range (0, count):\n first_ele = node_list.pop(0)\n avg += first_ele.val\n if first_ele.left:\n node_list.append(first_ele.left)\n num += 1\n if first_ele.right:\n node_list.append(first_ele.right)\n num += 1\n avg = avg*1.0 / count\n res.append(avg)\n return res\n ","sub_path":"637.py","file_name":"637.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"571384916","text":"from django.conf import settings\nfrom django.core import mail\nfrom django.urls import reverse\n\nfrom extforms.forms import WorkshopInquiryRequestExternalForm\nfrom extrequests.models import WorkshopInquiryRequest\nfrom workshops.models import Curriculum, InfoSource, Language\nfrom workshops.tests.base import TestBase\n\n\nclass TestWorkshopInquiryExternalForm(TestBase):\n \"\"\"Test external (accessible to non-logged in users) form.\"\"\"\n\n def test_fields_presence(self):\n \"\"\"Test if the form shows correct fields.\"\"\"\n form = WorkshopInquiryRequestExternalForm()\n fields_left = set(form.fields.keys())\n fields_right = set(\n [\n \"personal\",\n \"family\",\n \"email\",\n \"secondary_email\",\n \"institution\",\n \"institution_other_name\",\n \"institution_other_URL\",\n \"institution_department\",\n \"location\",\n \"country\",\n \"routine_data\",\n \"routine_data_other\",\n \"domains\",\n \"domains_other\",\n \"academic_levels\",\n \"computing_levels\",\n \"audience_description\",\n \"requested_workshop_types\",\n \"preferred_dates\",\n \"other_preferred_dates\",\n \"language\",\n \"number_attendees\",\n \"administrative_fee\",\n \"travel_expences_management\",\n \"travel_expences_management_other\",\n \"travel_expences_agreement\",\n \"institution_restrictions\",\n \"institution_restrictions_other\",\n \"public_event\",\n \"public_event_other\",\n \"additional_contact\",\n \"carpentries_info_source\",\n \"carpentries_info_source_other\",\n \"user_notes\",\n \"data_privacy_agreement\",\n \"code_of_conduct_agreement\",\n \"host_responsibilities\",\n \"instructor_availability\",\n \"workshop_listed\",\n \"online_inperson\",\n \"captcha\",\n ]\n )\n self.assertEqual(fields_left, fields_right)\n\n def test_request_added(self):\n \"\"\"Ensure the request is successfully added to the pool, and\n notification email is sent.\"\"\"\n data = {\n \"personal\": \"Harry\",\n \"family\": \"Potter\",\n \"email\": \"hpotter@magic.gov\",\n \"institution_other_name\": \"Ministry of Magic\",\n \"institution_other_URL\": \"magic.gov.uk\",\n \"location\": \"London\",\n \"country\": \"GB\",\n \"requested_workshop_types\": [\n Curriculum.objects.get(slug=\"swc-python\").pk,\n Curriculum.objects.get(slug=\"dc-ecology-r\").pk,\n ],\n \"preferred_dates\": \"\",\n \"other_preferred_dates\": \"03-04 November, 2018\",\n \"language\": Language.objects.get(name=\"English\").pk,\n \"number_attendees\": \"10-40\",\n \"audience_description\": \"Students of Hogwarts\",\n \"administrative_fee\": \"waiver\",\n \"scholarship_circumstances\": \"Bugdet cuts in Ministry of Magic\",\n \"travel_expences_management\": \"booked\",\n \"travel_expences_management_other\": \"\",\n \"travel_expences_agreement\": True,\n \"institution_restrictions\": \"other\",\n \"institution_restrictions_other\": \"Only for wizards\",\n \"public_event\": \"closed\",\n \"public_event_other\": \"\",\n \"additional_contact\": \"\",\n \"carpentries_info_source\": [InfoSource.objects.first().pk],\n \"carpentries_info_source_other\": \"\",\n \"user_notes\": \"n/c\",\n \"data_privacy_agreement\": True,\n \"code_of_conduct_agreement\": True,\n \"host_responsibilities\": True,\n \"instructor_availability\": True,\n \"online_inperson\": \"inperson\",\n }\n self.passCaptcha(data)\n\n rv = self.client.post(reverse(\"workshop_inquiry\"), data, follow=True)\n self.assertEqual(rv.status_code, 200)\n content = rv.content.decode(\"utf-8\")\n if \"form\" in rv.context:\n self.assertEqual(\n rv.context[\"form\"].is_valid(), True, dict(rv.context[\"form\"].errors)\n )\n self.assertNotIn(\"Please fix errors in the form below\", content)\n self.assertIn(\"Thank you for inquiring about The Carpentries\", content)\n self.assertEqual(WorkshopInquiryRequest.objects.all().count(), 1)\n self.assertEqual(WorkshopInquiryRequest.objects.all()[0].state, \"p\")\n\n # 1 email for autoresponder, 1 email for admins\n self.assertEqual(len(mail.outbox), 2)\n\n # save the email messages for test debuggig\n # with open('email0.eml', 'wb') as f:\n # f.write(mail.outbox[0].message().as_bytes())\n # with open('email1.eml', 'wb') as f:\n # f.write(mail.outbox[1].message().as_bytes())\n\n # before tests, check if the template invalid string exists\n self.assertTrue(settings.TEMPLATES[0][\"OPTIONS\"][\"string_if_invalid\"])\n\n # test autoresponder email\n msg = mail.outbox[0]\n self.assertEqual(msg.subject, \"Workshop inquiry confirmation\")\n self.assertEqual(msg.recipients(), [\"hpotter@magic.gov\"])\n self.assertNotIn(\n settings.TEMPLATES[0][\"OPTIONS\"][\"string_if_invalid\"], msg.body\n )\n # test email for admins\n msg = mail.outbox[1]\n self.assertEqual(\n msg.subject,\n \"New workshop inquiry: Ministry of Magic, 03-04 November, 2018\",\n )\n self.assertEqual(msg.recipients(), [\"admin-uk@carpentries.org\"])\n self.assertNotIn(\n settings.TEMPLATES[0][\"OPTIONS\"][\"string_if_invalid\"], msg.body\n )\n","sub_path":"amy/extforms/tests/test_workshop_inquiry_form.py","file_name":"test_workshop_inquiry_form.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"133318905","text":"import datetime\nimport pymysql.cursors\n\n\nconnection = pymysql.connect(host='192.168.0.37',\n user='root',\n password='12345',\n db='testbase',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\n\nlist_number = 598770 # list_number = 청원 글 시작 번호\nexcept_count = 0 # except_count = 예외 실행 횟수\nwith connection.cursor() as cursor:\n sel_date = \"SELECT subdate FROM daydata ORDER BY subdate DESC limit 1 \"\n cursor.execute(sel_date)\n final_date = cursor.fetchone()\n final_date = str(final_date['subdate'])\n\n\n sql = \"select no, subdate from petition where subdate = %s ORDER BY no DESC\"\n cursor.execute(sql, (final_date))\n row = cursor.fetchone()\n list_number = row['no'] + 1\n\nlast_date=\"\"\nword_list=\"\"\nwhile except_count <= 10: # 예외가 10번 실행될때까지 반복\n try:\n with connection.cursor() as cursor:\n no = list_number\n sql = \"select no, subdate from petition where no = %s\"\n cursor.execute(sql, (no))\n row = cursor.fetchone()\n #print(row)\n subdate = row['subdate']\n\n sql_2 = \"select worddata from PETITIONDATA where no = %s\"\n cursor.execute(sql_2, (no))\n row = cursor.fetchone()\n worddata = row['worddata']\n #print(subdate,worddata)\n\n\n\n if last_date == subdate:\n word_list += worddata\n\n elif last_date != subdate:\n if word_list !=\"\":\n with connection.cursor() as cursor:\n cursor.execute(\"insert into daydata values(%s, %s)\", (last_date , word_list))\n connection.commit()\n\n\n word_list = \"\"\n word_list += worddata\n #print(last_date == subdate)\n\n\n\n #print(word_list)\n list_number += 1\n except_count = 0\n\n last_date = subdate\n except Exception as e:\n except_count += 1\n print(list_number, '예외가 발생했습니다!!!!!', e, except_count)\n if except_count == 10 :\n if word_list != \"\":\n with connection.cursor() as cursor:\n cursor.execute(\"insert into daydata values(%s, %s)\", (last_date, word_list))\n connection.commit()\n list_number += 1","sub_path":"keywords/day_data.py","file_name":"day_data.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"592033931","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy import Request\nimport json\n\n\nclass XiciSpider(scrapy.Spider):\n name = 'xici_spider'\n allowed_domains = ['www.xicidaili.com']\n list_url = 'http://www.xicidaili.com/nn/%s'\n\n def start_requests(self):\n ip = \"127.0.0.1\"\n port = \"1087\"\n scheme = \"http\"\n url = '%s://httpbin.org/ip' % scheme\n proxy = '%s://%s:%s' % (scheme, ip, port)\n meta = {\n 'proxy': proxy,\n 'dont_rely': True,\n 'download_timeout': 10,\n\n # 检测字段,传递给check_available方法\n '_proxy_scheme': scheme,\n '_proxy_ip': ip,\n }\n\n yield Request(url, callback=self.check_available, meta=meta, dont_filter=True)\n\n for i in range(1, 4):\n yield Request(self.list_url % i)\n\n def parse(self, response):\n for sel in response.xpath('//table[@id=\"ip_list\"]/tr[position()>1]'):\n ip = sel.css('td:nth-child(2)::text').extract_first()\n port = sel.css('td:nth-child(3)::text').extract_first()\n scheme = sel.css('td:nth-child(6)::text').extract_first()\n\n # 验证代理是否可用\n url = '%s://httpbin.org/ip' % scheme\n proxy = '%s://%s:/%s' % (scheme, ip, port)\n\n meta = {\n 'proxy': proxy,\n 'dont_rely': True,\n 'download_timeout': 10,\n\n # 检测字段,传递给check_available方法\n '_proxy_scheme': scheme,\n '_proxy_ip': ip,\n }\n\n yield Request(url, callback=self.check_available, meta=meta, dont_filter=True)\n\n def check_available(self, response):\n proxy_ip = response.meta['_proxy_ip']\n print(\"proxy_ip \")\n print(proxy_ip)\n print(\"\\r\\r\")\n print(\"response.meta \")\n print(response.meta)\n print(\"\\r\\r\")\n print(\"response.text \")\n print(response.text)\n print(\"\\r\\r\")\n print(\"response \")\n print(response)\n\n if proxy_ip == json.loads(response.text)['origin']:\n yield {\n 'proxy_scheme': response.meta['_proxy_scheme'],\n 'proxy': response.meta['proxy']\n }\n\n\nclass TestRandomProxySpider(scrapy.Spider):\n name = \"test_random_proxy\"\n\n def start_requests(self):\n for _ in range(5):\n yield Request('http://httpbin.org/ip', dont_filter=True)\n yield Request('https://httpbin.org/ip', dont_filter=True)\n\n def parse(self, response):\n print(json.loads(response.text))\n","sub_path":"Scrapy/proxy_example/proxy_example/spiders/xici_spider.py","file_name":"xici_spider.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"568035316","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Listing\nfrom django.core.paginator import Paginator\nfrom realtors.models import Realtor\nfrom .choices import bedroom_choices, price_choices, state_choices\n# Create your views here.\n\n\ndef index(request):\n listings = Listing.objects.all()\n paginator = Paginator(listings, 3)\n page_num = request.GET.get('page')\n paged_listings = paginator.get_page(page_num)\n\n context = {'paged_listings':paged_listings}\n\n\n return render(request, 'listings/listings.html', context)\n\ndef listing(request, id):\n listing_obj = get_object_or_404(Listing, pk=id)\n #realtors = Realtor.objects.get(pk=id)\n\n context = {\n 'listing': listing_obj,\n # 'realtor': realtors\n }\n return render(request, 'listings/listing.html', context)\n\ndef search(request):\n listings = Listing.objects.order_by('-create_date')\n if 'keywords' in request.GET:\n keywords = request.GET['keywords']\n if keywords:\n listings = listings.filter(description__icontains=keywords)\n\n if 'city' in request.GET:\n city = request.GET['city']\n if city:\n listings = listings.filter(city__iexact=city)\n\n if 'state' in request.GET:\n state = request.GET['state']\n if state:\n listings = listings.filter(state__iexact=state)\n\n if 'bedrooms' in request.GET:\n bedrooms = request.GET['bedrooms']\n if bedrooms:\n listings = listings.filter(bedrooms__lte=bedrooms)\n\n if 'price' in request.GET:\n price = request.GET['price']\n if price:\n listings = listings.filter(price__lte=price)\n\n context = {\n 'listings': listings,\n 'state_choices': state_choices,\n 'bedroom_choices': bedroom_choices,\n 'price_choices': price_choices,\n 'values': request.GET\n }\n return render(request, 'listings/search.html', context)\n\n\n","sub_path":"listings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"424285200","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom lab4 import utils\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nclass DBN():\n\n def __init__(self):\n\n self.init_params()\n self.init_data()\n\n def init_params(self):\n\n self.Nv = 784 # broj elemenata vidljivog sloja\n self.v_shape = (28, 28) # velicina slike\n self.Nh1 = 100 # broj elemenata 1 skrivenog sloja\n self.h1_shape = (10, 10) # 2D prikaz broja stanja\n self.Nh2 = 100 # broj elemenata 2 skrivenog sloja\n self.h2_shape = (10, 10) # 2D prikaz broja stanja\n\n self.Nu = 5000 # broj uzoraka za vizualizaciju rekonstrukcije\n self.gibbs_sampling_steps = 1\n self.alpha = 1\n self.batch_size = 100\n self.epochs = 100\n\n def init_data(self):\n\n self.mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n self.train_x, self.train_y = self.mnist.train.images, self.mnist.train.labels\n self.test_x, self.test_y = self.mnist.test.images, self.mnist.test.labels\n\n self.n_samples = self.mnist.train.num_examples\n self.total_batch = int(self.n_samples / self.batch_size) * self.epochs\n\n def init_model(self, w1, vb, hb1):\n\n self.X2 = tf.placeholder(\"float\", [None, self.Nv])\n self.w1 = tf.Variable(w1)\n self.v_bias = tf.Variable(vb)\n self.h1_bias = tf.Variable(hb1)\n self.w2 = utils.weights([self.Nh1, self.Nh2])\n self.h2_bias = utils.bias([self.Nh2])\n\n self.h1up_prob = tf.nn.sigmoid(tf.matmul(self.X2, self.w1) + self.h1_bias) # dopuniti\n self.h1up = utils.sample_prob(self.h1up_prob) # dopuniti\n self.h2up_prob = tf.nn.sigmoid(tf.matmul(self.h1up, self.w2) + self.h2_bias) # dopuniti\n self.h2up = utils.sample_prob(self.h2up_prob) # dopuniti\n self.h2down = self.h2up\n\n for step in range(self.gibbs_sampling_steps):\n self.h1down_prob = tf.nn.sigmoid(tf.matmul(self.h2down, tf.transpose(self.w2)) + self.h1_bias) # dopuniti\n self.h1down = utils.sample_prob(self.h1down_prob) # dopuniti\n self.h2down_prob = tf.nn.sigmoid(tf.matmul(self.h1down, self.w2) + self.h2_bias) # dopuniti\n self.h2down = utils.sample_prob(self.h2down_prob) # dopuniti\n\n w2_positive_grad = tf.matmul(tf.transpose(self.h1up), self.h2up) # dopuniti\n w2_negative_grad = tf.matmul(tf.transpose(self.h1down), self.h2down) # dopuniti\n\n dw2 = (w2_positive_grad - w2_negative_grad) / tf.to_float(tf.shape(self.h1up)[0])\n\n update_w2 = tf.assign_add(self.w2, self.alpha * dw2)\n update_hb1a = tf.assign_add(self.h1_bias, self.alpha * tf.reduce_mean(self.h1up - self.h1down, 0))\n update_hb2 = tf.assign_add(self.h2_bias, self.alpha * tf.reduce_mean(self.h2up - self.h2down, 0))\n\n self.out = (update_w2, update_hb1a, update_hb2)\n\n # rekonsturkcija ulaza na temelju krovnog skrivenog stanja h3\n self.h1_rec_prob = tf.nn.sigmoid(tf.matmul(self.h2down, tf.transpose(self.w2)) + self.h1_bias)\n self.h1_rec = utils.sample_prob(self.h1_rec_prob)\n self.v_out_prob = tf.nn.sigmoid(tf.matmul(self.h1_rec, tf.transpose(self.w1)) + self.v_bias) # dopuniti\n self.v_out = utils.sample_prob(self.v_out_prob) # dopuniti\n\n err = self.X2 - self.v_out_prob\n self.err_sum = tf.reduce_mean(err * err)\n\n self.initialize = tf.global_variables_initializer()\n\n def init_session(self):\n\n self.sess = tf.Session()\n self.sess.run(self.initialize)\n\n def train(self):\n\n for i in range(self.total_batch):\n batch, label = self.mnist.train.next_batch(self.batch_size)\n err, _ = self.sess.run([self.err_sum, self.out], feed_dict={self.X2: batch})\n\n if i % (int(self.total_batch / 10)) == 0:\n print(i, err)\n\n w1, w2, v_bias, h1_bias, h2_bias = self.sess.run([self.w1, self.w2, self.v_bias, self.h1_bias, self.h2_bias], feed_dict={self.X2: batch})\n v_out_prob, h_top = self.sess.run([self.v_out_prob, self.h2down], feed_dict={self.X2: self.test_x[0:self.Nu, :]})\n\n return w1, w2, v_bias, h1_bias, h2_bias, v_out_prob, h_top\n\n def visualize(self, w1, w2, v_bias, h1_bias, h2_bias, v_out_prob, h_top):\n\n # vizualizacija težina\n utils.draw_weights(w1, self.v_shape, self.Nh1, self.h1_shape, name=\"dbn_weights_w1.png\")\n utils.draw_weights(w2, self.h1_shape, self.Nh2, self.h2_shape, name=\"dbn_weights_w2.png\")\n\n # vizualizacija rekonstrukcije i stanja\n utils.draw_reconstructions(self.test_x, v_out_prob, h_top, self.v_shape, self.h2_shape, 20, name=\"dbn_reconstructions.png\")\n\n self.reconstruct(0, h_top, self.test_x, w1, v_bias) # prvi argument je indeks znamenke u matrici znamenki\n\n utils.draw_weights_freq(h_top, w1, self.v_shape, self.h2_shape, self.Nh2, name=\"dbn_weights_freq.png\")\n\n r_input = self.generate_patterns()\n\n out = self.sess.run((self.v_out), feed_dict={self.h2up: r_input})\n\n # Emulacija dodatnih Gibbsovih uzorkovanja pomocu feed_dict\n for i in range(1000):\n out_prob, out, hout = self.sess.run((self.v_out_prob, self.v_out, self.h2down), feed_dict={self.X2: out})\n\n utils.draw_generated(r_input, hout, out_prob, self.v_shape, self.h2_shape, 50, name=\"dbn_generated.png\")\n\n def generate_patterns(self):\n\n # Generiranje uzoraka iz slucajnih vektora\n r_input = np.random.rand(100, self.Nh2)\n r_input[r_input > 0.9] = 1 # postotak aktivnih - slobodno varirajte\n r_input[r_input < 1] = 0\n r_input = r_input * 20 # pojacanje za slucaj ako je mali postotak aktivnih\n\n s = 10\n i = 0\n r_input[i, :] = 0\n r_input[i, i] = s\n i += 1\n r_input[i, :] = 0\n r_input[i, i] = s\n i += 1\n r_input[i, :] = 0\n r_input[i, i] = s\n i += 1\n r_input[i, :] = 0\n r_input[i, i] = s\n i += 1\n r_input[i, :] = 0\n r_input[i, i] = s\n i += 1\n r_input[i, :] = 0\n r_input[i, i] = s\n i += 1\n r_input[i, :] = 0\n r_input[i, i] = s\n\n return r_input\n\n def reconstruct(self, ind, states, orig, weights, biases):\n\n # Slijedno iscrtavanje rekonstrukcije vidljivog sloja\n # ind - indeks znamenke u orig (matrici sa znamenkama kao recima)\n # states - vektori stanja ulaznih vektora\n # orig - originalnalni ulazni vektori\n # weights - matrica težina\n # biases - vektori pomaka vidljivog sloja\n\n j = 1\n in_a_row = 6\n Nimg = states.shape[1] + 3\n Nrows = int(np.ceil(float(Nimg + 2) / in_a_row))\n\n plt.figure(figsize=(12, 2 * Nrows))\n\n utils.draw_rec(states[ind], 'states', self.h2_shape, Nrows, in_a_row, j)\n j += 1\n utils.draw_rec(orig[ind], 'input', self.v_shape, Nrows, in_a_row, j)\n\n reconstr = biases.copy()\n j += 1\n utils.draw_rec(utils.sigmoid(reconstr), 'biases', self.v_shape, Nrows, in_a_row, j)\n\n for i in range(self.Nh2):\n if states[ind, i] > 0:\n j += 1\n reconstr = reconstr + weights[:, i]\n titl = '+= s' + str(i + 1)\n utils.draw_rec(utils.sigmoid(reconstr), titl, self.v_shape, Nrows, in_a_row, j)\n plt.tight_layout()\n\n\n","sub_path":"lab4/DBN.py","file_name":"DBN.py","file_ext":"py","file_size_in_byte":7401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"271232279","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls import url, include\nfrom rest_framework import routers, serializers, viewsets\nfrom . import views\n\nadmin.autodiscover()\n\nrouter = routers.DefaultRouter()\nrouter.register(r'terminal', views.TerminalList)\nrouter.register(r'sessions', views.SessionList)\nurlpatterns = [\n url(r'^api\\/', include(router.urls)),\n url(r'^api\\/api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'^api_sessions/add_user/', views.AddUser.as_view()),\n url(r'^api_sessions/add_card/', views.AddCard.as_view()),\n url(r'^api_sessions/delete_user/', views.DelUser.as_view()),\n url(r'^api_sessions/get_pays/', views.GetPays.as_view()),\n url(r'^api_sessions/', views.SessionApi.as_view()),\n]\n","sub_path":"modules/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"333886100","text":"# -*- coding: UTF-8 -*-\r\n\r\nfrom django import template\r\nfrom django.template.loader import render_to_string\r\n\r\nfrom apps.catalogues.models import PrimaryProduct, Category\r\n\r\n\r\nregister = template.Library()\r\n\r\n@register.simple_tag(takes_context=True)\r\ndef all_products_slider(context, template='siteblocks/top/blocks/all_products_slider.html'):\r\n products = PrimaryProduct.objects.filter(published=True)\r\n request = context['request']\r\n full_path = request.get_full_path()\r\n full_path = full_path.split('/', 1)[1][3:]\r\n return render_to_string(template, {\r\n 'products': products,\r\n 'request': request,\r\n 'full_path': full_path,\r\n })\r\n\r\n","sub_path":"apps/catalogues/templatetags/catalogue_tags.py","file_name":"catalogue_tags.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"346733998","text":"import time\nimport logging as log\nimport struct\n\nfrom profilehooks import profile\n\nfrom PySide import QtCore, QtNetwork\n\n\nclass NetController(QtCore.QObject):\n\n ready_to_read = QtCore.Signal()\n data_received = QtCore.Signal()\n\n def __init__(self, app):\n super(NetController, self).__init__()\n self.socket = None\n self.app = app\n self.updates = 0\n self.last_time = time.clock()\n self.init_socket()\n self._byte_array_cache = {}\n\n def init_socket(self):\n self.socket = QtNetwork.QUdpSocket(self)\n self.socket.readyRead.connect(self.read_datagrams)\n self.socket.bind(3020, QtNetwork.QUdpSocket.ShareAddress | QtNetwork.QUdpSocket.ReuseAddressHint)\n log.info(\"Listening on UDP 3020\")\n\n @QtCore.Slot()\n @profile\n def read_datagrams(self):\n while self.socket.hasPendingDatagrams():\n datagram_size = self.socket.pendingDatagramSize()\n\n datagram = self._byte_array_cache.get(datagram_size, None)\n if datagram is None:\n datagram = QtCore.QByteArray()\n datagram.resize(datagram_size)\n self._byte_array_cache[datagram_size] = datagram\n\n (datagram, sender, sport) = self.socket.readDatagram(datagram_size)\n\n buffer = struct.unpack('B' * datagram_size, datagram.data())\n self.app.scenecontroller.process_command(buffer)\n self.updates += 1\n self.data_received.emit()\n\n #@QtCore.Slot(result=float)\n def get_ups(self):\n dt = time.clock() - self.last_time\n if dt == 0:\n return 0\n ups = self.updates / dt\n self.last_time = time.clock()\n self.updates = 0\n return ups\n","sub_path":"controllers/netcontroller.py","file_name":"netcontroller.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"487049074","text":"import unittest\nfrom core.internal_repr import problem\nfrom core.internal_repr import parameter\nfrom core.util_classes import common_predicates\nfrom core.internal_repr import state\nfrom errors_exceptions import ProblemConfigException\nimport numpy as np\n\nclass TestProblem(unittest.TestCase):\n def setUp(self):\n attrs = {\"name\": \"can\", \"pose\": \"undefined\", \"_type\": \"Can\"}\n attr_types = {\"name\": str, \"pose\": int, \"_type\": str}\n self.can = parameter.Object(attrs, attr_types)\n attrs = {\"name\": \"target\", \"pose\": \"undefined\", \"_type\": \"Target\"}\n attr_types = {\"name\": str, \"pose\": int, \"_type\": str}\n self.target = parameter.Object(attrs, attr_types)\n attrs = {\"name\": \"gp\", \"value\": \"undefined\", \"_type\": \"Sym\"}\n attr_types = {\"name\": str, \"value\": int, \"_type\": str}\n self.gp = parameter.Symbol(attrs, attr_types)\n self.at = common_predicates.At(\"at\", [self.can, self.target], [\"Can\", \"Target\"])\n self.isgp = common_predicates.IsGP(\"isgp\", [self.gp, self.can], [\"Sym\", \"Can\"])\n self.init_state = state.State(\"state\", [self.can, self.target, self.gp], [self.at, self.isgp], timestep=0)\n\n def test_init_state(self):\n with self.assertRaises(ProblemConfigException) as cm:\n problem.Problem(self.init_state, None)\n self.assertEqual(cm.exception.message, \"Initial state is not concrete. Have all non-symbol parameters been instantiated with a value?\")\n self.can.pose = np.array([[3, 0], [4, 2]])\n self.target.pose = np.array([[3, 1], [3, 2]])\n with self.assertRaises(ProblemConfigException) as cm:\n problem.Problem(self.init_state, None)\n self.assertEqual(cm.exception.message, \"Initial state is not consistent (predicates are violated).\")\n self.target.pose = np.array([[3, 1], [4, 2]])\n problem.Problem(self.init_state, None)\n\n def test_goal_test(self):\n self.can.pose = np.array([[3, 0, 5], [4, 1, 1]])\n self.target.pose = np.array([[3, 0, 4], [4, 2, 0]])\n p = problem.Problem(self.init_state, [self.at])\n # problems only consider timestep 0 in their goal test,\n # so this will be True even though the poses become different at timestep 1\n self.assertTrue(p.goal_test())\n","sub_path":"src/test/test_core/test_internal_repr/test_problem.py","file_name":"test_problem.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"93563685","text":"import pyautogui, time\r\n\r\ndef take_screenshot():\r\n a = pyautogui.screenshot()\r\n\r\ndef benchmark(timeout=1):\r\n count = 0\r\n end_loop = time.time() + (timeout)\r\n while time.time() < end_loop:\r\n take_screenshot()\r\n count += 1\r\n\r\n print(\"Result:\",count,\"pixels in\",timeout,\"seconds!\")\r\n print(\"Average:\",count/timeout,\"pixels per second!\")\r\n return [timeout, count, count/timeout]\r\n","sub_path":"Python/!PYTHON/py/screen recorder/backup/tests/with_pyautogui.py","file_name":"with_pyautogui.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"338692527","text":"#!/usr/bin/python3\n#\n# Copyright (c) 2012 Mikkel Schubert \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\nimport os\n\nfrom paleomix.common.utilities import safe_coerce_to_tuple\nfrom paleomix.nodes.picard import MergeSamFilesNode\nfrom paleomix.pipelines.bam.nodes import index_and_validate_bam\nfrom paleomix.nodes.validation import DetectInputDuplicationNode\n\n\nclass Prefix:\n def __init__(self, config, prefix, samples, features, target):\n self.name = prefix[\"Name\"]\n self.roi = prefix.get(\"RegionsOfInterest\", {})\n\n self.samples = safe_coerce_to_tuple(samples)\n self.folder = config.destination\n self.target = target\n\n files_and_nodes = {}\n for sample in self.samples:\n files_and_nodes.update(sample.bams.items())\n\n self.datadup_check = self._build_dataduplication_node(prefix, files_and_nodes)\n self.bams = self._build_bam(config, prefix, files_and_nodes)\n\n nodes = [self.datadup_check]\n for sample in self.samples:\n nodes.extend(sample.nodes)\n self.nodes = tuple(nodes)\n\n def _build_bam(self, config, prefix, files_and_bams):\n output_filename = os.path.join(\n self.folder, \"%s.%s.bam\" % (self.target, prefix[\"Name\"])\n )\n validated_filename = os.path.join(\n self.folder, self.target, prefix[\"Name\"] + \".validated\"\n )\n\n node = MergeSamFilesNode(\n config=config,\n input_bams=list(files_and_bams),\n output_bam=output_filename,\n dependencies=self.datadup_check,\n )\n validated_node = index_and_validate_bam(\n config=config, prefix=prefix, node=node, log_file=validated_filename\n )\n\n return {output_filename: validated_node}\n\n def _build_dataduplication_node(self, prefix, files_and_nodes):\n filename = prefix[\"Name\"] + \".duplications_checked\"\n destination = os.path.join(self.folder, self.target, filename)\n dependencies = list(files_and_nodes.values())\n\n return DetectInputDuplicationNode(\n input_files=list(files_and_nodes),\n output_file=destination,\n dependencies=dependencies,\n )\n","sub_path":"paleomix/pipelines/bam/parts/prefix.py","file_name":"prefix.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"161924651","text":"#%% Beginning\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nimport os, sys\r\nimport pandas\r\nimport sqlite3\r\nimport xlwings\r\nimport numpy\r\nimport win32api\r\nimport shutil\r\nimport tools\r\nimport arrow\r\n\r\n# 1 Prepare folders\r\n# 1.1 SAS Folder\r\nsas_output = r'C:\\NotBackedUp\\SAS\\output'\r\nsas_code = r'C:\\NotBackedUp\\SAS\\sas_code'\r\nsas_source = r'C:\\NotBackedUp\\SAS\\sas_source'\r\nsas_rep = r'C:\\NotBackedUp\\SAS\\sas_rep'\r\ntemp = r'C:\\Users\\Lid10\\AppData\\Local\\CN_Retail'\r\n# 1.2 Customer List\r\nput_customerlist_1 = r'I:\\Retail MIS\\output\\Customer List'\r\nput_customerlist_2 = r'I:\\Retail MIS\\Local Reporting\\Customer List'\r\n# 1.3 AUA Movement\r\nput_aua = r'I:\\Retail MIS\\Data Support and Customer information Record_v\\AUA Movement by product'\r\n# 1.4 FTS 1+1\r\nput_FTS=None\r\nput_1p1=None\r\n\r\n# 2.Pattern Variables\r\nbackward = -1 # shift the day backward by -1.\r\nbrach_names = ['MAT', 'XTD', 'BJM', 'ZGC', 'GZ', 'HZ']\r\n\r\n# 3.Time\r\n# 3.1 Prepare Arrow Object\r\nutc = arrow.utcnow()\r\nusi=input('Weekly(W) or Monthly(M):\\n')\r\nif usi[0].upper() == 'W':\r\n process_type = 'Weekly'\r\nelif usi[0].upper() == 'M':\r\n process_type = 'Monthly'\r\nelse:\r\n raise ValueError\r\n# 3.2 Process Type -- weekly or monthly\r\nif process_type == 'Weekly':\r\n sas_utc = utc.shift(days = backward)\r\n while sas_utc.isoweekday() != 4 :\r\n sas_utc = sas_utc.shift(days = backward)\r\nelse:\r\n pass\r\n \r\n# 3.3 Prepare times\r\nsas_DateAsOf = sas_utc.format('YYYYMMDD')\r\nsas_DateAsOfEx = sas_utc.format('YYYY/MM/DD')\r\nsas_ThisYear4 = sas_utc.format('YYYY')\r\nsas_ThisYear2 = sas_utc.format('YY')\r\nsas_ThisMonthNum = sas_utc.format('MM')\r\nsas_ThisMonthEng = sas_utc.format('MMM')\r\nsas_LastMonthNum = sas_utc.shift(months = -1).format('MM')\r\nsas_LastMonthEng = sas_utc.shift(months = -1).format('MMM')\r\nsas_ThisDate = sas_utc.format('DD')\r\n\r\ntemp = sas_utc.shift(days = backward)\r\nwhile temp.isoweekday() != 4:\r\n temp = temp.shift(days = backward)\r\nsas_LastDateAsOf = temp.format('YYYYMMDD')\r\n\r\n#%% functions\r\ndef cut_paste(wbsrc, srcname, srcrng, wbdst, dstname, formatrng, pdst, method):\r\n # wbsrc 源表, srcname, srcrng, \r\n # wbdst 目标表, dstname, \r\n # formatrng 样式, ipdst 位置, method\r\n # source\r\n if srcrng.find(':') == -1:\r\n srcrng = srcrng + ':' + srcrng\r\n value = wbsrc.sheets(srcname).range(srcrng).value\r\n # distination\r\n if method == 'P': # Directly\r\n nonemp = wbdst.sheets(dstname).range(formatrng).end('right')\r\n row_last_nonemp, col_last_nonemp = tools.AddressResolver(nonemp.address).cell_version\r\n emp = nonemp + 1\r\n #paste 1\r\n wbdst.sheets(dstname).cells(row_last_nonemp, emp).options(transpose=True).value = value\r\n # format\r\n wbdst.sheets(dstname).range(formatrng).api.Copy()\r\n wbdst.sheets(dstname).rng(emp + ':' + emp).aip.PasteSpecial(Paste=-4122, Operation=-4142, SkipBlanks=False, Transpose=False)\r\n elif method == 'I' : # Insert\r\n wbdst.sheets(dstname).range(pdst).api.Insert(Shift=-4161)\r\n wbdst.sheets(dstname).range(pdst).options(transpose=True).value=value\r\n wbdst.sheets(dstname).range(formatrng).api.Copy()\r\n wbdst.sheets(dstname).rng(pdst).aip.PasteSpecial(Paste=-4122, Operation=-4142, SkipBlanks=False, Transpose=False)\r\n# %% \r\n# 2.Weekly Process\r\n\r\n# 2.1.1 Open SAS \r\nwin32api.ShellExecute(0, 'open', sas_code + '\\\\1. Weekly Process.egp', '', '', 1)\r\n\r\n# 2.1.2 run SAS\r\ninput('After report, press ENTER')\r\n\r\n#%% \r\n# 2.2customer list\r\n# 2.2.1 Put files\r\n#多线程并行拷贝\r\nshutil.copy(src=sas_output + '\\\\Customer List\\Customer List_{sas_d}.xls'.format(sas_d=sas_DateAsOf),\r\n dst=put_customerlist_1)\r\nshutil.copy(src=sas_output + '\\\\Customer List\\Customer List_{sas_d}.xls'.format(sas_d=sas_DateAsOf),\r\n dst=put_customerlist_2)\r\n# 2.2.2 Email\r\ninput('After E-mailed, press ENTER')\r\n#%% \r\n# 2.3AUA_Movement\r\n# 2.3.1 Check Outputs\r\naua_output_list = 'Net_{sas_d}.xlsx,Onepage_{sas_d}.xlsx,IITD_{sas_d}.xlsx,New_Fund_{sas_d}.xlsx,' \\\r\n 'New_DCI_By_Branch_{sas_d}.xlsx,New_DCI_By_Currency_{sas_d}.xlsx'.format(sas_d=sas_DateAsOf)\r\naua_output_list = aua_output_list.split(',')\r\n # What we have in the folder\r\nfd = tools.FileCommander(sas_output + '\\\\AUA Movement')\r\nfd_ls=fd.files()\r\nfor item in aua_output_list:\r\n if item in fd_ls:\r\n print('OK,{i} has been found!'.format(i=item))\r\n else:\r\n raise SystemExit\r\n# 2.3.2 Put files\r\nsh_put_auamove = r'I:\\Retail MIS\\output\\AUA Movement'\r\nfor item in aua_output_list:\r\n shutil.copy(src=sas_output + '\\\\AUA Movement\\\\' + item,\r\n dst=sh_put_auamove)\r\n \r\n# 2.3.3 Merge files 2&3\r\nassert(aua_output_list[2] == 'IITD_{sas_d}.xlsx'.format(sas_d = sas_DateAsOf))\r\nassert(aua_output_list[3] == 'New_Fund_{sas_d}.xlsx'.format(sas_d = sas_DateAsOf))\r\nwbIITD = xlwings.Book(sas_output + '\\\\AUA Movement\\\\' + aua_output_list[2])\r\nwbNew_Fund = xlwings.Book(sas_output + '\\\\AUA Movement\\\\' + aua_output_list[3])\r\nwbNew_Fund.sheets(1).api.Move(After = wbIITD.sheets(1).api)\r\nwbIITD.save()\r\nwbIITD.close()\r\n#%% \r\n# 2.3.4 Update AUA Movement Tracking\r\n\r\n# 2.3.4.1 Prepare old file\r\nfile = 'I:\\\\Retail MIS\\\\Data Support and Customer information Record_v\\\\AUA Movement by product\\\\' + sas_LastMonthEng + '\\'' + sas_ThisYear2 + '\\\\' + sas_LastDateAsOf + ' AUA Movement Tracking.xlsx'\r\nshutil.copy(src=file,\r\n dst=sas_output + r'\\AUA Movement')\r\n\r\n# 2.3.4.2 Update by Excel\r\nwbAMT = xlwings.Book(sas_output + r'\\AUA Movement'+ '\\\\' + sas_DateAsOf + ' AUA Movement Tracking.xlsx')\r\nwbOnePage = xlwings.Book(sas_output + '\\\\AUA Movement\\\\' + 'Onepage_{sas_d}'.format(sas_d=sas_DateAsOf) + '.xlsx')\r\n\r\n## First Part \r\ni = 6 # From OnePage G:L\r\nfor item in brach_names:\r\n col = chr(65 + i)\r\n cut_paste(wbsrc=wbOnePage,srcname='OnePage',srcemp='DW1',srcrng=col,\r\n wbdst=wbAMT,dstname=item,formatrng='DW:DW',ipdst=None,\r\n method='P')\r\n i = i + 1\r\n\r\n## Second Part 1\r\ncol=input('Where to insert a new column in AUA Movement Total, Press Enter\\n')\r\nvalue = wbOnePage.sheets('OnePage').range('C2:C59').value\r\ncut_paste(wbsrc=wbOnePage,srcname='OnePage',srcemp='DW1',srcrng='C2:C59',\r\n wbdst=wbAMT,dstname='AUA Movement Total',formatrng='DW:DW',ipdst=None,\r\n method='I')\r\n## Second Part 2\r\ncut_paste(wbsrc=wbOnePage,srcname='OnePage',srcemp='DW1',srcrng='C60:C200',\r\n wbdst=wbAMT,dstname='AUA Movement Total',formatrng='DW:DW',ipdst=None,\r\n method='I')\r\n\r\n#replacement\r\nrow_ls = [2,19,36,49,72,92,116]\r\nvalue = sas_DateAsOf[0:4] + '/' + sas_DateAsOf[4:6] + '/' + sas_DateAsOf[6:8]\r\nfor item in row_ls:\r\n wbAMT.sheets('AUA Movement Total').range(col + str(item)).value = value\r\n\r\n##Third Part:CNY Movement\r\ncol = input('Where to insert a new column, Press Enter\\n')\r\ncut_paste(wbsrc=wbOnePage,srcname='OnePage',srcemp='DW1',srcrng='E2:E200',\r\n wbdst=wbAMT,dstname='CNY Movement',formatrng='DW:DW',ipdst=None,\r\n method='I')\r\nvalue = wbOnePage.sheets('OnePage').range('E2:E200').value\r\n\r\n \r\nrow_ls = [2,19,36,48,67,87,111]\r\nvalue = sas_DateAsOf[0:4] + '/' + sas_DateAsOf[4:6] + '/' + sas_DateAsOf[6:8]\r\nfor item in row_ls:\r\n wbAMT.sheets('CNY Movement').range(col + str(item)).value = value\r\n \r\n#replace in A:A of the MTD by Branch of AUA Movement Tracking by the new column\r\nvalue = tools.AddressResolver(last_nonemp.address).col_char(col_last_nonemp - 1).lower()\r\ntarget = tools.AddressResolver(last_nonemp.address).col_char(col_last_nonemp + 1).lower()\r\nwbAMT.sheets('MTD by Branch').range('A:A').api.Replace(What = target, Replacement = value,\r\n LookAt=2, SearchOrder=1,\r\n MatchCase=False, SearchFormat=False, ReplaceFormat=False)\r\nwbAMT.save()\r\nwbOnePage.close()\r\n#Copy\r\nshutil.copy(src=sas_output + '\\\\AUA Movement\\\\' + '{sas_d} AUA Movement Tracking.xlsx'.format(sas_d=sas_DateAsOf),\r\n dst=r'I:\\Retail MIS\\Data Support and Customer information Record_v\\AUA Movement by product')\r\nshutil.copy(src=sas_output + '\\\\AUA Movement\\\\' + 'IITD_{sas_d}.xlsx'.format(sas_d=sas_DateAsOf),\r\n dst=r'I:\\Retail MIS\\Data Support and Customer information Record_v\\AUA Movement by product')\r\nshutil.copy(src=sas_output + '\\\\AUA Movement\\\\' + 'Net_{sas_d}.xlsx'.format(sas_d=sas_DateAsOf),\r\n dst=r'I:\\Retail MIS\\Data Support and Customer information Record_v\\AUA Movement by product')\r\ninput('Release 2 emails, then Press Enter')\r\n\r\n#%% FTS 1+1\r\nos.system(r'C:\\NotBackedUp\\SAS\\FTS&1+1\\FTS1+1 Archive 1.bat')\r\nwork_fts = r'C:\\NotBackedUp\\SAS\\FTS&1+1\\FTS'\r\nwork_1p1 = r'C:\\NotBackedUp\\SAS\\FTS&1+1\\1+1'\r\ndest_fts = r'\\\\svrcn166mlp00\\general\\IntCN\\Retail\\Sales and Distribution\\SMO Report\\FTS report\\FTS Monthly Report 2017'\r\ndest_1p1 = r'\\\\svrcn166mlp00\\general\\IntCN\\Retail\\Sales and Distribution\\SMO Report\\Others\\1+1 Monthly Report\\2017'\r\nfls_fts = tools.FileCommander(work_fts).files() \r\nfls_1p1 = tools.FileCommander(work_1p1).files() \r\nfor item in fls_fts:\r\n wb_addr = work_fts + '\\\\' + item\r\n df = pandas.read_excel(wb_addr,sheetname = 'Sheet1',skiprows = 6,index_col = 0,\r\n parse_cols = 'E,F,D,G,B,A,H,I,J,O')\r\n df.columns = ['Branch', 'CIF', 'Customer Name' ,'Student Name' ,'Student Passport' ,'Year', 'AUD', 'CNY', 'Date']\r\n #find the last people in book by branch\r\n wb_FTS = xlwings.Book(r'C:/NotBackedUp/SAS/FTS&1+1/FTS reporting_Monthly_Jan 2017.xlsx')\r\n \r\n ","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":9600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"80473445","text":"#Import the pygame library and initialise the game engine\nimport pygame\nimport random\nimport csv\nimport time\n\n\npygame.init()\n \n# Define some colors\nWHITE = (255,255,255)\nDARK = (0,0,0)\nLIGHTBLUE = (0,176,240)\nRED = (255,0,0)\nORANGE = (255,100,0)\nYELLOW = (255,255,0)\n \nGauche = False\nDroite = False\nvaisseau = pygame.image.load('vaisseau.png')\nrectangle_vaisseau = pygame.Rect(235,600,31,32)\nmissiles = []\n\ncarre_blanc = pygame.image.load('carre_blanc.png')\ncarre_orange = pygame.image.load('carre_orange.png')\ncarre_vert = pygame.image.load('carre_vert.png')\ncarre_violet = pygame.image.load('carre_violet.png')\n\nbricks_blanc=[]\nbricks_orange=[]\nbricks_violet=[]\nbricks_vert=[]\n\nrunning_game = True\n\nf = open(\"donnees.csv\",\"r\")\nlecteur = csv.DictReader(f,delimiter=\",\")\nfor ligne in lecteur:\n\tcooldown = int(ligne['tir']) # la variable cooldown permettra de gérer la durée entre 2 tirs\n\tdefault_cooldown = cooldown\n\tvitesse_deplacement = int(ligne['vitesse'])\n\tcredit = int(ligne['credit'])\n\tvitesse_defilement = float(ligne['defilement'])\n\tscore = int(ligne['score'])\n\tvitesse_apparition = int(ligne['vitesse_apparition'])\n\tdefault_vitesse_apparition = vitesse_apparition\nf.close()\n\ntir_pret = True\n\nblock_pret = True\n\n# Open a new window\nsize = (500, 650)\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Brick Shooter\")\n \n# The clock will be used to control how fast the screen updates\nclock = pygame.time.Clock()\n\ndef deplace_bricks():\n\tfor brick in bricks_orange:\n\t\tbrick.bottom=brick.bottom+ vitesse_defilement\n\n\tfor brick in bricks_blanc:\n\t\tbrick.bottom=brick.bottom + vitesse_defilement\n\n\tfor brick in bricks_violet:\n\t\tbrick.bottom=brick.bottom + vitesse_defilement\n\n\tfor brick in bricks_vert:\n\t\tbrick.bottom=brick.bottom + vitesse_defilement\n\n\ndef placer_bricks():\n\tglobal block_pret,vitesse_apparition,default_vitesse_apparition\n\tif block_pret == False:\n\t\tvitesse_apparition = vitesse_apparition - 1\n\t\tif vitesse_apparition == 0:\n\t\t\tblock_pret = True\n\n\tif block_pret == True :\n\t\ty = random.randint(50,100)\n\t\tm = random.randint(10,400)\n\t\th = 480 - m\n\t\tfor i in range(m,h,y): # Margin left / Taille screen horizontal / Écart entre les blocks\n\t\t\tx = random.randint(1,100)\n\t\t\tif x < 20 and x >= 10:\n\t\t\t\tbricks_orange.append(pygame.Rect(i,random.randint(30,50),40,40))\n\t\t\tif x > 50:\n\t\t\t\tbricks_blanc.append(pygame.Rect(i,random.randint(30,50),40,40))\n\t\t\tif x < 5:\n\t\t\t\tbricks_violet.append(pygame.Rect(i,random.randint(30,50),40,40))\n\t\t\tif x < 10 and x >= 5:\n\t\t\t\tbricks_vert.append(pygame.Rect(i,random.randint(30,50),40,40))\n\t\t\tblock_pret = False\n\t\t\tvitesse_apparition = default_vitesse_apparition\n\n\tfor brick in bricks_orange:\n\t\tscreen.blit(carre_orange,brick)\n\t\n\tfor brick in bricks_blanc:\n\t\tscreen.blit(carre_blanc,brick)\n\t\n\tfor brick in bricks_violet:\n\t\tscreen.blit(carre_violet,brick)\n\t\n\tfor brick in bricks_vert:\n\t\tscreen.blit(carre_vert,brick)\n\ndef detecte_collision():\n\tglobal vitesse_defilement, vitesse_deplacement, default_cooldown,credit,score,default_vitesse_apparition\n\tfor missile in missiles:\n\t\t# Augmentation de la vitesse de defilement\n\t\tfor brick in bricks_orange:\n\t\t\tif missile.colliderect(brick):\n\t\t\t\tbricks_orange.remove(brick)\n\t\t\t\tmissiles.remove(missile)\n\t\t\t\tif default_vitesse_apparition > 50:\n\t\t\t\t\tvitesse_defilement += 0.2\n\t\t\t\t\tdefault_vitesse_apparition -= 5\n\t\t\t\tcredit += 10\n\t\t\t\tscore += 10\n\n\t\t# Diminution de la vitesse de deplacement\n\t\tfor brick in bricks_vert:\n\t\t\tif missile.colliderect(brick):\n\t\t\t\tbricks_vert.remove(brick)\n\t\t\t\tmissiles.remove(missile)\n\t\t\t\tif vitesse_deplacement > 1 :\n\t\t\t\t\tvitesse_deplacement -= 1\n\t\t\t\tcredit += 10\n\t\t\t\tscore += 10\n\n\t\t# Diminution de la vitesse de tir\n\t\tfor brick in bricks_violet:\n\t\t\tif missile.colliderect(brick):\n\t\t\t\tbricks_violet.remove(brick)\n\t\t\t\tmissiles.remove(missile)\n\t\t\t\tdefault_cooldown -= 1\n\t\t\t\tcredit += 10\n\t\t\t\tscore += 10\n\n\t\t# Brick neutre\n\t\tfor brick in bricks_blanc:\n\t\t\tif missile.colliderect(brick):\n\t\t\t\tbricks_blanc.remove(brick)\n\t\t\t\tmissiles.remove(missile)\n\t\t\t\tcredit += 10\n\t\t\t\tscore += 10\n\ndef detecte_end_game():\n\tfor brick in bricks_orange:\n\t\tif rectangle_vaisseau.colliderect(brick):\n\t\t\tbricks_orange.remove(brick)\n\t\t\tgame_over()\n\tfor brick in bricks_blanc:\n\t\tif rectangle_vaisseau.colliderect(brick):\n\t\t\tbricks_blanc.remove(brick)\n\t\t\tgame_over()\n\n\tfor brick in bricks_violet:\n\t\tif rectangle_vaisseau.colliderect(brick):\n\t\t\tbricks_violet.remove(brick)\n\t\t\tgame_over()\n\n\tfor brick in bricks_vert:\n\t\tif rectangle_vaisseau.colliderect(brick):\n\t\t\tbricks_vert.remove(brick)\n\t\t\tgame_over()\n\n\n\ndef game_over():\n\tglobal vitesse_defilement, vitesse_deplacement, default_cooldown,credit,score,default_vitesse_apparition\n\trunning = True\n\twhile running == True:\n\t\tglobal running_game\n\t\tscreen.fill(DARK)\n\t\trunning_game = False\n\t\tfont = pygame.font.Font(None, 100)\n\t\ttitle = font.render(\"GAME OVER\", 1, RED)\n\t\tscreen.blit(title, (48,223))\n\t\ttitle = font.render(\"GAME OVER\", 1, WHITE)\n\t\tscreen.blit(title, (45,220))\n\t\tfont = pygame.font.Font(None, 30)\n\t\ttext = font.render(\"Score: \" + str(score), 1, WHITE)\n\t\tscreen.blit(text, (190,360))\n\n\t\tfont = pygame.font.Font(None, 30)\n\t\ttext = font.render(\"ESC : Retourner au menu\", 1, WHITE)\n\t\tscreen.blit(text, (130,500))\n\t\tpygame.display.flip()\n\n\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n\t\t\t\t\tscreen.fill(DARK)\n\t\t\t\t\tvitesse_deplacement = 3\n\t\t\t\t\tdefault_cooldown = 30\n\t\t\t\t\tvitesse_defilement = 1\n\t\t\t\t\tscore = 0\n\t\t\t\t\tcredit = 0\n\t\t\t\t\tdefault_vitesse_apparition = 150\n\t\t\t\t\tclose_game()\n\t\t\t\t\trunning = False\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tclose_game()\n\ndef close_game():\n\t\n\twith open('donnees.csv', 'w', newline='') as csvfile:\n\t\tfieldnames = ['credit', 'vitesse','defilement','tir','score','vitesse_apparition']\n\t\twriter = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\n\t\twriter.writeheader()\n\t\twriter.writerow({'credit': str(credit), 'vitesse': str(vitesse_deplacement), 'defilement': str(vitesse_defilement), 'tir': str(default_cooldown),'score': str(score), 'vitesse_apparition': str(default_vitesse_apparition)})\n\t\n\tpygame.quit()\n\ndef menu():\n\tfont = pygame.font.Font(None, 74)\n\ttext = font.render(\"BrickShooter\", 1, WHITE)\n\tscreen.blit(text, (95,50))\n\t\n\tfont = pygame.font.Font(None, 40)\n\ttext = font.render(\"A : Lancer la partie\", 1, WHITE)\n\tscreen.blit(text, (130,200))\n\ttext = font.render(\"B : Règles du jeu\", 1, WHITE)\n\tscreen.blit(text, (130,250))\n\ttext = font.render(\"C : Equipement\", 1, WHITE)\n\tscreen.blit(text, (130,300))\n\ttext = font.render(\"D : Quitter\", 1, WHITE)\n\tscreen.blit(text, (130,350))\n\n\tpygame.display.flip()\n\n\tis_pressed = False\n\n\twhile not is_pressed:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tclose_game()\n\n\t\t\t# Nouvelle partie : a\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_a or event.type == pygame.KEYDOWN and event.key == pygame.K_t:\n\t\t\t\tscreen.fill(DARK)\n\t\t\t\tnew_game()\n\t\t\t\n\t\t\t# Règles du jeu : b\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_b:\n\t\t\t\tscreen.fill(DARK)\n\t\t\t\trules()\n\n\t\t\t# Equipement : c\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_c:\n\t\t\t\tscreen.fill(DARK)\n\t\t\t\tequipement()\n\n\t\t\t# Quitter : d\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_d:\n\t\t\t\tclose_game()\n\n\n\ndef rules():\n\trunning = True\n\twhile running == True:\n\t\tfont = pygame.font.Font(None, 40)\n\t\ttitle = font.render(\"Règles du jeu\", 1, WHITE)\n\t\tscreen.blit(title, (150,50))\n\n\t\tfont = pygame.font.Font(None, 30)\n\t\ttext = font.render(\"Le but du jeu est de détruire tous les blocs\", 1, WHITE)\n\t\tscreen.blit(text, (42,140))\n\t\ttext = font.render(\"sans qu'ils ne vous touchent !\", 1, WHITE)\n\t\tscreen.blit(text, (42,160))\n\t\ttext = font.render(\"Pour cela il suffit de vous déplacez de\", 1, WHITE)\n\t\tscreen.blit(text, (42,200))\n\t\ttext = font.render(\"gauche à droite avec les flèches de votre\", 1, WHITE)\n\t\tscreen.blit(text, (42,220))\n\t\ttext = font.render(\"clavier et de tirer avec espace.\", 1, WHITE)\n\t\tscreen.blit(text, (42,240))\n\n\t\ttext = font.render(\"Tirer sur les blocs pour gagner des crédits\", 1, WHITE)\n\t\tscreen.blit(text, (42,280))\n\t\ttext = font.render(\"et utilisez-les pour améliorer vos données\", 1, WHITE)\n\t\tscreen.blit(text, (42,300))\n\t\ttext = font.render(\"dans Equipement.\", 1, WHITE)\n\t\tscreen.blit(text, (42,320))\n\n\t\ttext = font.render(\"Les blocs :\", 1, WHITE)\n\t\tscreen.blit(text, (190,370))\n\t\ttext = font.render(\"Orange : augmente la vitesse de défilement\", 1, WHITE)\n\t\tscreen.blit(text, (42,410))\n\t\ttext = font.render(\"Vert : diminue la vitesse de déplacement\", 1, WHITE)\n\t\tscreen.blit(text, (42,440))\n\t\ttext = font.render(\"Violet : diminue la vitesse de tir\", 1, WHITE)\n\t\tscreen.blit(text, (42,470))\n\n\t\tfont = pygame.font.Font(None, 30)\n\t\ttext = font.render(\"ESC : Retourner au menu\", 1, WHITE)\n\t\tscreen.blit(text, (130,550))\n\n\t\tpygame.display.flip()\n\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n\t\t\t\tscreen.fill(DARK)\n\t\t\t\tmenu()\n\t\t\t\trunning = False\n\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tclose_game()\n\ndef detecte_touches():\n\n\tglobal Gauche,Droite,tir_pret,cooldown,default_cooldown\n\n\tif tir_pret == False:\n\t\tcooldown = cooldown - 1\n\t\tif cooldown == 0:\n\t\t\ttir_pret = True\n\n\tfor event in pygame.event.get():\n\t\tif event.type==pygame.QUIT:\t\t# Traite l'évènement fermer la fenêtre avec la souris\n\t\t\t\tclose_game()\n\t\tif event.type== pygame.KEYDOWN:\t# Traiter les évènements du clavier\n\t\t\tif event.key==pygame.K_ESCAPE:\n\t\t\t\tscreen.fill(DARK)\n\t\t\t\trunning = False\n\t\t\t\tmenu()\n\t\t\tif event.key==pygame.K_RIGHT:\n\t\t\t\tDroite = True\n\t\t\tif event.key==pygame.K_LEFT:\n\t\t\t\tGauche = True\n\t\t\tif event.key==pygame.K_SPACE and tir_pret == True:\n\t\t\t\tmissiles.append(pygame.Rect(rectangle_vaisseau.left+12,rectangle_vaisseau.top,5,15))\n\t\t\t\ttir_pret = False\n\t\t\t\tcooldown = default_cooldown\n\n\t\tif event.type== pygame.KEYUP:\n\t\t\tif event.key==pygame.K_RIGHT:\n\t\t\t\tDroite = False\n\t\t\tif event.key==pygame.K_LEFT:\n\t\t\t\tGauche = False\n\ndef deplace_missiles():\n\tfor missile in missiles:\t\t\t\t# pour chaque missiles existant\n\t\tmissile.top=missile.top-10\t\t\t# soustraire 10 à la coordonnée du point haut\n\t\tpygame.draw.rect(screen,WHITE,missile)\t# dessinner un rectangle de couleur blanc\n\t\tif missile.top<=5:\t\t\t\t# si le missiles arrive en haut de l'écran\n\t\t\tmissiles.remove(missile)\n\ndef new_game():\n\tglobal running_game\n\tscreen.fill(DARK)\n\tfont = pygame.font.Font(None, 200)\n\ttext = font.render(\"3\", 1, RED)\n\tscreen.blit(text, (210,150))\n\tpygame.display.flip()\n\ttime.sleep(1)\n\n\tscreen.fill(DARK)\n\ttext = font.render(\"2\", 1, RED)\n\tscreen.blit(text, (210,150))\n\tpygame.display.flip()\n\ttime.sleep(1)\n\n\tscreen.fill(DARK)\n\ttext = font.render(\"1\", 1, RED)\n\tscreen.blit(text, (210,150))\n\tpygame.display.flip()\n\ttime.sleep(1)\n\n\twhile running_game == True:\n\t\tplacer_bricks()\n\t\tscreen.blit(vaisseau,rectangle_vaisseau)\n\t\tscreen.fill(DARK)\n\t\tfont = pygame.font.Font(None, 30)\n\t\ttext = font.render(\"Score: \" + str(score), 1, WHITE)\n\t\tscreen.blit(text, (20,10))\n\t\ttext = font.render(\"Crédit: \" + str(credit), 1, WHITE)\n\t\tscreen.blit(text, (370,10))\n\t\tpygame.draw.line(screen, WHITE, [0, 32], [800, 32], 2)\n\t\tscreen.blit(vaisseau,rectangle_vaisseau)\t# placer l'image\n\t\tdetecte_collision()\n\t\tdeplace_bricks()\n\t\tdetecte_touches()\n\n\t\t# Déplacement du vaisseau d'un pixel \n\t\tif Gauche and rectangle_vaisseau.left > 5 : rectangle_vaisseau.left -= vitesse_deplacement\n\t\tif Droite and rectangle_vaisseau.right < 495 : rectangle_vaisseau.right += vitesse_deplacement\n\t\t\n\t\tplacer_bricks()\n\t\tdeplace_missiles()\n\t\tdetecte_end_game()\n\t\tpygame.display.update()\t\t\t\t# rafraichir l'affichage de la fenêtre jeu \n\t\tclock.tick(30)\n\n\ndef equipement():\n\trunning = True\n\twhile running == True:\n\t\tglobal credit, default_cooldown, vitesse_deplacement, vitesse_defilement, default_vitesse_apparition\n\t\tfont = pygame.font.Font(None, 40)\n\t\ttitle = font.render(\"Equipements du vaisseau\", 1, WHITE)\n\t\tscreen.blit(title, (80,50))\n\n\t\tfont = pygame.font.Font(None, 30)\n\t\ttext = font.render(\"Vous pouvez ici améliorer les capacités de \", 1, WHITE)\n\t\tscreen.blit(text, (42,150))\n\t\ttext = font.render(\"votre vaisseau à l'aide des crédits que vous\", 1, WHITE)\n\t\tscreen.blit(text, (42,170))\n\t\ttext = font.render(\"avez optenu lors de vos parties !\", 1, WHITE)\n\t\tscreen.blit(text, (42,190))\n\n\t\ttext = font.render(\"Crédits: \" + str(credit), 1, WHITE)\n\t\tscreen.blit(text, (190,250))\n\n\t\ttext = font.render(\"A : Augmenter la vitesse de tir (120c)\", 1, WHITE)\n\t\tscreen.blit(text, (26,320))\n\t\ttext = font.render(\"B : Augmenter la vitesse de déplacement (100c)\", 1, WHITE)\n\t\tscreen.blit(text, (26,350))\n\t\ttext = font.render(\"C : Diminuer la vitesse de défilement (100c)\", 1, WHITE)\n\t\tscreen.blit(text, (26,380))\n\n\t\ttext = font.render(\"ESC : Retourner au menu\", 1, WHITE)\n\t\tscreen.blit(text, (130,550))\n\n\t\tpygame.display.flip()\n\n\t\tfor event in pygame.event.get():\n\n\t\t\t# Augmenter la vitesse de tir : a\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_a or event.type == pygame.KEYDOWN and event.key == pygame.K_t :\n\t\t\t\tif credit >= 120:\n\t\t\t\t\tscreen.fill(DARK)\n\t\t\t\t\tif default_cooldown >= 10 :\n\t\t\t\t\t\tdefault_cooldown -= 2\n\t\t\t\t\t\tcredit -= 120\n\t\t\t\t\telse :\n\t\t\t\t\t\tfont = pygame.font.Font(None, 25)\n\t\t\t\t\t\ttext = font.render(\"Vous avez atteint la vitesse de tir max\", 1, WHITE)\n\t\t\t\t\t\tscreen.blit(text, (80,450))\n\t\t\t\t\t\n\t\t\t\n\t\t\t# Augmenter la vitesse de déplacement : b\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_b:\n\t\t\t\tif credit >= 100:\n\t\t\t\t\tscreen.fill(DARK)\n\t\t\t\t\tif vitesse_deplacement < 6 :\n\t\t\t\t\t\tvitesse_deplacement += 1\n\t\t\t\t\t\tcredit -= 100\n\t\t\t\t\telse :\n\t\t\t\t\t\tfont = pygame.font.Font(None, 25)\n\t\t\t\t\t\ttext = font.render(\"Vous avez atteint la vitesse de déplacement max\", 1, WHITE)\n\t\t\t\t\t\tscreen.blit(text, (48,450))\n\n\t\t\t# Diminuer la vitesse de défilement : c\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_c:\n\t\t\t\tif credit >= 100:\n\t\t\t\t\tscreen.fill(DARK)\n\t\t\t\t\tif vitesse_defilement >= 2 :\n\t\t\t\t\t\tvitesse_defilement -= 1\n\t\t\t\t\t\tdefault_vitesse_apparition += 25\n\t\t\t\t\t\tcredit -= 100\n\t\t\t\t\telse :\n\t\t\t\t\t\tfont = pygame.font.Font(None, 25)\n\t\t\t\t\t\ttext = font.render(\"Vous avez atteint la vitesse de défilement minimale\", 1, WHITE)\n\t\t\t\t\t\tscreen.blit(text, (45,450))\n\n\t\t\t# Retour au menu\n\t\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n\t\t\t\tscreen.fill(DARK)\n\t\t\t\tmenu()\n\t\t\t\trunning = False\n\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tclose_game()\n\ndef main_game_loop():\n\tmenu()\n\t\nmain_game_loop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"277481038","text":"try:\n import myPythonFunctions as m\n\n userName = input('''Please enter you user name or \n create a new one if this is the first time \n you are running the program: ''')\n\n userScore = int(m.getUserScore(userName))\n \n newUser = False\n if userScore == -1:\n newUser = True\n userScore = 0\n \n userChoice = 0\n\n while userChoice != '-1':\n userScore += m.generateQuestion()\n print (\"Current Score: \", userScore)\n userChoice = input(\"Press Enter to continue or -1 to Exit: \")\n \n m.updateUserPoints(newUser, userName, str(userScore))\n\nexcept Exception as e:\n print (\"An unexpected error occurred. Program wil be exited. Error: \\n\" + e)","sub_path":"mathGame.py","file_name":"mathGame.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"365079179","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport bisect\nimport math\nfrom typing import Any, Dict, List, NamedTuple, Optional, Union\n\nfrom classy_vision.generic.util import is_pos_int\n\nfrom . import ClassyParamScheduler, UpdateInterval, register_param_scheduler\n\n\n@register_param_scheduler(\"multistep\")\nclass MultiStepParamScheduler(ClassyParamScheduler):\n \"\"\"\n Takes a predefined schedule for a param value, and a list of epochs\n which stand for the upper boundary (excluded) of each range.\n The schedule is updated after every train epoch by default.\n\n Example:\n\n .. code-block:: python\n\n values: [0.1, 0.01, 0.001, 0.0001]\n milestones = [30, 60, 80]\n num_epochs = 120\n\n Then the param value will be 0.1 for epochs 0-29, 0.01 for\n epochs 30-59, 0.001 for epochs 60-79, 0.0001 for epochs after epoch 80.\n Note that the length of values must be equal to the length of milestones\n plus one.\n \"\"\"\n\n def __init__(\n self,\n values,\n num_epochs: int,\n milestones: Optional[List[int]] = None,\n update_interval: UpdateInterval = UpdateInterval.EPOCH,\n ):\n super().__init__(update_interval=update_interval)\n self._param_schedule = values\n self._num_epochs = num_epochs\n self._milestones = milestones\n\n if milestones is None:\n # Default equispaced drop_epochs behavior\n self._milestones = []\n step_width = math.ceil(self._num_epochs / float(len(self._param_schedule)))\n for idx in range(len(self._param_schedule) - 1):\n self._milestones.append(step_width * (idx + 1))\n\n start_epoch = 0\n for milestone in self._milestones:\n # Do not exceed the total number of epochs\n assert milestone < self._num_epochs, (\n \"Epoch milestone must be smaller than total number of epochs: num_epochs=%d, milestone=%d\"\n % (self._num_epochs, milestone)\n )\n # Must be in ascending order\n assert start_epoch < milestone, (\n \"Epoch milestone must be smaller than start epoch: start_epoch=%d, milestone=%d\"\n % (start_epoch, milestone)\n )\n start_epoch = milestone\n\n @classmethod\n def from_config(cls, config: Dict[str, Any]) -> \"MultiStepParamScheduler\":\n \"\"\"Instantiates a MultiStepParamScheduler from a configuration.\n\n Args:\n config: A configuration for a MultiStepParamScheduler.\n See :func:`__init__` for parameters expected in the config.\n\n Returns:\n A MultiStepParamScheduler instance.\n \"\"\"\n assert (\n \"values\" in config\n and isinstance(config[\"values\"], list)\n and len(config[\"values\"]) > 0\n ), \"Non-Equi Step scheduler requires a list of at least one param value\"\n assert is_pos_int(config[\"num_epochs\"]), \"Num epochs must be a positive integer\"\n assert config[\"num_epochs\"] >= len(\n config[\"values\"]\n ), \"Num epochs must be greater than param schedule\"\n\n milestones = config.get(\"milestones\", None)\n if \"milestones\" in config:\n assert (\n isinstance(config[\"milestones\"], list)\n and len(config[\"milestones\"]) == len(config[\"values\"]) - 1\n ), (\n \"Non-Equi Step scheduler requires a list of %d epochs\"\n % (len(config[\"values\"]) - 1)\n )\n\n return cls(\n values=config[\"values\"],\n num_epochs=config[\"num_epochs\"],\n milestones=milestones,\n update_interval=UpdateInterval.from_config(config, UpdateInterval.EPOCH),\n )\n\n def __call__(self, where: float):\n epoch_num = int((where + self.WHERE_EPSILON) * self._num_epochs)\n return self._param_schedule[bisect.bisect_right(self._milestones, epoch_num)]\n","sub_path":"classy_vision/optim/param_scheduler/multi_step_scheduler.py","file_name":"multi_step_scheduler.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"32878272","text":"import cv2 as cv\nimport numpy as np\n\nvc = cv.VideoCapture(0)\nvc2 = cv.VideoCapture(\"C:\\\\Users\\\\Mrmors\\\\Desktop\\\\geass.jpg\")\nret,Geass = vc2.read()\nwhile True:\n ret,img = vc.read()\n if ret:\n gray_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY)\n gimg = cv.medianBlur(gray_img,5)\n circles = cv.HoughCircles(gimg,cv.HOUGH_GRADIENT,1,120,param1=100,param2=30,minRadius=0,maxRadius=20)\n if not circles is None:\n circles = np.uint16(np.around(circles))\n for i in circles[0,:]:\n print(i[0],i[1],i[2])\n r = i[2]\n a = i[0]\n b = i[1]\n if r != 0:\n reGeass = cv.resize(Geass,(np.round(2*r),np.round(2*r)))\n print(reGeass.shape)\n for i in range(1,reGeass.shape[0]):\n for j in range(1,reGeass.shape[1]):\n for k in range(1,reGeass.shape[2]):\n if reGeass[i, j, k] != 0 and reGeass[i, j, k] <= 250:\n img[np.round(b - r + i), np.round(a - r + j),k] = reGeass[i,j,k]\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\nvc.release()\ncv.destroyAllWindows()\n","sub_path":"geass/huofuyuan.py","file_name":"huofuyuan.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"52488063","text":"from . import Stats\nfrom . import Constants\nfrom collections import defaultdict\n\nclass Nodes(object):\n \n def __init__(self):\n self.nodes = {}\n\n def __getitem__(self, nodeId):\n if nodeId not in self.nodes:\n self.nodes[nodeId] = NodeStats(nodeId)\n \n return self.nodes[nodeId]\n\n def __contains__(self, nodeId):\n if nodeId in self.nodes:\n return True\n return False\n\n\nclass NodeStats(object):\n\n def __init__(self, nodeId, baseTS = 0, devices = None, options = None):\n self.nodeId = nodeId\n self.desc = \"\"\n self.baseTS = baseTS\n self.devices = devices\n self.stats = Stats.Stats(self)\n self.options = options\n self.extractLayers(self.options)\n\n def processPacket(self, packet):\n #print (dir(packet.eth))\n if packet.eth.src == self.nodeId.mac:\n self.sndPacket(packet)\n else:\n self.rcvPacket(packet)\n\n def rcvPacket(self, packet):\n addr = NodeId()\n addr.extractFromPacket(packet, Constants.Direction.SND, self.devices)\n #print (\"rcv\", addr)\n packet.addr = addr\n for layer in packet.layers:\n if layer.layer_name not in self.layersToProcess:\n continue\n\n stats = self.stats.getStats(layer.layer_name, Constants.Direction.RCV)\n stats.processLayer(packet, layer)\n\n def sndPacket(self, packet):\n addr = NodeId()\n addr.extractFromPacket(packet, Constants.Direction.RCV, self.devices)\n packet.addr = addr\n #print (\"snd\", addr)\n for layer in packet.layers:\n if layer.layer_name not in self.layersToProcess:\n continue\n\n stats = self.stats.getStats(layer.layer_name, Constants.Direction.SND)\n stats.processLayer(packet, layer)\n\n def extractLayers(self, options):\n layers = defaultdict(int)\n layers['eth'] += 1\n \n self.layersToProcess = ['eth'] #dict.keys(layers)\n \n\nclass NodeId(object):\n\n def __init__(self, mac = None, ip = None, time = 0):\n self.mac = mac\n self.ip = ip\n self.deviceName = None\n self.ipHistory = []\n if ip is not None:\n self.ipHistory.append((ip, time))\n \n def setMacIp(self, mac, ip, time = 0):\n self.mac = mac\n self.ip = ip\n self.ipHistory.append((ip, time))\n\n def addIP(self, ip, time):\n self.ip = ip\n self.ipHistory.append((ip, time))\n\n def extractFromPacket(self, packet, direction, devices):\n if direction == Constants.Direction.SND:\n self.mac = packet.eth.src\n self.deviceName = devices.getDeviceName(self.mac)\n try:\n self.ip = packet.ip.src\n except AttributeError:\n pass\n else:\n self.mac = packet.eth.dst\n self.deviceName = devices.getDeviceName(self.mac)\n try:\n self.ip = packet.ip.dst\n except AttributeError:\n pass\n\n def getAddr(self):\n if self.deviceName is not None:\n return self.deviceName\n elif self.ip is not None:\n return self.ip\n return self.mac\n\n def __str__(self):\n return \"mac: {} ip: {} history ip: {}\".format(self.mac, self.ip, self.ipHistory)\n\n\n","sub_path":"destination/trafficAnalyser/Node.py","file_name":"Node.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"71323698","text":"# Copyright © 2019 Province of British Columbia\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\"\"\"Manage the database and some other items required to run the API\n\"\"\"\nimport logging\nimport os\nimport sys\n\nfrom flask import current_app, url_for\nfrom flask_script import Manager # class for handling a set of commands\nfrom flask_migrate import Migrate, MigrateCommand\nfrom sqlalchemy.sql import text\n\nfrom mhr_api import create_app\nfrom mhr_api.models import db\n# models included so that migrate can build the database migrations\nfrom mhr_api import models # pylint: disable=unused-import\n\nAPP = create_app()\nMIGRATE = Migrate(APP, db)\nMANAGER = Manager(APP)\n\nMANAGER.add_command('db', MigrateCommand)\n\n\n@MANAGER.command\ndef list_routes():\n output = []\n for rule in APP.url_map.iter_rules():\n\n options = {}\n for arg in rule.arguments:\n options[arg] = \"[{0}]\".format(arg)\n\n methods = ','.join(rule.methods)\n url = url_for(rule.endpoint, **options)\n line = (\"{:50s} {:20s} {}\".format(rule.endpoint, methods, url))\n output.append(line)\n\n for line in sorted(output):\n print(line)\n\n\ndef execute_script(session, file_name):\n \"\"\"Execute a SQL script as one or more SQL statements in a single file.\"\"\"\n print('Executing SQL statements in file ' + file_name)\n with open(file_name, 'r') as sql_file:\n sql_command = ''\n # Iterate over all lines in the sql file\n for line in sql_file:\n # Ignore commented lines\n if not line.startswith('--') and line.strip('\\n'):\n # Append line to the command string\n sql_command += line.strip('\\n')\n\n # If the command string ends with ';', it is a full statement\n if sql_command.endswith(';'):\n sql_command = sql_command.replace(';', '')\n # print('Executing SQL: ' + sql_command)\n # Try to execute statement and commit it\n try:\n session.execute(text(sql_command))\n\n # Assert in case of error\n except Exception as ex:\n print(repr(ex))\n\n # Finally, clear command string\n finally:\n sql_command = ''\n\n session.commit()\n sql_file.close()\n\n\n@MANAGER.command\ndef create_test_data():\n \"\"\"Load unit test data in the dev/local environment. Delete all existing test data as a first step.\"\"\"\n execute_script(db.session, 'test_data/postgres_test_reset.sql')\n execute_script(db.session, 'test_data/postgres_create_first.sql')\n filenames = os.listdir(os.path.join(os.getcwd(), 'test_data/postgres_data_files'))\n sorted_names = sorted(filenames)\n for filename in sorted_names:\n execute_script(db.session, os.path.join(os.getcwd(), ('test_data/postgres_data_files/' + filename)))\n\n\nif __name__ == '__main__':\n logging.log(logging.INFO, 'Running the Manager')\n MANAGER.run()\n","sub_path":"mhr_api/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"547487102","text":"#Welcome message\nprint(\"Welcome to the Tip Calculator.\")\n\n#Input the total bill\nbill = float(input(\"What was the total bill?\\n$\"))\n\n#Input the tip percentage\ntip_percentage = int(input(\"What percentage tip would you like to give? 10, 12, or 15.\\n\"))\n\n#Input the number of people\nsplit = int(input(\"How many people to split the bill?\\n\"))\n\n#Calculate the tip\ntip = (bill * (tip_percentage / 100) )\n\n#Calculate the total bill along with the tip.\ntotal_bill = tip + bill\n\n#Calculate the bill which has to be paid by each person.\nresult = round((total_bill/split), 2)\n\n#Printing the result\nprint(f\"Each person should pay ${result}.\")\n","sub_path":"Project 2 - Tip Calculator/Tip_Calculator.py","file_name":"Tip_Calculator.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"137255755","text":"from typing import *\nfrom Board import Board\nfrom Ship import Ship\n\n\nclass Player(object):\n def __init__(self, other_players: Iterable[\"Player\"])->None:\n self.name = self.get_name_from_player(other_players)\n self.ships = Ship()\n\n def get_name_from_player(self, other_players: Iterable[\"Player\"]) -> str:\n already_used_names = set([i for i in other_players])\n while True:\n name = input(f'Player {len(other_players)+1} please enter your name: ')\n if name not in already_used_names:\n return name\n else:\n print(f'Someone is already using {name} for their name.')\n print(\"Please choose another name.\")\n\n def place_ships(self, ships: List[Tuple[str, int]], player_name: str, play_board: \"Board\") -> None:\n for i in range(len(ships)):\n ship_coordinates = [ships[i][0]]\n while True:\n while True:\n self.direction = input(f\"{player_name} enter horizontal or vertical for the orientation of {ships[i][0]} which is {ships[i][1]} long: \")\n if self.direction != \"h\" and self.direction != \"v\" and self.direction != \"horizontal\" and self.direction != \"vertical\":\n continue\n else:\n break\n while True:\n user_Input=input(f\"{player_name}, enter the starting position for your {ships[i][0]} ship, which is {ships[i][1]} long, in the form row, column: \")\n try:\n user_Input.split()\n except:\n continue\n line = user_Input.split()\n if len(line) != 2:\n continue\n self.y=line[0]\n self.x=line[1]\n self.y = self.y.strip(\",\")\n try:\n int(self.y)\n except:\n continue\n try:\n int(self.x)\n break\n except:\n continue\n if self.check_ship_valid(ships[i], play_board) == True:\n if self.direction == \"h\" or self.direction == \"horizontal\":\n for k in range(int(self.x), int(self.x) + ships[i][1]):\n play_board.grid[int(self.y)][k] = ships[i][0][0]\n for l in range(ships[i][1]):\n ship_coordinates.append(self.y + str(int(self.x) + l))\n elif self.direction == \"v\" or self.direction == \"vertical\":\n for k in range(int(self.y), int(self.y) + ships[i][1]):\n play_board.grid[k][int(self.x)] = ships[i][0][0]\n for l in range(ships[i][1]):\n ship_coordinates.append(str(int(self.y) + l) + self.x)\n break\n else:\n continue\n self.ships.boat_cover_point.append(ship_coordinates)\n print(f\"{player_name}'s Placement Board\")\n print(play_board)\n\n def orientation_overlapped(self, play_board: \"Board\") -> bool:\n if int(self.x) <= (len(play_board.grid[0]) - 1) and int(self.y) <= (len(play_board.grid) - 1):\n if play_board.grid[int(self.y)][int(self.x)] == \"*\":\n return False\n else:\n return True\n else:\n return True\n\n def ship_horizontal_valid(self, ship: Tuple[str, int], play_board: \"Board\") -> bool:\n count=0\n for hrz in range(ship[1]):\n if (int(self.x) + hrz) > (len(play_board.grid[0]) - 1):\n count+=1\n else:\n if play_board.grid[int(self.y)][int(self.x) + hrz] != \"*\":\n count+=1\n else:\n pass\n if count==0:\n return True\n else:\n return False\n\n def ship_vertical_valid(self, ship: Tuple[str, int], play_board: \"Board\") -> bool:\n count=0\n for vet in range(ship[1]):\n if (int(self.y) + vet) > (len(play_board.grid)-1):\n count+=1\n else:\n if play_board.grid[int(self.y)+vet][int(self.x)] != \"*\":\n count+=1\n else:\n pass\n if count==0:\n return True\n else:\n return False\n\n def check_ship_valid(self, ship: Tuple[str, int], play_board: \"Board\") -> bool:\n if self.orientation_overlapped(play_board) == False:\n if self.direction == \"h\":\n if self.ship_horizontal_valid(ship, play_board) == True:\n return True\n else:\n return False\n elif self.direction == \"v\":\n if self.ship_vertical_valid(ship, play_board) == True:\n return True\n else:\n return False\n else:\n return False\n","sub_path":"Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":5106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"549304092","text":"import json\r\nfrom faker import Faker\r\nimport random\r\nfrom random import randint\r\n\r\n#matcehs and users count\r\n# itrs = 200000\r\nitrs = 200000\r\n\r\nTEAMS_NUM = 1000\r\nSTADIUMS_NUM = 200\r\nCITY_NUM = 500\r\nDATES_COUNT = itrs // 10\r\nfake = Faker('en_US')\r\n\r\n#get list of cities\r\n_cities = []\r\nfor _ in range(CITY_NUM):\r\n city = fake.city()\r\n while city in _cities:\r\n city = fake.city()\r\n _cities.append(city)\r\n\r\n\r\ndata = []\r\nuser_ids = []\r\nmanagers = []\r\nfans = []\r\nwith open(\"users.json\", \"w\") as write_file:\r\n for i in range(1000000):\r\n if i % 1000 == 0: print (f\"user: Iteration: {i//1000}K\")\r\n ev = random.randint(0, 2)\r\n\r\n role = 'manager' if (ev==0 or i==0) else 'fan'\r\n\r\n #unique\r\n username = fake.user_name()\r\n\r\n #unique\r\n user_id = {\"$oid\": fake.hexify('^^^^^^^^^^^^^^^^^^^^^^^^')}\r\n user_ids.append(user_id)\r\n \r\n ev = randint(0, 10)\r\n reserve_info = {}\r\n if role == 'manager':\r\n managers.append(user_id)\r\n else:\r\n fans.append(user_id)\r\n \r\n\r\n my_dict = {\r\n '_id':user_id,\r\n 'username':username,\r\n 'role':role,\r\n 'email':fake.profile()['mail'],\r\n 'pass':fake.password(length=8),\r\n 'fname':fake.first_name(),\r\n 'lname':fake.last_name(),\r\n 'bdate':fake.date_time().strftime('%Y-%m-%dT%H:%M:%S.%f'),\r\n 'gender':fake.profile()['sex'],\r\n 'city':random.choice(_cities)\r\n }\r\n data.append(my_dict)\r\n json.dump(data, write_file)\r\n\r\n\r\n#unique match ids\r\nmatch_ids = []\r\nfor i in range (500000):\r\n match_id = {\"$oid\": fake.hexify('^^^^^^^^^^^^^^^^^^^^^^^^')}\r\n match_ids.append(match_id)\r\n\r\n#unique teams\r\nteams_names = []\r\nteams_ids = []\r\nfor i in range (TEAMS_NUM):\r\n team = fake.profile()['company']\r\n teams_names.append(team)\r\n\r\n team_id = {\"$oid\": fake.hexify('^^^^^^^^^^^^^^^^^^^^^^^^')}\r\n teams_ids.append(team_id)\r\n\r\n#unique stads\r\nstads_names = []\r\nstads_ids = []\r\nstad_x_y = []\r\nfor i in range (STADIUMS_NUM):\r\n stad = fake.city()\r\n stads_names.append(stad)\r\n stad_x_y.append([randint(2,15),randint(2,15)])\r\n\r\n stads_id = {\"$oid\": fake.hexify('^^^^^^^^^^^^^^^^^^^^^^^^')}\r\n stads_ids.append(stads_id)\r\n\r\n#unique dates but specific\r\n_dates = []\r\nfor i in range (DATES_COUNT):\r\n date = fake.date_time().strftime('%Y-%m-%dT%H:%M:%S.%f')\r\n while date in _dates:\r\n date = fake.date_time().strftime('%Y-%m-%dT%H:%M:%S.%f')\r\n _dates.append(date)\r\n\r\n\r\nmatches_picked = []\r\nmanagers_taken = []\r\ndata_y = []\r\ndata = []\r\nwith open(\"matches.json\", \"w\") as write_file:\r\n for i in range(500000):\r\n if i % 1000 == 0: print (f\"Match: Iteration: {i//1000}K\")\r\n\r\n m_id = match_ids[i]\r\n\r\n #pick one random manager\r\n manager_user = random.choice(managers)\r\n\r\n #home team\r\n team_x = random.choice(teams_names)\r\n team_y = random.choice(teams_names)\r\n while team_x == team_y:\r\n team_y = random.choice(teams_names)\r\n\r\n stad_i = randint(0, len(stads_ids)-1)\r\n stad_name = stads_names[stad_i]\r\n\r\n width, height = stad_x_y[stad_i]\r\n k = 0\r\n users_picked = []\r\n for ii in range (width):\r\n for jj in range (height):\r\n ev = randint(0,2)\r\n if ev == 1 and len (users_picked) != len(fans):\r\n #assign\r\n fan = random.choice(fans)\r\n users_picked.append({'user_id':fan, 'x_i':ii, 'y_i':jj})\r\n k += 1\r\n\r\n \r\n my_dict = {\r\n '_id':m_id,\r\n 'referee':fake.profile()['name'],\r\n 'date_time':random.choice(_dates),\r\n 'teams':{\r\n 'home':team_x,\r\n 'away':team_y\r\n },\r\n 'stadium':{\r\n 'name':stad_name,\r\n 'width':stad_x_y[stad_i][0],\r\n 'height':stad_x_y[stad_i][1]\r\n },\r\n 'line_men':{\r\n 'first':fake.profile()['name'],\r\n 'second':fake.profile()['name']\r\n },\r\n 'manager_scheduled':manager_user,\r\n 'users_reserved':users_picked\r\n \r\n }\r\n data_y.append(my_dict)\r\n json.dump(data_y, write_file)\r\n\r\n\r\ndata = []\r\nwith open(\"teams.json\", \"w\") as write_file:\r\n for i in range(TEAMS_NUM):\r\n if i % 100 == 0: \r\n print (f\"Team: Iteration: {i}\")\r\n team_id = teams_ids[i]\r\n team_name = teams_names[i]\r\n\r\n my_dict={\r\n '_id':team_id,\r\n 'team_name':team_name\r\n }\r\n data.append(my_dict)\r\n json.dump(data, write_file)\r\n\r\n\r\n\r\ndata = []\r\nwith open(\"stadiums.json\", \"w\") as write_file:\r\n for i in range(STADIUMS_NUM):\r\n if i % 10 == 0: \r\n print (f\"stadium: Iteration: {i}\")\r\n stad_id = stads_ids[i]\r\n stads_name = stads_names[i]\r\n\r\n my_dict={\r\n '_id':stad_id,\r\n 'stad_name':stads_name,\r\n 'width':stad_x_y[i][0],\r\n 'height':stad_x_y[i][1]\r\n }\r\n data.append(my_dict)\r\n json.dump(data, write_file)\r\n\r\n ","sub_path":"scripts/nosql_generator.py","file_name":"nosql_generator.py","file_ext":"py","file_size_in_byte":5482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"292216452","text":"import re\nfrom slack import WebClient\nfrom slack.errors import SlackApiError\nfrom sym_api_client_python.auth.rsa_auth import SymBotRSAAuth\nfrom sym_api_client_python.clients.sym_bot_client import SymBotClient\nfrom sym_api_client_python.configure.configure import SymConfig\n\nclass SlackImport():\n\n def __init__(self, slack_token, room_obj):\n self.slack_token = slack_token\n self.user_id_map = self.user_id_map = \"\"\"{SLACK_USER_ID: SYMPHONY_USER_ID\"\"\"\n self.client = WebClient(token=self.slack_token)\n self.room_obj = room_obj\n\n #returns array of all slack channels your app/bot is a member of:\n def get_slack_channels(self):\n response = client.conversations_list().get('channels')\n rooms = []\n for i in response:\n room_attributes = {\"name\": \"\", \"description\": \"\", \"public\": \"\", \"creator\": \"\", \"conversation_id\": \"\"}\n room_attributes.update(name = i.get('name'))\n room_attributes.update(description = i.get('purpose').get('value'))\n room_attributes.update(public = not i.get('is_private'))\n room_attributes.update(creator = i.get('creator'))\n room_attributes.update(conversation_id = i.get('id'))\n rooms.append(room_attributes)\n return rooms\n\n def clean_messages(self, channel_id, symphony_stream_id):\n #get messages from desired chatroom\n slack_messages = self.client.conversations_history(channel=channel_id)\n #array to store cleaned messages\n cleaned_messages = []\n\n for i in slack_messages.get('messages'):\n cleaned_message = {\"message\": \"\", \"intendedMessageTimestamp\": \"\", \"intendedMessageFromUserId\": \"\", \"originatingSystemId\" : \"Slack\", \"originalMessageId\": \"\", \"streamId\": symphony_stream_id}\n cleaned_message.update(message = '' + i.get('text') + \"\")\n cleaned_message.update(intendedMessageTimestamp = int(i.get('ts').split('.')[0] + i.get('ts').split('.')[1][:3]))\n cleaned_message.update(intendedMessageFromUserId = i.get('user'))\n\n if i.get('user') in self.user_id_map:\n cleaned_message.update(intendedMessageFromUserId = self.user_id_map.get(i.get('user')))\n\n cleaned_message.update(originalMessageId=i.get('ts'))\n cleaned_messages.append(cleaned_message)\n\n return cleaned_messages\n\n def format_mentions(self, msg_array):\n regex_pattern = '<@...........>'\n for i in msg_array:\n match = re.findall(regex_pattern, i.get('message'))\n if match:\n if match[0][2:-1] in self.user_id_map:\n i.update(message = i.get('message').replace(match[0], \"\"))\n return msg_array\n\n #imports cleaned messages array into desired room:\n #cleaned_messages -> array of cleaned message objected returned from clean_messages()\n def import_messages(self, bot_client, cleaned_messages):\n bot_client.get_message_client().import_message(cleaned_messages)\n return None\n\n def run_import(self, bot_client):\n for i in self.room_obj:\n formatted_messages = self.format_mentions(self.clean_messages(i.get(\"conversation_id\"), i.get(\"stream_id\")))\n self.import_messages(bot_client, formatted_messages)\n","sub_path":"slack_import.py","file_name":"slack_import.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"410011591","text":"#!/usr/bin/env python\n# Copyright 2011 The greplin-nagios-utils Authors.\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\"\"\"Server that runs Python checks.\"\"\"\n\nfrom greplin_nagios_utils import settings\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport imp\nimport os\nimport sys\n\n\ntornado.options.define(name=\"debug\", default=False, help=\"run in debug mode\", type=bool)\n\nCHECK_CACHE = {}\n\nclass UpdateCheckHandler(tornado.web.RequestHandler):\n \"\"\"Removes the cached version of a check.\"\"\"\n\n def get(self, name): # pylint: disable=W0221\n if name in CHECK_CACHE:\n del CHECK_CACHE[name]\n\n\n\nclass CheckHandler(tornado.web.RequestHandler):\n \"\"\"Handles running a check.\"\"\"\n\n def get(self, name):\n if name not in CHECK_CACHE:\n filename = settings.CHECKSCRIPT_PATH % name\n if os.path.exists(filename):\n CHECK_CACHE[name] = imp.load_source('check_%s' % name, filename)\n else:\n raise Exception('No such file: %s' % filename)\n\n try:\n sys.stdout = self\n sys.stderr = self\n \n args = self.get_arguments('arg')\n args.insert(0, 'check_%s' % name)\n CHECK_CACHE[name].check(args)\n except SystemExit:\n pass\n \n finally:\n sys.stdout = sys.__stdout__\n sys.stderr = sys.__stderr__\n\n\ndef main():\n \"\"\"Starts the web server.\"\"\"\n tornado.options.parse_command_line()\n\n application = tornado.web.Application([\n (r\"/check/(.+)\", CheckHandler),\n (r\"/update/(.+)\", UpdateCheckHandler),\n ], debug = tornado.options.options.debug)\n\n httpServer = tornado.httpserver.HTTPServer(application)\n httpServer.listen(settings.CHECKSERVER_PORT)\n\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"checkserver/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"575566355","text":"import copy\nimport math\nimport time\nimport numpy as np\nfrom Common.CreateDistanceMatrix import load_data_from_file, create_distance_matrix\nfrom Common.Visualize import plot_results\nfrom ExtendedLocalSearch.GreedyCycleForILS2 import greedy_cycle_for_ils2\nfrom Heuristics.GreedyCycle import greedy_cycle\nfrom ImprovedLocalSearch.SteepestList import ls_steepest_list\nfrom LocalSearch.RandomWalk import cycle_length\n\n\ndef ils2_perturbation(cycle_1, cycle_2, distance_matrix):\n k = math.ceil(distance_matrix.shape[0]*0.2 / 2.) * 2\n vertices_to_remove_1 = np.random.choice(cycle_1, int(k/2), replace=False)\n vertices_to_remove_2 = np.random.choice(cycle_2, int(k/2), replace=False)\n cycle_1_with_perturbation = [vertex for vertex in cycle_1 if vertex not in vertices_to_remove_1]\n cycle_2_with_perturbation = [vertex for vertex in cycle_2 if vertex not in vertices_to_remove_2]\n return cycle_1_with_perturbation, cycle_2_with_perturbation\n\n\ndef ils2_method(cycle_1, cycle_2, distance_matrix, with_ls=True, runtime=5):\n cycle_1_with_updates = copy.deepcopy(cycle_1)\n cycle_2_with_updates = copy.deepcopy(cycle_2)\n best_cycles = (cycle_1, cycle_2)\n best_cycles_length = cycle_length(cycle_1, distance_matrix) + cycle_length(cycle_2, distance_matrix)\n start_time = time.time()\n\n cycle_1_with_updates, cycle_2_with_updates = ls_steepest_list(cycle_1_with_updates, cycle_2_with_updates, distance_matrix)\n\n while time.time() - start_time < runtime:\n cycle_1_with_updates, cycle_2_with_updates = ils2_perturbation(cycle_1_with_updates, cycle_2_with_updates, distance_matrix)\n cycle_1_with_updates, cycle_2_with_updates = greedy_cycle_for_ils2(cycle_1_with_updates, cycle_2_with_updates, distance_matrix)\n if with_ls:\n cycle_1_with_updates, cycle_2_with_updates = ls_steepest_list(cycle_1_with_updates, cycle_2_with_updates,\n distance_matrix)\n cycles_length = cycle_length(cycle_1_with_updates, distance_matrix) + cycle_length(cycle_2_with_updates, distance_matrix)\n if cycles_length < best_cycles_length:\n best_cycles = (cycle_1_with_updates, cycle_2_with_updates)\n best_cycles_length = cycles_length\n return best_cycles\n\n\n# coordinates_a = load_data_from_file('../Heuristics/kroA100.tsp')\n# distance_matrix_a = create_distance_matrix('../Heuristics/kroA100.tsp')\n# cycle_1, cycle_2 = greedy_cycle(distance_matrix_a, start_vertex_1=None)\n# print(cycle_length(cycle_1, distance_matrix_a))\n# print(cycle_length(cycle_2, distance_matrix_a))\n# xs = [coord[0] for coord in coordinates_a]\n# ys = [coord[1] for coord in coordinates_a]\n# plot_results(xs, ys, cycle_1, cycle_2)\n# cycle_1_improved, cycle_2_improved = ils2_method(cycle_1, cycle_2, distance_matrix_a, False, 5)\n# print(cycle_length(cycle_1_improved, distance_matrix_a))\n# print(cycle_length(cycle_2_improved, distance_matrix_a))\n# plot_results(xs, ys, cycle_1_improved, cycle_2_improved)\n","sub_path":"ExtendedLocalSearch/ILS2.py","file_name":"ILS2.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"556427004","text":"\"\"\"\n:Module: slice_timing\n:Author: dohmatob elvis dopgima\n:Synopsis: module for Slice Timing Correction (STC) business\n\n\"\"\"\n\nimport os\nimport nipy\nfrom nipy.algorithms.registration.groupwise_registration import FmriRealign4d\nimport numpy as np\n\n\ndef do_slicetiming_and_motion_correction(func,\n output_dir=None,\n **fmrirealign4d_kwargs):\n \"\"\"\n Function to do slice-timing and motion correction together.\n\n Parameters\n ----------\n func: string or list of strings, or list of list of strings\n filename (4D image path) or list of filenames (4D image paths) or\n list of lists of filenames (3D image paths) for images to be\n realigned\n\n output_dir: string (optional, default None)\n output directory to which all output files will be written,\n if write_output option is set\n\n **fmrirealign4D_kwargs:\n options to be passed to\n ``nipy.algorithms.registration.groupwise_registration.FmriRealign4D``\n constructor\n\n tr: float (TR for images)\n slice_order ['ascending' | 'descending' | etc.]\n time_interp: [True | False]\n\n\n Returns\n -------\n list or realiged images (one per run, with 3D input images concatenated\n to realigned 4D niftis)\n\n \"\"\"\n\n # sanity\n single = False\n if isinstance(func, basestring):\n single = True\n func = [func]\n\n if not output_dir is None:\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n # instantiate FmriRealign4d object\n input_fmri_files = func\n\n # load images\n runs = [nipy.load_image(x) for x in input_fmri_files]\n\n # instantiate FmriRealign4d object\n R = FmriRealign4d(runs,\n **fmrirealign4d_kwargs)\n\n # estimate transforms\n R.estimate()\n\n # apply transforms\n realigned_runs = R.resample()\n\n # sanity checks\n assert len(runs) == len(realigned_runs)\n\n # collect output stuff\n rp_files = []\n output_fmri_files = []\n for j in xrange(len(realigned_runs)):\n realignment_params = np.array(\n [np.hstack((R._transforms[j][i].translation,\n R._transforms[j][i].rotation))\n for i in xrange(len(R._transforms[j]))])\n\n if not output_dir is None:\n if isinstance(input_fmri_files[j], basestring):\n input_fmri_file = input_fmri_files[j]\n else:\n input_fmri_file = input_fmri_files[j][0]\n\n # save realigned image\n # input_dtype = ni.load(input_fmri_file).get_data_dtype()\n\n input_file_basename = os.path.basename(\n input_fmri_file).split(\".\")\n output_file_basename = input_file_basename[\n 0] + \"_nipy_realigned\" + \".\" + input_file_basename[1]\n output_img_path = os.path.join(output_dir,\n output_file_basename)\n\n nipy.save_image(\n realigned_runs[j],\n output_img_path,\n # dtype_from=input_dtype,\n )\n\n output_fmri_files.append(output_img_path)\n\n # save motion params\n rp_file = os.path.join(output_dir,\n \"rp_run_%i.txt\" % j)\n\n np.savetxt(rp_file, realignment_params)\n\n rp_files.append(rp_file)\n else:\n output_fmri_files.append(realigned_runs[j])\n rp_files.append(realignment_params)\n\n # return outputs\n if single:\n output_fmri_files = output_fmri_files[0]\n\n return output_fmri_files, rp_files\n","sub_path":"algorithms/slice_timing/slice_timing.py","file_name":"slice_timing.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"142060573","text":"import cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\ndef dist(a, b):\r\n \"\"\"distancia Euclidea\"\"\"\r\n return np.linalg.norm(np.array(a) - np.array(b))\r\n\r\n\r\ndef cos_law(p1, p2, p3):\r\n p12 = dist(p1, p2) \r\n p13 = dist(p1, p3)\r\n p23 = dist(p2, p3)\r\n p122 = np.square(p12)\r\n p132 = np.square(p13)\r\n p232 = np.square(p23)\r\n\r\n aux = (p122 + p132 - p232) / (2 * p12 * p13)\r\n angle = np.arccos(aux) * 180 / np.pi\r\n return angle\r\n\r\n\r\ndef recorta(lista, umbral):\r\n aux = lista\r\n cambios = 1\r\n\r\n while cambios!= 0:\r\n lista = aux\r\n aux = []\r\n cambios = 0\r\n ind = []\r\n for i in range(0,len(lista)):\r\n for j in range(i+1, len(lista)):\r\n d = dist(lista[i],lista[j])\r\n if d < umbral:\r\n if not np.isin(i,ind) and not np.isin(j,ind):\r\n aux.append((lista[i]+lista[j])/2)\r\n cambios += 1\r\n ind.append(i)\r\n ind.append(j)\r\n\r\n for i in range(0,len(lista)):\r\n if not np.isin(i, ind):\r\n aux.append(lista[i])\r\n\r\n return aux\r\n\r\n\r\nimg = cv2.imread('Images/9.jpg')\r\nimg2 = img.copy()\r\n\r\nim2 = cv2.cvtColor(cv2.medianBlur(img,5), cv2.COLOR_BGR2HSV)\r\na1 = np.uint8([[0, 0, 0]])\r\na2 = np.uint8([[35, 255, 255]])\r\nb1 = np.uint8([[175, 0, 0]])\r\nb2 = np.uint8([[180, 255, 255]])\r\nthresh1 = cv2.inRange(im2, a1, a2) + cv2.inRange(im2, b1, b2)\r\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\r\nthresh2 = cv2.dilate(thresh1,kernel)\r\nthresh2 = cv2.erode(thresh2,kernel)\r\n\r\n\r\nim2, contours, hierarchy = cv2.findContours(thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\ndrawing = np.zeros(img.shape, np.uint8)\r\n\r\nif type(contours) != type(None):\r\n max_area = 0\r\n ci = -1\r\n for i in range(len(contours)):\r\n cnt = contours[i]\r\n area = cv2.contourArea(cnt)\r\n if area > max_area:\r\n max_area = area\r\n ci = i\r\n\r\n cnt = contours[ci]\r\n\r\n hull = cv2.convexHull(cnt)\r\n\r\n cv2.drawContours(drawing, [cnt], 0, (0, 255, 0), 2)\r\n cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 5)\r\n\r\n lista = []\r\n for i in range(0, len(hull)):\r\n for j in range(0, len(cnt)):\r\n if np.array_equal(hull[i], cnt[j]):\r\n lista.append(hull[i])\r\n\r\n ret = np.int32(recorta(lista, 50))\r\n\r\n for i in range(0, len(ret)):\r\n cv2.circle(drawing, tuple(ret[i][0]), 9, [255, 255, 255], 2)\r\n cv2.circle(drawing, tuple(ret[i][0]), 2, [255, 255, 255], -1)\r\n\r\n cnt = cv2.approxPolyDP(cnt, 0.005 * cv2.arcLength(cnt, True), True)\r\n hull = cv2.convexHull(cnt, returnPoints=False)\r\n defects = cv2.convexityDefects(cnt, hull)\r\n\r\n soyelmapa = []\r\n defmap = []\r\n\r\n if type(defects) != type(None):\r\n for i in range(defects.shape[0]):\r\n s, e, f, d = defects[i, 0]\r\n start = tuple(cnt[s][0])\r\n end = tuple(cnt[e][0])\r\n far = tuple(cnt[f][0])\r\n\r\n soyelmapa.append([cnt[s][0], i])\r\n soyelmapa.append([cnt[e][0], i])\r\n defmap.append([cnt[f][0], i])\r\n\r\n\r\n count = 0\r\n fingers = []\r\n fdefect = []\r\n\r\n for i in range(0, len(ret)):\r\n p1 = ret[i]\r\n ind = []\r\n for j in range(0, len(soyelmapa)):\r\n d = dist(p1, soyelmapa[j][0])\r\n if d < 50:\r\n ind.append(j)\r\n\r\n if len(ind) == 2:\r\n idef1 = soyelmapa[ind[0]][1]\r\n def1 = defmap[idef1][0]\r\n idef2 = soyelmapa[ind[1]][1]\r\n def2 = defmap[idef2][0]\r\n angulo = cos_law(ret[i], def1, def2)\r\n\r\n if angulo < 60:\r\n cv2.line(img2, tuple(ret[i][0]), tuple(def1), [0, 255, 0], 4)\r\n cv2.line(img2, tuple(ret[i][0]), tuple(def2), [0, 255, 0], 4)\r\n cv2.circle(img2, tuple(def1), 9, [255, 0, 255], -1)\r\n cv2.circle(img2, tuple(def2), 9, [255, 0, 255], -1)\r\n cv2.circle(img2, tuple(p1[0]), 9, [0, 0, 255], 3)\r\n\r\n count += 1\r\n fingers.append(p1[0])\r\n fdefect.append([def1, def2])\r\n cv2.circle(img, tuple(p1[0]), 15, [0, 0, 255], 4)\r\n\r\n cv2.imwrite('angulos.png', img2)\r\n\r\n dedos = None\r\n\r\n if count != 3:\r\n cv2.putText(img, str(count), (0, 150), cv2.FONT_HERSHEY_DUPLEX, 5, (255, 255, 255), thickness=5)\r\n dedos = count\r\n else:\r\n f = np.argsort(fingers, axis=0)\r\n f = f[:, 0]\r\n df = np.argsort(fdefect[f[1]], axis=0)[0]\r\n a12 = cos_law(fdefect[f[1]][df[0]], fingers[f[0]], fingers[f[1]])\r\n a23 = cos_law(fdefect[f[1]][df[1]], fingers[f[1]], fingers[f[2]])\r\n d12 = fingers[f[1]] - fingers[f[0]]\r\n d23 = fingers[f[2]] - fingers[f[1]]\r\n\r\n coef = 1.3\r\n\r\n\r\n if a23 > a12*coef and d23[1] > 100:\r\n cv2.putText(img, str(3), (0, 150), cv2.FONT_HERSHEY_DUPLEX, 5, (255, 255, 255), thickness=5)\r\n dedos = 3\r\n else:\r\n if a12 > a23*coef and d23[0] < d12[0]:\r\n cv2.putText(img, str(7), (0, 150), cv2.FONT_HERSHEY_DUPLEX, 5, (255, 255, 255), thickness=5)\r\n print(7)\r\n else:\r\n if a23 > a12 * coef and d23[0] > d12[0]:\r\n cv2.putText(img, str(8), (0, 150), cv2.FONT_HERSHEY_DUPLEX, 5, (255, 255, 255), thickness=5)\r\n print(8)\r\n else:\r\n if fingers[f[0]][1] > fingers[f[2]][1] and fingers[f[0]][1] > fingers[f[1]][1]:\r\n if fingers[f[1]][1] > fingers[f[2]][1]:\r\n cv2.putText(img, str(9), (0, 150), cv2.FONT_HERSHEY_DUPLEX, 5, (255, 255, 255), thickness=5)\r\n dedos = 9\r\n else:\r\n cv2.putText(img, str(6), (0, 150), cv2.FONT_HERSHEY_DUPLEX, 5, (255, 255, 255), thickness=5)\r\n dedos = 6\r\n else:\r\n cv2.putText(img, str(6), (0, 150), cv2.FONT_HERSHEY_DUPLEX, 5, (255, 255, 255), thickness=5)\r\n dedos = 6\r\n\r\n print(dedos)\r\n\r\n plt.subplot(1, 3, 1)\r\n plt.imshow(drawing[:, :, ::-1])\r\n plt.subplot(1, 3, 2)\r\n plt.imshow(img2[:, :, ::-1])\r\n plt.subplot(1, 3, 3)\r\n plt.imshow(img[:, :, ::-1])\r\n plt.show()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"185515615","text":"global wyjscie\nwyjscie = []\ndef przecina(plot, inny):\n return (plot[1] > inny[0] and plot[0] < inny[0] and plot[1] < inny[1]) or (inny[1] > plot[0] and inny[0] < plot[0] and inny[1] < plot[1])\n\n\ndef wypisz(p):\n wyjscie.append(p)\n\ndef znajdz(ploty):\n przeciecia = set()\n for plot in ploty:\n for inny in ploty:\n if (plot[1] > inny[0] and plot[0] < inny[0] and plot[1] < inny[1]) or (inny[1] > plot[0] and inny[0] < plot[0] and inny[1] < plot[1]):\n przeciecia.add(plot)\n przeciecia.add(inny)\n\n if (len(przeciecia)) == 2:\n wypisz(next(iter(przeciecia)))\n else:\n sek = iter(przeciecia)\n p1 = next(sek)\n p2 = next(sek)\n p3 = next(sek)\n if przecina(p1, p2) and przecina(p1, p3):\n wypisz(p1)\n elif przecina(p2, p1) and przecina(p2, p3):\n wypisz(p2)\n else:\n wypisz(p3)\n\n\ndef ploty():\n Z = int(input())\n for i in range(Z):\n N = int(input())\n ploty = []\n for j in range(N - 2):\n plot = [int(x) for x in input().split()]\n if (plot[0] > plot[1]):\n ploty.append((plot[1], plot[0]))\n else:\n ploty.append((plot[0], plot[1]))\n\n znajdz(ploty)\n\n\n\nploty()\nfor p in wyjscie:\n print(p[0], p[1])\n\n","sub_path":"OIJ_olimpiada_konkurs/wlasciwy_konkurs/ploty.py","file_name":"ploty.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"576831214","text":"import torch\nimport torch.nn as nn\n\nfrom torch.nn import init\n\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find('Linear') != -1:\n init.normal(m.weight.data, 0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n init.normal_(m.weight.data, 1.0, 0.02)\n init.constant_(m.bias.data, 0.0)\n\n\ndef weights_init_orthogonal(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n init.orthogonal_(m.weight.data)\n elif classname.find('Linear') != -1:\n init.orthogonal_(m.weight.data)\n elif classname.find('BatchNorm') != -1:\n init.normal_(m.weight.data, 1.0, 0.02)\n init.constant_(m.bias.data, 0.0)\n\n\ndef weights_init_xavier(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n init.xavier_normal_(m.weight.data, gain=0.02)\n elif classname.find('Linear') != -1:\n init.xavier_normal_(m.weight.data, gain=0.02)\n elif classname.find('BatchNorm2d') != -1:\n init.normal_(m.weight.data, 1.0, 0.02)\n init.constant_(m.bias.data, 0.0)\n\n\ndef weights_init_kaiming(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif classname.find('Linear') != -1:\n init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif classname.find('BatchNorm2d') != -1:\n init.normal_(m.weight.data, 1.0, 0.02)\n init.constant_(m.bias.data, 0.0)\n\n\ndef init_weights(net, init_type='ortho'):\n print('initialization method [%s]' % init_type)\n if init_type == 'ortho':\n net.apply(weights_init_orthogonal)\n elif init_type == 'xavier':\n net.apply(weights_init_xavier)\n elif init_type == 'kaiming':\n net.apply(weights_init_kaiming)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n\n\ndef calc_mean_std(feat, eps=1e-5):\n size = feat.size()\n N, C = size[:2]\n feat_var = feat.view(N, C, -1).var(dim=2) + eps\n feat_std = feat_var.sqrt().view(N, C, 1)\n feat_mean = feat.view(N, C, -1).mean(dim=2).view(N, C, 1)\n\n return feat_mean, feat_std\n\n\ndef adain(content_feat, style_feat):\n size = content_feat.size()\n style_mean, style_std = style_feat[:, :128], style_feat[:, 128:]\n style_mean = style_mean.unsqueeze(dim=2)\n style_std = style_std.unsqueeze(dim=2)\n content_mean, content_std = calc_mean_std(content_feat)\n\n normalized_feat = (content_feat - content_mean.expand(\n size)) / content_std.expand(size)\n\n return normalized_feat * style_std.expand(size) + style_mean.expand(size)\n\n\nclass Block(nn.Module):\n def __init__(self, in_ch, out_ch, kernel=3, stride=1, norm=False):\n super(Block, self).__init__()\n\n self.norm = norm\n\n if norm:\n self.block = nn.Sequential(\n nn.Conv1d(in_ch, out_ch, kernel, stride, 1),\n nn.ReLU(),\n nn.Dropout(p=0.0),\n nn.InstanceNorm1d(out_ch)\n )\n\n else:\n self.block = nn.Sequential(\n nn.Conv1d(in_ch, out_ch, kernel, stride, 1),\n nn.ReLU(),\n nn.Dropout(p=0.0)\n )\n\n def forward(self, x):\n return self.block(x)\n\n\nclass AdaINBlock(nn.Module):\n def __init__(self, in_ch, out_ch, up=False):\n super(AdaINBlock, self).__init__()\n self.up = up\n\n if up:\n self.block = nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.Conv1d(in_ch, out_ch, 3, 1, 1),\n nn.ReLU(),\n nn.Dropout(p=0.0)\n )\n\n else:\n self.block = nn.Sequential(\n nn.Conv1d(in_ch, out_ch, 3, 1, 1),\n nn.ReLU(),\n nn.Dropout(p=0.0)\n )\n\n def forward(self, x, z):\n h = self.block(x)\n h = adain(h, z)\n\n return h\n\n\nclass Connection(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(Connection, self).__init__()\n\n self.connection = nn.Sequential(\n nn.Linear(in_ch, out_ch),\n nn.ReLU(),\n nn.Linear(out_ch, out_ch),\n nn.ReLU()\n )\n\n def forward(self, x):\n return self.connection(x) + x\n\n\nclass AdaINConnection(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(AdaINConnection, self).__init__()\n\n self.block = nn.Sequential(\n Connection(in_ch, out_ch),\n Connection(out_ch, out_ch),\n Connection(out_ch, out_ch),\n Connection(out_ch, out_ch)\n )\n\n def forward(self, x):\n return self.block(x)\n\n\nclass AffineTransform(nn.Module):\n def __init__(self, in_ch, out_ch, up=False):\n super(AffineTransform, self).__init__()\n self.up = up\n self.c0 = nn.Linear(in_ch, out_ch)\n\n def forward(self, z):\n return self.c0(z)\n\n\nclass Bank(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(Bank, self).__init__()\n\n self.bank0 = nn.Sequential(\n nn.Conv1d(in_ch, out_ch, 3, 1, 1),\n nn.ReLU()\n )\n self.bank1 = nn.Sequential(\n nn.Conv1d(in_ch, out_ch, 5, 1, 2),\n nn.ReLU()\n )\n self.bank2 = nn.Sequential(\n nn.Conv1d(in_ch, out_ch, 7, 1, 3),\n nn.ReLU()\n )\n self.bank3 = nn.Sequential(\n nn.Conv1d(in_ch, out_ch, 9, 1, 4),\n nn.ReLU()\n )\n\n def forward(self, x):\n h_list = []\n h_list.append(self.bank0(x))\n h_list.append(self.bank1(x))\n h_list.append(self.bank2(x))\n h_list.append(self.bank3(x))\n h_list.append(x)\n\n h = torch.cat(h_list, dim=1)\n\n return h\n\n\nclass SpeakerEncoderBlock(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(SpeakerEncoderBlock, self).__init__()\n\n self.c0 = nn.Sequential(\n Block(in_ch, out_ch),\n Block(out_ch, out_ch)\n )\n\n self.c1 = nn.Sequential(\n Block(out_ch, out_ch),\n Block(out_ch, out_ch, 4, 2)\n )\n\n self.pool = nn.AvgPool1d(2, 2, 0)\n\n def forward(self, x):\n h = self.c0(x)\n h = h + x\n h = self.c1(h)\n h = h + self.pool(x)\n\n return h\n\n\nclass ContentEncoderBlock(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(ContentEncoderBlock, self).__init__()\n\n self.c0 = nn.Sequential(\n Block(in_ch, out_ch, norm=True),\n Block(out_ch, out_ch, norm=True)\n )\n\n self.c1 = nn.Sequential(\n Block(out_ch, out_ch, norm=True),\n Block(out_ch, out_ch, 4, 2, True)\n )\n\n self.pool = nn.AvgPool1d(2, 2, 0)\n\n def forward(self, x):\n h = self.c0(x)\n h = h + x\n h = self.c1(h)\n h = h + self.pool(x)\n\n return h\n\n\nclass DecoderBlock(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(DecoderBlock, self).__init__()\n\n self.ab0 = AdaINBlock(in_ch, out_ch)\n self.ab1 = AdaINBlock(out_ch, out_ch)\n self.ab2 = AdaINBlock(out_ch, out_ch)\n self.ab3 = AdaINBlock(out_ch, out_ch, up=True)\n\n self.at0 = AffineTransform(in_ch, out_ch*2)\n self.at1 = AffineTransform(out_ch, out_ch*2)\n self.at2 = AffineTransform(out_ch, out_ch*2)\n self.at3 = AffineTransform(out_ch, out_ch*2, up=True)\n\n self.up = nn.Upsample(scale_factor=2)\n\n def forward(self, x, z):\n h = self.ab0(x, self.at0(z))\n h = self.ab1(h, self.at1(z))\n h = h + x\n h = self.ab2(h, self.at2(z))\n h = self.ab3(h, self.at3(z))\n h = h + self.up(x)\n\n return h\n\n\nclass SpeakerEncoder(nn.Module):\n def __init__(self, dim, base=128):\n super(SpeakerEncoder, self).__init__()\n\n self.convbank = Bank(dim, base)\n\n self.in_layer = nn.Sequential(\n nn.Conv1d(base*8, base, 1, 1, 0),\n nn.ReLU()\n )\n\n self.blocks = nn.Sequential(\n SpeakerEncoderBlock(base, base),\n SpeakerEncoderBlock(base, base),\n SpeakerEncoderBlock(base, base)\n )\n\n self.conn = nn.Sequential(\n Connection(base, base),\n Connection(base, base)\n )\n\n self.gap = nn.AdaptiveAvgPool1d(1)\n\n def forward(self, x):\n h = self.convbank(x)\n h = self.in_layer(h)\n h = self.blocks(h)\n h = self.gap(h)\n h = self.conn(h.squeeze(2))\n\n return h\n\n\nclass ContentEncoder(nn.Module):\n def __init__(self, dim, base=128):\n super(ContentEncoder, self).__init__()\n\n self.convbank = Bank(dim, base)\n self.in_layer = nn.Sequential(\n nn.Conv1d(base*8, base, 1, 1, 0),\n nn.ReLU(),\n nn.InstanceNorm1d(base)\n )\n\n self.blocks = nn.Sequential(\n ContentEncoderBlock(base, base),\n ContentEncoderBlock(base, base),\n ContentEncoderBlock(base, base)\n )\n\n self.lm = nn.Conv1d(base, base, 1, 1, 0)\n self.ls = nn.Conv1d(base, base, 1, 1, 0)\n\n def forward(self, x):\n h = self.convbank(x)\n h = self.in_layer(h)\n h = self.blocks(h)\n\n mu = self.lm(h)\n sigma = self.ls(h)\n\n return mu, sigma\n\n\nclass Decoder(nn.Module):\n def __init__(self, base=128):\n super(Decoder, self).__init__()\n\n self.conn = AdaINConnection(base, base)\n\n self.dec0 = DecoderBlock(base, base)\n self.dec1 = DecoderBlock(base, base)\n self.dec2 = DecoderBlock(base, base)\n self.out = nn.Conv1d(base, base*4, 1, 1, 0)\n\n def forward(self, x, z):\n z = self.conn(z)\n\n h = self.dec0(x, z)\n h = self.dec1(h, z)\n h = self.dec2(h, z)\n h = self.out(h)\n\n return h\n\n\nclass Model(nn.Module):\n def __init__(self, dim):\n super(Model, self).__init__()\n\n self.se = SpeakerEncoder(dim)\n self.ce = ContentEncoder(dim)\n self.dec = Decoder()\n\n init_weights(self.se)\n init_weights(self.ce)\n init_weights(self.dec)\n\n def forward(self, x, z):\n z = self.se(z)\n mu, sigma = self.ce(x)\n eps = sigma.new(*sigma.size()).normal_(0, 1)\n h = mu + torch.exp(sigma / 2) * eps\n\n h = self.dec(h, z)\n\n return h, mu, sigma\n","sub_path":"Oneshot/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":10457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"619778361","text":"\n\nclass Item(object):\n itemid = \"\"\n size = 0\n value = 0\n\n def __init__(self, itemid, size):\n self.itemid = itemid\n if size == 0:\n raise Exception(\"Item size is zero. Itemid:%s\" % (str(itemid)))\n self.size = size\n\n def norm_value(self, value):\n return value*1.0/self.size\n","sub_path":"parts/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"43585696","text":"## Script (Python) \"pauta_expediente_salvar_pysc\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=cod_sessao_plen, dat_sessao, num_legislatura, cod_sessao_leg, tip_sessao\n##title=\n##\n\nREQUEST = context.REQUEST\nRESPONSE = REQUEST.RESPONSE\n\nvotadas=[]\nnao_votadas=[]\nanuladas = []\n\nfor item in context.zsql.ordem_dia_obter_zsql(cod_sessao_plen = cod_sessao_plen, ind_excluido=0):\n if item.cod_materia !='' and item.cod_materia !=None:\n for materia in context.zsql.materia_obter_zsql(cod_materia=item.cod_materia, des_tipo_materia='Requerimento', ind_excluido=0):\n dic_materias = {}\n for votacao in context.zsql.votacao_ordem_dia_obter_zsql(cod_ordem=item.cod_ordem, cod_materia=item.cod_materia):\n votadas.append(int(item.cod_materia))\n if votacao.tip_resultado_votacao == 0:\n dic_materias['cod_materia'] = int(item.cod_materia)\n dic_materias['cod_ordem'] = int(item.cod_ordem)\n dic_materias['cod_votacao'] = int(votacao.cod_votacao) \n anuladas.append(dic_materias) \n if int(item.cod_materia) not in votadas:\n dic_materias['cod_materia'] = int(item.cod_materia)\n dic_materias['cod_ordem'] = int(item.cod_ordem)\n nao_votadas.append(dic_materias)\n\npresentes = context.pysc.quantidade_presentes_ordem_dia_pysc(cod_sessao_plen=cod_sessao_plen, dat_ordem=dat_sessao)\n\nif int(presentes) != 0:\n votos_sim = int(presentes) - 1\nelse:\n votos_sim = 0\n\nfor resultado in context.zsql.tipo_resultado_votacao_obter_zsql(nom_resultado='Aprovado'):\n lst_tip_resultado = resultado.tip_resultado_votacao\n nom_resultado = resultado.nom_resultado\n\nfor dic in nao_votadas:\n try:\n context.zsql.trans_begin_zsql()\n context.zsql.votacao_incluir_zsql(num_votos_sim=votos_sim, num_votos_nao='0', num_abstencao='0', cod_ordem=dic.get('cod_ordem',dic), cod_materia=dic.get('cod_materia',dic), tip_resultado_votacao=lst_tip_resultado)\n context.modelo_proposicao.requerimento_aprovar(cod_sessao_plen=cod_sessao_plen, nom_resultado=nom_resultado, cod_materia=dic.get('cod_materia',dic))\n context.zsql.trans_commit_zsql() \n except:\n context.zsql.trans_rollback_zsql()\n \nfor dic in anuladas:\n try:\n context.zsql.trans_begin_zsql()\n context.zsql.votacao_atualizar_zsql(cod_votacao=dic.get('cod_votacao',dic), num_votos_sim=votos_sim, num_votos_nao='0', num_abstencao='0', cod_ordem=dic.get('cod_ordem',dic), cod_materia=dic.get('cod_materia',dic), tip_resultado_votacao=lst_tip_resultado)\n context.modelo_proposicao.requerimento_aprovar(cod_sessao_plen=cod_sessao_plen, nom_resultado=nom_resultado, cod_materia=dic.get('cod_materia',dic))\n context.zsql.trans_commit_zsql() \n except:\n context.zsql.trans_rollback_zsql()\n\nredirect_url = 'index_html?cod_sessao_plen=' + cod_sessao_plen + '&cod_sessao_leg=' + cod_sessao_leg + '&num_legislatura=' + num_legislatura + '&dat_sessao=' + dat_sessao + '&tip_sessao=' + tip_sessao\n\nRESPONSE.redirect(redirect_url)\n","sub_path":"branches/4.1_buildout_cmm/openlegis/sagl/skins/cadastros/sessao_plenaria/ordem_dia_sessao/aprovacao_lote_salvar_pysc.py","file_name":"aprovacao_lote_salvar_pysc.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"442352863","text":"\"\"\"\nRun test as: pytest test_mailroom_pt4.py -vv\n\"\"\"\nimport os\nimport pytest\nfrom Python210_Fall2019.students.cem.mailroom.mailroom_pt4 import *\n\nMY_LETTER = (\n f\"\"\"\n\n Dear Bill Gates,\n\n Thank you for your amazingly generous donation of $653784.49!\n We, at Cem's Charity, greatly appreciate your donation, and your sacrifice.\n\n Your support helps to further our mission.\n\n Regards,\n Cem\n\n \"\"\"\n)\n\n\ndef test_answer():\n assert inc(3) == 4\n\n\ndef capital_case(x):\n return x.capitalize()\n\n\ndef test_capital_case():\n assert capital_case('semaphore') == 'Semaphore'\n\n\ndef test_write_files_to_dir():\n assert write_files_to_dir(\"TestFolder\")\n assert os.path.isfile(\"TestFolder/Bill_Gates_2019-12-03.txt\") is True\n\n\n# Test print report\ndef test_create_report():\n assert create_report() is None\n\n\n# Test sending a thank you letter\ndef test_thank_you_email():\n response = 'Test User'\n donated = 889.99\n letter = (\n f\"\"\"\n Dear Test User, \n\n Thank you for your amazingly generous donation of $889.99! \n We, at {CHARITY_NAME}, greatly appreciate your donation, and your sacrifice. \n\n Your support helps to further our mission.\n\n Regards,\n Cem\n \"\"\".format(**donors))\n assert thank_you_email(response, donated) == letter\n\n\ndef test_send_thank_you():\n assert \"Bill Gates\" in list_donors()\n assert \"James Smith\" not in list_donors()\n","sub_path":"students/cem/mailroom/test_mailroom_pt4.py","file_name":"test_mailroom_pt4.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"397183212","text":"from flask import Flask, render_template, flash, request\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField\n\n# App config.\nDEBUG = True\napp = Flask(__name__)\napp.config.from_object(__name__)\napp.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'\n\nlist_data =[] #this is donar list adding to the list\nallist =[] #to keep track how many times the donar name in the list\nunique_name = [] # unique donar names\nlist_sum = [] # donar names and total amount and number of times donated\nlist_add =[]\n\nclass donar():\n def __data(self,name,amount):\n self.donarname = name\n self.donaramount = amount\n alldata = (name,amount,1)\n data = (name)\n list_data.append(alldata)\n allist.append(data)\n\n def donarname(self):\n self.__data(\"mike\",80)\n self.__data(\"ketty\",175)\n self.__data(\"john hoop\",45)\n self.__data(\"ravi\",780)\n self.__data(\"david\",123)\n self.__data(\"bratte\",45)\n self.__data(\"mike\", 180)\n self.__data(\"mike\", 800)\n self.__data(\"david\",100)\n\n def countname(self):\n import collections\n k = allist\n counter = collections.Counter(k) #how many times the donar name in the donation list\n uniname = set(allist)\n for i in uniname:\n unique_name.append(i) #this is unique names of the donar\n\n for i in unique_name: #this will find the sum of the donation amount and number of times donated\n sum = 0\n times = 0\n for j in list_data:\n if(i == j[0]):\n sum = sum+j[1]\n times = times+j[2]\n all =(j[0],sum,times)\n if(counter[i] == times):\n list_sum.append(all)\n\n def report(self):\n print(\"+----------------------------+------------------+-------------------+-------------------+\")\n print(\"| Donar Name | Total given | Number of gifts | Average gift |\")\n print(\"+----------------------------+------------------+-------------------+--------------------\")\n\n for i in list_sum:\n name = i[0].upper()\n total = '$' + str(i[1])\n avg = i[2]\n k = int(i[1] / i[2])\n avggift = '$' + str(k)\n print(\"{: >20} {: >20} {: >20} {: >20}\".format(name, total, avg, avggift))\n\n def sendmail(self, listm):\n listd = listm\n for i in listd:\n a = i[0].upper()\n b = '$' + str(i[1])\n file = open(\"{}\"\".txt\".format(a), 'a+')\n file.write(\" Dear \"\"{}\".format(a))\n file.write(\"\\n\")\n file.write(\" \\n\")\n file.write(\" Thank you for your very kind donation of \")\n file.write(\"{}\".format(b))\n file.write(\"\\n\")\n file.write(\"\\n\")\n file.write(\" It will be used for very good cause.\")\n file.write(\"\\n\")\n file.write(\" Sincerely, \\n\")\n file.write(\" -The Team \")\n file.close\n\nclass donarreport(donar):\n\n def __init__(self):\n print(\"Menu:\")\n print(\"1.Send thank you mail\")\n print(\"2.Create report\")\n print(\"3.Add donars\")\n print(\"4.quit\")\n i = int(input(\"enter your choice 1 or 2 or 3 or 4: \"))\n if (i == 2):\n s = donar()\n s.donarname()\n s.countname()\n s.report()\n elif(i == 1):\n s = donar()\n s.donarname()\n s.countname()\n l = list_sum\n s.sendmail(l)\n print(\"The Thank you mail has been send to the list of donars\")\n for i in l:\n print(i[0].upper())\n\n\n elif(i == 3):\n self.add_donar()\n s = donar()\n s.donarname()\n s.countname()\n s.report()\n\n\nclass ReusableForm(Form):\n name = TextField('Name:', validators=[validators.required()])\n email = TextField('Email:', validators=[validators.required(), validators.Length(min=6, max=35)])\n donation_amount = TextField('Amount:', validators=[validators.required()])\n\n\n@app.route('/')\ndef hello_world():\n form = ReusableForm(request.form)\n e = donarreport()\n if request.method == 'POST':\n name = request.form['name']\n donation_amount = request.form['amount']\n email = request.form['email']\n data = (name,donation_amount,1)\n s = donar()\n list_add.append(data)\n list_data.append(data)\n alist.append(name)\n print(name, \" \", email, \" \", donation_amount)\n return render_template('hello.html', form=form)\n\n\n\nif __name__ == '__main__':\n app.run()","sub_path":"Project_submit/9module/assig122.py","file_name":"assig122.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"474033874","text":"from aiida.orm import QueryBuilder, UpfData, load_node\n\ndef get_Zvalence_from_pseudo(pseudo):\n \"\"\"\n Extract the number of valence electrons from a pseudo\n \"\"\"\n with pseudo.open() as f:\n lines = f.readlines()\n for line in lines:\n if 'valence' in line:\n try:\n return int(float(line.split('z_valence=\"')[-1].split('\"')[0].strip()))\n except (ValueError, IndexError):\n try:\n return int(float(line.split('Z')[0].strip()))\n except (ValueError, IndexError):\n return None\n \ndef get_starting_magnetization(structure):\n info_dict = load_node('8f5b7a63-07f8-4f62-8442-cb81c659170d').get_dict()\n elements = [k.symbol for k in structure.kinds]\n start_mag = {}\n for element in elements:\n # find the pseudo and its Z-valence\n qb = QueryBuilder()\n qb.append(UpfData,\n filters={\n 'attributes.element': {'==': element},\n })\n pseudo = qb.first()[0]\n Zval = get_Zvalence_from_pseudo(pseudo)\n start_mag[element] = info_dict[element]['magmom'] / float(Zval)\n \n return start_mag","sub_path":"notebooks/magnetism_helper.py","file_name":"magnetism_helper.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"278095115","text":"# -*- coding: utf-8 -*-\n#############################################################################\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program 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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom odoo import api, fields, models, _\nfrom datetime import datetime, date, time\nimport time\nfrom datetime import timedelta,datetime\nimport datetime\nfrom odoo.tools.translate import _\nimport psycopg2\nclass product_template(models.Model):\n _inherit = 'product.template'\n \n prestashop_product_category = fields.Char('Prestashop Category',size=64)\n wholesale_price = fields.Float('Whole Sale Price',digits=(16,2))\n combination_price = fields.Float(string=\"Extra Price of combination\")\n prdct_unit_price = fields.Float('Unit Price')\n prestashop_product = fields.Boolean('Prestashop Product')\n product_onsale = fields.Boolean('On sale')\n product_instock = fields.Boolean('In Stock')\n product_img_ids = fields.One2many('product.images','product_t_id','Product Images')\n prd_label = fields.Char('Label')\n supplier_id = fields.Many2one('res.partner','Supplier')\n manufacturer_id = fields.Many2one('res.partner','Manufacturer')\n product_lngth=fields.Float('Length')\n product_wght=fields.Float('Weight')\n product_hght=fields.Float('Height')\n product_width=fields.Float('Weight')\n prd_type_name=fields.Char('Product Type Name')\n prest_active=fields.Boolean('Active')\n prest_img_id=fields.Integer('Imge ID')\n product_list_id=fields.One2many('product.listing','product_id','Product Shops')\n presta_id = fields.Char('Presta ID')\n write_date = fields.Datetime(string=\"Write Date\")\n tmpl_shop_ids = fields.Many2many('sale.shop', 'product_templ_shop_rel', 'product_id', 'shop_id', string=\"Shop\")\n product_category_ids = fields.Many2many('product.category', 'product_template_categ_relation', 'product_id', 'categ_id', string=\"Category\")\n product_shop_count = fields.Integer(string=\"Shops\",compute = 'get_product_shop_count',default=0)\n product_to_be_exported = fields.Boolean(string=\"Product to be exported?\")\n sku = fields.Char(string=\"SKU\")\n\n # @api.multi\n def get_product_shop_count(self):\n for temp in self:\n temp.product_shop_count = len(temp.tmpl_shop_ids)\n\n\n\n # @api.multi\n def action_get_shop_product(self):\n action = self.env.ref('prestashop_connector_gt.act_prestashop_shop_form')\n\n result = {\n 'name': action.name,\n 'help': action.help,\n 'type': action.type,\n # 'view_type': action.view_type,\n 'view_mode': action.view_mode,\n 'target': action.target,\n 'context': action.context,\n 'res_model': action.res_model,\n 'domain': [('id', 'in', self.tmpl_shop_ids.ids)]\n }\n\n\n return result\n\nproduct_template()\n\n\n\n\n\n\nclass product_product(models.Model):\n _inherit='product.product'\n\n prestashop_product=fields.Boolean('Prestashop Product')\n # shop_ids = fields.Many2many('sale.shop', 'product_prod_shop_rel', 'product_prod_id', 'shop_id', string=\"Shop\")\n presta_id = fields.Char('Presta ID')\n\n combination_price = fields.Float(string=\"Extra Price of combination\")\n combination_id = fields.Char(string=\"Combination ID\")\n presta_inventory_id = fields.Char(string= 'Presta inventory ID')\n # v_product_img_ids = fields.One2many('product.images', 'product_v_id', 'Product Images')\n\n prodshop_ids = fields.Many2many('sale.shop', 'product_prod_shop_rel', 'product_prod_id', 'shop_id', string=\"Shop\")\n# presta_id = fields.Char('Presta ID')\n\nclass product_images(models.Model):\n _inherit ='product.images'\n\n product_t_id=fields.Many2one('product.template','Product Images')\n image_url=fields.Char('Image URL')\n image=fields.Binary('Image')\n prest_img_id=fields.Integer('Img ID')\n is_default_img=fields.Boolean('Default')\n prest_product_id=fields.Integer('Presta Product ID')\n shop_ids = fields.Many2many('sale.shop', 'img_shop_rel', 'img_id', 'shop_id', string=\"Shop\")\n write_date = fields.Datetime(string=\"Write Date\")\n\nclass product_attribute(models.Model):\n _inherit='product.attribute'\n \n is_presta=fields.Boolean(\"Is Prestashop\")\n public_name=fields.Boolean(\"Public Name\")\n presta_id = fields.Char(string='Presta Id')\n shop_ids = fields.Many2many('sale.shop', 'attr_shop_rel', 'attr_id', 'shop_id', string=\"Shop\")\n\nclass product_attribute_value(models.Model):\n _inherit= \"product.attribute.value\"\n\n _sql_constraints = [('value_company_uniq', 'CHECK(1=1)', 'You cannot create two values with the same name for the same attribute.')]\n\n is_presta=fields.Boolean(\"Is Prestashop\")\n presta_id = fields.Char(string='Presta Id')\n write_date = fields.Datetime(string=\"Write Date\")\n shop_ids = fields.Many2many('sale.shop', 'attr_val_shop_rel', 'attr_val_id', 'shop_id', string=\"Shop\")\n\n\nclass product_category(models.Model):\n _inherit=\"product.category\"\n presta_id =fields.Char(\"Presta ID\")\n sequence = fields.Integer( 'Sequence', default=1, help=\"Assigns the priority to the list of product Category.\")\n write_date = fields.Datetime(string=\"Write Date\")\n is_presta = fields.Boolean(\"Is Prestashop\")\n active = fields.Boolean(\"Active\")\n friendly_url = fields.Char(\"Friendly URL\")\n meta_title = fields.Char(\"Meta Title\", size=70)\n meta_description = fields.Text(\"Meta description\", )\n shop_id = fields.Many2one('sale.shop', 'Shop ID')\n shop_ids = fields.Many2many('sale.shop', 'categ_shop_rel', 'categ_id', 'shop_id', string=\"Shop\")\n to_be_exported = fields.Boolean(string=\"To be exported?\")\n\nclass product_listing(models.Model):\n _name='product.listing'\n shop_id=fields.Many2one('sale.shop','Shop ID')\n product_id =fields.Many2one('product.template','product_id')\n\nclass stock_warehouse(models.Model):\n _inherit = 'stock.warehouse'\n write_date = fields.Datetime(string=\"Write Date\")\n presta_id = fields.Char(\"Presta ID\")\n shop_ids = fields.Many2many('sale.shop', 'stockware_shop_rel', 'stockware_id', 'shop_id', string=\"Shop\")\n\nclass stock_quant(models.Model):\n _inherit = 'stock.quant'\n\n presta_id = fields.Char(\"Presta ID\")\n is_presta = fields.Char(\"Presta stock\")\n\n\n \n @api.model\n def _get_inventory_fields_create(self):\n res = super(stock_quant, self)._get_inventory_fields_create()\n res.append('presta_id')\n res.append('is_presta')\n return res\n","sub_path":"prestashop_connector_gt/models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":7128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"525987639","text":"# No video, no DWT, no compression, no bitplanes, no data-flow\n# control, no buffering. Only the transmission of the raw audio data,\n# splitted into chunks of fixed length.\n#\n# https://github.com/Tecnologias-multimedia/intercom\n#\n# Based on: https://python-sounddevice.readthedocs.io/en/0.3.13/_downloads/wire.py\n\n# SOULUTION 1 working solution\n\n#IMPLEMENTATION:\n#Current VERSION 1.6\n\n#1.6 -Added comments for explanation\n\n#1.5 -struct for correct byte order\n\n#1.4 -CPU and size measurement\n\n#1.3 -inheritance from parent class\n\n#1.2 -buffer dynamic by argument\n# -implementation of delay of playback\n\n#1.1 -index sent with package\n\n#1.0 -implementation buffer \n\nimport sounddevice as sd \nfrom intercom import Intercom\nimport numpy # https://numpy.org/\nimport argparse # https://docs.python.org/3/library/argparse.html\nimport socket \nimport math\nimport psutil\nimport struct\n\nif __debug__:\n import sys\n \nclass IntercomBuffer(Intercom):\n\n def init(self, args):\n Intercom.init(self,args)\n self.buffer_size=args.buffer_size\n self.packet_list=[]\n for x in range(self.buffer_size):\n self.packet_list.append([])\n self.packet_send=0\n\n #Benchmark Variables\n self.cpu_load=0\n self.cpu_max=0\n self.cycle=0 #caculation cycle for average value\n \n #first index -1 for delaying play\n self.packet_received=-1\n \n #calc size of message example: s. per chunk = 1024 & channel=2 (1024*2)\n self.msgsize=(self.samples_per_chunk*self.number_of_channels)\n\n if __debug__:\n print(\"buffer_size={}\".format(self.buffer_size))\n \n def run(self):\n sending_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n receiving_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n listening_endpoint = (\"0.0.0.0\", self.listening_port)\n receiving_sock.bind(listening_endpoint)\n \n def receive_and_buffer():\n messagepack, source_address = receiving_sock.recvfrom(\n Intercom.max_packet_size)\n \n out=struct.unpack('0:\n\n #if distnace between lowest received package and highest on is higher than half-size of buffer, bypass and start playing\n if max(nonzeros)-min(nonzeros) >= math.ceil(self.buffer_size/2): \n\n #get buffer-index of lowest received package\n self.packet_received=nonzeros[0] \n print(\"\\nBUFFERING FINISHED - START PLAYING\")\n\n try:\n message=self.packet_list[self.packet_received]\n\n #if message is empty (no package in buffer[index]) raise error (override message with silence)\n if len(message)<=0:\n raise ValueError\n\n idx=message[0]\n message=numpy.delete(message,0)\n \n except ValueError:\n #override message with silence\n message = numpy.zeros(\n (self.samples_per_chunk, self.bytes_per_sample),\n self.dtype)\n\n #if we started playing (after buffer was filled more than half-size) increase received counter\n if self.packet_received>=0: \n self.packet_received=(self.packet_received+1)%self.buffer_size\n \n outdata[:] = numpy.reshape(message,(\n self.samples_per_chunk, self.number_of_channels))\n\n if __debug__:\n sys.stderr.write(\".\"); sys.stderr.flush()\n\n with sd.Stream(\n samplerate=self.samples_per_second,\n blocksize=self.samples_per_chunk,\n dtype=self.dtype,\n channels=self.number_of_channels,\n callback=record_send_and_play):\n print('-=- Press + to quit -=-')\n while True:\n receive_and_buffer()\n\n \n def parse_args(self):\n parser = Intercom.add_args(self)\n\n #add buffer size argument for command line\n parser.add_argument(\"-bs\",\n \"--buffer_size\",\n help=\"tamaño de buffer\",\n type=int,\n default=4)\n\n #overwrite default chunk-size by 1024 if no argument is given (system specific)\n parser.set_defaults(samples_per_chunk=1024)\n args = parser.parse_args()\n return args\n \nif __name__ == \"__main__\":\n intercom2 = IntercomBuffer()\n args=intercom2.parse_args()\n intercom2.init(args)\n intercom2.run()","sub_path":"development/COPIES/intercomBufferSTRUCT - Kopie.py","file_name":"intercomBufferSTRUCT - Kopie.py","file_ext":"py","file_size_in_byte":7142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"405818953","text":"import pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\n\n'''\nThis class takes the h5 file created by deeplabcut.triangulate() and extracts a csv from the x, y, z coordinates within.\nYou can add metrics to the csv that this class outputs by passing their names in a list to the metrics argument. List of metrics can be seen below.\n\nmetrics:\nsd: standard deviation over a specified rolling window\npeak_velocity_point: takes the difference between each value as data[n+1] - data[n], gets the mean over a specified rolling window,\n then normalizes the data between -1 and 1. 1 is the point of peak velocity forwards, and -1 is the point of peak velocity moving\n backwards.\n'''\n\n\nh5_file_path = '/home/gavin/Documents/python_projects/DLC/stereo_2nd-silasi_lab-2020-07-31-3d/2020-07-29_(15-41-23)_00783A32F484_16_2024_DLC_3D.h5'\nset_of_metrics = {'peak_velocity_point'}\nlist_of_bodyparts = ['index', 'pinky', 'hand']\n\nclass h5_to_csv:\n def __init__(self, h5_file_path, list_of_bodyparts, list_of_metrics, sliding_window_num_frames):\n self.set_of_metrics = set_of_metrics\n self.df = pd.read_hdf(h5_file_path)\n self.df.dropna(how='all', inplace=True)\n self.sliding_window_num_frames = sliding_window_num_frames\n self.list_of_bodyparts = list_of_bodyparts\n\n def print_csv_output(self):\n print(self.df.isna().sum())\n print(self.df[500:550])\n\n # requires 50% of data in window or will fill as NaN\n # change dimensions to 2 if using 2D data, 3 for 3D data\n def add_metrics(self):\n coords = ['x', 'y', 'z']\n col_names = []\n dimensions = 3\n N = len(self.list_of_bodyparts)\n idx = pd.IndexSlice\n if 'peak_velocity_point' in self.set_of_metrics: \n for bp in self.list_of_bodyparts:\n for coord in coords:\n self.df['metrics', bp, coord + '_diff'] = self.df.loc[:, ('DLC_3D', bp, coord)].diff()\n self.df['metrics', bp, coord + '_diff_ma'] = self.df.loc[:, ('metrics', bp, coord + '_diff')].rolling(self.sliding_window_num_frames, self.sliding_window_num_frames//2).mean()\n tmp = self.df['metrics', bp, coord + '_diff_ma']\n self.df['metrics', bp, coord + '_diff_ma_scaled'] = 2 * ((tmp - tmp.min())/ (tmp.max() - tmp.min())) - 1\n self.df.drop(columns= coord + '_diff_ma', level=2, inplace=True)\n self.df.drop(columns= coord + '_diff', level=2, inplace=True)\n col_names.extend(['metrics', bp, coord + '_diff_ma_scaled'])\n\n self.df['velocity'] = self.df.loc[:, idx['metrics', 4:6, (N*dimensions)+1:]] # .apply(lambda x: abs(x)).sum()/(N*dimensions)\n \n\n if 'sd' in self.set_of_metrics:\n for bp in self.list_of_bodyparts:\n for coord in coords:\n self.df['metrics', bp, coord + '_std'] = self.df.loc[:, ('DLC_3D', bp, coord)].rolling(self.sliding_window_num_frames, self.sliding_window_num_frames//2).std()\n\n \n\ncsvMaker = h5_to_csv(h5_file_path, list_of_bodyparts, set_of_metrics, 15)\ncsvMaker.add_metrics()\ncsvMaker.print_csv_output()\n","sub_path":"dlc_data_analysis.py","file_name":"dlc_data_analysis.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"578098707","text":"\"\"\"\ndoc.py\n\nThis module allows documentation for Python classes and modules to be viewed\nin-game via the 'doc' command. \n\"\"\"\nimport pydoc, os, mudsys, display\n\n\n\n################################################################################\n# local variables\n################################################################################\n\n# where do we store documentation?\nHTML_DOC_DIR = \"../html/pydocs\"\n\nshortcuts = { \"ch\" : \"char\",\n \"sock\" : \"mudsock\",\n }\n\n# just a list of all our builtin modules\nbuiltins = [\n \"char\",\n \"room\",\n \"obj\",\n \"exit\",\n \"account\",\n \"mudsock\",\n \"mud\",\n \"mudsys\",\n \"hooks\",\n \"event\",\n \"auxiliary\",\n \"storage\",\n \"olc\",\n ]\n\n# append all of our builtins to suggested reading list\nsuggested_reading = [mod for mod in builtins]\n\ndef register_module_doc(modname, package = None, root = \"pymodules\"):\n \"\"\"Add a new module name to suggested_reading. If modname is a package,\n recursively add its packages as well\n \"\"\"\n fname = root + \"/\" + modname.replace(\".\", \"/\")\n suggested_reading.append(modname)\n if os.path.isdir(fname):\n for file in os.listdir(fname):\n if (file.endswith(\".py\") or not \".\" in file) and not file[0] in \"._\":\n module = modname + \".\" + file.split(\".\", 1)[0]\n register_module_doc(module, root)\n \n# now, append all of our Python packages and modules\nfor fname in os.listdir(\"pymodules/\"):\n # look for modules and packages\n if (fname.endswith(\".py\") or not \".\" in fname) and not fname[0] in \"._\":\n modname = fname.split(\".\", 1)[0]\n register_module_doc(modname)\n\n\n\n################################################################################\n# player commands\n################################################################################\ndef cmd_htmldoc(ch, cmd, arg):\n \"\"\"Creates html documentation for all registered modules. html files will\n be saved to html/pydocs/\n \"\"\"\n try:\n os.makedirs(HTML_DOC_DIR)\n except: pass\n doc = pydoc.HTMLDoc()\n for modname in suggested_reading:\n todoc = pydoc.locate(modname)\n if todoc != None:\n fname = HTML_DOC_DIR + \"/\" + modname + \".html\"\n fl = file(fname, \"w+\")\n fl.write(doc.page(modname, doc.document(todoc)))\n fl.close()\n\n builtin_index = doc.multicolumn([doc.modulelink(pydoc.locate(modname)) for modname in builtins], lambda x: x)\n \n # build our index page. That includes things in pymodules/ and builtins\n index_contents =\"\".join([doc.section(\"builtins\",\n 'white', '#ee77aa', builtin_index),\n doc.index(\"../lib/pymodules/\")])\n\n # go over all of our builtins and add them to the index\n index = file(HTML_DOC_DIR + \"/index.html\", \"w+\")\n index.write(doc.page(\"index\", index_contents))\n index.close()\n \n ch.send(\"html documentation generated for all known modules.\")\n\ndef cmd_doc(ch, cmd, arg):\n \"\"\"Return Python documentation for the specified module, class, function,\n etc... for example:\n \n > doc char.Char\n\n Will return all available documentation for the Char class.\n \"\"\"\n if arg == \"\":\n ch.page(\"\\r\\n\".join(display.pagedlist({ \"Topics\" : suggested_reading },\n header = \"Suggested doc readings include:\")))\n else:\n # just because sometimes I forget periods\n arg = arg.replace(\" \", \".\")\n\n # are we looking for a shortcut value?\n if arg in shortcuts:\n arg = shortcuts[arg]\n\n # try to find what we're documenting\n todoc = pydoc.locate(arg)\n if todoc == None:\n ch.send(\"Could not find Python documentation on: '%s'\" % arg)\n else:\n doc = pydoc.TextDoc()\n ch.page(doc.document(todoc).replace(\"{\", \"{{\"))\n\n\n\n################################################################################\n# initialization\n################################################################################\nmudsys.add_cmd(\"doc\", None, cmd_doc, \"wizard\", False)\nmudsys.add_cmd(\"htmldoc\", None, cmd_htmldoc, \"admin\", False)\n","sub_path":"lib/pymodules/doc.py","file_name":"doc.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"328741665","text":"# -*- coding: utf-8 -*-\n\"\"\"\n circle_select.py: Load an image file and find the average color in a\n scalable circle area\n \n Copyright (C) 2013 Greg von Winckel\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU 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 This program 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 General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n\n Last updated: Thu Oct 10 11:35:21 MDT 2013\n\"\"\"\n\nimport numpy as np\nimport Tkinter,tkFileDialog\nfrom pylab import *\n\nclass selector(object):\n \"\"\" Movable, resizable, circluar pixel selector \"\"\"\n def __init__(self,ax,facecolor,edgecolor):\n self.radius = 1\n self.patch = Circle((5,5),radius = self.radius,\n fc=facecolor,ec=edgecolor)\n self.patch.set_alpha(0.3)\n ax.add_patch(self.patch)\n\n def update_position(self,x,y):\n \"\"\" Move the selector with the mouse \"\"\"\n self.patch.center = (x,y) \n draw()\n\n def increase_size(self):\n \"\"\" Make the selection circle larger \"\"\"\n self.radius += 1\n self.patch.set_radius(self.radius)\n draw()\n\n def decrease_size(self):\n \"\"\" make the selection circle smaller \"\"\"\n if self.radius > 0: \n self.radius -= 1\n self.patch.set_radius(self.radius)\n draw()\n\nclass index_manager(object):\n def __init__(self,shape):\n x = np.arange(shape[1])\n y = np.arange(shape[0])\n xx,yy = np.meshgrid(x,y) \n self.xf = xx.flatten(\"F\")\n self.yf = yy.flatten(\"F\")\n \n def get_indices(self,x,y,r):\n \"\"\" Find the index of every pixel which lies within\n the circle of radius r, centered at (x,y) \"\"\" \n dex = np.where((self.xf-x)**2+(self.yf-y)**2 5:\n\t\t# exit()\n\ntiming = []\nfor i in range(len(m)):\n\ttiming.append(i*t)\n\t# print(timing)\n\t# if i >5:\n\t\t# exit()\n\n\nfig3, ax6 = plt.subplots()\nax6.set_ylabel('theta/t^4')\nax6.set_xlabel('time')\nax6.set_title(\"theta/t^4 Plot Comparison\")\nax6.plot(timing,m)\nplt.show()\n\n\"\"\"","sub_path":"HW3/Problem 1.py","file_name":"Problem 1.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"329743108","text":"import pandas as pd\n\ninput = 'dataset.csv'\n\n# reading and renaming data\ndf = pd.read_csv(input, sep=';', usecols=['Perioden', 'TotaalBevolking_4', 'k_0Tot20Jaar_5', 'k_20Tot45Jaar_6', 'k_45Tot65Jaar_7', 'k_65Tot80Jaar_8', 'k_80JaarOfOuder_9'])\n\n# cleaning data\ndf = df.dropna()\ndf['Perioden'] = df['Perioden'].str.replace('JJ00', '')\n\n# turn DataFrame into json object\ndata = df.to_json(orient='index')\n\n# write json object to file\nwith open('data.json', 'w') as outfile:\n outfile.write(data)\n outfile.close()\n","sub_path":"Homework/week_3/convertCSV2JSON.py","file_name":"convertCSV2JSON.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"68488701","text":"from abc import ABC, abstractmethod\nimport requests\nimport json\nimport sqlite3\nfrom bs4 import BeautifulSoup\nimport random\nimport time\n\nclass Persona():\n\n def __init__(self, id, first, last, city, cellphone, email, age, gender, taqueria):\n\n self.id = id\n self.first = first\n self.last = last\n self.city = city\n self.cellphone = cellphone\n self.email = email\n self.age = age\n self.gender = gender\n self.taqueria = taqueria\n\n def comer(self, cantidad):\n print('{} ha empezado a comer sus {} taquitos con mucho amor\\n'.format(self.first, cantidad))\n\n def ordenar_taquito(self):\n taquitoid = random.randint(1,50)\n cantidad = random.randint(2,12)\n db = sqlite3.connect(self.taqueria)\n cursor = db.cursor()\n cursor.execute('''\n INSERT INTO Orden (\n id_cliente,\n id_taco,\n Cantidad,\n Total)\n VALUES (\n :id_cliente,\n :id_taco,\n :cantidad,\n :total\n )''',\n {\n 'id_cliente': self.id,\n 'id_taco': taquitoid,\n 'cantidad': cantidad,\n 'total': 15 * cantidad\n }\n )\n db.commit()\n cursor.execute('''SELECT Nombre FROM Tacos WHERE Id = :id''', {'id': taquitoid})\n nombre = ''.join(cursor.fetchone())\n print('{} ha ordenado {} taquito(s) de {}, que rico! :O'.format(self.first, cantidad, nombre))\n return cantidad\n\n\n\nclass Taquito():\n\n def __init__(self, id, nombre, relleno, aderezo, salsa, sazonador, tortilla, precio):\n self.id = id\n self.nombre = nombre\n self.relleno = relleno\n self.aderezo = aderezo\n self.salsa = salsa\n self.sazonador = sazonador\n self.tortilla = tortilla\n self.precio = precio\n\nclass AbstractApiClients(ABC):\n\n @abstractmethod\n def get_clients():\n pass\n\nclass AbstractApiTaco(ABC):\n\n @abstractmethod\n def get_info():\n pass\n\nclass AbstractDb(ABC):\n\n @abstractmethod\n def createDB():\n pass\n\n @abstractmethod\n def insert_cliente():\n pass\n\n @abstractmethod\n def get_cliente():\n pass\n\n @abstractmethod\n def insert_ingrediente():\n pass\n\n @abstractmethod\n def insert_taco():\n pass\n\n\nclass ClientsApi(AbstractApiClients):\n\n def __init__(self,url):\n\n self.url = url\n\n def get_clients(self):\n\n request = requests.get(self.url, params = {'results': 30, 'nat': 'es'})\n if request.status_code == 200:\n listaclientes = request.json()\n else:\n print('Request Fallido')\n return listaclientes\n\nclass TacoApi(AbstractApiTaco):\n\n def __init__(self,url):\n\n self.url = url\n\n def get_info(self):\n\n request = requests.get(self.url)\n soup = BeautifulSoup(request.content, 'html.parser')\n\n nombretaco = soup.find('h1', attrs={'class': 'light'})\n nombretaco = nombretaco.text.strip()\n\n nombreing = soup.find_all('h5')[1].a.get('href')\n link = self.url + nombreing[1:]\n\n nombreing = nombreing.replace('/', ' ')\n inglist = nombreing.split()\n\n contribuidores = soup.find_all('h6')\n contlist = []\n for contribuidor in contribuidores:\n resultado = contribuidor.text.strip()\n contlist.append(resultado)\n\n recetas = soup.find_all('div', attrs={'class': 'recipe'})\n recipelist = []\n for recipe in recetas:\n location = recipe.text.find('tags')\n result = recipe.text[:location].strip()\n recipelist.append(result)\n\n tags = soup.find_all('div', attrs={'class': 'recipe'})\n taglist = []\n for tag in tags:\n location = tag.text.find('tags')\n res = tag.text[location:].rstrip()\n taglist.append(res)\n #time.sleep(1)\n return nombretaco, link, inglist, contlist, recipelist, taglist\n\n\nclass Sqlite(AbstractDb):\n\n def __init__(self,dbname):\n\n self.dbname = dbname\n\n def createDB(self):\n\n db = sqlite3.connect(self.dbname)\n cursor = db.cursor()\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS Ingredientes (\n\t Nombre TEXT NOT NULL,\n\t Receta TEXT,\n\t Contribuidores TEXT,\n\t Tags TEXT,\n\t PRIMARY KEY(Nombre)\n );'''\n )\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS Clientes (\n\t Id INTEGER PRIMARY KEY AUTOINCREMENT,\n\t Nombre TEXT,\n\t Apellido TEXT,\n\t Ciudad TEXT,\n\t Celular TEXT,\n\t Email TEXT,\n\t Edad INTEGER,\n\t Genero TEXT\n );'''\n )\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS Tacos (\n Id INTEGER PRIMARY KEY AUTOINCREMENT,\n Link TEXT,\n Nombre TEXT,\n Relleno\tTEXT,\n Aderezo\tTEXT,\n Salsa TEXT,\n Sazonador TEXT,\n Tortilla TEXT,\n\t Precio INTEGER,\n FOREIGN KEY(Salsa) REFERENCES Ingredientes(Nombre),\n FOREIGN KEY(Aderezo) REFERENCES Ingredientes(Nombre),\n FOREIGN KEY(Tortilla) REFERENCES Ingredientes(Nombre),\n FOREIGN KEY(Sazonador) REFERENCES Ingredientes(Nombre),\n FOREIGN KEY(Relleno) REFERENCES Ingredientes(Nombre)\n );'''\n )\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS Orden (\n Id INTEGER PRIMARY KEY AUTOINCREMENT,\n id_cliente INTEGER,\n id_taco INTEGER,\n Cantidad INTEGER,\n Total INTEGER,\n Status TEXT,\n FOREIGN KEY(id_taco) REFERENCES Tacos(Id),\n FOREIGN KEY(id_cliente) REFERENCES Clientes(Id)\n );'''\n )\n db.commit()\n db.close()\n\n def insert_cliente(self, listaclientes):\n\n db = sqlite3.connect(self.dbname)\n cursor = db.cursor()\n\n for i in range(0, len(listaclientes['results'])):\n cursor.execute('''\n\t\t\t\tINSERT INTO clientes (\n Nombre,\n Apellido,\n Ciudad,\n Celular,\n Email,\n Edad,\n Genero)\n VALUES (\n\t\t\t\t\t:nombre,\n\t\t\t\t\t:apellido,\n\t\t\t\t\t:ciudad,\n\t\t\t\t\t:celular,\n\t\t\t\t\t:email,\n\t\t\t\t\t:edad,\n\t\t\t\t\t:genero\n\t\t\t\t)''',\n\t\t\t\t{\n\t\t\t\t'nombre': listaclientes['results'][i]['name']['first'],\n\t\t\t\t'apellido': listaclientes['results'][i]['name']['last'],\n\t\t\t\t'ciudad': listaclientes['results'][i]['location']['city'],\n\t\t\t\t'celular': listaclientes['results'][i]['cell'],\n\t\t\t\t'email': listaclientes['results'][i]['email'],\n\t\t\t\t'edad': listaclientes['results'][i]['dob']['age'],\n\t\t\t\t'genero': listaclientes['results'][i]['gender']\n\t\t\t\t}\n\t\t\t)\n db.commit()\n db.close()\n\n def get_cliente(self):\n\n db = sqlite3.connect(self.dbname)\n cursor = db.cursor()\n cursor.execute('''SELECT * FROM clientes''')\n clientes = cursor.fetchall()\n cliente = random.choice(clientes)\n objeto = Persona(cliente[0], cliente[1], cliente[2], cliente[3], cliente[4], cliente[5], cliente[6], cliente[7], self.dbname)\n return objeto\n\n def insert_ingrediente(self, info):\n db = sqlite3.connect(self.dbname)\n cursor = db.cursor()\n\n\n for i in range(len(info[2])):\n cursor.execute('''\n SELECT * FROM Ingredientes\n WHERE Nombre = :nombre\n ''',\n {\n 'nombre': info[2][i]\n })\n if cursor.fetchall() == []:\n cursor.execute('''\n INSERT INTO Ingredientes (\n Nombre)\n VALUES (\n :nombre\n )''',\n {\n 'nombre': info[2][i]\n }\n )\n db.commit()\n\n for i in range(len(info[3])):\n\n cursor.execute('''UPDATE Ingredientes SET Contribuidores = :contribuidores WHERE Nombre = :nombre''',{'contribuidores': info[3][i], 'nombre': info[2][i]})\n db.commit()\n\n for i in range(len(info[4])):\n cursor.execute('''UPDATE Ingredientes SET Receta = :receta WHERE Nombre = :nombre''',{'receta': info[4][i], 'nombre': info[2][i]})\n db.commit()\n\n for i in range(len(info[5])):\n cursor.execute('''UPDATE Ingredientes SET Tags = :tags WHERE Nombre = :nombre''',{'tags': info[5][i], 'nombre': info[2][i]})\n db.commit()\n\n\n db.close()\n\n def insert_taco(self,info):\n\n db = sqlite3.connect(self.dbname)\n cursor = db.cursor()\n\n cursor.execute('''\n SELECT * FROM Tacos\n WHERE Nombre = :nombre\n ''',\n {\n 'nombre': info[0]\n })\n\n if cursor.fetchall() == []:\n cursor.execute('''\n INSERT INTO Tacos (\n Nombre)\n VALUES (\n :nombre\n )''',\n {\n 'nombre': info[0]\n }\n )\n db.commit()\n\n cursor.execute('''UPDATE Tacos SET Link = :link WHERE Nombre = :nombre''',{'link': info[1], 'nombre': info[0]})\n db.commit()\n\n cursor.execute('''UPDATE Tacos SET Relleno = :relleno, Aderezo = :aderezo, Salsa = :salsa, Sazonador = :sazonador, Tortilla = :tortilla\n WHERE Nombre = :nombre''',{'relleno': info[2][0], 'aderezo': info[2][1], 'salsa': info[2][2], 'sazonador': info[2][3],\n 'tortilla': info[2][4], 'nombre': info[0]})\n db.commit()\n\n cursor.execute('''UPDATE Tacos SET Precio = :precio WHERE Nombre = :nombre''',{'precio': 15, 'nombre': info[0]})\n db.commit()\n","sub_path":"Ago-Dic-2018/Ruben Campos/Ordinario/ordi.py","file_name":"ordi.py","file_ext":"py","file_size_in_byte":10105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"71896382","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\nfrom flask import Flask, request, render_template\nfrom werkzeug.exceptions import BadRequest\nimport wssh\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/console')\ndef console():\n return render_template('console.html')\n\n\n@app.route('/remote')\ndef remote():\n if not request.environ.get('wsgi.websocket'):\n app.logger.error('Abort: Request is not WebSocket upgradable')\n raise BadRequest()\n\n bridge = wssh.WSSHBridge(request.environ['wsgi.websocket'])\n try:\n bridge.open(\n hostname='210.32.157.188',\n username='sfeer',\n password='f3r0a8nk',\n port=22)\n except Exception as e:\n app.logger.exception('Error while connectinG: {0}'.format(e.message))\n request.environ['wsgi.websocket'].close()\n return str()\n if 'run' in request.args:\n bridge.execute(request.args)\n else:\n bridge.shell()\n\n request.environ['wsgi.websocket'].close()\n return str()\n\n\nif __name__ == '__main__':\n from gevent.pywsgi import WSGIServer\n from geventwebsocket.handler import WebSocketHandler\n\n app.debug = False\n # app.run(host='0.0.0.0', port=80)\n http_server = WSGIServer(('0.0.0.0', 80), app,\n log=None,\n handler_class=WebSocketHandler)\n try:\n http_server.serve_forever()\n except KeyboardInterrupt:\n pass","sub_path":"sfbox.py","file_name":"sfbox.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"221117278","text":"import json, re, ndjson\n\nfile = \"convertjson.json\"\noutfile = \"processedTweets.json\"\n\nregex = \"(#[-0-9a-zÀ-ÿA-Z]*)\"\n\ni = 1\n\nf = open(file)\ncontent = f.read()\njsonContent = json.loads(content)\n\ntweetsList = jsonContent['tweet']\n\nprocessedTweets = []\n\nfor tweet in tweetsList:\n hashtags = re.findall(regex, tweet.get('message'))\n\n tweet['hashtags'] = hashtags\n\n processedTweets.append(tweet)\n\n print(\"processed {}\".format(i))\n\n #if i == 100:\n # break\n\n i = i + 1\n\n\nwith open(outfile, 'w') as outputStream:\n ndjson.dump(processedTweets, outputStream)\n","sub_path":"hashtagsExtractor.py","file_name":"hashtagsExtractor.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"399021252","text":"# Page 36\n#\n# Demonstration:\n# python point_explicity.py\n# 0 0\n\nclass Point:\n\tdef reset(self):\n\t\tself.x = 0\n\t\tself.y = 0\n\np = Point()\nPoint.reset(p) # Explicity calling reset\nprint(p.x, p.y)","sub_path":"Chapter02_Objects_in_Python/01_Creating_Python_classes/02_Make_it_do_something/point_explicity.py","file_name":"point_explicity.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33515582","text":"# Definition for a binary tree node\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef printTree(head):\n q=[head]\n s=''\n lvls=[1]\n prevLev=0\n while(len(q)>0):\n n = q.pop(0)\n curLev = lvls.pop()\n if (curLev!=prevLev):\n s+='\\n'\n prevLev=curLev\n s+=str(n.val)+\" \"\n if n.left:\n q.append(n.left)\n lvls.append(curLev+1)\n if n.right:\n q.append(n.right)\n lvls.append(curLev+1)\n print(s)\n \nclass Solution:\n # @param preorder, a list of integers\n # @param inorder, a list of integers\n # @return a tree node\n def buildTree(self, preorder, inorder):\n if not preorder:\n return []\n head = TreeNode(preorder[0])\n if len(preorder)==1:\n return head\n indHead =0\n while inorder[indHead]!=preorder[0]:\n indHead+=1\n print(preorder[1:indHead+1], \" |\", inorder[:indHead])\n print(preorder[indHead+1:], \" |\", inorder[indHead+1:])\n print (\"=========\")\n head.left = self.buildTree( preorder[1:indHead+1], inorder[:indHead])\n head.right = self.buildTree(preorder[indHead+1:], inorder[indHead+1:])\n return head\n\n def findD(self, root,l):\n ll = l\n if root.left:\n ll=max(ll,self.findD(root.left,l+1))\n if root.right:\n ll=max(ll,self.findD(root.right,l+1))\n return ll\n \n # @param root, a tree node\n # @return an integer\n def maxDepth(self, root):\n if not root:\n return 0\n return self.findD(root,1)\n\ns= Solution()\n\nprintTree(s.buildTree([1,2,4,5,3], [4,2,5,1,3]))\nprint(\"depth:\" , s.maxDepth(s.buildTree([1,2,4,5,3], [4,2,5,1,3])))\n \n","sub_path":"programming/python/reconTree.py","file_name":"reconTree.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"374688898","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nWrapper functions around JavaScript code to be used from Selenium WebDriver. The main reason to store JS code in\nfiles instead of embedding it in Python code is convenience: it is more readable and has better IDE support.\n\"\"\"\n\nimport functools\nimport logging\nimport os\nfrom datetime import datetime\nfrom functools import wraps\nfrom pathlib import Path\nfrom typing import Any, Dict, Iterable, List, Union\n\nfrom selenium.common.exceptions import (\n JavascriptException,\n NoAlertPresentException,\n UnexpectedAlertPresentException,\n WebDriverException,\n)\nfrom selenium.webdriver.common.alert import Alert\nfrom selenium.webdriver.remote.webdriver import WebDriver\n\nfrom .color import Color\nfrom .config import Config\nfrom .error import WindowClosedError\nfrom .geometry import Point, Rectangle\nfrom .selector import Selector\n\nlogger = logging.getLogger(\"wtl\")\n\n\ndef safe_selenium_method(func):\n \"\"\"\n Handles errors thrown in the browser while executing javascript and outputs information to the log.\n Note: This is a clumsy decorator for instance methods and assumes there is a self.driver member.\n \"\"\"\n\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n def to_logger(msg, js_level):\n if js_level == \"INFO\":\n level = self.config.javascript.info\n elif js_level == \"WARNING\":\n level = self.config.javascript.warning\n elif js_level == \"SEVERE\":\n level = self.config.javascript.severe\n else:\n return\n if level == \"debug\":\n logger.debug(msg)\n elif level == \"info\":\n logger.info(msg)\n elif level == \"warning\":\n logger.warning(msg)\n elif level == \"error\":\n logger.error(msg)\n elif level == \"critical\":\n logger.critical(msg)\n\n alert_text = None\n try:\n return func(self, *args, **kwargs)\n except UnexpectedAlertPresentException:\n # Some websites create an alert to communicate an error message instead of throwing the normal exception\n # or instead of things normal people use popups for.\n # However, selenium can be \"too quick\" to dismiss the alerts and crash.\n alert = Alert(self.driver)\n try:\n alert_text = alert.text\n alert.dismiss()\n except NoAlertPresentException:\n pass\n except JavascriptException as e:\n logger.error(\"Exception thrown in the browser's Javascript engine.\")\n logger.debug(e)\n finally:\n log_records = []\n try:\n log_records = self.driver.get_log(\"browser\")\n except (WebDriverException, WindowClosedError):\n logger.warning(\"Failed to fetch log records from the driver\")\n\n # Print browser logs\n for record in sorted(log_records, key=lambda x: int(x[\"timestamp\"])):\n record[\"timestamp\"] = datetime.fromtimestamp(record[\"timestamp\"] / 1000).strftime(\"%H:%M\")\n log_line = \"[{level}] {message}\".format(**record)\n log_level = record[\"level\"]\n to_logger(log_line, log_level)\n\n # Then alert text, if there was any\n if alert_text is not None:\n logger.error(f\" JS Alert text: {alert_text}\")\n\n return wrapper\n\n\nclass JavascriptWrapper:\n \"\"\"\n Helper class for executing built-in javascript scripts or custom\n files and snippets.\n \"\"\"\n\n def __init__(self, driver: WebDriver, config: Config = None):\n assert driver\n config = config or Config.default()\n self.driver = driver\n self.config = config\n\n def save_mhtml(self, filename: str):\n \"\"\"\n Executes the MHTML saving extension. Saves to the path specified in config.scraping.temp_path.\n Note: If the file already exists, it will not be overwritten.\n \"\"\"\n self.execute_script('window.postMessage({type: \"SAVE_MHTML\", filename: \"' + filename + '\"})')\n\n def get_full_height(self) -> int:\n \"\"\"\n Get the full page height, i.e. the height of the document.\n :return: document height in pixels\n \"\"\"\n return self.execute_file(Path(\"get_full_page_height.js\"))\n\n def find_iframe_name(self, identifier: str) -> str:\n \"\"\"\n Looks for an iframe where name, ID, or class equals the identifier,\n and returns its name. Returns empty string if no matching object was found.\n :return: iframe name or empty string\n \"\"\"\n return self.execute_file(Path(\"find_iframe_name.js\"), identifier)\n\n def find_viewport(self) -> Rectangle:\n \"\"\"\n Get the width of the web browser window with content.\n :return: viewport height in pixels\n \"\"\"\n result = self.execute_file(Path(\"find_viewport.js\"))\n\n if not result:\n logger.error(\"Failed to compute get viewport size\")\n return Rectangle.empty()\n\n return Rectangle.from_list([result[\"x\"], result[\"y\"], result[\"x\"] + result[\"w\"], result[\"y\"] + result[\"h\"]])\n\n def get_element_metadata(self) -> List[Dict[str, Any]]:\n \"\"\"\n Collects metadata about web page DOM elements: their tags, some of the HTML attributes, position and size on the\n page, CSS styles and classes, inner text.\n\n Each element on the page is assigned a unique within the scope of the page ``wtl_uid`` and\n has a pointer to the parent DOM element in the ``wtl_parent_uid`` field and are not to be confused\n with ``id`` attribute in HTML which is neither unique nor mandatory.\n\n :return: a list of JSON objects (in their Python dict form) with HTML attributes, additionally calculated\n properties and unique IDs. Refer to the script code for the keys' names.\n \"\"\"\n return self.execute_file(Path(\"get_element_metadata.js\"))\n\n def hide_position_fixed_elements(self, elements: List[str] = None) -> dict:\n \"\"\"\n Hides page elements that are fixed or sticky (the ones that stay on the page when you scroll)\n by setting their visibility to \"hidden\".\n\n Returns a map from element ids (wtl-uid) to the old visibility values.\n\n Mutates the web page.\n \"\"\"\n elements = elements or []\n return self.execute_file(Path(\"hide_position_fixed_elements.js\"), elements)\n\n def show_position_fixed_elements(self, id_to_visibility: dict):\n \"\"\"\n Set the specified visibility to the elements with ids listed in ``id_to_visibility``.\n\n The 2nd parameter is expected to be the (possibly accumulated) output of hide_position_fixed_elements.\n\n Mutates the web page (hopefully undoing the changes made by hide_position_fixed_elements)\n \"\"\"\n\n self.execute_file(Path(\"show_position_fixed_elements.js\"), id_to_visibility)\n\n def element_exists(self, selector: Selector) -> bool:\n \"\"\"\n Returns True if an element exists, otherwise False.\n \"\"\"\n\n return self.execute_file(Path(\"element_exists.js\"), selector.css)\n\n def disable_animations(self):\n \"\"\"\n Turns off animation on the page. Works for jQuery by setting a certain flag and for CSS animations by injecting\n an additional style into the page code.\n\n Mutates the web page.\n \"\"\"\n self.execute_file(Path(\"disable_animations.js\"))\n\n def is_page_loaded(self, *_) -> bool:\n \"\"\"\n Applies some heuristics to check if the page is loaded. But since it is in general a hard question to answer,\n is known to be faulty in some cases.\n \"\"\"\n # Ignores any input arguments given by WebDriverWait.until()\n return self.execute_file(Path(\"is_page_loaded.js\"))\n\n def find_active_elements(self) -> list:\n \"\"\"\n Uses a couple of heuristics to try and find all clickable elements in the page.\n \"\"\"\n return self.execute_file(Path(\"find_active_elements.js\"))\n\n def scroll_to(self, x: float, y: float):\n \"\"\"\n Scroll the page to given coordinates.\n \"\"\"\n self.execute_script(f\"scrollTo({int(x)}, {int(y)});\")\n\n def make_canvas(self):\n \"\"\"\n Create viewport and page canvases and add them to the DOM.\n \"\"\"\n self.execute_file(Path(\"make_canvas.js\"))\n\n def annotate(\n self,\n location: Point,\n color: Color,\n size: int,\n text: str,\n background: Color = Color(0, 0, 0, 0),\n viewport: bool = False,\n ):\n \"\"\"\n Writes text with a given color on the page.\n Shares an HTML canvas with `highlight`.\n \"\"\"\n self.make_canvas()\n self.execute_file(\n Path(\"annotate.js\"),\n location.x,\n location.y,\n color.to_str(),\n size,\n text,\n background.to_str(),\n background.a / 255,\n viewport,\n )\n\n def highlight(self, selector: Selector, color: Color, fill: bool = False, viewport: bool = False):\n \"\"\"\n Highlight an element as found by a given selector with arbitrary\n color and intensity.\n Note: If more elements can be found, only one will be highlighted.\n Shares an HTML canvas with `annotate`.\n \"\"\"\n self.make_canvas()\n self.execute_file(Path(\"highlight.js\"), selector.css, color.to_str(), color.a / 255, fill, viewport)\n\n def clear_highlights(self, viewport: bool = False):\n \"\"\"Removes all highlights created by :func:`highlight`.\"\"\"\n self.execute_file(Path(\"clear_highlights.js\"), viewport)\n\n def click_element(self, selector: Selector):\n \"\"\"\n Clicks an element found by the given selector.\n Note: If more elements can be found, only one will be clicked.\n \"\"\"\n self.execute_file([Path(\"dom.js\"), Path(\"click_element.js\")], selector.css)\n\n def delete_element(self, selector: Selector):\n \"\"\"\n Deletes an element found by the given selector.\n Note: If more elements can be found, only one will be clicked.\n \"\"\"\n self.execute_file(Path(\"delete_element.js\"), selector.css)\n\n def fill_text(self, selector: Selector, value: str):\n \"\"\"\n Fills an element as found by a given selector with given text.\n Note: If more elements can be found, only one will be used.\n \"\"\"\n self.execute_file([Path(\"dom.js\"), Path(\"fill_text.js\")], selector.css, value)\n\n def select(self, selector: Selector, value: str):\n \"\"\"\n Select an element of a dropdown (select) element.\n Note: If more elements can be found, only one will be used.\n \"\"\"\n self.execute_file([Path(\"dom.js\"), Path(\"select.js\")], selector.css, value)\n\n @classmethod\n @functools.lru_cache(maxsize=32)\n def assemble_script(cls, filenames: Iterable[Path]) -> str:\n \"\"\"\n Concatenates the contents of several Javascript files into one, with caching.\n :param filenames: Path to the JS files either in webtraversallibrary/js or an absolute path.\n \"\"\"\n contents = []\n\n for filename in filenames:\n if not filename.exists():\n filename = Path(os.path.dirname(__file__)) / \"js\" / filename\n\n assert filename.exists() and filename.is_file()\n\n with open(filename, \"rt\", encoding=\"utf8\") as f:\n contents.append(f.read())\n\n return \"\\n\".join(contents)\n\n def execute_file(self, filename: Union[Path, Iterable[Path]], *args, execute_async: bool = False) -> Any:\n \"\"\"\n Execute the JavaScript code in given file and return the result\n :param filename: Path to the JS file(s) either in webtraversallibrary/js or an absolute path.\n :param execute_async: if True, will wait until the javascript code has called\n arguments[arguments.length-1] and will return its input arguments.\n \"\"\"\n if isinstance(filename, Path):\n filename = [filename]\n\n script = JavascriptWrapper.assemble_script(tuple(filename))\n\n if execute_async:\n return self.execute_script_async(script, *args)\n return self.execute_script(script, *args)\n\n @safe_selenium_method\n def execute_script(self, script: str, *args) -> Any:\n \"\"\"\n Execute the JavaScript code in `script` and return the result\n :param script: path to the JS file relative to this package\n \"\"\"\n return self.driver.execute_script(script, *args)\n\n @safe_selenium_method\n def execute_script_async(self, script: str, *args) -> Any:\n \"\"\"\n Execute the JavaScript code in `script` asynchronously and returns the result\n :param script: path to the JS file relative to this package\n \"\"\"\n return self.driver.execute_async_script(script, *args)\n","sub_path":"webtraversallibrary/javascript.py","file_name":"javascript.py","file_ext":"py","file_size_in_byte":13752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"393372599","text":"#\n# Pyserini: Reproducible IR research with sparse and dense representations\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\nimport json\nimport argparse\nimport string\nfrom nltk import bigrams, word_tokenize, SnowballStemmer\nfrom nltk.corpus import stopwords\nfrom tqdm import tqdm\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Convert KILT Knowledge Source into a Document-level JSONL that can be processed by Pyserini')\n parser.add_argument('--input', required=True, help='Path to the kilt_knowledgesource.json file')\n parser.add_argument('--output', required=True, help='Path to the output directory and file name')\n parser.add_argument('--bigrams', action='store_true', help='Enable bigrams')\n parser.add_argument('--stem', action='store_true', help='Enable stemming on bigrams')\n parser.add_argument('--flen', default=5903530, type=int, help='Number of lines in the file')\n\n args = parser.parse_args()\n\n FILE_LENGTH = args.flen\n STOPWORDS = set(stopwords.words('english') + list(string.punctuation))\n stemmer = SnowballStemmer(\"english\")\n\n with open(args.input, 'r') as f, open(f'{args.output}', 'w') as outp:\n for line in tqdm(f, total=FILE_LENGTH, mininterval=10.0, maxinterval=20.0):\n raw = json.loads(line)\n doc = {}\n doc[\"id\"] = raw[\"_id\"]\n doc[\"contents\"] = \"\".join(raw[\"text\"])\n if args.bigrams:\n tokens = filter(lambda word: word.lower() not in STOPWORDS, word_tokenize(doc[\"contents\"]))\n if args.stem:\n tokens = map(stemmer.stem, tokens)\n bigram_doc = bigrams(tokens)\n bigram_doc = \" \".join([\"\".join(bigram) for bigram in bigram_doc])\n doc[\"contents\"] += \" \" + bigram_doc\n doc[\"wikipedia_id\"] = raw[\"wikipedia_id\"]\n doc[\"wikipedia_title\"] = raw[\"wikipedia_title\"]\n doc[\"categories\"] = raw[\"categories\"]\n _ = outp.write(json.dumps(doc))\n _ = outp.write('\\n')\n\n","sub_path":"scripts/kilt/convert_kilt_to_document_jsonl.py","file_name":"convert_kilt_to_document_jsonl.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"123441141","text":"###############################################################################\n# Project Euler: 14\n# Name: Longest Collatz Sequence\n###############################################################################\n# Description:\n# The following iterative sequence is defined for the set of positive integers:\n# n → n/2 (n is even)\n# n → 3n + 1 (n is odd)\n# Using the rule above and starting with 13, we generate the following sequence:\n# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1\n# It can be seen that this sequence (starting at 13 and finishing at 1) contains\n# 10 terms. Although it has not been proved yet (Collatz Problem), it is thought\n# that all starting numbers finish at 1.\n#\n# Which starting number, under one million, produces the longest chain?\n#\n# NOTE: Once the chain starts the terms are allowed to go above one million.\n################################################################################\n\n#Finds longest callotz chain below n\n#Takes about 1 minute for n = 1000000\n#Could be sped up considerably using a cache\n#to store already calculated values of n\ndef longest_chain(n):\n longest = [0, 'length']\n for i in xrange(2, n):\n length = 0\n x = i\n while x != 1:\n if x % 2 == 0:\n x = x/2\n length += 1\n else:\n x = 3*x + 1\n length += 1\n length += 1\n if length > longest[0]:\n longest = [length, i]\n return longest\n\ndef timeIt(n):\n import time\n start = time.time()\n return longest_chain(n), time.time() - start\n\n###########################################################\n# Solution \n# Found [525, 837799] in 48.55s\n###########################################################","sub_path":"14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255046517","text":"# CMPT 145 Assignment 5\r\n# Cordell Blanchard\r\n# chb344, 11236660\r\n# 04, L06\r\n\r\nimport TStack as Stack\r\n\r\n\r\ndef create():\r\n \"\"\"\r\n Purpose\r\n creates an empty queue\r\n Return\r\n an empty queue\r\n \"\"\"\r\n return Stack.create()\r\n\r\n\r\ndef is_empty(queue):\r\n \"\"\"\r\n Purpose\r\n checks if the given queue has no data in it\r\n Pre-conditions:\r\n queue is a queue created by create()\r\n Return:\r\n True if the queue has no data, or false otherwise\r\n \"\"\"\r\n return Stack.is_empty(queue)\r\n\r\n\r\ndef size(queue):\r\n \"\"\"\r\n Purpose\r\n returns the number of data values in the given queue\r\n Pre-conditions:\r\n queue: a queue created by create()\r\n Return:\r\n The number of data values in the queue\r\n \"\"\"\r\n return Stack.size(queue)\r\n\r\n\r\ndef enqueue(queue, value):\r\n \"\"\"\r\n Purpose\r\n adds the given data value to the given queue\r\n Pre-conditions:\r\n queue: a queue created by create()\r\n value: data to be added\r\n Post-condition:\r\n the value is added to the queue\r\n Return:\r\n (none)\r\n \"\"\"\r\n return Stack.push(queue, value)\r\n\r\n \r\ndef dequeue(queue):\r\n \"\"\"\r\n Purpose\r\n removes and returns a data value from the given queue\r\n Pre-conditions:\r\n queue: a queue created by create()\r\n Post-condition:\r\n the first value is removed from the queue\r\n Return:\r\n the first value in the queue\r\n \"\"\"\r\n TempStack = Stack.create() # Temporary stack to aid in the process of removing and returning first in queue\r\n\r\n # inputs all all values from queue in reverse order into TempStack\r\n # and pops all values out of queue\r\n for j in range(Stack.size(queue)):\r\n val = Stack.pop(queue)\r\n Stack.push(TempStack, val)\r\n\r\n first = Stack.pop(TempStack) # first value of queue\r\n\r\n # pushes all values back into queue in correct order with first value removed\r\n for i in range(Stack.size(TempStack)):\r\n val = Stack.pop(TempStack)\r\n Stack.push(queue, val)\r\n\r\n return first\r\n\r\n\r\n\r\ndef peek(queue):\r\n \"\"\"\r\n Purpose\r\n returns the value from the front of given queue\r\n without removing it\r\n Pre-conditions:\r\n queue: a queue created by create()\r\n Post-condition:\r\n None\r\n Return:\r\n the value at the front of the queue\r\n \"\"\"\r\n TempStack = Stack.create() # Temporary stack to aid in the process of removing and returning first in queue\r\n\r\n # inputs all all values from queue in reverse order into TempStack\r\n # and pops all values out of queue\r\n for j in range(Stack.size(queue)):\r\n val = Stack.pop(queue)\r\n Stack.push(TempStack, val)\r\n\r\n first = Stack.pop(TempStack) # first value of queue\r\n Stack.push(TempStack, first) # puts value back\r\n\r\n # pushes all values back into queue in correct order with first value removed\r\n for i in range(Stack.size(TempStack)):\r\n val = Stack.pop(TempStack)\r\n Stack.push(queue, val)\r\n\r\n return first\r\n","sub_path":"Assignment 5/RQueue.py","file_name":"RQueue.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"28179514","text":"#On the digits dataset, plot the cross-validation score of a SVC estimator with an linear kernel as a function of parameter C (use a logarithmic grid of points, from 1 to 10).\n\n\n#import numpy as np\n#from sklearn import cross_validation, datasets, svm\n\n#digits = datasets.load_digits()\n#X = digits.data\n#y = digits.target\n\n#svc = svm.SVC(kernel='linear')\n#C_s = np.logspace(-10, 0, 10)\n\nimport os\nimport numpy as np\nfrom sklearn import cross_validation, datasets, svm, neighbors, linear_model\n \n\nclass mydata:\n def __init__(self):\n self.X = list()\n self.Y = list()\n \n X = None\n Y = None\n \n\nclass data_set:\n def __init__(self):\n self.training = mydata()\n self.predict = mydata()\n \n training = None\n predict = None\n \n\n\nclass exercise_2_3_1(object):\n \"\"\"On the digits dataset, plot the cross-validation score of a SVC estimator with an linear kernel as a function of parameter C (use a logarithmic grid of points, from 1 to 10).\n http://scikit-learn.org/stable/tutorial/statistical_inference/model_selection.html#cross-validation-generators\"\"\"\n\n\n def get_data(self, X,Y , kfold = None):\n if kfold == None:\n kfold = cross_validation.KFold(len(X),3, True)\n result = list()\n\n for train_indices, test_indices in kfold:\n data = data_set()\n\n for index in train_indices:\n data.training.X.append(X[index])\n data.training.Y.append(Y[index])\n for index in test_indices:\n data.predict.X.append(X[index])\n data.predict.Y.append(Y[index])\n print(data.predict.X[:5],data.predict.X[-5:])\n print(data.predict.Y[:5], data.predict.Y[-5:])\n\n result.append(data);\n return result\n\n\n\n def getResult(self, estimator, predictX, expected):\n \n results = estimator.predict(predictX)\n \n correct = 0;\n for i in range(len(results)):\n #print(\"Expected: \", expected[i], \"\\t\", \"Result: \", results[i])\n \n if(results[i] == expected[i]):\n correct += 1\n \n \n return correct/len(results);\n \n \n\n def run(self):\n digits = datasets.load_iris()\n\n X = digits.data\n Y = digits.target\n \n C_s = np.logspace(-10, 0, 10)\n \n\n results = []\n results.append([\"C value\", \"Score\"])\n \n for c in C_s:\n kfold = cross_validation.KFold(len(X),3,True)\n svc = svm.SVC(kernel='linear',C= c)\n score = np.mean(cross_validation.cross_val_score(svc, X,Y,cv=kfold))\n results.append([c, score])\n \n return results\n\n \n def test_run(self):\n digits = datasets.load_iris()\n\n X = digits.data\n Y = digits.target\n kfold = cross_validation.KFold(len(X),3,True)\n data = self.get_data(X,Y,kfold)\n\n\n C_s = np.logspace(-10, 0, 10)\n \n\n skScore = []\n myScore = []\n\n for c in C_s:\n svc = svm.SVC(kernel='linear',C= c)\n score = np.mean(cross_validation.cross_val_score(svc, X,Y,cv=kfold))\n skScore.append(score)\n\n for c in C_s:\n svc = svm.SVC(kernel='linear',C= c)\n score = []\n for data_set in data:\n svc.fit(data_set.training.X, data_set.training.Y) \n score.append(svc.score(data_set.predict.X, data_set.predict.Y))\n \n myScore.append(np.mean(score))\n \n\n results = []\n results.append([\"Scikit Score\", skScore])\n results.append([\"My Score\",myScore])\n return results\n","sub_path":"Scikit/Scikit/exercise_2_3_1.py","file_name":"exercise_2_3_1.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"463823127","text":"import unittest\nimport random\n\nfrom ch3.stacks.stack import Stack\nfrom ch3.stacks.stack_sort import stack_sort\n\n\nclass TestStack(unittest.TestCase):\n def test_ds(self):\n pass\n \n def test_stack_sort(self):\n key = []\n unsorted = Stack()\n\n for _ in range(10):\n num = random.randint(1, 100)\n key.append(num)\n unsorted.push(num)\n\n key = sorted(key)\n result = stack_sort(unsorted)\n\n for val in key:\n tmp = result.pop()\n self.assertEqual(val, tmp)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"ctci/ch3/stacks/test_stack.py","file_name":"test_stack.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"592501972","text":"# -*- coding: utf-8 -*-\nimport json\nimport urllib.request\nimport slacker_test\n\nfrom bs4 import BeautifulSoup\nfrom flask import Flask, request, make_response\nfrom slackclient import SlackClient\n\napp = Flask(__name__)\n\nslack_token = \"xoxb-502213453520-507384248019-BsMUDahN9t0xkAgG9nUKIkB9\"\nslack_client_id = \"502213453520.507688847685\"\nslack_client_secret = \"c667f791180fb05ddf7fdf5dccfad9c2\"\nslack_verification = \"9raU6TJb1GWVDcrpnioHiCPW\"\nsc = SlackClient(slack_token)\n\n\n# 크롤링 함수 구현하기\ndef _crawl_naver_keywords(text):\n # 여기에 함수를 구현해봅시다.\n url = \"https://www.youtube.com/feed/trending\"\n req = urllib.request.Request(url)\n\n sourcecode = urllib.request.urlopen(url).read()\n soup = BeautifulSoup(sourcecode, \"html.parser\")\n keywords = []\n\n if \"유튜브\" in text:\n keywords = [\"유튭 Top 5\\n\"]\n datas = []\n for i, row in enumerate(soup.find_all(\"div\", class_=\"yt-lockup-content\")):\n title = row.find(\"a\", class_=\"yt-uix-tile-link\").get_text().strip()\n views = row.find(\"ul\", class_=\"yt-lockup-meta-info\").get_text().strip()\n title = title if len(title) < 20 else title[:20]+\"...\"\n views = views.strip().split()[-1]\n datas.append([title, views])\n datas.sort(key = lambda d: d[1], reverse = True)\n for i in range(5):\n keywords.append(\"{}위 : {} / 조회수 : {}\".format(i+1, datas[i][0], datas[i][1]))\n # if i< 5:\n # tt = title.get_text().strip()\n # keywords.append(\"> {}\".format(tt if len(tt) < 20 else tt[:17]+'...'))\n\n # 한글 지원을 위해 앞에 unicode u를 붙혀준다.\n return u'\\n'.join(keywords)\n\n\n# 이벤트 핸들하는 함수\ndef _event_handler(event_type, slack_event):\n print(slack_event[\"event\"])\n\n if event_type == \"app_mention\":\n channel = slack_event[\"event\"][\"channel\"]\n text = slack_event[\"event\"][\"text\"]\n\n keywords = _crawl_naver_keywords(text)\n sc.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=keywords\n )\n\n return make_response(\"App mention message has been sent\", 200, )\n\n # ============= Event Type Not Found! ============= #\n # If the event_type does not have a handler\n message = \"You have not added an event handler for the %s\" % event_type\n # Return a helpful error message\n return make_response(message, 200, {\"X-Slack-No-Retry\": 1})\n\n\n@app.route(\"/listening\", methods=[\"GET\", \"POST\"])\ndef hears():\n slack_event = json.loads(request.data)\n\n if \"challenge\" in slack_event:\n return make_response(slack_event[\"challenge\"], 200, {\"content_type\":\n \"application/json\"\n })\n\n if slack_verification != slack_event.get(\"token\"):\n message = \"Invalid Slack verification token: %s\" % (slack_event[\"token\"])\n make_response(message, 403, {\"X-Slack-No-Retry\": 1})\n\n if \"event\" in slack_event:\n event_type = slack_event[\"event\"][\"type\"]\n return _event_handler(event_type, slack_event)\n\n # If our bot hears things that are not events we've subscribed to,\n # send a quirky but helpful error response\n return make_response(\"[NO EVENT IN SLACK REQUEST] These are not the droids\\\n you're looking for.\", 404, {\"X-Slack-No-Retry\": 1})\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef index():\n return \"

        Server is ready.

        \"\n\n\nif __name__ == '__main__':\n app.run('127.0.0.1', port=5000)\n","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"578850875","text":"# (c) Copyright [2018-2020] Micro Focus or one of its affiliates. \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# |_ |~) _ _| _ /~\\ _ |.\n# |_)\\/ |_)(_|(_|| \\_/|_|(_|||\n# / \n# ____________ ______\n# / __ `\\ / /\n# | \\/ / / /\n# |______ / / /\n# |____/ / /\n# _____________ / /\n# \\ / / /\n# \\ / / /\n# \\_______/ / /\n# ______ / /\n# \\ / / /\n# \\ / / /\n# \\/ / /\n# / /\n# / /\n# \\ /\n# \\ /\n# \\/\n# _\n# \\ / _ __|_. _ _ |_)\n# \\/ (/_| | |(_(_|| \\/\n# / \n# VerticaPy allows user to create vDataFrames (Virtual Dataframes). \n# vDataFrames simplify data exploration, data cleaning and MACHINE LEARNING \n# in VERTICA. It is an object which keeps in it all the actions that the user \n# wants to achieve and execute them when they are needed. \t\t\t\t\t\t\t\t\t\t\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n# The purpose is to bring the logic to the data and not the opposite !\n#\n# \n# Modules\n#\n# Standard Python Modules\nimport os\n# VerticaPy Modules\nfrom verticapy.utilities import *\nfrom verticapy.toolbox import *\nfrom verticapy import vDataFrame\nfrom verticapy.connections.connect import read_auto_connect\n#---#\nclass DBSCAN:\n\t\"\"\"\n---------------------------------------------------------------------------\n[Beta Version]\nCreates a DBSCAN object by using the DBSCAN algorithm as defined by Martin \nEster, Hans-Peter Kriegel, Jörg Sander and Xiaowei Xu. This object is using \npure SQL to compute all the distances and neighbors. It is also using Python \nto compute the cluster propagation (non scalable phase). This model is using \nCROSS JOIN and may be really expensive in some cases. It will index all the \nelements of the table in order to be optimal (the CROSS JOIN will happen only \nwith IDs which are integers). As DBSCAN is using the p-distance, it is highly \nsensible to un-normalized data. However, DBSCAN is really robust to outliers \nand can find non-linear clusters. It is a very powerful algorithm for outliers \ndetection and clustering. \n\nParameters\n----------\nname: str\n\tName of the the model. As it is not a built in model, this name will be used\n\tto build the final table.\ncursor: DBcursor, optional\n\tVertica DB cursor.\neps: float, optional\n\tThe radius of a neighborhood with respect to some point.\nmin_samples: int, optional\n\tMinimum number of points required to form a dense region.\np: int, optional\n\tThe p of the p-distance (distance metric used during the model computation).\n\nAttributes\n----------\nAfter the object creation, all the parameters become attributes. \nThe model will also create extra attributes when fitting the model:\n\nn_cluster: int\n\tNumber of clusters created during the process.\nn_noise: int\n\tNumber of points with no clusters.\ninput_relation: str\n\tTrain relation.\nX: list\n\tList of the predictors.\nkey_columns: list\n\tColumns not used during the algorithm computation but which will be used\n\tto create the final relation.\n\t\"\"\"\n\t#\n\t# Special Methods\n\t#\n\t#---#\n\tdef __init__(self,\n\t\t\t\t name: str,\n\t\t\t\t cursor = None,\n\t\t\t\t eps: float = 0.5,\n\t\t\t\t min_samples: int = 5,\n\t\t\t\t p: int = 2):\n\t\tcheck_types([\n\t\t\t(\"name\", name, [str], False),\n\t\t\t(\"eps\", eps, [int, float], False),\n\t\t\t(\"min_samples\", min_samples, [int, float], False),\n\t\t\t(\"p\", p, [int, float], False)])\n\t\tif not(cursor):\n\t\t\tcursor = read_auto_connect().cursor()\n\t\telse:\n\t\t\tcheck_cursor(cursor)\n\t\tself.type = \"clustering\"\n\t\tself.name = name\n\t\tself.cursor = cursor\n\t\tself.eps = eps\n\t\tself.min_samples = min_samples\n\t\tself.p = p \n\t#---#\n\tdef __repr__(self):\n\t\ttry:\n\t\t\trep = \"\\nNumber of Clusters: {}\\nNumber of Outliers: {}\".format(self.n_cluster, self.n_noise)\n\t\t\treturn (rep)\n\t\texcept:\n\t\t\treturn \"\"\n\t#\n\t# Methods\n\t#\n\t#---#\n\tdef fit(self, \n\t\t\tinput_relation: str, \n\t\t\tX: list, \n\t\t\tkey_columns: list = [], \n\t\t\tindex: str = \"\"):\n\t\t\"\"\"\n\t---------------------------------------------------------------------------\n\tTrains the model.\n\n\tParameters\n\t----------\n\tinput_relation: str\n\t\tTrain relation.\n\tX: list\n\t\tList of the predictors.\n\tkey_columns: list, optional\n\t\tColumns not used during the algorithm computation but which will be used\n\t\tto create the final relation.\n\tindex: str, optional\n\t\tIndex used to identify each row separately. It is highly recommanded to\n\t\thave one already in the main table to avoid creation of temporary tables.\n\n\tReturns\n\t-------\n\tobject\n \t\tself\n\t\t\"\"\"\n\t\tcheck_types([\n\t\t\t(\"input_relation\", input_relation, [str], False),\n\t\t\t(\"X\", X, [list], False),\n\t\t\t(\"key_columns\", key_columns, [list], False),\n\t\t\t(\"index\", index, [str], False)])\n\t\tX = [str_column(column) for column in X]\n\t\tself.X = X\n\t\tself.key_columns = [str_column(column) for column in key_columns]\n\t\tself.input_relation = input_relation\n\t\tschema, relation = schema_relation(input_relation)\n\t\trelation_alpha = ''.join(ch for ch in relation if ch.isalnum())\n\t\tcursor = self.cursor\n\t\tif not(index):\n\t\t\tindex = \"id\"\n\t\t\tmain_table = \"VERTICAPY_MAIN_{}\".format(relation_alpha)\n\t\t\ttry:\n\t\t\t\tcursor.execute(\"DROP TABLE IF EXISTS v_temp_schema.{}\".format(main_table))\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tsql = \"CREATE LOCAL TEMPORARY TABLE {} ON COMMIT PRESERVE ROWS AS SELECT ROW_NUMBER() OVER() AS id, {} FROM {} WHERE {}\".format(main_table, \", \".join(X + key_columns), input_relation, \" AND \".join([\"{} IS NOT NULL\".format(item) for item in X]))\n\t\t\tcursor.execute(sql)\n\t\telse:\n\t\t\tcursor.execute(\"SELECT {} FROM {} LIMIT 10\".format(\", \".join(X + key_columns + [index]), input_relation))\n\t\t\tmain_table = input_relation\n\t\tsql = [\"POWER(ABS(x.{} - y.{}), {})\".format(X[i], X[i], self.p) for i in range(len(X))] \n\t\tdistance = \"POWER({}, 1 / {})\".format(\" + \".join(sql), self.p)\n\t\tsql = \"SELECT x.{} AS node_id, y.{} AS nn_id, {} AS distance FROM {} AS x CROSS JOIN {} AS y\".format(index, index, distance, main_table, main_table)\n\t\tsql = \"SELECT node_id, nn_id, SUM(CASE WHEN distance <= {} THEN 1 ELSE 0 END) OVER (PARTITION BY node_id) AS density, distance FROM ({}) distance_table\".format(self.eps, sql)\n\t\tsql = \"SELECT node_id, nn_id FROM ({}) x WHERE density > {} AND distance < {} AND node_id != nn_id\".format(sql, self.min_samples, self.eps)\n\t\tcursor.execute(sql)\n\t\tgraph = cursor.fetchall()\n\t\tmain_nodes = list(dict.fromkeys([elem[0] for elem in graph] + [elem[1] for elem in graph]))\n\t\tclusters = {}\n\t\tfor elem in main_nodes:\n\t\t\tclusters[elem] = None\n\t\ti = 0\n\t\twhile (graph):\n\t\t\tnode = graph[0][0]\n\t\t\tnode_neighbor = graph[0][1]\n\t\t\tif (clusters[node] == None) and (clusters[node_neighbor] == None):\n\t\t\t\tclusters[node] = i \n\t\t\t\tclusters[node_neighbor] = i\n\t\t\t\ti = i + 1\n\t\t\telse:\n\t\t\t\tif (clusters[node] != None and clusters[node_neighbor] == None):\n\t\t\t\t\tclusters[node_neighbor] = clusters[node]\n\t\t\t\telif (clusters[node_neighbor] != None and clusters[node] == None):\n\t\t\t\t\tclusters[node] = clusters[node_neighbor]\n\t\t\tdel(graph[0])\n\t\ttry:\n\t\t\tf = open(\"VERTICAPY_DBSCAN_CLUSTERS_ID.csv\", 'w')\n\t\t\tfor elem in clusters:\n\t\t\t\tf.write(\"{}, {}\\n\".format(elem, clusters[elem]))\n\t\t\tf.close()\n\t\t\ttry:\n\t\t\t\tcursor.execute(\"DROP TABLE IF EXISTS v_temp_schema.VERTICAPY_DBSCAN_CLUSTERS\")\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tcursor.execute(\"CREATE LOCAL TEMPORARY TABLE VERTICAPY_DBSCAN_CLUSTERS(node_id int, cluster int) ON COMMIT PRESERVE ROWS\")\n\t\t\tif (\"vertica_python\" in str(type(cursor))):\n\t\t\t\twith open('./VERTICAPY_DBSCAN_CLUSTERS_ID.csv', \"r\") as fs:\n\t\t\t\t\tcursor.copy(\"COPY v_temp_schema.VERTICAPY_DBSCAN_CLUSTERS(node_id, cluster) FROM STDIN DELIMITER ',' ESCAPE AS '\\\\';\", fs)\n\t\t\telse:\n\t\t\t\tcursor.execute(\"COPY v_temp_schema.VERTICAPY_DBSCAN_CLUSTERS(node_id, cluster) FROM LOCAL './VERTICAPY_DBSCAN_CLUSTERS_ID.csv' DELIMITER ',' ESCAPE AS '\\\\';\")\n\t\t\ttry:\n\t\t\t\tcursor.execute(\"COMMIT\")\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tos.remove(\"VERTICAPY_DBSCAN_CLUSTERS_ID.csv\")\n\t\texcept:\n\t\t\tos.remove(\"VERTICAPY_DBSCAN_CLUSTERS_ID.csv\")\n\t\t\traise\n\t\tself.n_cluster = i\n\t\tcursor.execute(\"CREATE TABLE {} AS SELECT {}, COALESCE(cluster, -1) AS dbscan_cluster FROM v_temp_schema.{} AS x LEFT JOIN v_temp_schema.VERTICAPY_DBSCAN_CLUSTERS AS y ON x.{} = y.node_id\".format(self.name, \", \".join(self.X + self.key_columns), main_table, index))\n\t\tcursor.execute(\"SELECT COUNT(*) FROM {} WHERE dbscan_cluster = -1\".format(self.name))\n\t\tself.n_noise = cursor.fetchone()[0]\n\t\tcursor.execute(\"DROP TABLE IF EXISTS v_temp_schema.VERTICAPY_MAIN_{}\".format(relation_alpha))\n\t\tcursor.execute(\"DROP TABLE IF EXISTS v_temp_schema.VERTICAPY_DBSCAN_CLUSTERS\")\n\t\treturn (self)\n\t#---#\n\tdef info(self):\n\t\t\"\"\"\n\t---------------------------------------------------------------------------\n\tDisplays some information about the model.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tprint(\"DBSCAN was successfully achieved by building {} cluster(s) and by identifying {} elements as noise.\\nIf you are not happy with the result, do not forget to normalise the data before applying DBSCAN. As this algorithm is using the p-distance, it is really sensible to the data distribution.\".format(self.n_cluster, self.n_noise))\n\t\texcept:\n\t\t\tprint(\"Please use the 'fit' method to start the algorithm.\")\n\t#---#\n\tdef plot(self):\n\t\t\"\"\"\n\t---------------------------------------------------------------------------\n\tDraws the model is the number of predictors is 2 or 3.\n\t\t\"\"\"\n\t\tif (2 <= len(self.X) <= 3):\n\t\t\tvDataFrame(self.name, self.cursor).scatter(columns = self.X, catcol = \"dbscan_cluster\", max_cardinality = 100, max_nb_points = 10000)\n\t\telse:\n\t\t\traise ValueError(\"Clustering Plots are only available in 2D or 3D\")\n\t#---#\n\tdef to_vdf(self):\n\t\t\"\"\"\n\t---------------------------------------------------------------------------\n\tCreates a vDataFrame of the model.\n\n\tReturns\n\t-------\n\tvDataFrame\n \t\tmodel vDataFrame\n\t\t\"\"\"\n\t\treturn (vDataFrame(self.name, self.cursor))\n#---#\nclass KMeans:\n\t\"\"\"\n---------------------------------------------------------------------------\nCreates a KMeans object by using the Vertica Highly Distributed and Scalable \nKMeans on the data. K-means clustering is a method of vector quantization, \noriginally from signal processing, that aims to partition n observations into \nk clusters in which each observation belongs to the cluster with the nearest \nmean (cluster centers or cluster centroid), serving as a prototype of the \ncluster. This results in a partitioning of the data space into Voronoi cells. \n\nParameters\n----------\nname: str\n\tName of the the model. The model will be stored in the DB.\ncursor: DBcursor, optional\n\tVertica DB cursor.\nn_cluster: int, optional\n\tNumber of clusters\ninit: str/list, optional\n\tThe method used to find the initial cluster centers.\n\t\tkmeanspp : Uses the KMeans++ method to initialize the centers.\n\t\trandom : The initial centers.\n\tIt can be also a list with the initial cluster centers to use.\nmax_iter: int, optional\n\tThe maximum number of iterations the algorithm performs.\ntol: float, optional\n\tDetermines whether the algorithm has converged. The algorithm is considered \n\tconverged after no center has moved more than a distance of 'tol' from the \n\tprevious iteration. \n\nAttributes\n----------\nAfter the object creation, all the parameters become attributes. \nThe model will also create extra attributes when fitting the model:\n\ncluster_centers: tablesample\n\tClusters result of the algorithm.\nmetrics: tablesample\n\tDifferent metrics to evaluate the model.\ninput_relation: str\n\tTrain relation.\nX: list\n\tList of the predictors.\n\t\"\"\"\n\tdef __init__(self,\n\t\t\t\t name: str,\n\t\t\t\t cursor = None,\n\t\t\t\t n_cluster: int = 8,\n\t\t\t\t init: str = \"kmeanspp\",\n\t\t\t\t max_iter: int = 300,\n\t\t\t\t tol: float = 1e-4):\n\t\tcheck_types([\n\t\t\t(\"name\", name, [str], False),\n\t\t\t(\"n_cluster\", n_cluster, [int, float], False),\n\t\t\t(\"max_iter\", max_iter, [int, float], False),\n\t\t\t(\"tol\", tol, [int, float], False)])\n\t\tif not(cursor):\n\t\t\tcursor = read_auto_connect().cursor()\n\t\telse:\n\t\t\tcheck_cursor(cursor)\n\t\tself.type = \"clustering\"\n\t\tself.name = name\n\t\tself.cursor = cursor\n\t\tself.n_cluster = n_cluster\n\t\tif (type(init) == str):\n\t\t\tself.init = init.lower()\n\t\telse:\n\t\t\tself.init = init\n\t\tself.max_iter = max_iter \n\t\tself.tol = tol \n\t#---#\n\tdef __repr__(self):\n\t\ttry:\n\t\t\tself.cursor.execute(\"SELECT GET_MODEL_SUMMARY(USING PARAMETERS model_name = '\" + self.name + \"')\")\n\t\t\treturn (self.cursor.fetchone()[0])\n\t\texcept:\n\t\t\treturn \"\"\n\t#\n\t# Methods\n\t#\n\t#---#\n\tdef deploySQL(self):\n\t\t\"\"\"\n\t---------------------------------------------------------------------------\n\tReturns the SQL code needed to deploy the model. \n\n\tReturns\n\t-------\n\tstr\n \t\tthe SQL code needed to deploy the model.\n\t\t\"\"\"\n\t\tsql = \"APPLY_KMEANS({} USING PARAMETERS model_name = '{}', match_by_pos = 'true')\"\n\t\treturn (sql.format(\", \".join(self.X), self.name))\n\t#---#\n\tdef drop(self):\n\t\t\"\"\"\n\t---------------------------------------------------------------------------\n\tDrops the model from the Vertica DB.\n\t\t\"\"\"\n\t\tdrop_model(self.name, self.cursor, print_info = False)\n\t#---#\n\tdef fit(self, \n\t\t\tinput_relation: str, \n\t\t\tX: list):\n\t\t\"\"\"\n\t---------------------------------------------------------------------------\n\tTrains the model.\n\n\tParameters\n\t----------\n\tinput_relation: str\n\t\tTrain relation.\n\tX: list\n\t\tList of the predictors.\n\n\tReturns\n\t-------\n\tobject\n \t\tself\n\t\t\"\"\"\n\t\tcheck_types([\n\t\t\t(\"input_relation\", input_relation, [str], False),\n\t\t\t(\"X\", X, [list], False)])\n\t\tself.input_relation = input_relation\n\t\tself.X = [str_column(column) for column in X]\n\t\tquery = \"SELECT KMEANS('{}', '{}', '{}', {} USING PARAMETERS max_iterations = {}, epsilon = {}\".format(self.name, input_relation, \", \".join(self.X), self.n_cluster, self.max_iter, self.tol)\n\t\tschema = schema_relation(self.name)[0]\n\t\tname = \"VERTICAPY_KMEANS_INITIAL\"\n\t\tif (type(self.init) != str):\n\t\t\ttry:\n\t\t\t\tself.cursor.execute(\"DROP TABLE IF EXISTS {}.{}\".format(schema, name))\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tif (len(self.init) != self.n_cluster):\n\t\t\t\traise ValueError(\"'init' must be a list of 'n_cluster' = {} points\".format(self.n_cluster))\n\t\t\telse:\n\t\t\t\tfor item in self.init:\n\t\t\t\t\tif (len(X) != len(item)):\n\t\t\t\t\t\traise ValueError(\"Each points of 'init' must be of size len(X) = {}\".format(len(self.X)))\n\t\t\t\tquery0 = []\n\t\t\t\tfor i in range(len(self.init)):\n\t\t\t\t\tline = []\n\t\t\t\t\tfor j in range(len(self.init[0])):\n\t\t\t\t\t\tline += [str(self.init[i][j]) + \" AS \" + X[j]]\n\t\t\t\t\tline = \",\".join(line)\n\t\t\t\t\tquery0 += [\"SELECT \" + line]\n\t\t\t\tquery0 = \" UNION \".join(query0)\n\t\t\t\tquery0 = \"CREATE TABLE {}.{} AS {}\".format(schema, name, query0)\n\t\t\t\tself.cursor.execute(query0)\n\t\t\t\tquery += \", initial_centers_table = '{}.{}'\".format(schema, name)\n\t\telse:\n\t\t\tquery += \", init_method = '{}'\".format(self.init)\n\t\tquery += \")\"\n\t\tself.cursor.execute(query)\n\t\ttry:\n\t\t\tself.cursor.execute(\"DROP TABLE IF EXISTS {}.{}\".format(schema, name))\n\t\texcept:\n\t\t\tpass\n\t\tself.cluster_centers = to_tablesample(query = \"SELECT GET_MODEL_ATTRIBUTE(USING PARAMETERS model_name = '{}', attr_name = 'centers')\".format(self.name), cursor = self.cursor)\n\t\tself.cluster_centers.table_info = False\n\t\tquery = \"SELECT GET_MODEL_ATTRIBUTE(USING PARAMETERS model_name = '{}', attr_name = 'metrics')\".format(self.name)\n\t\tself.cursor.execute(query)\n\t\tresult = self.cursor.fetchone()[0]\n\t\tvalues = {\"index\": [\"Between-Cluster Sum of Squares\", \"Total Sum of Squares\", \"Total Within-Cluster Sum of Squares\", \"Between-Cluster SS / Total SS\", \"converged\"]}\n\t\tvalues[\"value\"] = [float(result.split(\"Between-Cluster Sum of Squares: \")[1].split(\"\\n\")[0]), float(result.split(\"Total Sum of Squares: \")[1].split(\"\\n\")[0]), float(result.split(\"Total Within-Cluster Sum of Squares: \")[1].split(\"\\n\")[0]), float(result.split(\"Between-Cluster Sum of Squares: \")[1].split(\"\\n\")[0]) / float(result.split(\"Total Sum of Squares: \")[1].split(\"\\n\")[0]), result.split(\"Converged: \")[1].split(\"\\n\")[0] == \"True\"] \n\t\tself.metrics = tablesample(values, table_info = False)\n\t\treturn (self)\n\t#---#\n\tdef plot(self, \n\t\t\t voronoi: bool = False):\n\t\t\"\"\"\n\t---------------------------------------------------------------------------\n\tDraws the KMeans clusters.\n\n\tParameters\n\t----------\n\tvoronoi: bool, optional\n\t\tIf set to true, a voronoi plot will be drawn. It is only available for\n\t\tKMeans using 2 predictors.\n\t\t\"\"\"\n\t\tif (voronoi):\n\t\t\tif (len(self.X) == 2):\n\t\t\t\tfrom verticapy.learn.plot import voronoi_plot\n\t\t\t\tquery = \"SELECT GET_MODEL_ATTRIBUTE(USING PARAMETERS model_name = '{}', attr_name = 'centers')\".format(self.name)\n\t\t\t\tself.cursor.execute(query)\n\t\t\t\tclusters = self.cursor.fetchall()\n\t\t\t\tvoronoi_plot(clusters = clusters, columns = self.X)\n\t\t\telse:\n\t\t\t\traise ValueError(\"Voronoi Plots are only available in 2D\")\n\t\telse:\n\t\t\tvdf = vDataFrame(self.input_relation, self.cursor)\n\t\t\tself.predict(vdf, \"kmeans_cluster\")\n\t\t\tif (len(self.X) <= 3):\n\t\t\t\tvdf.scatter(columns = self.X, catcol = \"kmeans_cluster\", max_cardinality = 100, max_nb_points = 10000)\n\t\t\telse:\n\t\t\t\traise ValueError(\"Clustering Plots are only available in 2D or 3D\")\n\t#---#\n\tdef predict(self, \n\t\t\t\tvdf, \n\t\t\t\tname: str = \"\"):\n\t\t\"\"\"\n\t---------------------------------------------------------------------------\n\tAdds the prediction in a vDataFrame.\n\n\tParameters\n\t----------\n\tvdf: vDataFrame\n\t\tObject used to insert the prediction as a vcolumn.\n\tname: str, optional\n\t\tName of the added vcolumn. If empty, a name will be generated.\n\n\tReturns\n\t-------\n\tvDataFrame\n\t\tthe input object.\n\t\t\"\"\"\n\t\tcheck_types([\n\t\t\t(\"name\", name, [str], False)],\n\t\t\tvdf = [\"vdf\", vdf])\n\t\tname = \"KMeans_\" + ''.join(ch for ch in self.name if ch.isalnum()) if not (name) else name\n\t\treturn (vdf.eval(name, self.deploySQL()))","sub_path":"verticapy/learn/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":18142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"389528857","text":"import os\r\n\r\n#给定一个整数数组nums和一个目标值target,找出数组中和为目标值的那两个数并返回数组下标\r\n#方法一:暴力破解法\r\ndef twoSum(nums, target):\r\n\tfor i in range(len(nums)):\r\n\t\tfor j in range(i + 1, len(nums)):\r\n\t\t\tsums = nums[i] + nums[j]\r\n\t\t\tif sums == target:\r\n\t\t\t\tprint(i, j)\r\n\t\t\t\treturn i, j\r\n\t\t\t\t\r\ndef main(*args, **kw):\r\n\ttwoSum(\t [17, 3, 8, 11, 2, 5, 19, 20], 30)\r\n\t\r\nif __name__ == '__main__':\r\n\tmain()\r\n","sub_path":"twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"99652093","text":"class GameObject:\r\n \"\"\" A general game object with x and y coordinates representing its location on the gameboard.\r\n\r\n Attributes:\r\n x (int): Represents the x-coordinate on the gameboard.\r\n y (int): Represents the y-coordinate on the gameboard.\r\n \"\"\"\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\n\r\nclass PowerUp(GameObject):\r\n \"\"\" A general object representing power-ups with x and y coordinates representing its location on the gameboard.\r\n\r\n Inherits from GameObject.\r\n\r\n Attributes:\r\n power_up_type (Enum): The type of power-up as either SHIELD, LASER, or TELEPORT .\r\n \"\"\"\r\n def __init__(self, x, y, power_up_type):\r\n super().__init__(x, y)\r\n self.power_up_type = power_up_type\r\n\r\n\r\nclass Turret(GameObject):\r\n \"\"\" An object representing a turret on the gameboard.\r\n\r\n A turret fires for fire_time consecutive turns and is inactive for cooldown_time turns.\r\n\r\n Inherits from GameObject.\r\n\r\n Attributes:\r\n is_firing_next_turn (boolean): True iff this turret is firing the next turn.\r\n is_dead (boolean): True iff this turret has been destroyed and is no longer active.\r\n did_fire (boolean): True iff this turret fired in the last turn.\r\n fire_time (int): The number of consecutive turns the turret will fire.\r\n cooldown_time (int): The number of consecutive turns the turret will not fire.\r\n \"\"\"\r\n def __init__(self, x, y, is_firing_next_turn, is_dead, did_fire, fire_time, cooldown_time):\r\n super().__init__(x, y)\r\n self.is_firing_next_turn = is_firing_next_turn\r\n self.is_dead = is_dead\r\n self.did_fire = did_fire\r\n self.fire_time = fire_time\r\n self.cooldown_time = cooldown_time\r\n\r\n\r\nclass Wall(GameObject):\r\n \"\"\" An object representing a wall and its location on the gameboard.\r\n\r\n Inherits from GameObject.\r\n \"\"\"\r\n def __init__(self, x, y):\r\n super().__init__(x, y)\r\n\r\n\r\nclass DirectionalGameObject(GameObject):\r\n \"\"\" An object representing any GameObject with a direction.\r\n\r\n Inherits from GameObject.\r\n\r\n Attributes:\r\n direction (Enum): The direction the object is facing as either UP, DOWN, LEFT, RIGHT.\r\n \"\"\"\r\n def __init__(self, x, y, direction):\r\n super().__init__(x, y)\r\n self.direction = direction\r\n\r\n\r\nclass Bullet(DirectionalGameObject):\r\n \"\"\" An object representing a bullet on the gameboard.\r\n\r\n Attributes:\r\n shooter (Combatant): A reference to the Combatant that fired the bullet.\r\n \"\"\"\r\n def __init__(self, x, y, direction, shooter):\r\n super().__init__(x, y, direction)\r\n self.shooter = shooter\r\n\r\n\r\nclass Combatant(DirectionalGameObject):\r\n \"\"\" A general object representing a player on the gameboard.\r\n\r\n Attributes:\r\n score (int): This Combatant's current score.\r\n hp (int): This Combatant's current hp (remaining lives/hit points).\r\n shield_active (boolean): True iff this Combatant's shield is currently active.\r\n laser_count (int): The number of laser power-ups this Combatant has.\r\n teleport_count (int): The number of teleport power-ups this Combatant has.\r\n shield_count (int): The number of shield power-ups this Combatant has.\r\n \"\"\"\r\n def __init__(self, x, y, direction, score, hp, shield_active, laser_count, teleport_count, shield_count):\r\n super().__init__(x, y, direction)\r\n self.score = score\r\n self.hp = hp\r\n self.shield_active = shield_active\r\n self.laser_count = laser_count\r\n self.teleport_count = teleport_count\r\n self.shield_count = shield_count\r\n\r\n\r\nclass Opponent(Combatant):\r\n \"\"\" An object representing a player's Opponent in the game.\r\n\r\n Inherits from Combatant.\r\n\r\n Attributes:\r\n last_move (Enum) = The last move this Opponent made. All possible moves are listed in Move in Enums.py.\r\n \"\"\"\r\n\r\n def __init__(self, x, y, direction, score, hp, shield_active, last_move, laser_count, teleport_count, shield_count):\r\n super().__init__(x, y, direction, score, hp, shield_active, laser_count, teleport_count, shield_count)\r\n self.last_move = last_move\r\n\r\n\r\nclass Player(Combatant):\r\n \"\"\" An object representing the player (you) on the gameboard.\r\n\r\n Inherits from Combatant.\r\n\r\n Attributes:\r\n projectiles (List[Enum]): A list of projectiles this Player was hit by, either a LASER or BULLET.\r\n shooters (List[Combatant]): A list of Combatants that fired the projectiles in projectiles. Each index contains\r\n a reference to the combatant that fired it or None (where a Turret fired that projectile).\r\n This list is the same length as projectiles and the indices are mapped such that\r\n projectiles[x] was fired by shooters[x], where x an index.\r\n did_make_a_move (boolean): True iff this Player made a valid move last turn.\r\n \"\"\"\r\n def __init__(self, x, y, direction, score, hp, laser_count, teleport_count, shield_count, did_make_a_move,\r\n projectiles,\r\n shooters, shield_active):\r\n super().__init__(x, y, direction, score, hp, shield_active, laser_count, teleport_count, shield_count)\r\n self.projectiles = projectiles\r\n self.shooters = shooters\r\n self.did_make_a_move = did_make_a_move\r\n\r\n def was_hit(self):\r\n if (len(self.projectiles) > 0):\r\n return True\r\n else:\r\n return False\r\n","sub_path":"orbis/starterKit/Validator/PythonClientAPI/libs/Game/GameObjects.py","file_name":"GameObjects.py","file_ext":"py","file_size_in_byte":5575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"432089905","text":"#! /usr/bin/env python\n\n\ndef get_functions_from_module(mod, pattern=None):\n import inspect, re\n\n funcs = {}\n for name, func in inspect.getmembers(mod, inspect.isroutine):\n if pattern is None or re.match(pattern, name):\n funcs[name] = func\n return funcs\n\n\ndef add_functions_to_class(cls, funcs):\n for name, func in funcs.items():\n setattr(cls, name, func)\n\n\ndef add_module_functions_to_class(cls, module, pattern=None):\n import inspect, imp, os\n\n caller = inspect.stack()[1]\n path = os.path.join(os.path.dirname(caller[1]), os.path.dirname(module))\n\n (module, _) = os.path.splitext(os.path.basename(module))\n\n mod = imp.load_module(module, *imp.find_module(module, [path]))\n\n funcs = get_functions_from_module(mod, pattern=pattern)\n add_functions_to_class(cls, funcs)\n\n\n","sub_path":"landlab/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"209519552","text":"#!/usr/bin/env python\n# coding=utf-8\n\n# System imports\nimport threading\nimport queue\nfrom time import sleep\nfrom sys import exit\n\n# PyQt5 imports\nfrom PyQt5.QtCore import pyqtSignal\nfrom PyQt5.QtCore import QObject\n\n# PySerial imports\nimport serial\nfrom serial.serialutil import SerialException\n\nfrom config import config\n\nclass Model(threading.Thread, QObject):\n\n # This signal emitted when program fail to read serial port (self.port)\n error = pyqtSignal(object)\n # Signal emitted when port configuratin changes\n port_conf_change = pyqtSignal(object)\n\n def __init__(self):\n threading.Thread.__init__(self)\n QObject.__init__(self)\n # Queue with data (lines) received from serial port\n self.queue = queue.Queue()\n self.paused = threading.Event()\n self.paused.set()\n\n # Communications settings\n self._port = config['port']\n self._br = config['baudrate']\n self._parity = config['parity']\n self._bytesize = config['bytesize']\n self._stopbits = config['stopbits']\n self.timeout = config['timeout']\n # Line ending id\n self.eol = config['eol'][0]\n\n # PySerial object\n self.ser = None\n # Flag for main cycle\n self.running = True\n\n def run(self):\n '''\n Run thread.\n In every iteration trying to read one line from serial port and put\n it in queue.\n '''\n try:\n while self.running:\n self.paused.wait()\n if not self.ser.isOpen():\n sleep(0.05)\n continue\n\n try:\n data = self.readline()\n except SerialException as e:\n print('Error occured while reading data. ' + str(e))\n continue\n\n if data:\n\n if config['in_hex']:\n # Only for Python 3.5 and newer\n decoded = data.hex().upper()\n else:\n if config['encode'].upper() in ['ASCII', 'UTF-8']:\n try:\n decoded = data.decode(config['encode'])\n except UnicodeError as e:\n print('Fail to decode bytes. Error: {}'.format(\n e))\n else:\n print('Wrong decoding format. Using ASCII.')\n decoded = data.decode('ASCII')\n\n # One not formated and formated string for hex\n # representation\n hex_repr = self.add_html_colors(decoded)\n # print(hex_repr)\n result = [decoded, hex_repr]\n\n self.queue.put(result)\n\n except KeyboardInterrupt:\n if self.ser:\n self.ser.close()\n exit()\n\n def pause(self):\n self.ser.close()\n if self.paused.isSet():\n self.paused.clear()\n\n def resume(self):\n self.ser.open()\n if not self.paused.isSet():\n self.paused.set()\n\n def stop(self):\n '''\n Stop thread.\n '''\n self.running = False\n self.paused.set()\n if self.ser:\n self.ser.close()\n\n def begin(self):\n '''\n Initializate PySerial object\n '''\n try:\n self.ser = serial.Serial(\n port=self._port, baudrate=self._br, timeout=self.timeout,\n bytesize=self._bytesize, stopbits=self._stopbits\n )\n except SerialException:\n print('Fail to open default port.')\n self.ser = serial.Serial(\n baudrate=self._br, timeout=self.timeout)\n\n#==============================================================================\n# Attributes\n#==============================================================================\n\n @property\n def br(self):\n return self._br\n\n @br.setter\n def br(self, baudrate):\n self.ser.reset_input_buffer()\n if int(baudrate) in serial.Serial.BAUDRATES:\n self._br = baudrate\n self.ser.baudrate = baudrate\n\n self.emit_port_conf_change(self.port_config())\n\n @property\n def port(self):\n return self._port\n\n @port.setter\n def port(self, port):\n if self.ser and self.ser.isOpen():\n self.ser.close()\n\n if self._port != port:\n self._port = port\n else:\n return\n\n try:\n self.ser.port = port\n self.resume()\n except SerialException as e:\n self.emit_error('Can\\'t open this port: ' + str(port) + '.')\n print(e)\n self.ser.close()\n\n self.emit_port_conf_change(self.port_config())\n\n def get_queue(self):\n return self.queue\n\n def set_eol(self, index):\n if index < len(config['eol']) and index >= 0:\n self.eol = config['eol'][index]\n else:\n print('Can\\t set up this type of End Of Line. Because it\\'s not in'\n 'standart list.')\n\n def get_eol(self):\n return self.eol\n\n#==============================================================================\n# PySerial communication\n#==============================================================================\n def read(self, size=1):\n '''\n Read bytes from port. \n Args:\n size: integer specify number of bytes to read. Default is 1.\n Returns:\n String\n '''\n data = None\n\n try:\n if self.ser.isOpen():\n try:\n data = self.ser.read(size)\n except TypeError:\n print('Strange bug in the library.')\n else:\n print('Can\\'t read from the port. Port isn\\'t open.')\n except SerialException as e:\n print('Exception occured, while reading from serial port. ' \n + str(e))\n\n return data\n\n def readline(self):\n '''\n Read line from serial port. Read byte by byte until program get '\\n'\n symbol.\n Returns:\n String\n '''\n data = b''\n\n try:\n if self.ser.isOpen():\n sym = self.read()\n while sym != b'\\n' and sym and len(data) < 256:\n data += sym\n sym = self.read()\n else:\n print('Can\\'t read from the port. Port isn\\'t open.')\n\n except SerialException as e:\n print('Exception occured, while reading line from serial port.')\n\n # return data.decode('UTF-8')\n # return data.decode('ASCII')\n return data\n\n def write(self, data):\n '''\n Write data to serial port.\n Args:\n data: data to send\n '''\n try:\n if self.ser.isOpen():\n self.ser.write(\n bytes(data, 'ASCII') + \n bytes(self.get_eol(), 'ASCII')\n )\n else:\n print('Can\\'t write to the port. Port isn\\'t open.')\n except SerialExceptin as e:\n print('Exception occured, while writing to serial port.')\n print(e)\n\n#==============================================================================\n# Utils\n#==============================================================================\n \n def add_html_colors(self, string):\n '''\n Use predifiend dictionary to find regex at the string and add color HTML\n tags to them.\n Args:\n string: String to parse\n Returns:\n HTML parsed string.\n '''\n clr_set = {\n 0xA: '#0000AA',\n 0xD: '#00AA00'\n }\n\n i = 0\n line = list(string)\n result = list()\n for i, sym in enumerate(line):\n if ord(sym) in clr_set.keys():\n result.append(''.format(\n clr_set[ord(sym)]))\n result.append('{0:02x}'.format(ord(sym)).upper())\n result.append('')\n else:\n result.append('{0:02x}'.format(ord(sym)).upper())\n\n if (i + 1)%2 == 0:\n result.append(' ')\n\n return ''.join(result)\n\n\n def divide_text_in_blocks(self, string, length=4):\n \"\"\"\n Divide string into substring of the 'length'.\n Args:\n string: string to divide.\n Returns:\n Divided string.\n \"\"\"\n if length < 0:\n return None\n\n if len(string) < length:\n return string\n\n return ' '.join(string[i:i + length] for i in range(\n 0, len(string), length))\n\n\n def port_config(self):\n '''\n Generate port configuration dictinoary. (Used in view)\n Returns:\n Dictionary.\n '''\n return {'baudrate': self._br, 'num_of_bits': self._bytesize, \n 'parity': self._parity, 'num_of_stop': self._stopbits}\n\n#==============================================================================\n# Signals\n#==============================================================================\n\n def emit_error(self, value):\n self.error.emit(value)\n\n def emit_port_conf_change(self, value):\n self.port_conf_change.emit(value)\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"193536252","text":"class NestedIterator(object):\n\n def __init__(self, nestedList):\n # Initialize your data structure here.\n self.ds = nestedList\n self.idx = 0\n self.stack = []\n self.find_next()\n\n def find_next(self):\n while ((self.idx < len(self.ds) and isinstance(self.ds[self.idx], list)) or\n (self.idx == len(self.ds) and self.stack)):\n if self.idx == len(self.ds):\n self.ds, self.idx = self.stack.pop()\n continue\n if self.idx < len(self.ds) - 1:\n self.stack.append((self.ds, self.idx+1))\n self.ds = self.ds[self.idx]\n self.idx = 0\n\n # @return {int} the next element in the iteration\n def next(self):\n # Write your code here\n ans = self.ds[self.idx]\n self.idx += 1\n if self.idx < len(self.ds) and isinstance(self.ds[self.idx], int):\n return ans\n self.find_next()\n return ans\n\n\n # @return {boolean} true if the iteration has more element or false\n def hasNext(self):\n # Write your code here\n return self.idx < len(self.ds)\n","sub_path":"data_structures/array/nested_list_iterator.py","file_name":"nested_list_iterator.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"76794430","text":"import math\nimport numpy as np\nimport createPower as cp\nimport pylab as plt\n\ndef moSin(frequency=50.0, amplitude=5.0, phase=1, timePerDetect=1e-04, duration=0.5):\n\n sinSignal=[]\n cycleTime=1.0/frequency\n freSin=float(2*math.pi*frequency)\n for detectNum in xrange(int(cycleTime/timePerDetect+0.5)):\n value=amplitude*math.sin(freSin*detectNum*timePerDetect+phase)\n # if value<0:\n # value=0\n sinSignal.append(value)\n\n # plt.figure()\n # plt.plot(range(int(cycleTime/timePerDetect+0.5)), sinSignal, \"oc-\")\n # plt.show()\n\n return sinSignal\n\ndef FM():\n selFre = 10000.0\n selNum = 1000.0\n\n # signal1 = moSin(50, 10.0)\n signal1 = [1]\n signal2 = moSin(500, 10.0)\n\n signalTot = []\n for detectTime in xrange(int(selNum)):\n signalTot.append( signal1[detectTime % len(signal1)] * signal2[detectTime % len(signal2)] )\n\n plt.figure()\n plt.plot(range(int(selNum)), signalTot, \"oc-\")\n plt.xlim((0, 500))\n plt.show()\n\n signalTot = np.array(signalTot)\n\n freqNums = [i * selFre / selNum for i in xrange(int(selNum/2+1))]\n\n ffts = [1]\n fftNums = np.fft.fft(signalTot)\n ffts[0] = np.abs(fftNums[0]) / selNum\n ffts.extend([np.abs(fftNum) / (selNum/2) for fftNum in fftNums[1 : ]])\n\n flt = plt.figure()\n flt = plt.subplot(111)\n\n for index, frequency in enumerate(freqNums):\n flt.plot([frequency, frequency], [0, ffts[index]], \"ok-\", linewidth = 2)\n\n plt.xlim((0, 500))\n\n plt.show()\n\nif __name__==\"__main__\":\n FM()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"584048244","text":"from django.db import models\n\n\nclass Album(models.Model):\n name = models.TextField(\n blank=False,\n db_index=True,\n unique=True,\n help_text=\"Album name - can alternatively use 'id' field set to id of existing album when creating new lyrics\")\n\n objects = models.Manager()\n\n\nclass Song(models.Model):\n name = models.TextField(\n blank=False,\n db_index=True,\n unique=True,\n help_text=\"Song name - can alternatively use 'id' field set to id of existing song when creating new lyrics\")\n\n album = models.ForeignKey(\n Album,\n related_name='songs',\n null=True,\n on_delete=models.CASCADE,\n help_text=\"Album\")\n\n objects = models.Manager()\n\n\nclass Lyric(models.Model):\n text = models.TextField(\n blank=False,\n db_index=True,\n help_text=\"Lyrics from a song/album\")\n\n song = models.ForeignKey(\n Song,\n related_name='lyrics',\n null=True,\n on_delete=models.CASCADE,\n help_text=\"Song\")\n\n votes = models.IntegerField(\n default=0\n )\n\n objects = models.Manager()\n","sub_path":"lyrics_api/swift_lyrics/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"605189146","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nModule that contains theme implementation\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\n\nimport os\n\nfrom Qt.QtCore import *\nfrom Qt.QtGui import *\n\nfrom six import string_types\n\nimport tpDcc\nfrom tpDcc.libs import qt\nfrom tpDcc.libs.python import yamlio, color, python\nfrom tpDcc.libs.qt.core import style, qtutils, cache, color as qt_color\n\n\nclass Theme(QObject, object):\n\n class Sizes(object):\n\n TINY = 18\n SMALL = 24\n MEDIUM = 32\n LARGE = 40\n HUGE = 48\n\n class Colors(object):\n\n BLUE = '#1890FF'\n PURPLE = '#722ED1'\n CYAN = '#13C2C2'\n GREEN = '#52C41A'\n MAGENTA = '#EB2F96'\n PINK = '#EF5B97'\n RED = '#F5222D'\n ORANGE = '#FA8C16'\n YELLOW = '#FADB14'\n VOLCANO = '#FA541C'\n GEEK_BLUE = '#2F54EB'\n LIME = '#A0D911'\n GOLD = '#FAAD14'\n\n updated = Signal()\n\n EXTENSION = 'yml'\n DEFAULT_ACCENT_COLOR = QColor(0, 175, 255)\n DEFAULT_SIZE = Sizes.SMALL\n\n def __init__(self, theme_file=None, accent_color=None, dark_mode=True):\n super(Theme, self).__init__()\n\n self._name = 'Default'\n self._style = 'default'\n self._file = theme_file\n self._dpi = 1\n self._background_color = None\n self._overrides = list()\n\n self._init_colors()\n self._init_sizes()\n self._init_font()\n\n accent_color = accent_color or self.Colors.BLUE\n if dark_mode:\n self.set_dark(accent_color)\n else:\n self.set_light(accent_color)\n\n self._init_icons()\n\n self.unit = 'px'\n self.default_size = self.small\n self.text_color_inverse = '#FFF'\n\n self._load_theme_data_from_file(theme_file)\n\n def __getattr__(self, item):\n options = self.options(skip_instance_attrs=True)\n if not options or item not in options:\n return super(Theme, self).__getattribute__(item)\n\n option_value = options[item]\n if isinstance(option_value, string_types):\n if option_value.startswith('^'):\n return qtutils.dpi_scale(int(option_value[1:]))\n if color.string_is_hex(option_value):\n return color.hex_to_rgb(option_value)\n else:\n return option_value\n\n def _load_theme_data_from_file(self, theme_file):\n \"\"\"\n Internal function that laods file data from given file\n :param theme_file: str\n :return: dict\n \"\"\"\n\n if not theme_file or not os.path.isfile(theme_file):\n return\n\n try:\n theme_data = yamlio.read_file(theme_file)\n except Exception:\n qt.logger.warning('Impossible to load theme data from file: \"{}\"!'.format(theme_file))\n return None\n\n theme_name = theme_data.get('name', None)\n if not theme_name:\n qt.logger.warning('Impossible to retrieve them name from theme file: \"{}\"!'.format(theme_file))\n return None\n accent_color = theme_data.get('accent_color', None)\n if not accent_color:\n qt.logger.warning('No theme color definitions found in theme file: \"{}\"'.format(theme_file))\n return None\n self._style = theme_data.get('style', 'default.css')\n self._overrides = theme_data.get('overrides', list())\n\n self.set_name(theme_name)\n self.set_accent_color(accent_color)\n\n def name(self):\n \"\"\"\n Returns the name for this theme\n :return: str\n \"\"\"\n\n return self._name\n\n def set_name(self, name):\n \"\"\"\n Sets the name for this theme\n :param name: str\n \"\"\"\n\n self._name = name\n\n def dpi(self):\n \"\"\"\n Returns zoom amount for this theme\n :return: float\n \"\"\"\n\n return self._dpi\n\n def set_dpi(self, dpi):\n \"\"\"\n Sets the zoom amount for this theme\n :param dpi: float\n \"\"\"\n\n self._dpi = dpi\n\n def set_accent_color(self, accent_color):\n \"\"\"\n Sets the main/accent color of the theme\n :param accent_color:\n \"\"\"\n\n self._update_accent_color(accent_color)\n self.updated.emit()\n\n def is_dark(self):\n \"\"\"\n Returns whether the current theme is dark or not\n :return: bool\n \"\"\"\n\n bg_color = qt_color.Color(self.background_color)\n\n red = bg_color.redF() * 0.299\n green = bg_color.greenF() * 0.587\n blue = bg_color.blueF() * 0.114\n\n darkness = red + green + blue\n if darkness < 0.6:\n return True\n\n return False\n\n def set_dark(self, accent_color):\n \"\"\"\n Sets the current theme to the default dark color\n \"\"\"\n\n self.background_color = '#323232'\n self.background_selected_color = '#292929'\n self.background_in_color = '#3A3A3A'\n self.background_out_color = '#494949'\n self.mask_color = self._fade_color(self.background_color, '90%')\n self.toast_color = '#555555'\n self.title_color = \"#FFFFFF\"\n self.primary_text_color = \"#D9D9D9\"\n self.secondary_text_color = \"#A6A6A6\"\n self.disable_color = \"#737373\"\n self.border_color = \"#1E1E1E\"\n self.divider_color = \"#262626\"\n self.header_color = \"#0A0A0A\"\n self.icon_color = \"#A6A6A6\"\n self.window_dragger_color = \"#232323\"\n self.window_dragger_label_color = \"#D9D9D9\"\n\n self.set_accent_color(accent_color)\n\n def set_light(self, accent_color):\n \"\"\"\n Sets the current theme to the default light color\n \"\"\"\n\n self.background_color = '#F8F8F9'\n self.background_selected_color = '#BFBFBF'\n self.background_in_color = '#FFFFFF'\n self.background_out_color = '#EEEEEE'\n self.mask_color = self._fade_color(self.background_color, '90%')\n self.toast_color = '#333333'\n self.title_color = \"#262626\"\n self.primary_text_color = \"#595959\"\n self.secondary_text_color = \"#8C8C8C\"\n self.disable_color = \"#E5E5E5\"\n self.border_color = \"#D9D9D9\"\n self.divider_color = \"#E8E8E8\"\n self.header_color = \"#FAFAFA\"\n self.icon_color = \"#8C8C8C\"\n self.window_dragger_color = \"#f2f2fd\"\n self.window_dragger_label_color = \"#262626\"\n\n self.set_accent_color(accent_color)\n\n def _init_colors(self):\n \"\"\"\n Internal function that initializes all theme colors\n \"\"\"\n\n self.info_color = self.Colors.BLUE\n self.success_color = self.Colors.GREEN\n self.processing_color = self.Colors.BLUE\n self.error_color = self.Colors.RED\n self.warning_color = self.Colors.GOLD\n\n self.info_1 = self._fade_color(self.info_color, '15%')\n self.info_2 = qt_color.generate_color(self.info_color, 2)\n self.info_3 = self._fade_color(self.info_color, '35%')\n self.info_4 = qt_color.generate_color(self.info_color, 4)\n self.info_5 = qt_color.generate_color(self.info_color, 5)\n self.info_6 = qt_color.generate_color(self.info_color, 6)\n self.info_7 = qt_color.generate_color(self.info_color, 7)\n self.info_8 = qt_color.generate_color(self.info_color, 8)\n self.info_9 = qt_color.generate_color(self.info_color, 9)\n self.info_10 = qt_color.generate_color(self.info_color, 10)\n\n self.success_1 = self._fade_color(self.success_color, '15%')\n self.success_2 = qt_color.generate_color(self.success_color, 2)\n self.success_3 = self._fade_color(self.success_color, '35%')\n self.success_4 = qt_color.generate_color(self.success_color, 4)\n self.success_5 = qt_color.generate_color(self.success_color, 5)\n self.success_6 = qt_color.generate_color(self.success_color, 6)\n self.success_7 = qt_color.generate_color(self.success_color, 7)\n self.success_8 = qt_color.generate_color(self.success_color, 8)\n self.success_9 = qt_color.generate_color(self.success_color, 9)\n self.success_10 = qt_color.generate_color(self.success_color, 10)\n\n self.warning_1 = self._fade_color(self.warning_color, '15%')\n self.warning_2 = qt_color.generate_color(self.warning_color, 2)\n self.warning_3 = self._fade_color(self.warning_color, '35%')\n self.warning_4 = qt_color.generate_color(self.warning_color, 4)\n self.warning_5 = qt_color.generate_color(self.warning_color, 5)\n self.warning_6 = qt_color.generate_color(self.warning_color, 6)\n self.warning_7 = qt_color.generate_color(self.warning_color, 7)\n self.warning_8 = qt_color.generate_color(self.warning_color, 8)\n self.warning_9 = qt_color.generate_color(self.warning_color, 9)\n self.warning_10 = qt_color.generate_color(self.warning_color, 10)\n\n self.error_1 = self._fade_color(self.error_color, '15%')\n self.error_2 = qt_color.generate_color(self.error_color, 2)\n self.error_3 = self._fade_color(self.error_color, '35%')\n self.error_4 = qt_color.generate_color(self.error_color, 4)\n self.error_5 = qt_color.generate_color(self.error_color, 5)\n self.error_6 = qt_color.generate_color(self.error_color, 6)\n self.error_7 = qt_color.generate_color(self.error_color, 7)\n self.error_8 = qt_color.generate_color(self.error_color, 8)\n self.error_9 = qt_color.generate_color(self.error_color, 9)\n self.error_10 = qt_color.generate_color(self.error_color, 10)\n\n def _init_sizes(self):\n \"\"\"\n Internal function that initializes all themes sizes\n \"\"\"\n\n self.border_radius_large = 8\n self.border_radius_base = 4\n self.border_radius_small = 2\n self.tiny = self.Sizes.TINY\n self.small = self.Sizes.SMALL\n self.medium = self.Sizes.MEDIUM\n self.large = self.Sizes.LARGE\n self.huge = self.Sizes.HUGE\n self.tiny_icon = self.tiny - 8\n self.small_icon = self.small - 10\n self.medium_icon = self.medium - 12\n self.large_icon = self.large - 16\n self.huge_icon = self.huge - 20\n self.window_dragger_rounded_corners = 5\n self.window_dragger_font_size = 12\n self.window_rounded_corners = 5\n self.button_padding = 4\n\n def _init_font(self):\n \"\"\"\n Internal function that initializes all theme fonts\n \"\"\"\n\n self.font_family = 'BlinkMacSystemFont,\"Segoe UI\",\"PingFang SC\",\"Hiragino Sans GB\",\"Microsoft YaHei\",' \\\n '\"Helvetica Neue\",Helvetica,Arial,sans-serif'\n self.font_size_base = 14\n self.font_size_large = self.font_size_base + 2\n self.font_size_small = self.font_size_base - 2\n self.h1_size = int(self.font_size_base * 2.71)\n self.h2_size = int(self.font_size_base * 2.12)\n self.h3_size = int(self.font_size_base * 1.71)\n self.h4_size = int(self.font_size_base * 1.41)\n\n def _init_icons(self):\n \"\"\"\n Internal function that initializes all theme icons\n \"\"\"\n\n self.radio_checked_icon = 'radio_button_checked.png'\n self.radio_unchecked_icon = 'radio_button_unchecked.png'\n self.up_icon = 'collapse.png'\n self.down_icon = 'expand.png'\n self.up_arrow_icon = 'up_arrow.png'\n self.down_arrow_icon = 'down_arrow.png'\n self.left_icon = 'back.png'\n self.right_icon = 'next.png'\n self.calendar_icon = 'calendar.png'\n self.check_icon = 'check.png'\n self.uncheck_icon = 'uncheck.png'\n self.circle_icon = 'circle.png'\n self.splitter_icon = 'splitter.png'\n\n def _update_accent_color(self, accent_color):\n accent_color = qt_color.convert_2_hex(accent_color)\n self.accent_color = accent_color\n self.accent_color_1 = qt_color.generate_color(accent_color, 1)\n self.accent_color_2 = qt_color.generate_color(accent_color, 2)\n self.accent_color_3 = qt_color.generate_color(accent_color, 3)\n self.accent_color_4 = qt_color.generate_color(accent_color, 4)\n self.accent_color_5 = qt_color.generate_color(accent_color, 5)\n self.accent_color_6 = qt_color.generate_color(accent_color, 6)\n self.accent_color_7 = qt_color.generate_color(accent_color, 7)\n self.accent_color_8 = qt_color.generate_color(accent_color, 8)\n self.accent_color_9 = qt_color.generate_color(accent_color, 9)\n self.accent_color_10 = qt_color.generate_color(accent_color, 10)\n self.item_hover_background_color = self.accent_color_1\n\n def _get_color(self, color_value, alpha=None):\n \"\"\"\n Internal function that returns a color value in proper format to be handled by theme\n :param color_value: variant, str or QColor or color.Color\n \"\"\"\n\n if isinstance(color_value, (str, unicode)):\n color_value = qt_color.Color.from_string(color_value)\n elif isinstance(color_value, QColor):\n color_value = qt_color.Color.from_color(color_value)\n elif isinstance(color_value, (list, tuple)):\n color_value = qt_color.Color(*color_value)\n\n return color_value\n\n def _fade_color(self, color, alpha):\n \"\"\"\n Internal function that fades given color\n :param color: QColor\n :param alpha: float\n :return:\n \"\"\"\n\n qt_color = QColor(color)\n return 'rgba({}, {}, {}, {})'.format(qt_color.red(), qt_color.green(), qt_color.blue(), alpha)\n\n def foreground_color(self):\n \"\"\"\n Returns the foreground color for this theme\n :return: color.Color\n \"\"\"\n\n if self.is_dark():\n return qt_color.Color(250, 250, 250, 255)\n else:\n return qt_color.Color(0, 40, 80, 180)\n\n # def icon_color(self):\n # \"\"\"\n # Returns the icon color for this theme\n # :return: color.Color\n # \"\"\"\n #\n # return self.foreground_color()\n #\n # def accent_foreground_color(self):\n # \"\"\"\n # Returns the foregound color for the accent color\n # \"\"\"\n #\n # return qt_color.Color(255, 255, 255, 255)\n #\n # def item_background_color(self):\n # \"\"\"\n # Returns the item background color\n # :return: color.Color\n # \"\"\"\n #\n # if self.is_dark():\n # return qt_color.Color(255, 255, 255, 20)\n # else:\n # return qt_color.Color(255, 255, 255, 120)\n #\n # def item_background_hover_color(self):\n # \"\"\"\n # Returns the item background color when the mouse hovers over the item\n # :return: color.Color\n # \"\"\"\n #\n # return qt_color.Color(255, 255, 255, 60)\n #\n # def settings(self):\n # \"\"\"\n # Returns a dictionary of settings for the current theme\n # :return: dict\n # \"\"\"\n #\n # return {\n # 'name': self.name(),\n # 'accentColor': self.accent_color().to_string(),\n # 'backgroundColor': self.background_color().to_string()\n # }\n\n def set_settings(self, settings):\n \"\"\"\n Sets a dictionary of settings for the current theme\n :param settings: dict\n \"\"\"\n\n for theme_sett_name, theme_sett_value in settings.items():\n if hasattr(self, theme_sett_name):\n setattr(self, theme_sett_name, theme_sett_value)\n\n def get_theme_option(self, option_name, default_value=None):\n \"\"\"\n Returns option of the style\n :return: object\n \"\"\"\n\n theme_options = self.options()\n if not theme_options:\n return default_value\n\n return theme_options[option_name] if option_name in theme_options else default_value\n\n def options(self, skip_instance_attrs=False):\n \"\"\"\n Returns the variables used to customize the style sheet\n :return: dict\n \"\"\"\n if self.is_dark():\n darkness = 'white'\n else:\n darkness = 'black'\n\n theme_resources_dir = ''\n if self._file and os.path.isfile(self._file):\n theme_dir = os.path.dirname(self._file)\n theme_name = os.path.splitext(os.path.basename(self._file))[0]\n theme_resources_dir = os.path.join(theme_dir, 'resources', theme_name)\n\n style_resources_dir = ''\n style_path = self.stylesheet_file()\n if style_path and os.path.isfile(style_path):\n style_dir = os.path.dirname(style_path)\n style_name = os.path.splitext(os.path.basename(style_path))[0]\n style_resources_dir = os.path.join(style_dir, 'resources', style_name)\n\n options = {\n 'darkness': darkness,\n 'theme_resources': theme_resources_dir,\n 'style_resources': style_resources_dir\n }\n\n if not skip_instance_attrs:\n inst_attrs = python.get_instance_user_attributes(self)\n for attr in inst_attrs:\n if isinstance(attr[1], QColor):\n options[attr[0]] = qt_color.Color(attr[1]).to_string()\n else:\n options[attr[0]] = str(attr[1])\n\n # options = {\n # \"ACCENT_COLOR\": accent_color.to_string(),\n # \"ACCENT_COLOR_DARKER\": qt_color.Color(accent_color.darker(150)).to_string(),\n # \"ACCENT_COLOR_LIGHTER\": qt_color.Color(accent_color.lighter(150)).to_string(),\n # \"ACCENT_COLOR_R\": str(accent_color.red()),\n # \"ACCENT_COLOR_G\": str(accent_color.green()),\n # \"ACCENT_COLOR_B\": str(accent_color.blue()),\n #\n # \"ACCENT_FOREGROUND_COLOR\": accent_foreground_color.to_string(),\n # \"ACCENT_FOREGROUND_COLOR_DARKER\": qt_color.Color(accent_foreground_color.darker(150)).to_string(),\n #\n # \"FOREGROUND_COLOR\": foreground_color.to_string(),\n # \"FOREGROUND_COLOR_R\": str(foreground_color.red()),\n # \"FOREGROUND_COLOR_G\": str(foreground_color.green()),\n # \"FOREGROUND_COLOR_B\": str(foreground_color.blue()),\n #\n # \"BACKGROUND_COLOR\": background_color.to_string(),\n # \"BACKGROUND_COLOR_LIGHTER\": qt_color.Color(background_color.lighter(150)).to_string(),\n # \"BACKGROUND_COLOR_DARKER\": qt_color.Color(background_color.darker(150)).to_string(),\n # \"BACKGROUND_COLOR_R\": str(background_color.red()),\n # \"BACKGROUND_COLOR_G\": str(background_color.green()),\n # \"BACKGROUND_COLOR_B\": str(background_color.blue()),\n #\n # \"ITEM_TEXT_COLOR\": foreground_color.to_string(),\n # \"ITEM_TEXT_SELECTED_COLOR\": accent_foreground_color.to_string(),\n #\n # \"ITEM_BACKGROUND_COLOR\": item_background_color.to_string(),\n # \"ITEM_BACKGROUND_HOVER_COLOR\": item_background_hover_color.to_string(),\n # \"ITEM_BACKGROUND_SELECTED_COLOR\": accent_color.to_string(),\n # }\n #\n overrides = self._overrides or dict()\n options.update(overrides)\n #\n return options\n\n def stylesheet_file(self):\n \"\"\"\n Returns path where theme stylesheet is located\n :return: str\n \"\"\"\n\n style_name = self._style or 'default'\n style_extension = style.StyleSheet.EXTENSION\n if not style_extension.startswith('.'):\n style_extension = '.{}'.format(style_extension)\n style_file_name = '{}{}'.format(style_name, style_extension)\n style_path = tpDcc.ResourcesMgr().get('styles', style_file_name)\n\n return style_path\n\n def stylesheet(self):\n \"\"\"\n Returns the style sheet for this theme\n :return: str\n \"\"\"\n\n style_path = self.stylesheet_file()\n options = self.options()\n\n stylesheet = style.StyleSheet.from_path(style_path, options=options, theme_name=self._name, dpi=self.dpi())\n\n return stylesheet.data()\n #\n # def create_color_dialog(self, parent, standard_colors=None, current_color=None):\n # \"\"\"\n # Creates a new instance of color dialog\n # :param parent: QWidget\n # :param standard_colors: list(int)\n # :param current_color: QColor\n # :return: QColorDialog\n # \"\"\"\n #\n # dlg = QColorDialog(parent)\n # if standard_colors:\n # index = -1\n # for r, g, b in standard_colors:\n # index += 1\n # clr = QColor(r, g, b).rgba()\n # try:\n # clr = QColor(clr)\n # dlg.setStandardColor(index, clr)\n # except Exception:\n # clr = QColor(clr).rgba()\n # dlg.setStandardColor(index, clr)\n #\n # # PySide2 does not supports d.open(), we pass a blank slot\n # dlg.open(self, Slot('blankSlot()'))\n #\n # if current_color:\n # dlg.setCurrentColor(current_color)\n #\n # return dlg\n #\n # def browse_accent_color(self, parent=None):\n # \"\"\"\n # Shows the color dialog for changing the accent color\n # :param parent: QWidget\n # \"\"\"\n #\n # standard_colors = [\n # (230, 60, 60), (210, 40, 40), (190, 20, 20), (250, 80, 130),\n # (230, 60, 110), (210, 40, 90), (255, 90, 40), (235, 70, 20),\n # (215, 50, 0), (240, 100, 170), (220, 80, 150), (200, 60, 130),\n # (255, 125, 100), (235, 105, 80), (215, 85, 60), (240, 200, 150),\n # (220, 180, 130), (200, 160, 110), (250, 200, 0), (230, 180, 0),\n # (210, 160, 0), (225, 200, 40), (205, 180, 20), (185, 160, 0),\n # (80, 200, 140), (60, 180, 120), (40, 160, 100), (80, 225, 120),\n # (60, 205, 100), (40, 185, 80), (50, 180, 240), (30, 160, 220),\n # (10, 140, 200), (100, 200, 245), (80, 180, 225), (60, 160, 205),\n # (130, 110, 240), (110, 90, 220), (90, 70, 200), (180, 160, 255),\n # (160, 140, 235), (140, 120, 215), (180, 110, 240), (160, 90, 220),\n # (140, 70, 200), (210, 110, 255), (190, 90, 235), (170, 70, 215)\n # ]\n #\n # current_color = self.accent_color()\n #\n # dialog = self.create_color_dialog(parent, standard_colors, current_color)\n # dialog.currentColorChanged.connect(self.set_accent_color)\n #\n # if dialog.exec_():\n # self.set_accent_color(dialog.selectedColor())\n # else:\n # self.set_accent_color(current_color)\n #\n # def browse_background_color(self, parent=None):\n # \"\"\"\n # Shows the color dialog for changing the background color\n # :param parent: QWidget\n # \"\"\"\n #\n # standard_colors = [\n # (0, 0, 0), (20, 20, 20), (40, 40, 40), (60, 60, 60),\n # (80, 80, 80), (100, 100, 100), (20, 20, 30), (40, 40, 50),\n # (60, 60, 70), (80, 80, 90), (100, 100, 110), (120, 120, 130),\n # (0, 30, 60), (20, 50, 80), (40, 70, 100), (60, 90, 120),\n # (80, 110, 140), (100, 130, 160), (0, 60, 60), (20, 80, 80),\n # (40, 100, 100), (60, 120, 120), (80, 140, 140), (100, 160, 160),\n # (0, 60, 30), (20, 80, 50), (40, 100, 70), (60, 120, 90),\n # (80, 140, 110), (100, 160, 130), (60, 0, 10), (80, 20, 30),\n # (100, 40, 50), (120, 60, 70), (140, 80, 90), (160, 100, 110),\n # (60, 0, 40), (80, 20, 60), (100, 40, 80), (120, 60, 100),\n # (140, 80, 120), (160, 100, 140), (40, 15, 5), (60, 35, 25),\n # (80, 55, 45), (100, 75, 65), (120, 95, 85), (140, 115, 105)\n # ]\n #\n # current_color = self.background_color()\n #\n # dialog = self.create_color_dialog(parent, standard_colors, current_color)\n # dialog.currentColorChanged.connect(self.set_background_color)\n #\n # if dialog.exec_():\n # self.set_background_color(dialog.selectedColor())\n # else:\n # self.set_background_color(current_color)\n\n\nThemeCache = cache.CacheResource(Theme)\n","sub_path":"tpDcc/libs/qt/core/theme.py","file_name":"theme.py","file_ext":"py","file_size_in_byte":24033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"111901568","text":"import time\nfrom firebase_admin import credentials\nfrom firebase_admin import db\nfrom firebase_admin import auth\nfrom firebase_admin import storage\nfrom firebase_admin import firestore\nimport paho.mqtt.client as mqtt\nfrom google.cloud import storage\nimport pyrebase\nimport threading\nimport os\nimport json\n\n\nPATH_CRED = '/Users/douglaskorgut/Desktop/TCC/newDevCourse/pythonScripts/cred.json'\nURL_DB = 'https://tccfirstattempt.firebaseio.com'\nURL_STORAGE = 'gs://tccfirstattempt.appspot.com'\nREF_HOME = 'tccfirstattempt'\nREF_VIDEOS = 'video_publicacoes'\nREF_IMAGES = 'imagens'\nREF_PUBLICACOES = 'publicacoes'\nREF_USER = 'user'\nPATH_TO_IMAGE= \"/Users/douglaskorgut/Desktop/TCC/newDevCourse/pythonScripts/FacialRecognitionProject/MqttProject/img3.png\"\n\n\nconfig = {\n \"apiKey\": \"AIzaSyCp0RIPqODI_Zxsrfu48Yt087XD8orxXWg\",\n \"authDomain\": \"tccfirstattempt.firebaseapp.com\",\n \"databaseURL\": \"https://tccfirstattempt.firebaseio.com\",\n \"projectId\": \"tccfirstattempt\",\n \"storageBucket\": \"tccfirstattempt.appspot.com\",\n \"messagingSenderId\": \"994487973781\",\n \"serviceAccount\": \"./cred.json\"\n}\n\nfirebase = pyrebase.initialize_app(config)\nstorage = firebase.storage()\ndatabase = firebase.database()\n\n\nclass FirebaseManager(threading.Thread):\n\n def __init__(self):\n super(FirebaseManager, self).__init__()\n\n\n def run(self):\n while True:\n time.sleep(0.05)\n\n\n @staticmethod\n def doPublishVideo():\n userEmail = \"ZG91Z2xhc2tvcmd1dHRAZ21haWwuY29t\"\n database.child(\"video_publicacoes\").child(userEmail).push({\"titulo\":\"newVideo\"})\n data = database.child(\"video_publicacoes/\" + userEmail).order_by_key().limit_to_last(1).get()\n print(data.val())\n print(data.key())\n\n\n for x in data.each():\n imageName = x.key()\n\n storage.child(\"videos/\"+imageName).put(\"output.mp4\")\n\n if os.path.exists(\"output.mp4\"):\n os.remove(\"output.mp4\")\n else:\n print(\"The file does not exist\")\n\n\n @staticmethod\n def doPublishImage():\n userEmail = \"ZG91Z2xhc2tvcmd1dHRAZ21haWwuY29t\"\n print(\"User email: \"+userEmail)\n database.child(\"publicacoes\").child(userEmail).push({\"titulo\":\"TituloAgora!!!!\"})\n data = database.child(\"publicacoes/\"+userEmail).order_by_key().limit_to_last(1).get()\n print(data.val())\n print(data.key())\n\n for x in data.each():\n imageName = x.key()\n\n storage.child(\"imagens/\"+str(imageName)).put(\"pictureTaken.png\")\n if os.path.exists(\"pictureTaken.png\"):\n os.remove(\"pictureTaken.png\")\n else:\n print(\"The file does not exist\")\n #doPublishImage()\n\n @staticmethod\n def downloadUsersPictures():\n macAddress = \"b8:27:eb:4d:f9:09\"\n users = []\n fbUsers = database.child(\"usuario_detalhe\").get()\n for fbUser in fbUsers.each():\n users.append(fbUser.key())\n #print(len(users))\n\n systemUsers = []\n for user in users:\n data = database.child(\"usuario_detalhe\").child(user).child(\"usuario\").child(\"mac_address\").get()\n if ( data.val() == macAddress ):\n systemUsers.append(user)\n\n storage.child(\"perfil_images/\"+\"-LPSnAc2on_8hzJ_g80J\").download(\"teste/IMAGE_DOWN.jpg\")\n print(\"downloaded\")\n\n # for systemUser in systemUsers:\n # #download all files from user using its reference, download must be made in this same loop\n # recognitionReferences = database.child(\"perfil_publicacoes\").child(systemUser).get()\n # for recognitionReference in recognitionReferences.each():\n # print(recognitionReference.key())\n # storage.child(\"perfil_images/\"+recognitionReference.key()).download(\"imageafd\")\n # for recognitionReference in data():\n # regonitionReferences.append(recognitionReference.val())\n # print(recognitionReference.val())\n","sub_path":"FacialRecognitionProject/TccFinal_working_1/firebase.py","file_name":"firebase.py","file_ext":"py","file_size_in_byte":3972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"506532104","text":"#!/usr/bin/env python\n\n\n\"\"\"\nTHIS IS A SKELETON OF WHAT A NORMAL PYTHON SCRIPT SHOULD LOOK LIKE\n\"\"\"\n\nimport time, os, sys\nfrom datetime import datetime\nfrom optparse import OptionParser\nimport time\nimport Tutils\n\ndef main():\n usage_str = \"%prog\"\n parser = OptionParser(usage = usage_str)\n \n (options, args) = parser.parse_args()\n \n if len(args) < 0:\n parser.print_help()\n sys.exit(2)\n\n cur_time = time.time()\n yesterday_time = cur_time - (3600*7) - 86400 - (cur_time%86400)\n dt = Tutils.epoch2tme(yesterday_time, \"%Y%m%d\")\n\n output_file = \"C:\\\\Users\\\\Tom\\\\programming\\\\OP_basketball_games\\%s_nba_scores.csv\" % dt\n # RUN NBA SCRAPING\n cmd = \"python C:\\\\Users\\\\Tom\\\\programming\\\\scripts\\\\python\\\\scrape_nba_game_scores.py %s %s\" % (dt, output_file)\n ret = os.system(cmd)\n\n # Sleep for 1 minute\n time.sleep(60)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/python/run_scrape_nba_game_scores.py","file_name":"run_scrape_nba_game_scores.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"265816842","text":"from functools import reduce # for code_metric; map and filter do not need to be imported\n\ndef is_sorted(s):\n if s == []:\n return True\n if len(s) == 1:\n return True\n else:\n return(s[0] <= s[1] and is_sorted(s[1:]))\n\ndef merge (l1,l2):\n if not l1:\n return l2\n elif not l2:\n return l1\n else:\n if l1[0] <= l2[0]:\n return [l1[0]] + merge(l1[1:],l2)\n if l2[0] < l1[0]:\n return [l2[0]] + merge(l1,l2[1:])\n\ndef sort(l):\n l1 = l[0:len(l)//2]\n l2 = l[len(l)//2:]\n if len(l) > 1:\n x = sort(l1)\n y = sort(l2)\n else:\n if not l1:\n return merge(l1,l2)\n if not l2:\n return merge(l1,l2)\n if len(l1) == 1:\n return merge(l1,l2)\n if len(l2) == 1:\n return merge(l1,l2)\n return(merge(x,y))\n \ndef compare(a,b):\n if not a and not b:\n return '='\n if a and not b:\n return '>'\n if b and not a:\n return '<'\n if a[0] < b[0]:\n return '<'\n if a[0] > b[0]:\n return '>'\n elif a[0] == b[0]:\n return compare(a[1:],b[1:])\n\ndef code_metric(file):\n infile = open(file,'r').read().splitlines()\n filt = filter(lambda x: x != '', infile)\n m = map(lambda x: (1,len(x)), filt)\n r = reduce(lambda x,y: (x[0]+y[0],x[1]+y[1]), m)\n return r\n\n\nif __name__==\"__main__\":\n import predicate,random,driver\n from goody import irange\n \n print('\\nTesting is_sorted')\n print(is_sorted([]))\n print(is_sorted([1,2,3,4,5,6,7]))\n print(is_sorted([1,2,3,7,4,5,6]))\n print(is_sorted([1,2,3,4,5,6,5]))\n print(is_sorted([7,6,5,4,3,2,1]))\n \n print('\\nTesting merge')\n print(merge([],[]))\n print(merge([],[1,2,3]))\n print(merge([1,2,3],[]))\n print(merge([1,2,3,4],[5,6,7,8]))\n print(merge([5,6,7,8],[1,2,3,4]))\n print(merge([1,3,5,7],[2,4,6,8]))\n print(merge([2,4,6,8],[1,3,5,7]))\n print(merge([1,2,5,7,10],[1,2,6,10,12]))\n\n\n print('\\nTesting sort')\n print(sort([1,2,3,4,5,6,7]))\n print(sort([7,6,5,4,3,2,1]))\n print(sort([4,5,3,1,2,7,6]))\n print(sort([1,7,2,6,3,5,4]))\n l = list(range(20)) # List of values 0-19\n for i in range(10): # Sort 10 times\n random.shuffle(l)\n print(sort(l),sep='-->')\n \n \n print('\\nTesting compare')\n print(compare('',''))\n print(compare('','abc'))\n print(compare('abc',''))\n print(compare('abc','abc'))\n print(compare('bc','abc'))\n print(compare('abc','bc'))\n print(compare('aaaxc','aaabc'))\n print(compare('aaabc','aaaxc'))\n \n \n print('\\nTesting code_metric')\n print(code_metric('cmtest.py'))\n print(code_metric('collatz.py'))\n print(code_metric('q5solution.py')) # A function analyzing the file it is in\n","sub_path":"q5helper/q5solution.py","file_name":"q5solution.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"102928831","text":"import os,random,shutil,json,re\nfrom hume_corpus import make_sgm_file,make_txt_file\n\ndef main():\n input_dir = \"/nfs/raid88/u10/users/hqiu_ad/raw_corpus/covid/chinese_news_vol2.extracted\"\n output_folder = \"/nfs/raid88/u10/users/hqiu_ad/raw_corpus/covid/chinese_news_vol2_sgms/\"\n shutil.rmtree(output_folder)\n os.makedirs(output_folder)\n booking_arr = list()\n sgm_path_list = list()\n breaking_point = 10000\n for file in os.listdir(input_dir):\n with open(os.path.join(input_dir,file)) as fp:\n for i in fp:\n i = i.strip()\n crawl_en = json.loads(i)\n # print(crawl_en)\n if \"extracted_text\" not in crawl_en:\n continue\n\n extracted_text = crawl_en[\"extracted_text\"]\n chars = re.findall(\"[\\u4e00-\\u9FFF]\", extracted_text)\n if len(chars) < 40:\n continue\n doc_uuid = crawl_en[\"BBN_docid\"]\n document_creation_time = crawl_en[\"BBN_website_creation_date\"]\n source_uri = crawl_en[\"url\"]\n author = crawl_en[\"BBN_website_name\"]\n make_sgm_file(extracted_text, doc_uuid, output_folder,\n \"NON_CDR\", source_uri,\n \"news_{}\".format(doc_uuid), \"CHS_NW_WM\", document_creation_time, author, booking_arr,sgm_path_list, breaking_point)\n make_txt_file(extracted_text, doc_uuid, output_folder)\n\n\n\n with open(os.path.join(output_folder, \"metadata.txt\"), 'w') as wfp:\n for i in booking_arr:\n wfp.write(\"{}\\n\".format(i))\n random.shuffle(sgm_path_list)\n with open(os.path.join(output_folder, 'sgms.list'), 'w') as wfp:\n for i in sgm_path_list:\n wfp.write(\"{}\\n\".format(i))\n with open(os.path.join(output_folder, 'txts.list'), 'w') as wfp:\n for i in sgm_path_list:\n wfp.write(\"{}\\n\".format(i))\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/python/data_digestion/common_crawl_chinese_vol2.py","file_name":"common_crawl_chinese_vol2.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"436348632","text":"# -*- coding: UTF-8 -*-\n\nimport numpy as np # python 矩阵操作lib\n\n\nclass Simplex():\n def __init__(self):\n self._A = \"\" # 系数矩阵\n self._b = \"\" #\n self._c = '' # 约束\n self._B = '' # 基变量的下标集合\n self.row = 0 # 约束个数\n\n def run(self, filename):\n # 读取文件内容,文件结构前两行分别为 变量数 和 约束条件个数\n # 接下来是系数矩阵\n # 然后是b数组\n # 然后是约束条件c\n\n A = []\n b = []\n c = []\n with open(filename, 'r') as f:\n self.var = int(f.readline())\n self.row = int(f.readline())\n\n for i in range(self.row):\n x = [int(item) for item in f.readline().strip().split(' ')]\n A.append(x)\n b = [int(item) for item in f.readline().split(' ')]\n c = [int(item) for item in f.readline().split(' ')]\n\n self._A = np.array(A, dtype=float)\n self._b = np.array(b, dtype=float)\n self._c = np.array(c, dtype=float)\n\n (x, obj) = self.Simplex(self._A, self._b, self._c)\n self.print_result(x, obj)\n\n @staticmethod\n def print_result(x, obj):\n px = ['x[%d] = %f' % (i + 1, x[i]) for i in range(len(x))]\n print(','.join(px))\n print('objective value is : %f' % obj)\n\n # 添加人工变量得到一个初始解\n def InitializeSimplex(self, A, b):\n\n # 添加松弛变量\n slacks = np.eye(self.row)\n A = np.concatenate((A, slacks), axis=1)\n c = np.concatenate((np.zeros(self.var), np.ones(self.row)), axis=0)\n # c [0. 0. 0. 0. 0. 0. 1. 1. 1.]\n\n b_min, min_pos = (np.min(b), np.argmin(b)) # 得到最小bi\n\n # 将bi全部转化成正数(相当于高斯行变换)\n if b_min < 0:\n for i in range(self.row):\n if i != min_pos:\n A[i] = A[i] - A[min_pos]\n b[i] = b[i] - b[min_pos]\n A[min_pos] *= -1\n b[min_pos] *= -1\n\n # 松弛变量全部加入基,初始解为b\n new_B = [i + self.var for i in range(self.row)]\n # new_B [6, 7, 8]\n\n # 辅助方程的目标函数值\n obj = - np.sum(b)\n\n c = c - c[new_B].reshape(1, -1).dot(A)\n c = c[0]\n # c [ 8. -7. 3. -4. -1. -1. -2. 2. 2.]\n\n # 入基, 要求ce<0 entering basis\n e = np.argmin(c)\n\n while c[e] < 0:\n theta = []\n for i in range(len(b)):\n # b [ 3. 7. 15.]\n if A[i][e] > 0:\n theta.append(b[i] / A[i][e])\n else:\n theta.append(float(\"inf\"))\n\n l = np.argmin(np.array(theta))\n\n if theta[l] == float('inf'):\n print('unbounded')\n return False\n\n (new_B, A, b, c, obj) = self.PIVOT(new_B, A, b, c, obj, l, e)\n\n e = np.argmin(c)\n\n return new_B, A[:, 0:self.var], b\n\n # 算法入口\n def Simplex(self, A, b, c):\n\n (B, A, b) = self.InitializeSimplex(A, b)\n\n # 函数目标值 -cTB-1b\n obj = - np.dot(c[B], b)\n # -26\n\n # reshape(1, -1) 让数组c变成一行\n c = c - c[B].reshape(1, -1).dot(A)\n c = c[0]\n # c [-11. 0. 0. -10. -11. 0.]\n\n # entering basis\n e = np.argmin(c)\n\n # 如果不存在检验数小于0, 则返回\n while c[e] < 0:\n theta = []\n for i in range(len(b)):\n if A[i][e] > 0:\n theta.append(b[i] / A[i][e])\n else:\n theta.append(float(\"inf\"))\n\n l = np.argmin(np.array(theta))\n\n if theta[l] == float('inf'):\n print('unbounded')\n return False\n\n (B, A, b, c, obj) = self.PIVOT(B, A, b, c, obj, l, e)\n\n e = np.argmin(c)\n\n x = self._CalculateX(B, A, b, c)\n return x, - obj # 左上角是负的目标函数\n\n # 得到完整解\n def _CalculateX(self, B, A, b, c):\n x = np.zeros(self.var, dtype=float)\n x[B] = b\n return x\n\n # 基变换\n def PIVOT(self, B, A, b, c, z, l, e):\n # main element is a_le\n # l 出基\n # e 入基\n\n main_elem = A[l][e]\n # scaling the l-th line\n A[l] = A[l] / main_elem\n b[l] = b[l] / main_elem\n\n # 进行高斯消元\n for i in range(self.row):\n if i != l:\n b[i] = b[i] - A[i][e] * b[l]\n A[i] = A[i] - A[i][e] * A[l]\n\n # 更新目标值\n z -= b[l] * c[e]\n c -= c[e] * A[l]\n\n # change the basis\n B[l] = e\n\n return B, A, b, c, z\n\n\nif __name__ == \"__main__\":\n s = Simplex()\n s.run('dualPro.txt')\n","sub_path":"DualSimplex/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"456544475","text":"# Copyright 2016 Intel Corporation\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\nimport logging\nimport sys\n\nfrom journal import transaction\n\nfrom sawtooth.exceptions import InvalidTransactionError\n\nfrom mktplace.transactions import holding_update\nfrom mktplace.transactions import liability_update\nfrom mktplace.transactions import market_place_object_update\nfrom mktplace.transactions import participant_update\n\nlogger = logging.getLogger(__name__)\n\n\nclass SellOfferObject(market_place_object_update.MarketPlaceObject):\n ObjectTypeName = 'SellOffer'\n ExecutionStyle = ['Any', 'ExecuteOnce', 'ExecuteOncePerParticipant']\n\n @classmethod\n def is_valid_object(cls, store, objectid):\n obj = cls.get_valid_object(store, objectid)\n if not obj:\n return False\n\n if not participant_update.ParticipantObject.is_valid_object(\n store, obj.get('creator')):\n return False\n\n if not liability_update.LiabilityObject.is_valid_object(\n store, obj.get('input')):\n return False\n\n if not holding_update.HoldingObject.is_valid_object(store,\n obj.get('output')):\n return False\n\n if float(obj.get('ratio', 0)) <= 0:\n return False\n\n if obj.get('minimum') < 0 or obj.get('maximum') < 0:\n return False\n\n if obj.get('maximum') < obj.get('minimum'):\n return False\n\n if obj.get('execution') not in cls.ExecutionStyle:\n return False\n\n return True\n\n def __init__(self, objectid=None, minfo=None):\n if minfo is None:\n minfo = {}\n super(SellOfferObject, self).__init__(objectid, minfo)\n\n self.CreatorID = minfo.get('creator', '**UNKNOWN**')\n self.InputID = minfo.get('input', '**UNKNOWN**')\n self.OutputID = minfo.get('output', '**UNKNOWN**')\n self.Ratio = float(minfo.get('ratio', 0))\n self.Description = minfo.get('description', '')\n self.Name = minfo.get('name', '')\n self.Minimum = int(minfo.get('minimum', 0))\n self.Maximum = int(minfo.get('maximum', sys.maxint))\n self.Execution = minfo.get('execution', 'Any')\n self.ExecutionState = {'ParticipantList': []}\n\n def dump(self):\n result = super(SellOfferObject, self).dump()\n\n result['creator'] = self.CreatorID\n result['input'] = self.InputID\n result['output'] = self.OutputID\n result['ratio'] = float(self.Ratio)\n result['description'] = self.Description\n result['name'] = self.Name\n result['minimum'] = int(self.Minimum)\n result['maximum'] = int(self.Maximum)\n result['execution'] = self.Execution\n result['execution-state'] = self.ExecutionState\n\n return result\n\n\nclass Register(transaction.Update):\n UpdateType = 'RegisterSellOffer'\n ObjectType = SellOfferObject\n CreatorType = participant_update.ParticipantObject\n\n def __init__(self,\n update_type,\n input_id,\n output_id,\n creator_id=None,\n ratio=1,\n description=None,\n name=None,\n minimum=0,\n maximum=None,\n execution=None):\n super(Register, self).__init__(update_type)\n\n self._creator_id = creator_id or '**UNKNOWN**'\n self._input_id = input_id\n self._output_id = output_id\n self._ratio = ratio\n self._description = description or ''\n self._name = name or ''\n self._minimum = minimum\n self._maximum = maximum or sys.maxint\n self._execution = execution or 'Any'\n\n @property\n def References(self):\n return [self._creator_id, self._input_id, self._output_id]\n\n def check_valid(self, store, txn):\n if txn.Identifier in store:\n raise InvalidTransactionError(\"ObjectId already in store\")\n\n if not market_place_object_update.global_is_permitted(\n store, txn, self._creator_id, self.CreatorType):\n raise InvalidTransactionError(\n \"Creator address is different from txn.OriginatorID\")\n\n if not market_place_object_update.global_is_valid_name(\n store, self._name, self.ObjectType, self._creator_id):\n raise InvalidTransactionError(\n \"Name, {}, is not valid\".format(self._name))\n\n if not liability_update.LiabilityObject.is_valid_object(\n store, self._input_id):\n raise InvalidTransactionError(\n \"{} is not a Liability\".format(self._input_id))\n\n obj = liability_update.LiabilityObject.get_valid_object(store,\n self._input_id)\n if not self.CreatorType.is_valid_creator(store, obj.get('creator'),\n txn.OriginatorID):\n logger.info('%s does not have permission to modify liability %s',\n txn.OriginatorID, self._input_id)\n raise InvalidTransactionError(\n \"Txn.OriginatorID not allowed to modify liability\")\n\n if not holding_update.HoldingObject.is_valid_object(store,\n self._output_id):\n raise InvalidTransactionError(\n \"OutputId is not a valid Holding\")\n\n obj = holding_update.HoldingObject.get_valid_object(\n store, self._output_id)\n if not self.CreatorType.is_valid_creator(store, obj.get('creator'),\n txn.OriginatorID):\n logger.info('%s does not have permission to modify liability %s',\n txn.OriginatorID, self._output_id)\n raise InvalidTransactionError(\n \"Txn.OriginatorID does not have permission to modify \"\n \"liability\")\n\n if self._ratio <= 0:\n logger.debug('invalid ratio %s in offer %s', self._ratio,\n txn.Identifier)\n raise InvalidTransactionError(\n \"Ratio < 0\")\n\n if self._minimum < 0 or self._maximum < 0 or \\\n self._maximum < self._minimum:\n logger.debug('inconsistent range %s < %s in offer %s',\n self._minimum, self._maximum, txn.Identifier)\n raise InvalidTransactionError(\n \"Minimum and Maximum are inconsistent\")\n if self._execution not in SellOfferObject.ExecutionStyle:\n logger.debug('invalid execution style %s in offer %s',\n self._execution, txn.Identifier)\n raise InvalidTransactionError(\n \"Execution not a valid ExecutionStyle\")\n\n def apply(self, store, txn):\n pobj = self.ObjectType(txn.Identifier)\n\n pobj.CreatorID = self._creator_id\n pobj.InputID = self._input_id\n pobj.OutputID = self._output_id\n pobj.Ratio = float(self._ratio)\n pobj.Description = self._description\n pobj.Name = self._name\n pobj.Minimum = self._minimum\n pobj.Maximum = self._maximum\n pobj.Execution = self._execution\n\n store[txn.Identifier] = pobj.dump()\n\n\nclass Unregister(transaction.Update):\n UpdateType = 'UnregisterSellOffer'\n ObjectType = SellOfferObject\n CreatorType = participant_update.ParticipantObject\n\n def __init__(self,\n update_type,\n object_id,\n creator_id):\n super(Unregister, self).__init__(update_type)\n self._object_id = object_id\n self._creator_id = creator_id\n\n @property\n def References(self):\n return []\n\n def check_valid(self, store, txn):\n if not market_place_object_update.global_is_permitted(\n store,\n txn,\n self._creator_id,\n self.CreatorType):\n raise InvalidTransactionError(\n \"Creator Address not the same as txn.OriginatorID\"\n )\n\n def apply(self, store, txn):\n del store[self._object_id]\n\n\nclass UpdateDescription(market_place_object_update.UpdateDescription):\n UpdateType = 'UpdateSellOfferDescription'\n ObjectType = SellOfferObject\n CreatorType = participant_update.ParticipantObject\n\n\nclass UpdateName(market_place_object_update.UpdateName):\n UpdateType = 'UpdateSellOfferName'\n ObjectType = SellOfferObject\n CreatorType = participant_update.ParticipantObject\n","sub_path":"extensions/mktplace/mktplace/transactions/sell_offer_update.py","file_name":"sell_offer_update.py","file_ext":"py","file_size_in_byte":9150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"489735139","text":"from task import Task\nfrom node import *\nfrom collections import deque\nimport math\nfrom constants import *\n\nclass Env:\n def __init__(self):\n # 系统设备状况\n self.transmitStore=TransmitStore\n self.mobileNum=MOBILE_NUM\n self.mecNum=MEC_NUM\n self.mobiles=list()\n self.mecs=list()\n for i in range(self.mobileNum):\n self.mobiles.append(Mobile(\"mobile\"+str(i),\"1.1.1.\"+str(i),{\"mem\":4}, 2))\n for i in range(self.mecNum):\n self.mecs.append(MEC(\"mec\"+str(i),\"1.1.2.\"+str(i), {\"mem\":16}, 3))\n # 时隙设定\n self.interval=1\n self.timeSlots=100\n self.currentTime=0\n # 信道带宽-MHz,信噪比-db\n self.bandwidth=20\n self.SNR=10\n # 执行功率 传输功率\n self.processPower=50\n self.transmitPower=20\n # 平衡系数\n self.W1=0.5\n self.W2=1-self.W1\n\n def reset(self):\n self.currentTime=0\n for mobile in self.mobiles:\n mobile.processQueue.clear()\n mobile.resourceAvil[\"mem\"]=4\n for mec in self.mecs:\n mec.processQueue.clear()\n mec.total_compdelay=0\n mec.resourceAvil[\"mem\"]=16\n self.transmitStore.storeQueue.clear()\n\n def create_tasks(self):\n tasks=list()\n for i in range(self.mobileNum):\n tasks.append(self.mobiles[i].createTask(self.currentTime))\n return tasks\n\n def createAllTasks(self):\n allTasks=list()\n for i in range(self.timeSlots):\n tasks=list()\n for j in range(self.mobileNum):\n tasks.append(self.mobiles[j].createTask(i))\n allTasks.append(tasks)\n return allTasks\n\n def step(self,tasks):\n for task in tasks:\n if task.offload_action==0:\n self.mobiles[int(task.node_from[-1])].updateByTime(task, self.currentTime, 'c', self.get_transpeed(), self.transmitStore.store_queue)\n else:\n self.mobiles[int(task.node_from[-1])].updateByTime(task, self.currentTime, 't', self.get_transpeed(), self.transmitStore.store_queue)\n self.mecs[task.offload_action-1].updateByTime(self.currentTime, self.transmitStore.store_queue)\n next_states=[]\n for mobile in self.mobiles:\n next_states.append([mobile.total_compdelay,mobile.total_trandelay,self.mecs[0].total_compdelay,self.mecs[1].total_compdelay])\n return next_states\n\n def end(self):\n if self.currentTime>self.timeSlots:\n return True\n return False\n\n def get_reward(self):\n total_delay=0\n total_consume=0\n for mobile in self.mobiles:\n total_delay=max(mobile.total_compdelay,total_delay)\n total_consume+= self.processPower * mobile.total_compdelay + self.transmitPower * mobile.total_trandelay\n for mec in self.mecs:\n total_delay=max(mec.total_compdelay,total_delay)\n total_consume+= self.processPower * mec.total_compdelay\n return -self.W1*total_delay-self.W2*total_consume\n\n def get_transpeed(self):\n return self.bandwidth*math.log(1+self.SNR,2)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"rl/env1.py","file_name":"env1.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"180494390","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2018 by\n# Marta Grobelna \n# Petre Petrov \n# Rudi Floren \n# Tobias Winkler \n# All rights reserved.\n# BSD license.\n#\n# Authors: Marta Grobelna \n# Petre Petrov \n# Rudi Floren \n# Tobias Winkler \n\nimport pyboltzmann as pybo\n\nfrom planar_graph_sampler.combinatorial_classes.one_connected_graph import OneConnectedPlanarGraph\nfrom planar_graph_sampler.grammar.binary_tree_decomposition import EarlyRejectionControl\nfrom planar_graph_sampler.grammar.grammar_utils import underive\nfrom planar_graph_sampler.grammar.two_connected_decomposition import two_connected_graph_grammar\n\n\nclass Merger(pybo.DefaultBuilder):\n \"\"\"\n Merges a set of l-derived graphs at their marked vertices.\n \"\"\"\n def set(self, graphs):\n # Merge a set of l-derived one-connected planar graphs at their marked vertices.\n # If the set is empty, return a single-node graph.\n if len(graphs) is 0:\n g = OneConnectedPlanarGraph()\n return pybo.LDerivedClass(OneConnectedPlanarGraph(), g.half_edge)\n result = graphs.pop()\n for g in graphs:\n result.marked_atom.insert_all_after(g.marked_atom)\n assert isinstance(result, pybo.LDerivedClass)\n return result\n\n\ndef merge(prod):\n \"\"\"Merges l-derived one-connected graphs at their marked vertices\"\"\"\n # lhs is a bi-derived connected and rhs a derived connected.\n lhs = prod.first\n rhs = prod.second\n if not lhs.marked_atom.is_trivial:\n rhs.marked_atom.insert_all_after(lhs.marked_atom)\n return lhs\n\n\ndef subs_marked_vertex(decomp):\n # decomp is of form (G_1_dx + L * G_1_dx_dx) * G_2_dx_dx.\n\n if isinstance(decomp.first, pybo.LDerivedClass):\n one_connected = decomp.first\n plug_in_he = one_connected.marked_atom\n if not plug_in_he.is_trivial:\n decomp.second.base_class_object.marked_atom.insert_all_after(plug_in_he)\n else:\n one_connected = decomp.first.second\n plug_in_he = one_connected.marked_atom\n if not plug_in_he.is_trivial:\n decomp.second.base_class_object.marked_atom.insert_all_after(plug_in_he)\n decomp.second.base_class_object.marked_atom = one_connected.base_class_object.marked_atom\n return decomp.second\n\n\ndef subs_marked_vertex_2(decomp):\n # decomp is of form ((G_1_dx + L * G_1_dx_dx) * (G_1_dx + L * G_1_dx_dx)) * G_2_dx_dx_dx.\n if isinstance(decomp.first.first, pybo.LDerivedClass):\n plug_in_he1 = decomp.first.first.marked_atom\n else:\n plug_in_he1 = decomp.first.first.second.marked_atom\n if isinstance(decomp.first.second, pybo.LDerivedClass):\n plug_in_he2 = decomp.first.second.marked_atom\n else:\n plug_in_he2 = decomp.first.second.second.marked_atom\n if not plug_in_he1.is_trivial:\n decomp.second.base_class_object.base_class_object.marked_atom.insert_all_after(plug_in_he1)\n if not plug_in_he2.is_trivial:\n decomp.second.base_class_object.marked_atom.insert_all_after(plug_in_he2)\n return decomp.second\n\n\ndef rej_to_G_1(g):\n return pybo.bern(1 / (g.l_size + 1))\n\n\ndef one_connected_graph_grammar():\n \"\"\"Constructs the grammar for connected planar graphs.\n\n Returns\n -------\n DecompositionGrammar\n The grammar for sampling from G_1_dx and G_1_dx_dx.\n \"\"\"\n\n # Some shortcuts to make the grammar more readable.\n L = pybo.LAtomSampler\n Rule = pybo.AliasSampler\n G_2_dx = Rule('G_2_dx')\n G_2_dx_dx = Rule('G_2_dx_dx')\n G_2_dx_dx_dx = Rule('G_2_dx_dx_dx')\n G_1_dx = Rule('G_1_dx')\n G_1_dx_dx = Rule('G_1_dx_dx')\n G_1_dx_dx_dx = Rule('G_1_dx_dx_dx')\n Set = pybo.SetSampler\n LSubs = pybo.LSubsSampler\n Bij = pybo.BijectionSampler\n Rej = pybo.RejectionSampler\n\n grammar = pybo.DecompositionGrammar()\n grammar.rules = two_connected_graph_grammar().rules\n EarlyRejectionControl.grammar = grammar\n\n grammar.add_rules({\n\n 'G_1':\n Bij(\n Rej(\n G_1_dx,\n rej_to_G_1 # See lemma 15.\n ),\n underive\n ),\n\n 'G_1_dx':\n Set(\n 0,\n LSubs(\n G_2_dx,\n L() * G_1_dx\n )\n ),\n\n 'G_1_dx_dx':\n Bij(\n Bij(\n (G_1_dx + L() * G_1_dx_dx) * LSubs(G_2_dx_dx, L() * G_1_dx),\n subs_marked_vertex\n ) * G_1_dx,\n merge\n ),\n\n 'G_1_dx_dx_dx':\n Bij(\n Bij(\n (2 * G_1_dx_dx + L() * G_1_dx_dx_dx) * LSubs(G_2_dx_dx, L() * G_1_dx),\n subs_marked_vertex\n ) * G_1_dx,\n merge\n )\n\n + Bij(\n Bij(\n (G_1_dx + L() * G_1_dx_dx) ** 2 * LSubs(G_2_dx_dx_dx, L() * G_1_dx),\n subs_marked_vertex_2\n ) * G_1_dx,\n merge\n )\n\n + Bij(\n Bij(\n (G_1_dx + L() * G_1_dx_dx) * LSubs(G_2_dx_dx, L() * G_1_dx),\n subs_marked_vertex\n ) * G_1_dx_dx,\n merge\n ),\n\n })\n\n grammar.set_builder(['G_1_dx'], Merger())\n\n return grammar\n\n\nif __name__ == '__main__':\n from planar_graph_sampler.evaluations_planar_graph import *\n from timeit import default_timer as timer\n\n oracle = pybo.EvaluationOracle(my_evals_10)\n pybo.BoltzmannSamplerBase.oracle = oracle\n pybo.BoltzmannSamplerBase.debug_mode = False\n\n start = timer()\n grammar = one_connected_graph_grammar()\n symbolic_x = 'x'\n symbolic_y = 'y'\n sampled_class = 'G_1_dx_dx_dx'\n grammar.init(sampled_class, symbolic_x, symbolic_y)\n end = timer()\n print(\"Time init: {}\".format(end - start))\n\n try:\n print(\"expected avg. size: {}\\n\".format(oracle.get_expected_l_size(sampled_class, symbolic_x, symbolic_y)))\n except pybo.PyBoltzmannError:\n pass\n\n # random.seed(0)\n # boltzmann_framework_random_gen.seed(13)\n\n l_sizes = []\n i = 0\n samples = 100\n start = timer()\n while i < samples:\n obj = grammar.sample_iterative(sampled_class)\n l_sizes.append(obj.l_size)\n # print(obj.l_size)\n i += 1\n end = timer()\n print()\n print(\"avg. size: {}\".format(sum(l_sizes) / len(l_sizes)))\n print(\"time: {}\".format(end - start))\n\n # while True:\n # g = grammar.sample_iterative(sampled_class, symbolic_x, symbolic_y)\n # print(g)\n # for key, value in sorted(Stats.rules.items(), key=lambda x: x[1]):\n # print(\"{} : {}\".format(key, value))\n # print()\n # # if g.l_size >= 1000:\n # # g = g.underive_all()\n # # print(g)\n # # print(g.u_size / g.l_size)\n # # # assert g.is_consistent\n # # #g.plot(with_labels=False, use_planar_drawer=False, node_size=13)\n # # #plt.show()\n","sub_path":"planar_graph_sampler/grammar/one_connected_decomposition.py","file_name":"one_connected_decomposition.py","file_ext":"py","file_size_in_byte":7276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"9561078","text":"import discord, aiohttp\nimport config\n\nclass Chatbot:\n\n def __init__(self, bot):\n self.bot = bot\n\n async def message_handler(self, message):\n channel = message.channel\n content = message.content\n if message.author.bot:\n return\n\n if content.startswith(\"<@310039170792030211> \") or content.startswith(\"<@!310039170792030211> \"):\n commands = []\n for command in self.bot.commands:\n commands.append(command.name)\n hascommand = 0\n for command in commands:\n if str(message.content[22:]).startswith(command) or str(message.content[23:]).startswith(command):\n hascommand += 1\n if hascommand >= 1:\n return\n await channel.trigger_typing()\n async with aiohttp.ClientSession(headers={\"Authorization\": config.chatbot}) as cs:\n terms = str(message.content[22:]).replace(\" \", \"%20\")\n async with cs.get(f'https://api.dialogflow.com/v1/query?v=20150910&lang=en&query={terms}&sessionId=0') as r:\n res = await r.json()\n await channel.send(embed=discord.Embed(color=0xDEADBF, description=res['result']['fulfillment']['messages'][0]['speech']))\n\ndef setup(bot):\n n = Chatbot(bot)\n bot.add_listener(n.message_handler, \"on_message\")\n bot.add_cog(n)","sub_path":"old/unused/chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"621126255","text":"\"\"\"\nSequence Of GET's\n+++++++++++++++++\n\nSend two SNMP GET requests in a row using the following options:\n\n* with SNMPv3, user 'usr-md5-none', MD5 authentication, no privacy\n* over IPv4/UDP\n* to an Agent at demo.snmplabs.com:161\n* for IF-MIB::ifInOctets.1 and IF-MIB::ifOutOctets.1 MIB objects\n\nUse a queue of MIB objects to query.\n\nThe next() call is used to forward Python iterator to the position where it\ncould consume input\n\nFunctionally similar to:\n\n| $ snmpget -v3 -l authNoPriv -u usr-md5-none -A authkey1 demo.snmplabs.com \\\n| IF-MIB::ifInOctets.1\n\n\"\"\"#\nfrom pysnmp.hlapi import *\n\nqueue = [ [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets', 1)) ],\n [ ObjectType(ObjectIdentity('IF-MIB', 'ifOutOctets', 1)) ] ]\n\niter = getCmd(SnmpEngine(),\n UsmUserData('usr-md5-none', 'authkey1'),\n UdpTransportTarget(('demo.snmplabs.com', 161)),\n ContextData())\n\nnext(iter)\n\nwhile queue:\n errorIndication, errorStatus, errorIndex, varBinds = iter.send(queue.pop())\n if errorIndication:\n print(errorIndication)\n elif errorStatus:\n print('%s at %s' % (\n errorStatus.prettyPrint(),\n errorIndex and varBinds[int(errorIndex)-1][0] or '?'\n )\n )\n else:\n for varBind in varBinds:\n print(' = '.join([ x.prettyPrint() for x in varBind ]))\n","sub_path":"examples/hlapi/asyncore/sync/manager/cmdgen/multiple-get-calls.py","file_name":"multiple-get-calls.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"646684442","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom xmls import Xmls\nfrom datetimes import Datetimes\nfrom logs import Logs\n\nREDENVELOPE_CONFIGURATION_FILE_PATH = \"project/configuration.xml\"\n# REDENVELOPE_NAME = \"root\"\nREDENVELOPE_NAME = \"redenvelope\"\nPURCHASE_NAME = \"purchase\"\n\nREDENVELOPE_ATTRIBUTE_FACTOR = \"factor\"\nREDENVELOPE_ATTRIBUTE_THRESHOLD = \"person_threshold\"\nREDENVELOPE_DEVICE_BONUS_PATH = \"device/bonus\"\nREDENVELOPE_EXTRA_MAX_PATH = \"extra/max\"\nREDENVELOPE_EXTRA_MIN_PATH = \"extra/min\"\nREDENVELOPE_EXTRA_POSSIBILITY_PATH = \"extra/possibility\"\nREDENVELOPE_EXTRA_THRESHOLD_PATH = \"extra/threshold\"\nREDENVELOPE_EXTRA_KEEP_PATH = \"extra/keep\"\nREDENVELOPE_RAIN_MAX_PATH = \"rain/max\"\nREDENVELOPE_RAIN_MIN_PATH = \"rain/min\"\nREDENVELOPE_RAIN_POSSIBILITY_PATH = \"rain/possibility\"\nREDENVELOPE_RAIN_THRESHOLD_PATH = \"rain/threshold\"\nREDENVELOPE_RAIN_START_DATE_PATH = \"rain/start_date\"\nREDENVELOPE_RAIN_END_DATE_PATH = \"rain/end_date\"\nREDENVELOPE_RAIN_WEEK_PATH = \"rain/week\"\nREDENVELOPE_RAIN_START_TIME_PATH = \"rain/start_time\"\nREDENVELOPE_RAIN_END_TIME_PATH = \"rain/end_time\"\nREDENVELOPE_RAIN_COUNT_PATH = \"rain/count\"\n\nPURCHASE_URL = \"url\"\n\nTIME_FORMAT = \"%H:%M:%S\"\nDATE_FORMAT = \"%Y:%m:%d\"\n\n\nclass RedEnvelopeConfiguration(object):\n modified_time = None\n text = None\n root = None\n RED_ENVELOPE_FACTOR = None\n RED_ENVELOPE_PERSON_THRESHOLD = None\n RED_ENVELOPE_BY_DEVICE = None\n RED_ENVELOPE_EXTRA_POSSIBILITY = None\n RED_ENVELOPE_EXTRA_THRESHOLD = None\n RED_ENVELOPE_EXTRA_MIN = None\n RED_ENVELOPE_EXTRA_MAX = None\n RED_ENVELOPE_EXTRA_KEEP = None\n RED_ENVELOPE_RAIN_POSSIBILITY = None\n RED_ENVELOPE_RAIN_THRESHOLD = None\n RED_ENVELOPE_RAIN_MIN = None\n RED_ENVELOPE_RAIN_MAX = None\n RED_ENVELOPE_RAIN_START_STR = None\n RED_ENVELOPE_RAIN_START = None\n RED_ENVELOPE_RAIN_END_STR = None\n RED_ENVELOPE_RAIN_END = None\n RED_ENVELOPE_RAIN_COUNT = None\n RED_ENVELOPE_RAIN_WEEK = []\n RED_ENVELOPE_RAIN_WEEK_STR = \"\"\n RED_ENVELOPE_RAIN_START_DATE = \"\"\n RED_ENVELOPE_RAIN_START_DATE_STR = \"\"\n RED_ENVELOPE_RAIN_END_DATE = \"\"\n RED_ENVELOPE_RAIN_END_DATE_STR = \"\"\n PURCHASE_URL = \"\"\n\n @classmethod\n def get_file_text(cls):\n \"\"\"\n 查看文件是否被改变, 如果改变了,重新读取;否则用原来的数据\n \"\"\"\n modified_time = os.path.getmtime(REDENVELOPE_CONFIGURATION_FILE_PATH)\n # Logs.print_log(\"modified_time\", modified_time)\n if cls.modified_time is not None and cls.modified_time == modified_time:\n return cls.text\n else:\n cls.modified_time = modified_time\n cls.text = Xmls.get_text(REDENVELOPE_CONFIGURATION_FILE_PATH)\n\n @classmethod\n def get_file_root(cls):\n cls.get_file_text()\n cls.root = Xmls.get_root(cls.text)\n\n @classmethod\n def set_red_envelope_configuration(cls):\n try:\n cls.get_file_root()\n redenvelope = Xmls.get_all_sub_nodes(cls.root, REDENVELOPE_NAME)[0]\n cls.RED_ENVELOPE_FACTOR = int(Xmls.get_node_attribute_value(redenvelope, REDENVELOPE_ATTRIBUTE_FACTOR))\n cls.RED_ENVELOPE_PERSON_THRESHOLD = float(\n Xmls.get_node_attribute_value(redenvelope, REDENVELOPE_ATTRIBUTE_THRESHOLD))\n cls.RED_ENVELOPE_BY_DEVICE = float(Xmls.get_some_node_text(redenvelope, REDENVELOPE_DEVICE_BONUS_PATH))\n\n cls.RED_ENVELOPE_EXTRA_POSSIBILITY = float(\n Xmls.get_some_node_text(redenvelope, REDENVELOPE_EXTRA_POSSIBILITY_PATH))\n cls.RED_ENVELOPE_EXTRA_THRESHOLD = float(\n Xmls.get_some_node_text(redenvelope, REDENVELOPE_EXTRA_THRESHOLD_PATH))\n cls.RED_ENVELOPE_EXTRA_MIN = float(Xmls.get_some_node_text(redenvelope, REDENVELOPE_EXTRA_MIN_PATH))\n cls.RED_ENVELOPE_EXTRA_MAX = float(Xmls.get_some_node_text(redenvelope, REDENVELOPE_EXTRA_MAX_PATH))\n cls.RED_ENVELOPE_EXTRA_KEEP = float(Xmls.get_some_node_text(redenvelope, REDENVELOPE_EXTRA_KEEP_PATH))\n cls.RED_ENVELOPE_RAIN_POSSIBILITY = float(\n Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_POSSIBILITY_PATH))\n cls.RED_ENVELOPE_RAIN_THRESHOLD = float(\n Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_THRESHOLD_PATH))\n cls.RED_ENVELOPE_RAIN_MIN = float(Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_MIN_PATH))\n cls.RED_ENVELOPE_RAIN_MAX = float(Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_MAX_PATH))\n # time_format = \"%H:%M:%S\"\n cls.RED_ENVELOPE_RAIN_START_STR = Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_START_TIME_PATH)\n cls.RED_ENVELOPE_RAIN_START = Datetimes.string_to_time(\n Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_START_TIME_PATH))\n cls.RED_ENVELOPE_RAIN_END_STR = Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_END_TIME_PATH)\n cls.RED_ENVELOPE_RAIN_END = Datetimes.string_to_time(\n Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_END_TIME_PATH))\n cls.RED_ENVELOPE_RAIN_COUNT = int(Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_COUNT_PATH))\n\n week = Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_WEEK_PATH)\n cls.RED_ENVELOPE_RAIN_WEEK_STR = week\n if week:\n cls.RED_ENVELOPE_RAIN_WEEK = week.split(\",\")\n else:\n cls.RED_ENVELOPE_RAIN_WEEK = []\n cls.RED_ENVELOPE_RAIN_WEEK_STR = \"\"\n # date_format = \"%Y:%m:%d\"\n start_date = Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_START_DATE_PATH)\n cls.RED_ENVELOPE_RAIN_START_DATE_STR = start_date\n if start_date:\n cls.RED_ENVELOPE_RAIN_START_DATE = Datetimes.string_to_date(start_date)\n else:\n cls.RED_ENVELOPE_RAIN_START_DATE = \"\"\n cls.RED_ENVELOPE_RAIN_START_DATE_STR = \"\"\n end_date = Xmls.get_some_node_text(redenvelope, REDENVELOPE_RAIN_END_DATE_PATH)\n cls.RED_ENVELOPE_RAIN_END_DATE_STR = end_date\n if end_date:\n cls.RED_ENVELOPE_RAIN_END_DATE = Datetimes.string_to_date(end_date)\n else:\n cls.RED_ENVELOPE_RAIN_END_DATE = \"\"\n cls.RED_ENVELOPE_RAIN_END_DATE_STR = \"\"\n\n purchase = Xmls.get_all_sub_nodes(cls.root, PURCHASE_NAME)[0]\n url = Xmls.get_some_node_text(purchase, PURCHASE_URL)\n if url:\n cls.PURCHASE_URL = url\n else:\n cls.PURCHASE_URL = \"\"\n except Exception as ex:\n Logs.print_current_function_name_and_line_number(ex)\n return False\n return True\n\n @classmethod\n def set_node_attribute(cls, root, path, key, value):\n try:\n node = Xmls.get_the_first_node(root, path)\n Xmls.set_node_attribute(node, key, value)\n return True\n except Exception as ex:\n Logs.print_current_function_name_and_line_number(ex)\n return False\n\n @classmethod\n def set_node_text(cls, root, path, text):\n try:\n node = Xmls.get_the_first_node(root, path)\n Xmls.set_node_text(node, text)\n return True\n except Exception as ex:\n Logs.print_current_function_name_and_line_number(ex)\n return False\n\n @classmethod\n def modify_configuration(cls, new_items):\n root = Xmls.parse_xml(REDENVELOPE_CONFIGURATION_FILE_PATH)\n if root:\n pass\n else:\n return False\n for k, v in new_items.iteritems():\n try:\n if k == \"factor\":\n cls.set_node_attribute(root, REDENVELOPE_NAME, k, v)\n elif k == \"person_threshold\":\n cls.set_node_attribute(root, REDENVELOPE_NAME, k, v)\n\n elif k == \"device_bonus\":\n cls.set_node_text(root, REDENVELOPE_DEVICE_BONUS_PATH, v)\n\n elif k == \"extra_possibility\":\n cls.set_node_text(root, REDENVELOPE_EXTRA_POSSIBILITY_PATH, v)\n elif k == \"extra_threshold\":\n cls.set_node_text(root, REDENVELOPE_EXTRA_THRESHOLD_PATH, v)\n elif k == \"extra_max\":\n cls.set_node_text(root, REDENVELOPE_EXTRA_MAX_PATH, v)\n elif k == \"extra_min\":\n cls.set_node_text(root, REDENVELOPE_EXTRA_MIN_PATH, v)\n elif k == \"extra_keep\":\n cls.set_node_text(root, REDENVELOPE_EXTRA_KEEP_PATH, v)\n\n elif k == \"rain_possibility\":\n cls.set_node_text(root, REDENVELOPE_RAIN_POSSIBILITY_PATH, v)\n elif k == \"rain_threshold\":\n cls.set_node_text(root, REDENVELOPE_RAIN_THRESHOLD_PATH, v)\n elif k == \"rain_max\":\n cls.set_node_text(root, REDENVELOPE_RAIN_MAX_PATH, v)\n elif k == \"rain_min\":\n cls.set_node_text(root, REDENVELOPE_RAIN_MIN_PATH, v)\n\n elif k == \"rain_start\":\n cls.set_node_text(root, REDENVELOPE_RAIN_START_TIME_PATH, v)\n elif k == \"rain_end\":\n cls.set_node_text(root, REDENVELOPE_RAIN_END_TIME_PATH, v)\n elif k == \"rain_count\":\n cls.set_node_text(root, REDENVELOPE_RAIN_COUNT_PATH, v)\n\n elif k == \"rain_week\":\n cls.set_node_text(root, REDENVELOPE_RAIN_WEEK_PATH, v)\n elif k == \"rain_start_date\":\n cls.set_node_text(root, REDENVELOPE_RAIN_START_DATE_PATH, v)\n elif k == \"rain_end_date\":\n cls.set_node_text(root, REDENVELOPE_RAIN_END_DATE_PATH, v)\n elif k == \"purchase_url\":\n cls.set_node_text(root, PURCHASE_URL, v)\n except Exception as ex:\n Logs.print_current_function_name_and_line_number(ex)\n\n root.write(REDENVELOPE_CONFIGURATION_FILE_PATH)\n return True\n\n @classmethod\n def get_configuration(cls):\n cls.set_red_envelope_configuration()\n redenvelope = dict()\n redenvelope[\"factor\"] = cls.RED_ENVELOPE_FACTOR\n redenvelope[\"person_threshold\"] = cls.RED_ENVELOPE_PERSON_THRESHOLD\n redenvelope[\"device_bonus\"] = cls.RED_ENVELOPE_BY_DEVICE\n redenvelope[\"extra_possibility\"] = cls.RED_ENVELOPE_EXTRA_POSSIBILITY\n redenvelope[\"extra_threshold\"] = cls.RED_ENVELOPE_EXTRA_THRESHOLD\n redenvelope[\"extra_min\"] = cls.RED_ENVELOPE_EXTRA_MIN\n redenvelope[\"extra_max\"] = cls.RED_ENVELOPE_EXTRA_MAX\n redenvelope[\"extra_keep\"] = cls.RED_ENVELOPE_EXTRA_KEEP\n redenvelope[\"rain_possibility\"] = cls.RED_ENVELOPE_RAIN_POSSIBILITY\n redenvelope[\"rain_threshold\"] = cls.RED_ENVELOPE_RAIN_THRESHOLD\n redenvelope[\"rain_min\"] = cls.RED_ENVELOPE_RAIN_MIN\n redenvelope[\"rain_max\"] = cls.RED_ENVELOPE_RAIN_MAX\n redenvelope[\"rain_start\"] = cls.RED_ENVELOPE_RAIN_START_STR\n redenvelope[\"rain_end\"] = cls.RED_ENVELOPE_RAIN_END_STR\n redenvelope[\"rain_count\"] = cls.RED_ENVELOPE_RAIN_COUNT\n redenvelope[\"rain_week\"] = cls.RED_ENVELOPE_RAIN_WEEK_STR\n redenvelope[\"rain_start_date\"] = cls.RED_ENVELOPE_RAIN_START_DATE_STR\n redenvelope[\"rain_end_date\"] = cls.RED_ENVELOPE_RAIN_END_DATE_STR\n redenvelope[\"purchase_url\"] = cls.PURCHASE_URL\n return redenvelope\n\n @classmethod\n def print_configuration(cls):\n pass\n # print cls.RED_ENVELOPE_FACTOR\n # print cls.RED_ENVELOPE_PERSON_THRESHOLD\n # print cls.RED_ENVELOPE_BY_DEVICE\n # print cls.RED_ENVELOPE_EXTRA_POSSIBILITY\n # print cls.RED_ENVELOPE_EXTRA_THRESHOLD\n # print cls.RED_ENVELOPE_EXTRA_MIN\n # print cls.RED_ENVELOPE_EXTRA_MAX\n # print cls.RED_ENVELOPE_EXTRA_KEEP\n # print cls.RED_ENVELOPE_RAIN_POSSIBILITY\n # print cls.RED_ENVELOPE_RAIN_THRESHOLD\n # print cls.RED_ENVELOPE_RAIN_MIN\n # print cls.RED_ENVELOPE_RAIN_MAX\n # print cls.RED_ENVELOPE_RAIN_START\n # print cls.RED_ENVELOPE_RAIN_END\n # print cls.RED_ENVELOPE_RAIN_COUNT\n # print cls.RED_ENVELOPE_RAIN_WEEK\n # print cls.RED_ENVELOPE_RAIN_START_DATE\n # print cls.RED_ENVELOPE_RAIN_END_DATE\n # print cls.PURCHASE_URL\n","sub_path":"xiuxiu_api/server/project/eye/common/red_envelope_configuration.py","file_name":"red_envelope_configuration.py","file_ext":"py","file_size_in_byte":12457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"227045723","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django_extensions.db.fields.json\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('contenttypes', '0002_remove_content_type_name'),\n ('data_importer', '0002_auto_20151125_1354'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CrossValidationResult',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('created', models.DateTimeField(verbose_name='date created', auto_now_add=True)),\n ('modified', models.DateTimeField(verbose_name='last modified', auto_now=True)),\n ('object_pk', models.IntegerField(db_index=True)),\n ('diff', django_extensions.db.fields.json.JSONField()),\n ('errors', django_extensions.db.fields.json.JSONField()),\n ('content_type', models.ForeignKey(to='contenttypes.ContentType')),\n ('old', models.ForeignKey(to='data_importer.ImportedObjects', null=True)),\n ],\n options={\n 'ordering': ('-modified', '-created'),\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='CrossValidationRun',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('created', models.DateTimeField(verbose_name='date created', auto_now_add=True)),\n ('modified', models.DateTimeField(verbose_name='last modified', auto_now=True)),\n ('checked_count', models.PositiveIntegerField(default=0)),\n ('invalid_count', models.PositiveIntegerField(default=0)),\n ('valid_count', models.PositiveIntegerField(default=0)),\n ],\n options={\n 'ordering': ('-modified', '-created'),\n 'abstract': False,\n },\n ),\n migrations.AddField(\n model_name='crossvalidationresult',\n name='run',\n field=models.ForeignKey(to='cross_validator.CrossValidationRun'),\n ),\n ]\n","sub_path":"src/ralph/cross_validator/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"151420415","text":"import pandas as pd\r\nimport numpy as np\r\nimport re\r\nimport pickle\r\n\r\nbankdata = pd.read_csv('D:\\\\data_science _data _set\\\\Loan_prediction\\\\final_source_data\\\\train.csv')\r\n\r\n#Train data\r\n#bankdata6.shape #o/p:(104999, 27)\r\ntrndt1 = bankdata.copy()\r\n#trndt1.shape #(104999, 27)\r\ntrndt1.head(10)\r\n\r\n#EDA for Train DATA\r\ntrndt1.shape #(104999, 27)\r\n#Found no duplicates in the dataframe\r\nany(trndt1.duplicated()) #o/p:False\r\n#Found duplicate records in all the columns of the dataframe\r\n#any(trndt1['Name'].duplicated()) #o/p:True\r\n#any(trndt1['ChgOffPrinGr'].duplicated()) #o/p:True\r\n#Number of missing/null values in the data\r\ntrndt1.isnull().sum()\r\n#Observed Null values in the following columns with their count:\r\n#Bank=111,BankState=112,RevLineCr=14,ChgOffDate=76722,DisbursementDate=156,MIS_Status=615\r\n\r\n#Removing null values from Train data\r\ntrndt1 = trndt1.dropna(axis=0,subset = ['Name','City','State','Bank','BankState','RevLineCr','DisbursementDate','MIS_Status'])\r\n#trndt1.isnull().sum() #o/p:only in ChgOffDate column:76035 na values are present now\r\n#After removing na values\r\n#trndt1.shape #o/p:(104145, 27)\r\ntrndt1.head(1)\r\n\r\n#Dropping unnecessary columns from Train Dataset\r\n#Dropping 'Unnamed: 0' column(as it is unnecessary for our analysis),and 'ChgOffDate' column as it has more than 75% missing data,from the Dataframe\r\ntrndt1.drop(columns = ['Unnamed: 0','ChgOffDate'], axis=1, inplace=True)\r\ntrndt1.shape #o/p:(104145, 25)\r\n\r\n#Train Data\r\n#converting MIS_Status column to numeric\r\n#trndt1.MIS_Status.value_counts()\r\n#o/p:P I F 76962\r\n#CHGOFF 27183\r\n#Name: MIS_Status, dtype: int64\r\ntrndt1['MIS_Status'] = trndt1['MIS_Status'].apply(lambda x: 1 if x == 'CHGOFF' else 0)\r\n#trndt1.MIS_Status.value_counts()\r\n#o/p:1 76962\r\n#0 27183\r\n#Name: MIS_Status, dtype: int64\r\ntrndt1.head(1)\r\n\r\n#Train Data\r\ntrndt1['MIS_Status'].value_counts(normalize=True)\r\ntrndt1['MIS_Status'].value_counts()\r\n#1 0.261011\r\n#Name: MIS_Status, dtype: float64\r\n\r\n#From Train Data removing the dollar sign and converting the following columns to numeric \r\ntrndt1[['DisbursementGross','BalanceGross','ChgOffPrinGr','GrAppv','SBA_Appv']] = trndt1[['DisbursementGross','BalanceGross','ChgOffPrinGr','GrAppv','SBA_Appv']].replace('[\\$,]','',regex=True).astype(float)\r\n#trndt1.head(1)\r\ntrndt1[['DisbursementGross','BalanceGross','ChgOffPrinGr','GrAppv','SBA_Appv']] = trndt1[['DisbursementGross','BalanceGross','ChgOffPrinGr','GrAppv','SBA_Appv']].astype(int)\r\ntrndt1.head(1)\r\n\r\n\r\n#In Train Data,converting the ApprovalDate column to numeric\r\ntrndt1['Approval_Date'],trndt1['Approval_Month'],trndt1['Approval_Year']=trndt1['ApprovalDate'].str.split('-',2).str\r\n#trndt1[['ApprovalDate','Approval_Date','Approval_Month','Approval_Year']].head(1)\r\n#converting the month names to month numbers in Approval Date column\r\nmonth_numbers = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07','Aug': '08','Sep': '09','Oct': '10','Nov': '11','Dec': '12'}\r\nfor k, v in month_numbers.items(): \r\n trndt1['Approval_Month'] = trndt1['Approval_Month'].replace(k, v)\r\n#trndt1['Approval_Month'].head(1)\r\n#concatenating all the 3 columns which are in numeric form as a single New column and checking it's datatype\r\ntrndt1['Approval_NewDate'] = trndt1[['Approval_Date','Approval_Month','Approval_Year']].apply(lambda x: ''.join(x),axis=1)\r\n#trndt1[['ApprovalDate','Approval_NewDate']].head(1)\r\n#trndt1['Approval_NewDate'].dtypes #o/p:dtype('O')\r\n#converting the newly created column from object(string) to int and checking it's datatype\r\ntrndt1['Approval_Date'] = trndt1['Approval_Date'].astype(int)\r\n#trndt1['Approval_Date'].dtypes\r\ntrndt1['Approval_Month'] = trndt1['Approval_Month'].astype(int)\r\n#trndt1['Approval_Month'].dtypes\r\ntrndt1['Approval_Year'] = trndt1['Approval_Year'].astype(int)\r\n#trndt1['Approval_Year'].dtypes\r\ntrndt1['Approval_NewDate'] = trndt1['Approval_NewDate'].astype(int)\r\ntrndt1['Approval_NewDate'].dtypes #o/p:dtype('int64')\r\n\r\n#In Train Data,converting the DisbursementDate column to numeric\r\ntrndt1['DisbursementDate'] = trndt1['DisbursementDate'].replace(0, np.NaN)\r\ntrndt1['Disbursement_Date'],trndt1['Disbursement_Month'],trndt1['Disbursement_Year']=trndt1['DisbursementDate'].str.split('-',2).str\r\n#trndt1[['DisbursementDate','Disbursement_Date','Disbursement_Month','Disbursement_Year']].head(1)\r\n#converting the month names to month numbers in Disbursement Date column\r\nmonth_numbers = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07','Aug': '08','Sep': '09','Oct': '10','Nov': '11','Dec': '12'}\r\nfor k, v in month_numbers.items(): \r\n trndt1['Disbursement_Month'] = trndt1['Disbursement_Month'].replace(k, v)\r\n#trndt1['Disbursement_Month'].head(1)\r\n#concatenating all the 3 columns which are in numeric form as a single New column and checking it's datatype\r\ntrndt1['Disbursement_NewDate'] = trndt1[['Disbursement_Date','Disbursement_Month','Disbursement_Year']].apply(lambda x: ''.join(x),axis=1)\r\n#trndt1[['DisbursementDate','Disbursement_NewDate']].head(1)\r\n#o/p:DisbursementDate\tDisbursement_Date1\r\n#0\t 31-Jul-98\t 310798\r\ntrndt1['Disbursement_NewDate'].dtypes #o/p:dtype('O')\r\n#converting the newly created column from object(string) to int and checking it's datatype\r\ntrndt1['Disbursement_Date'] = trndt1['Disbursement_Date'].astype(int)\r\n#trndt1['Disbursement_Date'].dtypes \r\ntrndt1['Disbursement_Month'] = trndt1['Disbursement_Month'].astype(int)\r\n#trndt1['Disbursement_Month'].dtypes\r\ntrndt1['Disbursement_Year'] = trndt1['Disbursement_Year'].astype(int)\r\n#trnd1['Disbursement_Year'].dtypes \r\ntrndt1['Disbursement_NewDate'] = trndt1['Disbursement_NewDate'].astype(int)\r\ntrndt1['Disbursement_NewDate'].dtypes #o/p:dtype('int64')\r\n\r\n\r\n\r\n#Train Data\r\ntrndt1.shape #o/p:(104145, 33)\r\n#trndt1.dtypes\r\n#trndt1.info() #o/p:dtypes: int64(23), object(9)\r\n\r\n#listendata woe and iv article coding\r\n#After removing null values and removing a column('chgoffdate') as it has more than 75% missing data\r\n#After converting $ columns,ApprovalDate and DisbursementDate columns to numeric \r\n##checking for woe and iv \r\ndef iv18_woe18(data, target, bins=10, show_woe=False):\r\n \r\n #Empty Dataframe\r\n newDF64,newDF65,newDF66,newDF67,woeivDF18 = pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), pd.DataFrame(), pd.DataFrame()\r\n \r\n #Extract Column Names\r\n cols = data.columns\r\n \r\n #Run WOE and IV on all the independent variables\r\n for ivars in cols[~cols.isin([target])]:\r\n if (data[ivars].dtype.kind in 'bifc') and (len(np.unique(data[ivars]))>10):\r\n binned_x = pd.qcut(data[ivars], bins, duplicates='drop')\r\n d0 = pd.DataFrame({'x': binned_x, 'y': data[target]})\r\n else:\r\n d0 = pd.DataFrame({'x': data[ivars], 'y': data[target]})\r\n d = d0.groupby(\"x\", as_index=False).agg({\"y\": [\"count\", \"sum\"]})\r\n d.columns = ['Cutoff', 'N', 'Events']\r\n d['% of Events'] = np.maximum(d['Events'], 0.5) / d['Events'].sum()\r\n d['Non-Events'] = d['N'] - d['Events']\r\n d['% of Non-Events'] = np.maximum(d['Non-Events'], 0.5) / d['Non-Events'].sum()\r\n d['WoE_18'] = np.log(d['% of Events']/d['% of Non-Events'])\r\n d['IV_18'] = d['WoE_18'] * (d['% of Events'] - d['% of Non-Events'])\r\n d.insert(loc=0, column='Variable', value=ivars)\r\n print(\"Information value of \" + ivars + \" is \" + str(round(d['IV_18'].sum(),6)))\r\n print(\"Weight Of Evidence of \" + ivars + \" is \" + str(round(d['WoE_18'].sum(),6)))\r\n temp_9 =pd.DataFrame({\"Variable\" : [ivars], \"IV_18\" : [d['IV_18'].sum()]}, columns = [\"Variable\", \"IV_18\"])\r\n tempWOE_18 =pd.DataFrame({\"variable\" : [ivars], \"WoE_18\" : [d['WoE_18'].sum()]}, columns = [\"variable\", \"WoE_18\"])\r\n tempIV_18 =pd.DataFrame({\"variable\" : [ivars], \"IV_18\" : [d['IV_18'].sum()]}, columns = [\"variable\", \"IV_18\"]) \r\n tempIVWOE_18 =pd.DataFrame({\"variable\" : [ivars], \"IV_18\" : [d['IV_18'].sum()], \"WoE_18\" : [d['WoE_18'].sum()]}, columns = [\"variable\", \"IV_18\", \"WoE_18\"])\r\n\r\n newDF64=pd.concat([newDF64,temp_9], axis=0)\r\n newDF65=pd.concat([newDF65,tempWOE_18], axis=0)\r\n newDF66=pd.concat([newDF66,tempIV_18], axis=0)\r\n newDF67=pd.concat([newDF67,tempIVWOE_18], axis=0)\r\n woeivDF18=pd.concat([woeivDF18,d], axis=0)\r\n ##newDF3=pd.concat([newDF3,tempWOE], axis=0)\r\n #woeivDF1=pd.concat([woeivDF1,d], axis=0)\r\n\r\n #Show WOE Table\r\n if show_woe == True:\r\n print(d)\r\n return newDF64,newDF65,newDF66,newDF67,woeivDF18\r\n\r\nfinal_18,woe_18,iv_18,IvWoe_18,woeiv_18 = iv18_woe18(data = trndt1, target = 'MIS_Status', bins=10, show_woe = True)\r\nfinal_18\r\n#print(woe_18)\r\n#print(iv_18)\r\n#print(IvWoe_18)\r\n#print(woeiv_18)\r\n\r\ntype(final_18) #o/p:pandas.core.frame.DataFrame\r\n\r\n#Weight of Evidence(WOE):\r\n#11-columns with +ve WOE:Name,City,DisbursementDate,ApprovalDate,ChgOffPrinGr,RetainedJob,RevLineCr,CCSC,BalanceGross,CreateJob,Disbursement_Month.\r\n#21-columns with _ve WOE:Approval_NewDate,Approval_Date,Approval_Month,Zip,Disbursement_NewDate,Disbursement_Date,DisbursementGross,NoEmp,FranschiseCode,\r\n#UrbanRural,ApprovalFY,Term,GrAppv,SBA_Appv,Approval_Year,NewExist,LowDoc,Disbursement_Year,State,BankState,Bank.\r\nwoe_18.sort_values(by='WoE_18',ascending=False)\r\n\r\n#INFORMATION VALUE(IV):\r\n##Rules related to Information Value\r\n#Information Value\t Variable Predictiveness columns\r\n#Less than 0.02\t Not useful for prediction BalanceGross,Approval_NewDate,Approval_Date,Disbursement_Month,NewExist,FranchiseCode,Approval_Month,Disbursement_Date(8)\r\n#0.02 to 0.1\t Weak predictive Power CreateJob,Disbursement_NewDate,Zip,NoEmp,State,DisbursementGross,CCSC(7)\r\n#0.1 to 0.3\t Medium predictive Power LowDoc,GrAppv,RetainedJob,SBA_Appv,RevLineCr(5)\r\n#0.3 to 0.5\t Strong predictive Power BankState,UrbanRural,Approval_Year,ApprovalFY,Disbursement_Year(5)\r\n#>0.5\t Suspicious Predictive Power City,Bank,ApprovalDate,DisbursementDate,Name,Term,ChgOffPrinGr(7)\r\n\r\n##predictors\r\n#not considering:notuseful(8)+weak(7) = Total = 15\r\n#considering:medium(5)+strong(5) = Total = 10\r\n#if we consider:suspicious(7) = Total = 10+7 = 17\r\n#or else(medium+strong=5+5=10)\r\niv_18.sort_values(by='IV_18',ascending=False)\r\n\r\nIvWoe_18.sort_values(by='WoE_18',ascending=False)\r\n\r\nIvWoe_18.sort_values(by='IV_18',ascending=False)\r\n\r\nwoeiv_18 #o/p:120074 rows × 9 columns\r\n\r\n#Train Data\r\ntrndt2 = trndt1.copy()\r\ntrndt2.shape #o/p:(104145, 33)\r\n\r\n##Based on Information Value Interpretation choosen the following columns for model building\r\n#Information Value Variable Predictiveness Columns\r\n#0.1 to 0.3\t Medium predictive Power LowDoc,GrAppv,RetainedJob,SBA_Appv,RevLineCr(5)\r\n#0.3 to 0.5\t Strong predictive Power BankState,UrbanRural,Approval_Year,ApprovalFY,Disbursement_Year(5)\r\n\r\n#In Train Data,converting the categorical columns 'BankState','RevLineCr','LowDoc' into numeric by using label encoder\r\ntrndt1.BankState.value_counts()\r\ntrndt1.BankState.value_counts().count() #o/p:52\r\n\r\n#Train Data\r\nfrom sklearn.preprocessing import LabelEncoder\r\nle_0 = LabelEncoder()\r\n# Encode labels in column 'BankState'\r\n## instantiate an encoder - here we use labelencoder()\r\ntrndt1[\"BankState\"] = trndt1[\"BankState\"].astype(str)\r\ntrndt1['BankState_code']= le_0.fit_transform(trndt1['BankState'])\r\ntrndt1[['BankState_code','BankState']]\r\ntrndt1.head(1)\r\n\r\n#Train Data\r\ntrndt1[\"RevLineCr\"].value_counts()\r\n#trndt1[\"RevLineCr\"].value_counts().count() #o/p:7\r\n\r\n#Train Data\r\n#from sklearn.preprocessing import LabelEncoder\r\nle_1 = LabelEncoder()\r\n# Encode labels in column 'RevLineCr'\r\n## instantiate an encoder - here we use labelencoder()\r\ntrndt1[\"RevLineCr\"] = trndt1[\"RevLineCr\"].astype(str)\r\ntrndt1['RevLineCr_code']= le_1.fit_transform(trndt1['RevLineCr'])\r\ntrndt1.head(1)\r\n\r\n#Train Data\r\ntrndt1[\"LowDoc\"].value_counts()\r\n#trndt1[\"LowDoc\"].value_counts().count() #o/p:4\r\n\r\n#Train Data\r\n#from sklearn.preprocessing import LabelEncoder\r\nle_2 = LabelEncoder()\r\n# Encode labels in column 'LowDoc'\r\n## instantiate an encoder - here we use labelencoder()\r\ntrndt1[\"LowDoc\"] = trndt1[\"LowDoc\"].astype(str)\r\ntrndt1['LowDoc_code']= le_2.fit_transform(trndt1['LowDoc'])\r\ntrndt1.head(1)\r\n\r\n\r\n#Train Data\r\n#Scaling the numerical columns before building the model\r\nfrom sklearn import preprocessing\r\nscaler = preprocessing.MinMaxScaler()\r\ntrndt1[['GrAppv', 'SBA_Appv']] = scaler.fit_transform(trndt1[['GrAppv', 'SBA_Appv']])\r\ntrndt1.head(2)\r\n\r\n#Train Data\r\n#After scaling the numerical variable columns save as copy\r\ntrndt4 = trndt1.copy()\r\ntrndt4.shape #o/p:(104145, 36)\r\n#trndt4.info() \r\n#The scaled 2-numerical variables have a data type:float \r\n#o/p:dtypes: float64(2), int64(25), object(9)\r\n\r\n#Train Data\r\n#selecting the columns based on Information Value\r\n#medium predictors-LowDoc,GrAppv,RetainedJob,SBA_Appv,RevLineCr\r\n#strong predictors-BankState,UrbanRural,Approval_Year,ApprovalFY,Disbursement_Year\r\ntrndt1.head(1)\r\n\r\n#Train Data\r\n#Remove the columns as they are not required for analysis \r\ntrndt1.drop(trndt1.columns[[0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 14, 16, 17, 18, 19, 20, 22, 25, 26, 28, 29, 30, 32]], axis = 1, inplace = True)\r\n\r\n#Train Data\r\n#After retaining the medium and strong predictive columns based on information value\r\ntrndt1.head(1)\r\n\r\n#Train Data\r\n#trndt1.shape #o/p:(104145, 11)\r\n#trndt1.info() #o/p:dtypes: float64(2), int64(9)\r\ntrndt5 = trndt1.copy()\r\ntrndt5.shape #o/p:(104145, 11)\r\n#trndt5.info() #o/p:dtypes: float64(2), int64(9)\r\n\r\n#trndt4.shape #(104145, 36)\r\n#testdt4.shape # (44900, 35)\r\ntrndt4.info() #o/p:dtypes: float64(2), int64(25), object(9)\r\n\r\n\r\n# Separate input features (X) and target variable (y)\r\nX_train_Features = trndt1.drop('MIS_Status', axis=1)\r\ny_train_label = trndt1.MIS_Status\r\n\r\n# import SMOTE module from imblearn library\r\nfrom imblearn.over_sampling import SMOTE \r\nsm = SMOTE(random_state = 2) \r\nX_train_Features_sm_1, y_train_label_sm_1 = sm.fit_sample(X_train_Features, y_train_label.ravel()) \r\n\r\nX_train_Features_sm_1.columns\r\n\r\n#Decision Tree Model\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.metrics import accuracy_score,precision_score,recall_score,classification_report,confusion_matrix,roc_auc_score,roc_curve,auc\r\n# Create DecisionTree model\r\nclf_DT = DecisionTreeClassifier()\r\nclf_DT.fit(X_train_Features_sm_1, y_train_label_sm_1)\r\n# Train model and make predictions\r\npred_y_1 = clf_DT.predict(X_train_Features_sm_1)\r\nconfusion_matrix(y_train_label_sm_1,pred_y_1)\r\n\r\n\r\nprint(\"classification_report_DT:\\n\", classification_report(y_train_label_sm_1,pred_y_1))\r\n\r\n\r\nprint(\"AUC&ROC_DT:\", roc_auc_score(y_train_label_sm_1,pred_y_1 ))\r\n#o/p:AUC&ROC_DT: 0.8110519204972385\r\n\r\n# Saving model to disk\r\n\r\npickle.dump(clf_DT, open('model.pkl','wb'))\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"model_train.py","file_name":"model_train.py","file_ext":"py","file_size_in_byte":15137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"476348972","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport xlrd\nimport csv\nimport os\n\nfrom datetime import date, datetime\n\n# In[23]:\n\ndef open_excel(file):\n\tprint(file.title())\n\tif file.title().startswith('Excel_Data/~$'):\n\t\t# print('Wrong')\n\t\treturn ['Wrong']\n\twb = xlrd.open_workbook(filename=file)\n\t# print(wb.sheet_names())\n\tsheets = wb.sheets()\n\t# sheet = wb.sheet_by_index(idx)\n\t# print(sheet)\n\n\t# print(sheet.row_values(0))\n\treturn sheets\n\n# In[88]:\ndef create_csv(sheet, prefix, prev_path):\n\tappend_csv_flag = False\n\tfor i in range(0, sheet.nrows):\n\t\ttitle = sheet.row_values(i)[0]\n\t\t# print(title)\n\t\t# print(sheet.row_values(i+2))\n\t\tpath = ''\n\t\tif title is not None and title.startswith('University'):\n\t\t\tpath = title\n\t\t\tif path == 'University of California, San Diego Survey of Parking Space Occupancy Levels':\n\t\t\t\tpath = sheet.row_values(i+1)[0].replace(':','_').replace(' ', '_')\n\t\t\t\t# print(path)\n\t\t\telse:\n\t\t\t\tpath = path.split(\"University of California, San Diego Survey of Parking Space Occupancy Levels \")[1].replace(':','_').replace(' ', '_')\n\t\t\t# print(path)\n\t\t\tbreak\n\tif path != '':\n\t\tpath = prefix + path + \".csv\"\n\t\tprev_path = path\n\t\t# print(path + \"--------------------------------\")\n\telse:\n\t\tpath = prev_path\n\t\tappend_csv_flag = True\n\t\t# print(path + \"--------------------------------\")\n\twith open(path, 'a', newline='') as f:\n\t\tcsv_write = csv.writer(f)\n\t\tcsv_head = [\"year\", \"quarter\", \"parking_spaces\", \"8am\", \"9am\", \"10am\", \"11am\", \"12pm\", \"1pm\", \"2pm\", \"3pm\",\n\t\t\t\t\t\"4pm\", \"5pm\", \"peak_empty_spaces\", \"peak_occupied_spaces\", \"%_occupied\"]\n\t\tif not append_csv_flag:\n\t\t\tcsv_write.writerow(csv_head)\n\t\tfor i in range(sheet.nrows):\n\t\t\ts = sheet.row_values(i)\n\t\t\tstart_word = s[2] if isinstance(s[2], str) and s[1] == '' else s[1]\n\t\t\t# print(start_word)\n\t\t\tif start_word.startswith('Summer') and len(start_word) > 15:\n\t\t\t\thandleCornerCase(csv_write, s)\n\t\t\t\tcontinue\n\n\t\t\tfall_list = list()\n\t\t\twinter_list = list()\n\n\t\t\tif start_word.startswith('Summer'):\n\t\t\t\tnext_row = sheet.row_values(i + 1)\n\t\t\telif start_word.startswith('Spring'):\n\t\t\t\tnext_row = sheet.row_values(i - 1)\n\t\t\telif start_word.startswith('Fall'):\n\t\t\t\tnext_row = sheet.row_values(i)\n\t\t\t\tfall_list.append(next_row[0])\n\t\t\t\twinter_list.append(next_row[0])\n\n\t\t\t\tfor idx, i in enumerate(s):\n\t\t\t\t\tif i != '':\n\t\t\t\t\t\tpattern = list()\n\t\t\t\t\t\tif isinstance(i, str):\n\t\t\t\t\t\t\tpattern = i.split('\\n')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpattern = [i for x in range(4)]\n\t\t\t\t\t\tif len(pattern) == 2:\n\t\t\t\t\t\t\tif idx == len(s) - 1:\n\t\t\t\t\t\t\t\tpattern = [float(i.strip('%')) / 100.0 for i in pattern]\n\t\t\t\t\t\t\tfall_list.append(pattern[0])\n\t\t\t\t\t\t\twinter_list.append(pattern[1])\n\t\t\telse:\n\t\t\t\tcontinue\n\t\t\tif len(fall_list) > 1:\n\t\t\t\tcsv_write.writerow(fall_list)\n\t\t\t\tcsv_write.writerow(winter_list)\n\t\t\t\tcontinue\n\t\t\tret_list = list()\n\t\t\tret_list.append(next_row[0])\n\t\t\tfor i in s:\n\t\t\t\tif i != '':\n\t\t\t\t\tret_list.append(i)\n\t\t\tcsv_write.writerow(ret_list)\n\treturn prev_path\n\n# In[86]:\ndef handleCornerCase(csv_write, s):\n\t# print('------------------')\n\tsummer_list = list()\n\tfall_list = list()\n\twinter_list = list()\n\tspring_list = list()\n\n\tif s[3] == '':\n\t\treturn\n\n\tfor i in range(len(s)):\n\t\tif i == 0:\n\t\t\tsummer_list.append(s[0])\n\t\t\tfall_list.append(s[0])\n\t\t\twinter_list.append(s[0])\n\t\t\tspring_list.append(s[0])\n\n\t\tif i > 1:\n\t\t\tpattern = list()\n\t\t\tif isinstance(s[i], str):\n\t\t\t\ttemp = s[i].replace('\\n', ' ')\n\t\t\t\tpattern = temp.split(' ')\n\t\t\t\tif len(pattern) == 1 and pattern[0] == '':\n\t\t\t\t\tcontinue\n\n\t\t\t\twhile len(pattern) != 4 and len(pattern) != 0:\n\t\t\t\t\ttemp_data = pattern[-1]\n\t\t\t\t\tpattern.append(temp_data)\n\t\t\telse:\n\t\t\t\tpattern = [s[i] for x in range(4)]\n\n\t\t\tif i == len(s) - 1 and isinstance(s[i], str):\n\t\t\t\tpattern = [float(i.strip('%')) / 100.0 if not (i == '#DIV/0!' or i == '') else 0.0 for i in pattern]\n\n\t\t\tif len(pattern) == 4:\n\n\t\t\t\tsummer_list.append(pattern[0])\n\t\t\t\tfall_list.append(pattern[1])\n\t\t\t\twinter_list.append(pattern[2])\n\t\t\t\tspring_list.append(pattern[3])\n\tcsv_write.writerow(summer_list)\n\tcsv_write.writerow(fall_list)\n\tcsv_write.writerow(winter_list)\n\tcsv_write.writerow(spring_list)\n\n\n# In[16]:\nif __name__ == '__main__':\n\tprefix = 'csv_data/'\n\texcel_location = 'excel_data/'\n\tfiles = os.listdir(excel_location)\n\n\t# for s in open_excel(excel_location + '3.1 Occupancy Scripps Institution Of Oceanography-Converted.Xlsx'):\n\t# \tcreate_csv(s, '', '')\n\n\n\tfor file in files:\n\t\tprev = ''\n\t\tfor sheet in open_excel(excel_location + file):\n\t\t\tif isinstance(sheet,str):\n\t\t\t\tbreak;\n\t\t\tfolder = ''\n\t\t\tif file.title().startswith('1'):\n\t\t\t\tfolder = prefix + 'University-wide/'\n\t\t\telif file.title().startswith('2'):\n\t\t\t\tfolder = prefix + 'By-Location/'\n\t\t\telif file.title().startswith('3'):\n\t\t\t\tfolder = prefix + 'By-Aera/'\n\t\t\telif file.title().startswith('4'):\n\t\t\t\tfolder = prefix + 'By-Neighborhood/'\n\t\t\tif not os.path.exists(folder):\n\t\t\t\tos.makedirs(folder)\n\t\t\tprev = create_csv(sheet, folder, prev)\n\n\n\n\t# print(open_excel('test1.xlsx')[-1].row_values(5)[1])\n\t# create_csv(open_excel('test1.xlsx')[-1])\n\n","sub_path":"DataExtraction.py","file_name":"DataExtraction.py","file_ext":"py","file_size_in_byte":4952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"653575789","text":"import argparse\nimport json\nimport os\nimport tempfile\n\n\nstorage_path = os.path.join(tempfile.gettempdir(), 'storage.data')\n\n\ndef clear():\n os.remove(storage_path)\n\n\ndef get_data():\n if not os.path.exists(storage_path):\n return {}\n\n with open(storage_path, 'r') as f:\n raw_data = f.read()\n if raw_data:\n return json.loads(raw_data)\n\n return {}\n\n\ndef put(key, value):\n data = get_data()\n if key in data:\n data[key].append(value)\n else:\n data[key] = [value]\n\n with open(storage_path, 'w') as f:\n f.write(json.dumps(data))\n\n\ndef get(key):\n data = get_data()\n return data.get(key)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--key', '-k', help='Key')\n parser.add_argument('--val', '-v', help='Value')\n parser.add_argument('--clear', action='store_true', help='Clear')\n\n args = parser.parse_args()\n\n if args.clear:\n clear()\n elif args.key and args.val:\n put(args.key, args.val)\n elif args.key:\n print(', '.join(get(args.key)))\n else:\n print('Wrong command')\n\n\n\"\"\"\nTAK suka pisat ne nado\ngde functons? gde structura coda?\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-k', '--key', help='a key')\nparser.add_argument('-v', '--value', help='a value to add to the key')\nargs = parser.parse_args()\n\nkey, value = args.key, args.value\n\nif value is None:\n if not os.path.isfile(storage_path):\n print(None)\n else:\n with open(storage_path, 'r') as f:\n kv = json.loads(f.read())\n\n if kv.get(key, None) is not None:\n print(', '.join(kv[key]))\n\nelse:\n kv = dict()\n if os.path.isfile(storage_path):\n with open(storage_path, 'r') as f:\n kv = json.loads(f.read())\n if kv.get(key, None) is None:\n kv[key] = [value]\n with open(storage_path, 'w') as f:\n json.dump(kv, f)\n else:\n kv[key].append(value)\n with open(storage_path, 'w') as f:\n json.dump(kv, f)\n\n else:\n with open(storage_path, 'w') as f:\n kv[key] = [value]\n json.dump(kv, f)\n \"\"\"\n","sub_path":"storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281511462","text":"from flask import Flask, jsonify, request, Response\nfrom models import db\nimport api\n\napp = Flask(__name__)\napp.config.from_object('config.DevelopmentConfig')\ndb.init_app(app)\n\n\n@app.route('/users', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n users = api.users()\n return jsonify(users=[row._asdict() for row in users])\n else:\n try:\n user = api.create_user_from_params(request.get_json())\n return jsonify(user=user._asdict())\n except:\n return Response(response='Unable to create user.',\n status=400,\n mimetype=\"application/json\")\n\n\n@app.route('/users/', methods=['GET'])\ndef get_user(userid):\n user = api.find_user(userid)\n\n if user is None:\n return Response(response='User not found.',\n status=404,\n mimetype=\"application/json\")\n\n if request.method == 'GET':\n return jsonify(user=user._asdict())\n\n\n@app.route('/users/', methods=['PUT'])\ndef update_user(userid):\n user = api.find_user(userid)\n\n try:\n user = api.update_user_from_params(user, request.get_json())\n\n return jsonify(user=user._asdict())\n except:\n return Response(response='Unable to update user.',\n status=400,\n mimetype=\"application/json\")\n\n\n@app.route('/users/', methods=['DELETE'])\ndef delete_user(userid):\n user = api.find_user(userid)\n\n try:\n api.destroy_user(user)\n return Response(response='Successfully deleted user.',\n status=200,\n mimetype=\"application/json\")\n except:\n return Response(response='Unable to delete user.',\n status=400,\n mimetype=\"application/json\")\n\n\n@app.route('/groups/', methods=['GET'])\ndef get_group(name):\n group = api.find_group(name)\n\n if group is None:\n return Response(response='Group not found.',\n status=404,\n mimetype=\"application/json\")\n\n if not group.users.all():\n return Response(response='Group has no associated users.',\n status=404,\n mimetype=\"application/json\")\n\n return jsonify(group=group._asdict(),\n users=[row._asdict() for row in group.users])\n\n\n@app.route('/groups/', methods=['POST'])\ndef create_group(name):\n group = api.find_group(name)\n\n if group is not None:\n return Response(response='Group already exists.',\n status=404,\n mimetype=\"application/json\")\n else:\n group = api.create_group(name)\n return jsonify(group=group._asdict())\n\n\n@app.route('/groups/', methods=['PUT'])\ndef update_group(name):\n group = api.find_group(name)\n\n if group is None:\n return Response(response='Group not found.',\n status=404,\n mimetype=\"application/json\")\n\n params = request.get_json()\n users = params.get('users')\n if users:\n group = api.add_users_to_group(group, users)\n return jsonify(group=group._asdict(),\n users=[row._asdict() for row in group.users])\n else:\n return Response(response='No users provided.',\n status=404,\n mimetype=\"application/json\")\n\n\n@app.route('/groups/', methods=['DELETE'])\ndef delete_group(name):\n group = api.find_group(name)\n\n if group is None:\n return Response(response='Group not found.',\n status=404,\n mimetype=\"application/json\")\n\n if not group.users.all():\n return Response(response='Group has no associated users.',\n status=404,\n mimetype=\"application/json\")\n\n group = api.empty_users_in_group(group)\n return Response(response='All users removed from \"%s\".' % group.name,\n status=200,\n mimetype=\"application/json\")\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"rest_user_groups/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"243918238","text":"\"\"\"projectash URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\n\nfrom ash import views\nadmin.site.site_header = 'System Administrator'\nadmin.site.site_title = 'site admin'\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', views.user_login, name='login'),\n url(r'^home', views.home, name='home'),\n url(r'^register', views.createAccount, name='registration'),\n url(r'^logout', views.user_logout, name='logout'),\n url(r'^expense', views.expense, name='expense'),\n url(r'^income/', views.income, name='income'),\n url(r'^incomes/', views.totalIncome, name='incomes'),\n url(r'^contact', views.contact, name='contact'),\n url(r'^creditors', views.creditors, name='creditors'),\n url(r'^debtors', views.debtors, name='debtors'),\n url(r'^calendar', views.calendar, name='calendar'),\n url(r'^tasks', views.addTask, name='task'),\n url(r'^debit/(?P\\d+)/$', views.debit, name='debit'),\n url(r'^clear/(?P\\d+)/$', views.clear_debit, name='debit'),\n url(r'^viewDebt/(?P\\d+)/$', views.view_debit, name='debit'),\n url(r'^payDebt/(?P\\d+)/$', views.pay_debt, name='payment'),\n]","sub_path":"projectash/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"12914111","text":"\"\"\" plot episode evaluation log and save \"\"\"\n\nfrom pathlib import Path\nimport argparse\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--exp-id', help='Experiment ID', type=int)\n args = parser.parse_args()\n\n LOG_DIR = \"logs/exp_\"+str(args.exp_id)\n\n FILE_PATH = str(list(Path(LOG_DIR).rglob('res_episode_1.csv'))[0])\n SAVE_PATH = FILE_PATH.replace(\"res_episode_1.csv\", \"plot_episode_eval_log.png\")\n\n # # read data\n log_df = pd.read_csv(FILE_PATH)\n\n # plot\n fig, axs = plt.subplots(4, 4, figsize=(20, 10), dpi=300, sharex=True)\n\n log_df.plot(x='timestep', y='joint_pos1', ax=axs[0, 0])\n log_df.plot(x='timestep', y='joint1_min', ax=axs[0, 0], style=\"r--\")\n log_df.plot(x='timestep', y='joint1_max', ax=axs[0, 0], style=\"r--\")\n\n log_df.plot(x='timestep', y='joint_pos2', ax=axs[1, 0])\n log_df.plot(x='timestep', y='joint2_min', ax=axs[1, 0], style=\"r--\")\n log_df.plot(x='timestep', y='joint2_max', ax=axs[1, 0], style=\"r--\")\n\n log_df.plot(x='timestep', y='joint_pos3', ax=axs[2, 0])\n log_df.plot(x='timestep', y='joint3_min', ax=axs[2, 0], style=\"r--\")\n log_df.plot(x='timestep', y='joint3_max', ax=axs[2, 0], style=\"r--\")\n\n log_df.plot(x='timestep', y='joint_pos4', ax=axs[3, 0])\n log_df.plot(x='timestep', y='joint4_min', ax=axs[3, 0], style=\"r--\")\n log_df.plot(x='timestep', y='joint4_max', ax=axs[3, 0], style=\"r--\")\n\n log_df.plot(x='timestep', y='joint_pos5', ax=axs[0, 2])\n log_df.plot(x='timestep', y='joint5_min', ax=axs[0, 2], style=\"r--\")\n log_df.plot(x='timestep', y='joint5_max', ax=axs[0, 2], style=\"r--\")\n\n log_df.plot(x='timestep', y='joint_pos6', ax=axs[1, 2])\n log_df.plot(x='timestep', y='joint6_min', ax=axs[1, 2], style=\"r--\")\n log_df.plot(x='timestep', y='joint6_max', ax=axs[1, 2], style=\"r--\")\n\n log_df.plot(x='timestep', y='action_1', ax=axs[0, 1])\n log_df.plot(x='timestep', y='action_low1', ax=axs[0, 1], style=\"r--\")\n log_df.plot(x='timestep', y='action_high1', ax=axs[0, 1], style=\"r--\")\n\n log_df.plot(x='timestep', y='action_2', ax=axs[1, 1])\n log_df.plot(x='timestep', y='action_low2', ax=axs[1, 1], style=\"r--\")\n log_df.plot(x='timestep', y='action_high2', ax=axs[1, 1], style=\"r--\")\n\n log_df.plot(x='timestep', y='action_3', ax=axs[2, 1])\n log_df.plot(x='timestep', y='action_low3', ax=axs[2, 1], style=\"r--\")\n log_df.plot(x='timestep', y='action_high3', ax=axs[2, 1], style=\"r--\")\n\n log_df.plot(x='timestep', y='action_4', ax=axs[3, 1])\n log_df.plot(x='timestep', y='action_low4', ax=axs[3, 1], style=\"r--\")\n log_df.plot(x='timestep', y='action_high4', ax=axs[3, 1], style=\"r--\")\n\n log_df.plot(x='timestep', y='action_5', ax=axs[0, 3])\n log_df.plot(x='timestep', y='action_low5', ax=axs[0, 3], style=\"r--\")\n log_df.plot(x='timestep', y='action_high5', ax=axs[0, 3], style=\"r--\")\n\n log_df.plot(x='timestep', y='action_6', ax=axs[1, 3])\n log_df.plot(x='timestep', y='action_low6', ax=axs[1, 3], style=\"r--\")\n log_df.plot(x='timestep', y='action_high6', ax=axs[1, 3], style=\"r--\")\n\n log_df.plot(x='timestep', y='reward', ax=axs[2, 2], color=\"b\")\n log_df.plot(x='timestep', y='term1', ax=axs[2, 2], color=\"r\")\n log_df.plot(x='timestep', y='term2', ax=axs[2, 2], color=\"g\")\n # ax_1 = axs[2, 2].twinx()\n # log_df.plot(x='timestep', y='return', ax=ax_1, color=\"r\")\n\n log_df.plot(x='timestep', y='distance', ax=axs[2, 3], color=\"b\", marker=\"x\")\n\n log_df.plot(x='timestep', y='est_acc', ax=axs[3, 2], color=\"g\", marker=\"*\")\n ax_3 = axs[3, 2].twinx()\n log_df.plot(x='timestep', y='est_vel', ax=ax_3, color=\"r\", marker=\"+\")\n\n log_df.plot(x='timestep', y='goal_x', ax=axs[3, 3], style='or')\n log_df.plot(x='timestep', y='goal_y', ax=axs[3, 3], style='ob')\n log_df.plot(x='timestep', y='goal_z', ax=axs[3, 3], style='og')\n log_df.plot(x='timestep', y='tip_x', ax=axs[3, 3], style='xr')\n log_df.plot(x='timestep', y='tip_y', ax=axs[3, 3], style='xb')\n log_df.plot(x='timestep', y='tip_z', ax=axs[3, 3], style='xg')\n\n axs[0, 0].set_ylabel(\"joint1 pos (rad)\")\n axs[1, 0].set_ylabel(\"joint2 pos (rad)\")\n axs[2, 0].set_ylabel(\"joint3 pos (rad)\")\n axs[3, 0].set_ylabel(\"joint4 pos (rad)\")\n axs[0, 2].set_ylabel(\"joint5 pos (rad)\")\n axs[1, 2].set_ylabel(\"joint6 pos (rad)\")\n\n axs[0, 1].set_ylabel(\"action1 (rad)\")\n axs[1, 1].set_ylabel(\"action2 (rad)\")\n axs[2, 1].set_ylabel(\"action3 (rad)\")\n axs[3, 1].set_ylabel(\"action4 (rad)\")\n axs[0, 3].set_ylabel(\"action5 (rad)\")\n axs[1, 3].set_ylabel(\"action6 (rad)\")\n\n axs[2, 2].set_ylabel(\"reward\")\n # axs[2, 2].set_ylabel(\"reward (m^2)\", color=\"b\")\n # ax_1.set_ylabel(\"return (m^2)\", color=\"r\")\n # axs[2, 2].tick_params(axis='y', labelcolor=\"b\")\n # ax_1.tick_params(axis='y', labelcolor=\"r\")\n\n axs[2, 3].set_ylabel(\"distance (m)\")\n # axs[2, 3].tick_params(axis='y', labelcolor=\"b\")\n\n axs[3, 2].set_ylabel(\"acc (m/s^2)\", color=\"g\")\n ax_3.set_ylabel(\"vel (m/s)\", color=\"r\")\n axs[3, 2].tick_params(axis='y', labelcolor=\"g\")\n ax_3.tick_params(axis='y', labelcolor=\"r\")\n\n axs[3, 3].set_ylabel(\"coordinates (m)\")\n\n axs[3, 3].legend(loc=\"upper right\")\n # ax3.legend(bbox_to_anchor=(1, 1.05))\n # ax4.legend(bbox_to_anchor=(1.2, 1.05))\n\n plt.tight_layout()\n # plt.show()\n plt.savefig(SAVE_PATH, bbox_inches='tight')\n","sub_path":"code/scripts/plot_episode_eval_log.py","file_name":"plot_episode_eval_log.py","file_ext":"py","file_size_in_byte":5426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"390894944","text":"# Copyright (c) 2019 Red Hat, Inc.\n#\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import\n\nimport shlex\n\nfrom oslo_log import log\nimport paramiko\nfrom paramiko import channel\n\nimport tobiko\nfrom tobiko.shell.sh import _exception\nfrom tobiko.shell.sh import _execute\nfrom tobiko.shell.sh import _io\nfrom tobiko.shell.sh import _local\nfrom tobiko.shell.sh import _process\nfrom tobiko.shell import ssh\nimport typing # noqa\n\nLOG = log.getLogger(__name__)\n\n\ndef ssh_execute(ssh_client, command, environment=None,\n timeout: tobiko.Seconds = None, stdin=None, stdout=None,\n stderr=None, shell=None, expect_exit_status=0, **kwargs):\n \"\"\"Execute command on remote host using SSH client\"\"\"\n process = ssh_process(command=command,\n environment=environment,\n timeout=timeout,\n shell=shell,\n stdin=stdin,\n stdout=stdout,\n stderr=stderr,\n ssh_client=ssh_client,\n **kwargs)\n return _execute.execute_process(process=process,\n stdin=stdin,\n expect_exit_status=expect_exit_status)\n\n\ndef ssh_process(command, environment=None, current_dir=None,\n timeout: tobiko.Seconds = None, shell=None, stdin=None,\n stdout=None, stderr=None, ssh_client=None, sudo=None,\n network_namespace=None):\n if ssh_client is None:\n ssh_client = ssh.ssh_proxy_client()\n if ssh_client:\n return SSHShellProcessFixture(\n command=command, environment=environment, current_dir=current_dir,\n timeout=timeout, shell=shell, stdin=stdin, stdout=stdout,\n stderr=stderr, ssh_client=ssh_client, sudo=sudo,\n network_namespace=network_namespace)\n else:\n return _local.local_process(\n command=command, environment=environment, current_dir=current_dir,\n timeout=timeout, shell=shell, stdin=stdin, stdout=stdout,\n stderr=stderr, sudo=sudo, network_namespace=network_namespace)\n\n\nclass SSHShellProcessParameters(_process.ShellProcessParameters):\n\n ssh_client = None\n\n\nclass SSHShellProcessFixture(_process.ShellProcessFixture):\n\n def init_parameters(self, **kwargs) -> SSHShellProcessParameters:\n return SSHShellProcessParameters(**kwargs)\n\n def create_process(self):\n \"\"\"Execute command on a remote host using SSH client\"\"\"\n command = str(self.command)\n ssh_client = self.ssh_client\n parameters = self.parameters\n\n tobiko.check_valid_type(ssh_client, ssh.SSHClientFixture)\n tobiko.check_valid_type(parameters, SSHShellProcessParameters)\n environment = parameters.environment\n current_dir = parameters.current_dir\n\n for attempt in tobiko.retry(\n timeout=self.parameters.timeout,\n default_count=self.parameters.retry_count,\n default_interval=self.parameters.retry_interval,\n default_timeout=self.parameters.retry_timeout):\n\n timeout = attempt.time_left\n details = (f\"command='{command}', \"\n f\"current_dir='{current_dir}', \"\n f\"login={ssh_client.login}, \"\n f\"timeout={timeout}, \"\n f\"attempt={attempt}, \"\n f\"environment={environment}\")\n LOG.debug(f\"Create remote process... ({details})\")\n try:\n client = ssh_client.connect()\n process = client.get_transport().open_session()\n if environment:\n variables = \" \".join(\n f\"{name}={shlex.quote(value)}\"\n for name, value in self.environment.items())\n command = variables + \" \" + command\n if current_dir is not None:\n command = f\"cd {current_dir} && {command}\"\n process.exec_command(command)\n LOG.debug(f\"Remote process created. ({details})\")\n return process\n except Exception:\n # Before doing anything else cleanup SSH connection\n ssh_client.close()\n LOG.debug(f\"Error creating remote process. ({details})\",\n exc_info=1)\n try:\n attempt.check_limits()\n except tobiko.RetryTimeLimitError as ex:\n LOG.debug(f\"Timed out creating remote process. ({details})\")\n raise _exception.ShellTimeoutExpired(command=command,\n stdin=None,\n stdout=None,\n stderr=None,\n timeout=timeout) from ex\n\n def setup_stdin(self):\n self.stdin = _io.ShellStdin(\n delegate=StdinSSHChannelFile(self.process, 'wb'),\n buffer_size=self.parameters.buffer_size)\n\n def setup_stdout(self):\n self.stdout = _io.ShellStdout(\n delegate=StdoutSSHChannelFile(self.process, 'rb'),\n buffer_size=self.parameters.buffer_size)\n\n def setup_stderr(self):\n self.stderr = _io.ShellStderr(\n delegate=StderrSSHChannelFile(self.process, 'rb'),\n buffer_size=self.parameters.buffer_size)\n\n def poll_exit_status(self):\n exit_status = getattr(self.process, 'exit_status', None)\n if exit_status and exit_status < 0:\n exit_status = None\n return exit_status\n\n def _get_exit_status(self, timeout: tobiko.Seconds = None):\n process = self.process\n if not process.exit_status_ready():\n # Workaround for Paramiko timeout problem\n # CirrOS instances could close SSH channel without sending process\n # exit status\n if timeout is None:\n timeout = 120.\n else:\n timeout = min(timeout, 120.0)\n LOG.debug(f\"Waiting for command '{self.command}' exit status \"\n f\"(timeout={timeout})\")\n # recv_exit_status method doesn't accept timeout parameter\n # therefore here we wait for next channel event expecting it is\n # actually the exit status\n # TODO (fressi): we could use an itimer to set a timeout for\n # recv_exit_status\n if not process.status_event.wait(timeout=timeout):\n LOG.error(\"Timed out before status event being set \"\n f\"(timeout={timeout})\")\n if process.exit_status >= 0:\n return process.exit_status\n else:\n return None\n\n def kill(self, sudo=False):\n process = self.process\n LOG.debug('Killing remote process: %r', self.command)\n try:\n process.close()\n except Exception:\n LOG.exception(\"Failed killing remote process: %r\",\n self.command)\n\n\nclass SSHChannelFile(channel.ChannelFile):\n\n def fileno(self):\n return self.channel.fileno()\n\n\nclass StdinSSHChannelFile(SSHChannelFile):\n\n def close(self):\n super(StdinSSHChannelFile, self).close()\n self.channel.shutdown_write()\n\n @property\n def write_ready(self):\n return self.channel.send_ready()\n\n\nclass StdoutSSHChannelFile(SSHChannelFile):\n\n def fileno(self):\n return self.channel.fileno()\n\n def close(self):\n super(StdoutSSHChannelFile, self).close()\n self.channel.shutdown_read()\n\n @property\n def read_ready(self):\n return self.channel.recv_ready()\n\n\nclass StderrSSHChannelFile(SSHChannelFile, paramiko.channel.ChannelStderrFile):\n\n def fileno(self):\n return self.channel.fileno()\n\n @property\n def read_ready(self):\n return self.channel.recv_stderr_ready()\n","sub_path":"tobiko/shell/sh/_ssh.py","file_name":"_ssh.py","file_ext":"py","file_size_in_byte":8603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"505889716","text":"# Caesar Cipher\r\n# https://www.nostarch.com/crackingcodes (BSD Licensed)\r\nimport sys\r\n\r\n\r\n# The string to be encrypted/decrypted:\r\nmessage = \"esi n ehohe hoe hi ldvhonsdlAtcadosr rctf ias au scb dc b'p,o,ntepcetrcdtrypnr fa'uilaalmn ga r pnn prpaee Caror tEtiaeginoev iemsy iura e.\"\r\n# sys.argv[3:]\r\nmessage = ' '.join(message)\r\n#message = eval(message)\r\n\r\nkeylist = [1,2,3,4,5,6,7,8,9]\r\n# Whether the program encrypts or decrypts:\r\nmode = 'decrypt'\r\n# sys.argv[2] # Set to either 'encrypt' or 'decrypt'.\r\n\r\n# Every possible symbol that can be encrypted:\r\nSYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\r\n\r\n# Stores the encrypted/decrypted form of the message:\r\ntranslated = ''\r\n# The encryption/decryption key:\r\nfor k in keylist:\r\n key = k\r\n\r\n# if sys.argv[2] != 'encrypt' and sys.argv[2] != 'decrypt':\r\n# print('Please enter encrypt or decrypt!')\r\n# sys.exit(0)\r\n\r\n\r\n\r\n\r\n for symbol in message:\r\n # Note: Only symbols in the `SYMBOLS` string can be encrypted/decrypted.\r\n if symbol in SYMBOLS:\r\n symbolIndex = SYMBOLS.find(symbol)\r\n # Perform encryption/decryption:\r\n if mode == 'encrypt':\r\n translatedIndex = symbolIndex + key\r\n elif mode == 'decrypt':\r\n translatedIndex = symbolIndex - key\r\n\r\n # Handle wrap-around, if needed:\r\n if translatedIndex >= len(SYMBOLS):\r\n translatedIndex = translatedIndex - len(SYMBOLS)\r\n elif translatedIndex < 0:\r\n translatedIndex = translatedIndex + len(SYMBOLS)\r\n\r\n if symbol.isupper():\r\n translated = translated + SYMBOLS[translatedIndex].upper()\r\n else:\r\n translated = translated + SYMBOLS[translatedIndex].lower()\r\n else:\r\n # Append the symbol without encrypting/decrypting:\r\n translated = translated + symbol\r\n\r\n # Output the translated string:\r\n print(translated)\r\n print(\"\")\r\n","sub_path":"as2/a2p1.py","file_name":"a2p1.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"83681724","text":"# write your code here\n\n\nclass TicTacToe:\n VALUE_X = \"X\"\n VALUE_O = \"O\"\n COORDS = [1, 2, 3]\n IMPOSSIBLE_STATE = \"Impossible\"\n X_WINS_STATE = f\"{VALUE_X} wins\"\n O_WINS_STATE = f\"{VALUE_O} wins\"\n DRAW_STATE = \"Draw\"\n GAME_NOT_FINISHED_STATE = \"Game not finished\"\n\n def __init__(self, state=None):\n self._state = state or \" \"\n self._cells = [\n list(self._state[i:i + 3]) for i in range(0, len(self._state), 3)\n ]\n self._value = self.VALUE_X\n\n def _count(self, value):\n return self._state.count(value)\n\n def _win(self, value):\n fill = [value, value, value]\n combinations = self._cells[:]\n combinations.extend([\n [self._cells[0][0], self._cells[1][1], self._cells[2][2]],\n [self._cells[0][2], self._cells[1][1], self._cells[2][0]],\n ])\n combinations.extend([\n [self._cells[0][i], self._cells[1][i], self._cells[2][i]]\n for i in range(len(self._cells))\n ])\n return fill in combinations\n\n @property\n def state(self):\n return self._state\n\n @property\n def completed(self):\n return (\n \" \" not in self._state or\n self.status != self.GAME_NOT_FINISHED_STATE\n )\n\n @property\n def status(self):\n x_wins = self._win(self.VALUE_X)\n x_count = self._count(self.VALUE_X)\n o_wins = self._win(self.VALUE_O)\n o_count = self._count(self.VALUE_O)\n\n if (x_wins and o_wins) or (abs(x_count - o_count) > 1):\n return self.IMPOSSIBLE_STATE\n elif x_wins:\n return self.X_WINS_STATE\n elif o_wins:\n return self.O_WINS_STATE\n elif \" \" not in self._state:\n return self.DRAW_STATE\n return self.GAME_NOT_FINISHED_STATE\n\n def _change_value(self):\n self._value = (\n self.VALUE_O if self._value == self.VALUE_X else self.VALUE_X\n )\n\n def _update_state(self):\n self._state = \"\".join(cell for row in self._cells for cell in row)\n\n def set(self, x, y):\n x, y = 3 - x, y - 1\n if self._cells[x][y] in [self.VALUE_X, self.VALUE_O]:\n return False\n self._cells[x][y] = self._value\n self._change_value()\n self._update_state()\n return True\n\n def __str__(self):\n return (\n f\"---------\\n\"\n f\"| {' '.join(self._state[:3])} |\\n\"\n f\"| {' '.join(self._state[3:6])} |\\n\"\n f\"| {' '.join(self._state[6:9])} |\\n\"\n f\"---------\"\n )\n\n\ndef parse_input_position(data):\n data = data.split()\n if not data or not data[0].isdigit() or not data[1].isdigit():\n return \"You should enter numbers!\", None, None\n y, x = int(data[0]), int(data[1])\n if x not in TicTacToe.COORDS or y not in TicTacToe.COORDS:\n return \"Coordinates should be from 1 to 3!\", None, None\n return None, x, y\n\n\ntic_tac_toe = TicTacToe()\nprint(tic_tac_toe)\n\nwhile not tic_tac_toe.completed:\n message, pos_x, pos_y = parse_input_position(input(\n \"Enter the coordinates: > \"\n ))\n if message is not None:\n print(message)\n else:\n if not tic_tac_toe.set(pos_x, pos_y):\n print(\"This cell is occupied! Choose another one!\")\n else:\n print(tic_tac_toe)\n\nprint(tic_tac_toe.status)\n","sub_path":"Easy/Tic-Tac-Toe/Tic-Tac-Toe/task/tictactoe/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"166161580","text":"import os\n\ndef fileExists(filename):\n\treturn os.path.isfile(filename)\n\ndef getCurveForImage(image):\n\ttmp = image.copy()\n\tif (tmp.dtype == cv2.CV_8UC3):\n\t\tgray = cv2.cvtColor(tmp, cv2.COLOR_BGR2GRAY)\n\telif (tmp.dtype == cv2.CV_8UC1):\n\t\tgray = tmp\n\telse:\n\t\traise Exception('Unsupported image format')\n\n\tgray = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)\n\n\t(_, contours, _) = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n\tif len(contours) <= 0:\n\t\treturn\n\n\tupperCurve = contours[0]\n\tif (len(upperCurve) <= 50):\n\t\treturn\t\n","sub_path":"compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"232158767","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nimport numpy as np\n\nfrom scilpy.samplingscheme.save_scheme import (save_scheme_bvecs_bvals,\n save_scheme_mrtrix)\nfrom scilpy.utils.filenames import split_name_with_nii\n\nDEFAULT_B0_THRESHOLD = 20\n\n\ndef is_normalized_bvecs(bvecs):\n \"\"\"\n Check if b-vectors are normalized.\n\n Parameters\n ----------\n bvecs : (N, 3) array\n input b-vectors (N, 3) array\n\n Returns\n -------\n True/False\n \"\"\"\n\n bvecs_norm = np.linalg.norm(bvecs, axis=1)\n return np.all(np.logical_or(np.abs(bvecs_norm - 1) < 1e-3,\n bvecs_norm == 0))\n\n\ndef normalize_bvecs(bvecs, filename=None):\n \"\"\"\n Normalize b-vectors\n\n Parameters\n ----------\n bvecs : (N, 3) array\n input b-vectors (N, 3) array\n filename : string\n output filename where to save the normalized bvecs\n\n Returns\n -------\n bvecs : (N, 3)\n normalized b-vectors\n \"\"\"\n\n bvecs_norm = np.linalg.norm(bvecs, axis=1)\n idx = bvecs_norm != 0\n bvecs[idx] /= bvecs_norm[idx, None]\n\n if filename is not None:\n logging.info('Saving new bvecs: {}'.format(filename))\n np.savetxt(filename, np.transpose(bvecs), \"%.8f\")\n\n return bvecs\n\n\ndef check_b0_threshold(force_b0_threshold, bvals_min):\n \"\"\"Check if the minimal bvalue is under zero or over the default threshold.\n If `force_b0_threshold` is true, don't raise an error even if the minimum\n bvalue is suspiciously high.\n\n Parameters\n ----------\n force_b0_threshold : bool\n If True, don't raise an error.\n bvals_min : float\n Minimum bvalue.\n\n Raises\n ------\n ValueError\n If the minimal bvalue is under zero or over the default threshold, and\n `force_b0_threshold` is False.\n \"\"\"\n if bvals_min != 0:\n if bvals_min < 0 or bvals_min > DEFAULT_B0_THRESHOLD:\n if force_b0_threshold:\n logging.warning(\n 'Warning: Your minimal bval is {}. This is highly '\n 'suspicious. The script will nonetheless proceed since '\n '--force_b0_threshold was specified.'.format(bvals_min))\n else:\n raise ValueError('The minimal bval is lesser than 0 or '\n 'greater than {}. This is highly ' +\n 'suspicious.\\n'\n 'Please check your data to ensure everything '\n 'is correct.\\n'\n 'Value found: {}\\n'\n 'Use --force_b0_threshold to execute '\n 'regardless.'\n .format(DEFAULT_B0_THRESHOLD, bvals_min))\n else:\n logging.warning('Warning: No b=0 image. Setting b0_threshold to '\n 'the minimum bval: {}'.format(bvals_min))\n\n\ndef get_shell_indices(bvals, shell, tol=10):\n \"\"\"\n Get shell indices\n\n Parameters\n ----------\n bvals: array (N,)\n array of bvals\n shell: list\n list of bvals\n tol: int\n tolerance to accept a bval\n\n Returns\n -------\n numpy.ndarray where shells are found\n \"\"\"\n\n return np.where(\n np.logical_and(bvals < shell + tol, bvals > shell - tol))[0]\n\n\ndef fsl2mrtrix(fsl_bval_filename, fsl_bvec_filename, mrtrix_filename):\n \"\"\"\n Convert a fsl dir_grad.bvec/.bval files to mrtrix encoding.b file.\n\n Parameters\n ----------\n fsl_bval_filename: str\n path to input fsl bval file.\n fsl_bvec_filename: str\n path to input fsl bvec file.\n mrtrix_filename : str, optional\n path to output mrtrix encoding.b file. Default is\n fsl_bvec_filename.b.\n\n Returns\n -------\n \"\"\"\n\n shells = np.loadtxt(fsl_bval_filename)\n points = np.loadtxt(fsl_bvec_filename)\n bvals = np.unique(shells).tolist()\n\n if not points.shape[0] == 3:\n points = points.transpose()\n logging.warning('WARNING: Your bvecs seem transposed. ' +\n 'Transposing them.')\n\n shell_idx = [int(np.where(bval == bvals)[0]) for bval in shells]\n\n basefilename, ext = split_name_with_nii(mrtrix_filename)\n\n save_scheme_mrtrix(points,\n shell_idx,\n bvals,\n basefilename,\n verbose=1)\n\n\ndef mrtrix2fsl(mrtrix_filename, fsl_bval_filename=None,\n fsl_bvec_filename=None):\n \"\"\"\n Convert a mrtrix encoding.b file to fsl dir_grad.bvec/.bval files.\n\n Parameters\n ----------\n mrtrix_filename : str\n path to mrtrix encoding.b file.\n fsl_bval_filename: str, optional\n path to the output fsl bval file. Default is\n mrtrix_filename.bval.\n fsl_bvec_filename: str, optional\n path to the output fsl bvec file. Default is\n mrtrix_filename.bvec.\n Returns\n -------\n \"\"\"\n\n mrtrix_b = np.loadtxt(mrtrix_filename)\n if not len(mrtrix_b.shape) == 2 or not mrtrix_b.shape[1] == 4:\n raise ValueError('mrtrix file must have 4 columns')\n\n points = np.array([mrtrix_b[:, 0], mrtrix_b[:, 1], mrtrix_b[:, 2]])\n shells = np.array(mrtrix_b[:, 3])\n\n bvals = np.unique(shells).tolist()\n shell_idx = [int(np.where(bval == bvals)[0]) for bval in shells]\n\n if fsl_bval_filename is None:\n fsl_bval_filename = mrtrix_filename + str(\".bval\")\n\n if fsl_bvec_filename is None:\n fsl_bvec_filename = mrtrix_filename + str(\".bvec\")\n\n save_scheme_bvecs_bvals(points,\n shell_idx,\n bvals,\n filename_bval=fsl_bval_filename,\n filename_bvec=fsl_bvec_filename,\n verbose=1)\n","sub_path":"scilpy/utils/bvec_bval_tools.py","file_name":"bvec_bval_tools.py","file_ext":"py","file_size_in_byte":5827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"179314746","text":"import torch\nfrom transformers import BertTokenizer, BertModel, BertForQuestionAnswering\n\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ntokenizer = BertTokenizer.from_pretrained('./final_model_whole')\nmodel = BertForQuestionAnswering.from_pretrained('./final_model_whole')\n\ncount = 0\n\nsens = []\n\nfo = open(\"./data/evaluate/test_predict_whole.answer\", \"w+\", encoding=\"utf8\")\nwith open(\"./data/train data/processed_test.doc_query\", \"r\", encoding=\"utf8\") as f:\n results = []\n for line in f:\n sens.append(line.strip())\n with open(\"./data/train data/train.answer\", \"r\", encoding=\"utf8\") as fl:\n '''for line in fl:\n labs.append(line.split(\"|||\")[1].strip())'''\n for sen in sens:\n count += 1\n data, num = sen.split(\"|||\")\n #label = labs[int(num.strip())]\n tokenized_data = tokenizer.tokenize(data)\n if len(tokenized_data) > 512:\n tokenized_data = tokenized_data[:512]\n token_type_id = [0]*len(tokenized_data)\n x = tokenized_data.index(\"[SEP]\")\n for i in range(x+1, len(token_type_id)):\n token_type_id[i] = 1\n token_type_id = torch.tensor(token_type_id)\n position_ids = torch.tensor([i for i in range(len(tokenized_data))])\n indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_data)\n tokens_tensor = torch.tensor([indexed_tokens])\n #input_ids = torch.tensor(tokenizer.encode(tokenized_data)).unsqueeze(0)\n model.cuda()\n tokens_tensor = tokens_tensor.cuda()\n token_type_id = token_type_id.cuda()\n position_ids = position_ids.cuda()\n outputs = model(tokens_tensor, token_type_ids=token_type_id, position_ids=position_ids)\n\n start_score = outputs[0].squeeze(0)\n end_score = outputs[1].squeeze(0)\n\n max_score = -100000\n count1 = 0\n best_start = 0\n best_end = 0\n for ty, start in zip(token_type_id, start_score):\n if ty == 1:\n if count1 < len(end_score) - 2:\n for i in range(1, 3):\n m = count1+i\n k = start + end_score[m]\n if k > max_score:\n max_score = start + end_score[count1+i]\n best_start = count1\n best_end = count1 + i\n count1 += 1\n pre = tokenized_data[best_start:best_end+1]\n result = ''.join(pre) + \"|||\"\n if len(results) < int(num) + 1:\n results.append([''.join(pre) + \"|||\" + str(max_score)])\n else:\n results[int(num)].append(''.join(pre) + \"|||\" + str(max_score))\n if count % 200 == 0:\n print(\"{} lines processed.\".format(count))\n\n for i, answers in enumerate(results):\n if len(answers) == 1:\n fo.write(\" ||| \"+answers[0].split(\"|||\")[0]+\"\\n\")\n else:\n k = 0\n word = []\n score = []\n for item in answers:\n word.append(item.split(\"|||\")[0])\n score.append(item.split(\"|||\")[1])\n if score[0] > score[1]:\n k = 0\n else:\n k = 1\n fo.write(\" ||| \" + answers[k].split(\"|||\")[0] + \"\\n\")\nfo.close()\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"639251265","text":"import logging\nimport pyaudio\nimport numpy as np\nfrom struct import unpack\nfrom matplotlib import pyplot as plt\nimport argparse\n\n# Define stream constants\nFORMAT = pyaudio.paInt16\nCHANNELS = 2\nRATE = 44100\nFREQUENCY = 1/RATE\nINPUT_BUFFER_TIME = 1\nINPUT_FRAMES_PER_BUFFER = int(RATE*INPUT_BUFFER_TIME)\nDECODE_FMT = '{}h'.format(RATE*2)\n\nlogger = logging.getLogger(name='Tuner')\n\n\nclass Sess:\n \"\"\" Audio stream context manager\"\"\"\n def __enter__(self):\n self.audio = pyaudio.PyAudio()\n self.stream = self.audio.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=INPUT_FRAMES_PER_BUFFER)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.stream.close()\n self.audio.terminate()\n\n\ndef decode_sample(raw_sample):\n \"\"\"\n We get one short out for each two chars in the bytes array.\n Args:\n raw_sample: bytes\n Sample buffer from the stream.\n\n Returns:\n signal: Audio signal as a Numpy array\n \"\"\"\n # Parse the buffer and return a tuple of signed integers.\n shorts = unpack(DECODE_FMT, raw_sample)\n\n # Type conversion\n signal = np.array(shorts)\n\n return signal\n\n\ndef sig_to_freq(signal):\n \"\"\"\n Calculate the frequencies of a signal. Also return the dominant frequency.\n \"\"\"\n # Fast fourier transform\n coeffs = np.fft.fft(signal)\n frequencies = np.fft.fftfreq(n=len(signal), d=FREQUENCY)\n\n # Filter out unrealistic frequencies.\n filter_id = ((frequencies > 20) * (frequencies < 1500)) + (\n (frequencies > -1500) * (frequencies < -20))\n frequencies, coeffs = frequencies[filter_id], coeffs[filter_id]\n\n # Find the largest fourier coefficient.\n idx = np.argmax(coeffs.imag)\n\n # Find the corresponding frequency.\n peak = frequencies[idx]\n peak = peak * np.sign(peak)\n\n return coeffs, frequencies, peak\n\n\ndef freq_to_note(frequency):\n \"\"\"\n Maps frequencies to the equivalent musical notes\n \"\"\"\n # Store the output strings.\n notes = ('A', 'Bb', 'B', 'C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'G#')\n directions = ('Flat', 'Sharp', 'Perfect!')\n\n # Map the frequency to a number between 0 and 12.\n c = np.log2(440)\n val = 12*(np.log2(frequency) - c)\n\n # Round to an integer to give the nearest note.\n rounded = int(np.round(val))\n note_idx = rounded % 12\n\n # Use the remainder to indicate tuning direction.\n remainder = val - rounded\n if remainder < - 0.1:\n idx = 0\n elif remainder > 0.1:\n idx = 1\n else:\n idx = 2\n return notes[note_idx], directions[idx]\n\n\ndef tuner(stream, sample_no):\n \"\"\"\n Print the loudest input frequency at regular intervals.\n \"\"\"\n slist = []\n flist = []\n for i in range(0, sample_no):\n # Read from the stream.\n sample = stream.read(INPUT_FRAMES_PER_BUFFER)\n\n # Decode the stream.\n signal = decode_sample(sample)\n\n # Take a fourier transform of the signal and find the loudest frequency.\n coeffs, frequencies, peak = sig_to_freq(signal=signal)\n\n # Store the recordings\n slist.append(signal)\n flist.append((coeffs, frequencies))\n\n # Map the frequency to the correct note.\n note, direction = freq_to_note(frequency=peak)\n\n # Display the frequency, note, and tuning guidance.\n print('Frequency: {}, Note: {}, Error: {}'.format(peak, note, direction))\n\n # Return some data for plotting and debugging.\n total_signal = np.concatenate(slist, 0)\n return total_signal, flist\n\n\ndef signalplot(s):\n \"\"\" Plot the full recorded audio\"\"\"\n plt.figure()\n plt.ylabel('Amplitude')\n plt.xlabel('Time')\n plt.plot(s)\n plt.savefig('signal.png')\n\n\ndef fftplot(coeffs, freqs):\n # Truncate the frequency range a bit.\n idx = (freqs < 2000) * (freqs > -2000)\n freqs, coeffs = freqs[idx], coeffs[idx]\n\n plt.subplot(2, 1, 1)\n plt.title('Real')\n plt.ylabel('Coeff')\n plt.plot(freqs, coeffs.real, color='b')\n\n plt.subplot(2, 1, 2)\n plt.title('Imaginary')\n plt.xlabel('Frequency')\n plt.ylabel('Coeff')\n plt.plot(freqs, coeffs.imag, color='g')\n plt.savefig('fft.png')\n\n\nif __name__ == '__main__':\n with Sess() as session:\n stream = session.stream\n parser = argparse.ArgumentParser(\n description='Tune your guitar!')\n parser.add_argument(\n '--time',\n type=int,\n default=10,\n help='Number of seconds to run the tuner for.')\n args = parser.parse_args()\n sample_no = args.time\n\n # Run the tuner.\n total_signal, freqlist = tuner(stream, sample_no)\n\n signalplot(total_signal)\n fftplot(*freqlist[min(5, sample_no-1)])\n","sub_path":"listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"287209402","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ndf=pd.read_csv('movie_dataset.csv')\n\nfeatures=['genres','keywords','title','director','cast']\n\ndef get_title_from_index(index):\n return df[df.index == index][\"title\"].values[0]\n\ndef get_index_from_title(title):\n return df[df.title == title][\"index\"].values[0]\n\nfor feature in features:\n df[feature] = df[feature].fillna('')\n\n\ndef combine_features(row):\n return row['genres']+' '+row['keywords']+' '+row['title']+' '+row['director']+' '+row['cast']\n\ndf['combined_features']=df.apply(combine_features,axis=1)\n\ncv=CountVectorizer()\ncount_matrix=cv.fit_transform(df['combined_features'])\n\ncos_simi=cosine_similarity(count_matrix)\n\nmovie=input('ENTER YOUR MOVIE >>')\n\nind=get_index_from_title(movie)\n\nsimilar_movies=list(enumerate(cos_simi[ind]))\n\nsorted_similar_movies=sorted(similar_movies,key=lambda x:x[1],reverse=True)\n\ni=0\nfor m in sorted_similar_movies:\n print(get_title_from_index(m[0]))\n i=i+1\n if i>50:\n break\n\ninput()\n\n","sub_path":"movie recommendation system/mrs2.py","file_name":"mrs2.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"449000245","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom sunbeam.items import SunbeamItem\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\n\nclass SunwzSpider(scrapy.Spider):\n name = 'sunwz' # 爬虫名字是唯一的\n allowed_domains = ['wz.sun0769.com']\n\n url = 'http://wz.sun0769.com/index.php/question/questionType?type=4&page={}' \n offset = 0\n start_urls = [url.format(offset)]\n #start_urls = ['http://http://wz.sun0769.com/index.php/question/questionType?type=4&page={}'.format(i) for i in range(0,94110, 30 )]\n#\n# def start_request(self):\n# for i in range(0, 90, 30):\n# yield scrapy.Request(self.url.format(i))\n\n def parse(self, response):\n #取页面帖子的链接\n links = response.xpath('//div[@class=\"greyframe\"]/table//td/a[@class=\"news14\"]/@href').extract()\n for link in links:\n yield scrapy.Request(link, callback=self.parse_item)\n # 设置翻页\n if self.offset <= 94410:\n self.offset += 30\n yield scrapy.Request(self.url.format(self.offset), callback=self.parse)\n\n\n def parse_item(self, response):\n items = SunbeamItem()\n # 内容\n items['content'] = response.xpath('//div[@class=\"c1 text14_2\"]/text()')[0].extract()\n # 标题\n items['title'] = response.xpath('//div[contains(@class, \"pagecenter p3\")]//strong/text()').extract()[0].split(':')[0].replace('编号', '')\n print(items['title'])\n # 编号\n items['number'] = response.xpath('//div[contains(@class, \"pagecenter p3\")]//strong/text()').extract()[0].split(':')[-1].strip()\n print(items['number'])\n \n print(items['title'][0])\n # url\n items['url'] = response.url\n yield items\n\n\n","sub_path":"sunbeam/sunbeam/spiders/sunwz.py","file_name":"sunwz.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"570602895","text":"# init_method.py\n\n# 此示例示意初始化方法的定义方法及用法\n\nclass Car:\n def __init__(self, c, b, m):\n self.color = c # 颜色\n self.brand = b # 品牌\n self.model = m # 型号\n print(\"初始化方法被调用\")\n \n def run(self, speed): # 行驶\n print(self.color, \"的\",\n self.brand, self.model, '正在以',\n speed, '公里/小时的速度行驶')\n\na4 = Car('红色', \"奥迪\", 'A4')\na4.run(230)\n\nt = Car('蓝色', \"TESLA\", 'Model S')\nt.run(199)\n\n","sub_path":"02-PythonBase/day17/code/init_method.py","file_name":"init_method.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"463116346","text":"from human import Human\r\nfrom ai import Artificial\r\n\r\nclass Game:\r\n def __init__(self):\r\n self.contestants = []\r\n pass\r\n\r\n def welcome_rules(self):\r\n print(\"Welcome to Rock, Paper, Scissors, Lizard, Spock (RPSLS)!\\n\"\r\n \"\\n\"\r\n \"The rules of RPSLS is:\\n\"\r\n \"\\n\"\r\n \"Rock crushes Scissors\\n\"\r\n \"Scissors cuts Paper\\n\"\r\n \"Paper covers Rock\\n\"\r\n \"Rock crushes Lizard\\n\"\r\n \"Lizard poisons Spock\\n\"\r\n \"Spock smashes Scissors\\n\"\r\n \"Scissors decapitates Lizard\\n\"\r\n \"Lizard eats Paper\\n\"\r\n \"Paper disproves Spock\\n\"\r\n \"Spock vaporizes Rock\\n\"\r\n \"\\n\"\r\n \"Let's play!\")\r\n \r\n def game_mode(self):\r\n game_choice = (input(\"How will you be playing?\\n\"\r\n \"Type (1) for single player\\n\"\r\n \"Type (2) for multiplayer \"))\r\n if game_choice == \"1\":\r\n ai_player = Artificial()\r\n self.contestants.append(ai_player)\r\n human_player1 = Human()\r\n self.contestants.append(human_player1)\r\n print(\"\\n\")\r\n self.ai_game()\r\n elif game_choice == \"2\":\r\n human_player1 = Human()\r\n self.contestants.append(human_player1)\r\n human_player2 = Human()\r\n self.contestants.append(human_player2)\r\n self.human_game()\r\n else:\r\n print(\"\\n\")\r\n self.game_mode()\r\n pass\r\n\r\n def ai_game(self):\r\n human_winner_counter = 0\r\n ai_winner_counter = 0\r\n\r\n human_round1 = self.human_turn(1)\r\n ai_round1 = self.ai_turn()\r\n round_one_winner = self.find_round_winner(human_round1, ai_round1)\r\n print(\"\\n\")\r\n print(f'{self.contestants[1].name} chose {human_round1} and\\n{self.contestants[0].name} chose {ai_round1}')\r\n print(f'{round_one_winner} wins round 1')\r\n print(\"\\n\")\r\n if round_one_winner == self.contestants[1].name:\r\n human_winner_counter += 1\r\n elif round_one_winner == self.contestants[0].name:\r\n ai_winner_counter += 1\r\n \r\n human_round2 = self.human_turn(1)\r\n ai_round2 = self.ai_turn()\r\n round_two_winner = self.find_round_winner(human_round2, ai_round2)\r\n print(\"\\n\")\r\n print(f'{self.contestants[1].name} chose {human_round2} and\\n{self.contestants[0].name} chose {ai_round2}')\r\n print(f'{round_two_winner} wins round 2')\r\n print(\"\\n\")\r\n if round_two_winner == self.contestants[1].name:\r\n human_winner_counter += 1\r\n elif round_two_winner == self.contestants[0].name:\r\n ai_winner_counter += 1\r\n if human_winner_counter == 2:\r\n print(f'{self.contestants[1].name} wins the game!!!\\n')\r\n self.ask_new_game()\r\n elif ai_winner_counter == 2:\r\n print(f'{self.contestants[0].name} wins the game!!!\\n''Better luck next time! ¯\\_(ツ)_/¯\\n')\r\n self.ask_new_game()\r\n elif human_winner_counter < 2 and ai_winner_counter < 2:\r\n human_round3 = self.human_turn(1)\r\n ai_round3 = self.ai_turn()\r\n round_three_winner = self.find_round_winner(human_round3, ai_round3)\r\n print(\"\\n\")\r\n print(f'{self.contestants[1].name} chose {human_round3} and\\n{self.contestants[0].name} chose {ai_round3}')\r\n print(f'{round_three_winner} wins round 3')\r\n print(\"\\n\")\r\n if round_three_winner == self.contestants[1].name:\r\n human_winner_counter += 1\r\n elif round_three_winner == self.contestants[0].name:\r\n ai_winner_counter += 1\r\n \r\n if human_winner_counter >= 2:\r\n print(f'{self.contestants[1].name} wins the game!!!\\n')\r\n self.ask_new_game()\r\n elif ai_winner_counter >= 2:\r\n print(f'{self.contestants[0].name} wins the game!!!\\n''Better luck next time! ¯\\_(ツ)_/¯\\n')\r\n self.ask_new_game()\r\n elif human_winner_counter == 1 and ai_winner_counter == 0:\r\n print(f'{self.contestants[1].name} wins the game!!!\\n')\r\n self.ask_new_game() \r\n elif ai_winner_counter == 1 and human_winner_counter == 0:\r\n print(f'{self.contestants[0].name} wins the game!!!\\n''Better luck next time! ¯\\_(ツ)_/¯\\n')\r\n self.ask_new_game()\r\n elif human_winner_counter == ai_winner_counter:\r\n print(\"How does it feel to tie and win nothing?! Sucks right?\\n\"\"Play again because if you ain't first, you're last!\\n\")\r\n self.ask_new_game()\r\n\r\n def ai_turn(self):\r\n ai_player_choice = self.contestants[0].choose_gesture()\r\n return ai_player_choice\r\n\r\n def human_turn(self, index_number):\r\n self.contestants[index_number].choose_gesture()\r\n human1_choice = self.valid_answer()\r\n return human1_choice\r\n\r\n def human_game(self):\r\n human1_winner_counter = 0\r\n human2_winner_counter = 0\r\n\r\n human1_round1 = self.human_turn(1)\r\n human2_round1 = self.human_turn(0)\r\n round_one_winner = self.find_round_winner(human1_round1, human2_round1)\r\n print(\"\\n\")\r\n print(f'{self.contestants[1].name} chose {human1_round1} and\\n{self.contestants[0].name} chose {human2_round1}')\r\n print(f'{round_one_winner} wins round 1!')\r\n print(\"\\n\")\r\n if round_one_winner == self.contestants[1].name:\r\n human1_winner_counter += 1\r\n elif round_one_winner == self.contestants[0].name:\r\n human2_winner_counter += 1\r\n \r\n human1_round2 = self.human_turn(1)\r\n human2_round2 = self.human_turn(0)\r\n round_two_winner = self.find_round_winner(human1_round2, human2_round2)\r\n print(\"\\n\")\r\n print(f'{self.contestants[1].name} chose {human1_round2} and\\n{self.contestants[0].name} chose {human2_round2}')\r\n print(f'{round_two_winner} wins round 2!')\r\n print(\"\\n\")\r\n if round_two_winner == self.contestants[1].name:\r\n human1_winner_counter += 1\r\n elif round_two_winner == self.contestants[0].name:\r\n human2_winner_counter += 1\r\n if human1_winner_counter == 2:\r\n print(f'{self.contestants[1].name} wins the game!!!\\n')\r\n self.ask_new_game()\r\n elif human2_winner_counter == 2:\r\n print(f'{self.contestants[0].name} wins the game!!!\\n')\r\n self.ask_new_game()\r\n elif human1_winner_counter < 2 and human2_winner_counter < 2:\r\n human1_round3 = self.human_turn(1)\r\n human2_round3 = self.human_turn(0)\r\n round_three_winner = self.find_round_winner(human1_round3, human2_round3)\r\n print(\"\\n\")\r\n print(f'{self.contestants[1].name} chose {human1_round3} and\\n{self.contestants[0].name} chose {human2_round3}')\r\n print(f'{round_three_winner} wins round 3!')\r\n print(\"\\n\")\r\n if round_three_winner == self.contestants[1].name:\r\n human1_winner_counter += 1\r\n elif round_three_winner == self.contestants[0].name:\r\n human2_winner_counter += 1\r\n \r\n if human1_winner_counter >= 2:\r\n print(f'{self.contestants[1].name} wins the game!!!\\n')\r\n self.ask_new_game()\r\n elif human2_winner_counter >= 2:\r\n print(f'{self.contestants[0].name} wins the game!!!\\n')\r\n self.ask_new_game()\r\n elif human1_winner_counter == 1 and human2_winner_counter == 0:\r\n print(f'{self.contestants[1].name} wins the game!!!\\n')\r\n self.ask_new_game() \r\n elif human2_winner_counter == 1 and human1_winner_counter == 0:\r\n print(f'{self.contestants[0].name} wins the game!!!\\n')\r\n self.ask_new_game()\r\n elif human1_winner_counter == human2_winner_counter:\r\n print(\"How does it feel to tie and win nothing?! Sucks right?\\n\"\"Play again because if you ain't first, you're last!\\n\")\r\n self.ask_new_game()\r\n pass \r\n\r\n def run_game(self):\r\n self.contestants = []\r\n self.welcome_rules()\r\n self.game_mode()\r\n\r\n def valid_answer(self):\r\n while True:\r\n choice = input(\"Please type your RPSLS gesture choice here: \").casefold()\r\n if choice.lower() not in (\"rock\", \"paper\", \"scissors\", \"lizard\", \"spock\"):\r\n print(\"Please re-type your gesture choice.\"\"\\n\")\r\n else:\r\n break\r\n return choice\r\n\r\n def find_round_winner(self, human1_choice, ai_player_choice):\r\n if human1_choice == ai_player_choice:\r\n return\"Nobody\"\r\n\r\n elif human1_choice == \"rock\": \r\n if ai_player_choice == \"scissors\" or ai_player_choice == \"lizard\":\r\n return self.contestants[1].name\r\n elif ai_player_choice == \"spock\" or ai_player_choice == \"paper\":\r\n return self.contestants[0].name\r\n\r\n elif human1_choice == \"paper\":\r\n if ai_player_choice == \"spock\" or ai_player_choice == \"rock\": \r\n return self.contestants[1].name\r\n elif ai_player_choice == \"lizard\" or ai_player_choice == \"scissors\":\r\n return self.contestants[0].name\r\n\r\n elif human1_choice == \"scissors\":\r\n if ai_player_choice == \"paper\" or ai_player_choice == \"lizard\":\r\n return self.contestants[1].name\r\n elif ai_player_choice == \"rock\" or ai_player_choice == \"spock\":\r\n return self.contestants[0].name\r\n\r\n elif human1_choice == \"lizard\":\r\n if ai_player_choice == \"spock\" or ai_player_choice == \"paper\":\r\n return self.contestants[1].name\r\n elif ai_player_choice == \"rock\" or ai_player_choice == \"scissors\":\r\n return self.contestants[0].name\r\n\r\n elif human1_choice == \"spock\":\r\n if ai_player_choice == \"rock\" or ai_player_choice == \"scissors\":\r\n return self.contestants[1].name\r\n elif ai_player_choice == \"paper\" or ai_player_choice == \"lizard\":\r\n return self.contestants[0].name\r\n\r\n def ask_new_game(self):\r\n new_game = input(\"Do you want to play again?\\n\"\r\n \"Type (y)\\n\"\r\n \"Type (n) \")\r\n if new_game == \"y\":\r\n self.run_game()\r\n elif new_game == \"n\":\r\n print(\"See you next time.\")\r\n else:\r\n self.ask_new_game()\r\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":10613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"415899508","text":"import numpy as np\n\ndef sor_solver(A, b, omega, initial_guess, tol):\n \"\"\"\n Implementacion del SOR\n Entradas:\n A: Matriz\n b: Vector \n omega: factor de relajacion\n tol: tolerancia (1e-5)\n initial_guess: solucion inicial\n Salidas:\n phi: vector solución\n \"\"\"\n phi = initial_guess[:]\n residual = np.linalg.norm(np.matmul(A, phi) - b) #residual\n itera = 1\n while residual > tol:\n print(\"iteracion: \", itera)\n for i in range(A.shape[0]):\n sigma = 0\n for j in range(A.shape[1]):\n if j != i:\n sigma += A[i][j] * phi[j]\n phi[i] = (1 - omega) * phi[i] + (omega / A[i][i]) * (b[i] - sigma)\n residual = np.linalg.norm(np.matmul(A, phi) - b)\n itera = itera + 1\n # print('Residual: {0:10.6g}'.format(residual))\n \n print(phi)\n return phi\n\n\n#Adaptación del pesudo código de SOR\ntol = 1e-5\nformato = \"{:.\"+str(tol).split('-')[1]+\"f}\"\nomega = 1.3 # factor de relajación w\n\nA = np.array([[4. , 3., 0.],\n [3., 4., -1.],\n [0., -1., 4.]])\n\n\nb = np.array([0.254,-1.425,2.978])\n\ninitial_guess = np.array([0.,0.,0.])\n\nphi = sor_solver(A, b, omega, initial_guess, tol)\nprint(\"Resultado: [ \", formato.format(phi[0]),\", \",formato.format(phi[1]),\", \",formato.format(phi[2]),\"]\")","sub_path":"Talleres/Taller 2/SOR.py","file_name":"SOR.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"216974896","text":"print(\"AGENDA do ADS\")\r\n\r\nmenu = \"1\"\r\n\r\nwhile menu == \"1\" or menu == \"2\" or menu == \"3\":\r\n menu = input(\"Digite a opção desejada: \\n 1 - Cadastrar \\n 2 - Consultar \\n 3 - Sair \\n\")\r\n\r\n\r\n\r\n while menu != \"1\" and menu != \"2\" and menu != \"3\":\r\n print(\"Opção invalida!!! DIGITE NOVAMENTE!!\")\r\n menu = input(\"Digite a opção desejada: \\n 1 - Cadastrar \\n 2 - Consultar \\n 3 - Sair \\n\")\r\n\r\n\r\n \r\n if menu ==\"1\":\r\n lista_nome = []\r\n nome = input(\"Digite seu Nome: \")\r\n \r\n\r\n rua = input(\"Digite da sua Rua: \")\r\n cep = input(\"Digite seu CEP:\")\r\n bairro = input(\"Digite seu Bairro: \")\r\n estado = input(\"Digite o estado onde mora\")\r\n telefone = int(input(\"Digite seu ddd e telefone \"))\r\n\r\n \r\n dados = (\"Nome:{0} Rua:{1} CEP:{2} Bairro:{3} Estado:{4} Telefone:{5}' \".format(nome,rua,cep,bairro,estado,telefone))\r\n \r\n\r\n print(\"{0} CADASTRADO COM SUCESSO\".format(nome))\r\n\r\n arquivo = open('cadastro.txt','a')\r\n arquivo.write(dados + \"\\n\")\r\n print(\"Dados Adicionados no arquivo\")\r\n arquivo.close()\r\n \r\n\r\n\r\n \r\n\r\n elif menu == \"2\":\r\n palavra = input('Digite o nome da pessoa que deseja consultar: ')\r\n for line in open('cadastro.txt'):\r\n if palavra in line:\r\n print(line)\r\n\r\n \r\n elif menu == \"3\":\r\n print(\"Obrigado por utilizar!!!\")\r\n break\r\n","sub_path":"cadastro.py","file_name":"cadastro.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"448824283","text":"from datetime import datetime, timedelta\n\nfrom scheme import UTC, current_timestamp\nfrom spire.schema import *\nfrom spire.support.logs import LogHelper\nfrom sqlalchemy.sql import bindparam, text\n\nfrom platoon.models.subscribedtask import SubscribedTask\n\n__all__ = ('Event',)\n\nlog = LogHelper('platoon')\nschema = Schema('platoon')\n\nclass Event(Model):\n \"\"\"An event.\"\"\"\n\n class meta:\n schema = schema\n tablename = 'event'\n\n id = Identifier()\n topic = Token(nullable=False)\n aspects = Hstore()\n status = Enumeration('pending completed', nullable=False, default='pending')\n occurrence = DateTime(timezone=True)\n\n HSTORE_FILTER = text(':aspects @> subscribed_task.aspects',\n bindparams=[bindparam('aspects', type_=aspects.type)])\n\n @classmethod\n def create(cls, session, topic, aspects=None):\n event = Event(topic=topic, aspects=aspects, occurrence=datetime.now(UTC))\n session.add(event)\n return event\n\n def collate_tasks(self, session):\n model = SubscribedTask\n return (session.query(model).with_lockmode('update')\n .filter(model.topic==self.topic)\n .filter((model.activation_limit == None) | (model.activations < model.activation_limit))\n .filter(self.HSTORE_FILTER | (model.aspects == None))\n .params(aspects=(self.aspects or {})))\n\n def describe(self):\n aspects = {'topic': self.topic}\n if self.aspects:\n aspects.update(self.aspects)\n return aspects\n\n @classmethod\n def process_events(cls, session):\n for event in session.query(cls).with_lockmode('update').filter_by(status='pending'):\n event.schedule_tasks(session)\n else:\n session.commit()\n\n @classmethod\n def purge(cls, session, lifetime):\n delta = datetime.now(UTC) - timedelta(days=lifetime)\n session.query(cls).filter(cls.status == 'completed', cls.occurrence < delta).delete()\n\n def schedule_tasks(self, session):\n description = self.describe()\n for task in self.collate_tasks(session):\n task.activate(session, description)\n\n self.status = 'completed'\n","sub_path":"platoon/models/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"157884909","text":"import sys\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget\n\nfrom xps.menubar import MenuBar\nfrom xps.navbar import TreeDockWidget\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n QMainWindow.__init__(self, parent=None, flags=Qt.Window)\n self.initUI()\n\n def initUI(self):\n self.setMenuBar(MenuBar(self))\n self.setDockNestingEnabled(True)\n self.addDockWidget(Qt.LeftDockWidgetArea, TreeDockWidget(self))\n self.setCentralWidget(QTabWidget(self))\n self.resize(1200, 800)\n\n\nif __name__ == '__main__':\n application = QApplication(sys.argv)\n application.setApplicationName('dcsTMS')\n application.setApplicationDisplayName('dcsTMS')\n application.setOrganizationName('shuker')\n application.setOrganizationDomain('shuker.io')\n window = MainWindow()\n window.show()\n sys.exit(application.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"311180123","text":"#python3\n\nimport json\n\ndef retrieve_username():\n \"Retrieves username from memory\"\n try:\n with open(\"username.json\") as f_obj:\n username = json.load(f_obj)\n except FileNotFoundError:\n return none\n else:\n return username\n\ndef store_username():\n \"Stores username\"\n with \"username.json\" as f_obj:\n username = input(\"What is your username? \")\n json.dump(username, f_obj)\n print(\"I'll remember that.\")\n\ndef greet_user():\n \"Verifies identity and greets user\"\n username = retrieve_username()\n if username:\n verify_id = input(\"Is this you? \" + username)\n if verify_id.lowercase() == \"yes\" or verify_id.lowercase() == \"y\":\n print(\"Welcome back, \" + username)\n elif verify_id.lowercase() == \"no\" or verify_id.lowercase() == \"n\":\n store_username()\n else:\n print(\"Please answer yes or no.\")\n else:\n store_username()\n\nif __name__ == \"__main__\":\n greet_user()\n","sub_path":"remember_me.py","file_name":"remember_me.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"116118751","text":"import sqlite3\r\nimport random\r\n\r\nconnect = sqlite3.connect('database.db')\r\nconnect.execute(\"PRAGMA foreign_keys = 1\")\r\ncursor = connect.cursor()\r\n\r\ncursor.execute('''CREATE TABLE IF NOT EXISTS Clients (\r\n id INTEGER PRIMARY KEY,\r\n surname TEXT,\r\n name TEXT,\r\n patronymic TEXT)''')\r\n\r\ncursor.execute('''CREATE TABLE IF NOT EXISTS House (\r\n client_id INTEGER,\r\n adress TEXT,\r\n type TEXT CHECK (type IN\r\n (\"Flat\", \"House\", \"Penthouse\", \"Room\")),\r\n FOREIGN KEY (client_id) REFERENCES clientss(id)\r\n ON DELETE RESTRICT)''')\r\n\r\ncursor.execute('''CREATE TABLE IF NOT EXISTS Car (\r\n house_id INTEGER,\r\n mark TEXT,\r\n year INTEGER CHECK (year>1899 AND year<2015),\r\n FOREIGN KEY (house_id) REFERENCES house(id)\r\n ON DELETE CASCADE)''')\r\n\r\nsurname = ['Smith', 'Jobs', 'Gates']\r\nname = ['Steve', 'Bill', 'Mark']\r\npatronymic = ['John', 'Leonard', 'Mario']\r\nfor id in range(1, 6):\r\n sql = 'INSERT INTO Clientss VALUES(?,?,?,?)'\r\n surname = random.choice(surname)\r\n name = random.choice(name)\r\n patronymic = random.choice(patronymic)\r\n cursor.execute(sql, (id, surname, name, patronymic))\r\n \r\nstatuses = [\"Flat\", \"House\", \"Penthouse\", \"Room\"]\r\nadresses = [\"Avenue\", \"Street\", \"Shosse\", \"Bulwaure\"]\r\nfor i in range(1, 11):\r\n sql = 'INSERT INTO House VALUES(?,?,?)'\r\n house_id = random.randint(1, 6)\r\n adress = random.choice(adresses)\r\n status = random.choice(statuses)\r\n cursor.execute(sql, (house_id, adress, status))\r\n \r\nmarkes = ['Mersedes', 'BMW', 'Opel', 'Nissan', 'Toyota', 'Audi']\r\nfor id in range(1, 11):\r\n sql = 'INSERT INTO Car VALUES(?,?,?)'\r\n car_id = random.randint(1, 11)\r\n mark = random.choice(markes)\r\n year = random.randint(1900, 2014)\r\n cursor.execute(sql, (id, car_id, mark, year))\r\n\r\n\r\n\r\nconnect.commit()\r\nconnect.close()","sub_path":"Lab 3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"70650280","text":"#__author__ = 'alenush'\n\nimport pandas\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata = pandas.read_csv('trainers.csv')\n\ngold_row = []\ngold_standard = {'BNC':[], 'BAWE':[], \"Original\":[]}\n\nfor row in data.iloc[0][2:38]:\n gold_row.append(row)\n\ngold_standard[\"BNC\"] = gold_row[:4] + gold_row[12:16] + gold_row[24:28]\ngold_standard[\"BAWE\"] = gold_row[4:8] + gold_row[16:20] + gold_row[28:32]\ngold_standard[\"Original\"] = gold_row[8:12] + gold_row[20:24] + gold_row[32:36]\n\nprint(gold_standard)\n\nstudents_answers = {}\n\nfor i in range(1,23):\n answers = []\n for st_rows in data.iloc[i][2:38]:\n answers.append(st_rows.lower())\n students_answers[data.iloc[i][1]] = answers\n\nfor_mean = {'BNC':[], \"BAWE\":[], 'Origin':[]}\nprint(len(students_answers))\nfor key, value in students_answers.items():\n print(\"Student\",key)\n bnc, bawe, origin = 0,0,0\n bnc_answ = value[:4] + value[12:16] + value[24:28]\n bawe_answers = value[4:8] + value[16:20] + value[28:32]\n origin_answers = value[8:12] + value[20:24] + value[32:36]\n for gold, answer in zip(gold_standard['BNC'], bnc_answ):\n if answer in gold:\n bnc +=1\n for gold, answer in zip(gold_standard['BAWE'], bawe_answers):\n if answer in gold:\n bawe +=1\n for gold, answer in zip(gold_standard['Original'], origin_answers):\n if answer in gold:\n origin +=1\n print(bnc/len(bnc_answ)*100, bawe/len(bnc_answ)*100, origin/len(bnc_answ)*100)\n for_mean['BNC'].append(bnc/len(bnc_answ)*100)\n for_mean['BAWE'].append(bawe/len(bnc_answ)*100)\n for_mean['Origin'].append(origin/len(bnc_answ)*100)\n\nprint(for_mean)\nlabels = []\nfor key, value in for_mean.items():\n print(key, np.mean(value), max(value), min(value))\n\n\n","sub_path":"nug_needs/experiment_data.py","file_name":"experiment_data.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"154478251","text":"__all__ = ['BioPaxObject', 'Entity', 'Pathway', 'Gene', 'Unresolved']\n\nfrom ..xml_util import *\n\n\nclass Unresolved:\n def __init__(self, obj_id):\n self.obj_id = obj_id\n\n\nclass BioPaxObject:\n \"\"\"Generic BioPAX Object. It is the parent class of all more specific\n BioPAX classes.\"\"\"\n list_types = ['xref', 'comment']\n xml_types = {}\n\n def __init__(self, uid, name=None, comment=None, xref=None):\n self.uid = uid\n # TODO: is name in the right place here?\n self.name = name\n self.comment = comment\n # TODO: is xref in the right place here?\n self.xref = xref\n\n @classmethod\n def from_xml(cls, element):\n uid = get_id_or_about(element)\n kwargs = {'uid': uid}\n for key in cls.list_types:\n kwargs[key] = []\n for child in element.getchildren():\n key = get_attr_tag(child)\n # In some OWL formats, the child is directly defined\n # under this tag, in that case we directly deserialize it.\n if child.getchildren():\n gchild = child.getchildren()[0]\n obj_cls = globals()[get_tag(gchild)]\n val_to_add = obj_cls.from_xml(gchild)\n # Otherwise, we check if the element is a simple type that we\n # can just get as a text value\n elif (get_datatype(child.attrib) is None\n and not get_resource(child.attrib)) \\\n or is_datatype(child.attrib, nssuffix('xsd', 'string')) \\\n or is_datatype(child.attrib, nssuffix('xsd', 'int')) \\\n or is_datatype(child.attrib, nssuffix('xsd', 'float')):\n val_to_add = child.text\n # If neither of the above is the case, then we assume that the\n # element is a reference that is defined in another block\n # somewhere so we treat is as Unresolved until later.\n else:\n res = get_resource(child.attrib)\n val_to_add = Unresolved(res)\n\n if key in cls.list_types:\n kwargs[key].append(val_to_add)\n else:\n kwargs[key] = val_to_add\n return cls(**kwargs)\n\n def to_xml(self):\n id_type = 'about' if is_url(self.uid) else 'ID'\n element = makers['bp'](self.__class__.__name__,\n **{nselem('rdf', id_type): self.uid})\n for attr in [a for a in dir(self)\n if not a.startswith('_')\n and a not in {'list_types', 'xml_types',\n 'to_xml', 'from_xml', 'uid'}]:\n val = getattr(self, attr)\n if val is None:\n continue\n if isinstance(val, list):\n for v in val:\n child_elem = self._simple_to_xml(attr, v)\n if child_elem is not None:\n element.append(child_elem)\n else:\n child_elem = self._simple_to_xml(attr, val)\n if child_elem is not None:\n element.append(child_elem)\n return element\n\n def _simple_to_xml(self, attr, val):\n if isinstance(val, BioPaxObject):\n child_elem = makers['bp'](\n snake_to_camel(attr),\n **{nselem('rdf', 'resource'):\n ('#%s' % val.uid) if not is_url(val.uid) else val.uid}\n )\n return child_elem\n elif isinstance(val, str):\n xml_type = self.xml_types.get(attr, 'string')\n child_elem = makers['bp'](\n snake_to_camel(attr),\n val,\n **{nselem('rdf', 'datatype'): nssuffix('xsd', xml_type)}\n )\n return child_elem\n return None\n\n\nclass Entity(BioPaxObject):\n \"\"\"BioPAX Entity.\"\"\"\n list_types = BioPaxObject.list_types + \\\n ['evidence', 'data_source']\n\n def __init__(self,\n standard_name=None,\n display_name=None,\n all_names=None,\n participant_of=None,\n availability=None,\n data_source=None,\n evidence=None,\n **kwargs):\n super().__init__(**kwargs)\n self.standard_name = standard_name\n self.display_name = display_name\n self.all_names = all_names\n self.participant_of = participant_of\n self.availability = availability\n self.data_source = data_source\n self.evidence = evidence\n\n\nclass Gene(Entity):\n \"\"\"BioPAX Gene\"\"\"\n def __init__(self, organism, **kwargs):\n super().__init__(**kwargs)\n self.organism = organism\n\n\nclass Pathway(Entity):\n \"\"\"BioPAX Pathway.\"\"\"\n list_types = Entity.list_types + ['pathway_component']\n\n def __init__(self,\n pathway_component=None,\n pathway_order=None,\n organism=None,\n **kwargs):\n super().__init__(**kwargs)\n self.pathway_component = pathway_component\n self.pathway_order = pathway_order\n self.organism = organism\n\n\n# These are necessary to have the objects in the global\n# scope, required for some modes of deserialization\nfrom .interaction import *\nfrom .physical_entity import *\nfrom .util import *\n","sub_path":"pybiopax/biopax/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281918073","text":"'''\nAuthor: Puffrora\nDate: 2020-10-13 10:45:43\nLastModifiedBy: Puffrora\nLastEditTime: 2020-10-13 12:00:36\n'''\n\n\nclass RangeModule:\n\n import bisect\n\n def __init__(self):\n self.range = []\n\n # 找到目标区间的起始下标和终止下标\n def get_bounds(self, left, right):\n i, j = 0, len(self.range) - 1\n for k in (100, 10, 1):\n while i + k - 1 < len(self.range) and self.range[i+k-1][1] < left:\n i += k\n while j - k + 1 >= 0 and self.range[j-k+1][0] > right:\n j -= k\n return i, j\n\n def addRange(self, left, right):\n i, j = self.get_bounds(left, right)\n if i <= j:\n left = min(self.range[i][0], left)\n right = max(self.range[j][1], right)\n \n self.range[i:j+1] = [(left, right)]\n\n def queryRange(self, left, right):\n i = bisect.bisect_left(self.range, (left, float('inf')))\n if i: i -= 1\n return bool(self.range) and self.range[i][0] <= left and self.range[i][1] >= right\n \n def removeRange(self, left, right):\n i, j = self.get_bounds(left, right)\n merge = []\n for k in range(i, j+1):\n if self.range[k][0] < left:\n merge.append((self.range[k][0], left))\n if right < self.range[k][1]:\n merge.append((right, self.range[k][1]))\n self.range[i:j+1] = merge\n\n # Your RangeModule object will be instantiated and called as such:\n # obj = RangeModule()\n # obj.addRange(left,right)\n # param_2 = obj.queryRange(left,right)\n # obj.removeRange(left,right)\n","sub_path":"Leetcode/leetcode715 Range 模块.py","file_name":"leetcode715 Range 模块.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"119453466","text":"# LRU Page Replacement Policy\n# Least Recently Used\n# Ayush Jain - 2017UCP1168\nimport sys\nfhand = open(\"test.dat\",\"r\")\nnumPages = fhand.readline()\nnumPages = int(numPages)\ntmp = list(map(int,fhand.readline().split()))\nif(tmp[-1] != -1):\n print(\"Incorrect input format..Try Again..Exiting\")\n sys.exit(1)\ntmp = tmp[:-1]\nref_string = tmp\n############# Input from file done ##############\nbool_arr = [0 for i in range(100)]\nqueue = [] ; count = 0\nnum_Hits = 0 ; ttt = 0\nfor i in range(len(ref_string)):\n count += 1 ; ttt += 1\n tmp = ref_string[i]\n if(bool_arr[tmp] == 1):\n print(\"Page Requested : \",tmp,\" - Hit\",sep='')\n queue.remove(tmp)\n queue.append(tmp)\n num_Hits += 1\n else:\n print(\"Page Requested : \",tmp,\" - Miss\",sep='')\n bool_arr[tmp] = 1\n if(len(queue) < numPages):\n queue.append(tmp)\n else:\n x = queue[0]\n bool_arr[x] = 0\n queue = queue[1:]\n queue.append(tmp)\n if(ttt == 25):\n print(\"Hit Ratio = \",(num_Hits/count)*100,\"%\")\n ttt = 0\nprint(\"Hit Ratio = \",(num_Hits/count)*100,\"%\")\n","sub_path":"Assign_12_Memory_Management/Page_Replacement/LRU.py","file_name":"LRU.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"314701726","text":"#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2020\n# Leandro Toledo de Souza \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser 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# This program 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 Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program. If not, see [http://www.gnu.org/licenses/].\nfrom telegram import PhotoSize, UserProfilePhotos\n\n\nclass TestUserProfilePhotos(object):\n total_count = 2\n photos = [\n [\n PhotoSize('file_id1', 'file_un_id1', 512, 512),\n PhotoSize('file_id2', 'file_un_id1', 512, 512)\n ],\n [\n PhotoSize('file_id3', 'file_un_id3', 512, 512),\n PhotoSize('file_id4', 'file_un_id4', 512, 512)\n ]\n ]\n\n def test_de_json(self, bot):\n json_dict = {\n 'total_count': 2,\n 'photos': [[y.to_dict() for y in x] for x in self.photos]\n }\n user_profile_photos = UserProfilePhotos.de_json(json_dict, bot)\n assert user_profile_photos.total_count == self.total_count\n assert user_profile_photos.photos == self.photos\n\n def test_to_dict(self):\n user_profile_photos = UserProfilePhotos(self.total_count, self.photos)\n user_profile_photos_dict = user_profile_photos.to_dict()\n assert user_profile_photos_dict['total_count'] == user_profile_photos.total_count\n for ix, x in enumerate(user_profile_photos_dict['photos']):\n for iy, y in enumerate(x):\n assert y == user_profile_photos.photos[ix][iy].to_dict()\n","sub_path":"tests/test_userprofilephotos.py","file_name":"test_userprofilephotos.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"148635036","text":"import ElementTree2 as ET\nfrom ROOT import TLorentzVector, TCanvas, TH1F,TLegend,gStyle, TLatex\n\ntree1 = ET.parse('pp_h3_h1h2_h1aa_h2bb_lhapdf.lhe')\nroot1=tree1.getroot()\n\ntree2 = ET.parse('pp_h3_h1h2_h1bb_h2aa_lhapdf.lhe')\nroot2=tree2.getroot()\n\n\neta_b_l1=[]\neta_bbar_l1=[]\nphi_b_l1=[]\nphi_bbar_l1=[]\nphi_a_l1=[]\nphi_a2_l1=[]\neta_a_l1=[]\neta_a2_l1=[]\npt_b_l1=[]\npt_a2_l1=[]\npt_bbar_l1=[]\npt_a_l1=[]\nm_1_H1_l1=[]\nm_1_H2_l1=[]\nm_1_H3_l1=[]\n\n\neta_b_l2=[]\neta_bbar_l2=[]\nphi_b_l2=[]\nphi_bbar_l2=[]\nphi_a_l2=[]\nphi_a2_l2=[]\neta_a_l2=[]\neta_a2_l2=[]\npt_b_l2=[]\npt_a2_l2=[]\npt_bbar_l2=[]\npt_a_l2=[]\nm_1_H1_l2=[]\nm_1_H2_l2=[]\nm_1_H3_l2=[]\n\n\n\ngStyle.SetFrameLineWidth(3)\ngStyle.SetOptTitle(1)\ngStyle.SetOptStat(111)\ngStyle.SetFillColor(2)\ngStyle.SetLineWidth(1)\ngStyle.SetPadColor(1)\n\n#legend=TLegend(.63,.69,.87,.89,\"\",\"#gamma #gamma\")\n#legend=TLegend(0.57, 0.5, 0.94,0.65,\"\",\"b b~\")\n\nc=TCanvas(\"c\",\"First canvas\",2000,1900)\n\ncmsname=TLatex(0.15,1.85,\"Trials\")\n#cmsname=TLatex(0.15,1.85,\"CMS #it{#bf{Preliminary}}\")\ncmsname.SetTextSize(0.036)\ncmsname.SetTextAlign(12)\ncmsname.SetNDC(1)\ncmsname.SetTextFont(61)\n#lhefdata=LHEFData(float(root.attrib['version']))\n#lhefdata=LHEFData(float(root.attrib['version']))\nfor child in root1:\n if(child.tag=='event'):\n lines=child.text.strip().split('\\n')\n event_header=lines[0].strip()\n num_part=int(event_header.split()[0].strip())\n\n a1_1=[s for s in lines if s.split()[0]=='22']\n a1=a1_1[1::2]\n a2=a1_1[0::2]\n b1=[s for s in lines if s.split()[0]=='5']\n bbar1=[s for s in lines if s.split()[0]=='-5']\n\n px3_l1= float (a1[0].split()[6])\n py3_l1= float (a1[0].split()[7])\n pz3_l1= float (a1[0].split()[8])\n e3_l1= float (a1[0].split()[9])\n\n px4_l1= float (a2[0].split()[6])\n py4_l1= float (a2[0].split()[7])\n pz4_l1= float (a2[0].split()[8])\n e4_l1= float (a2[0].split()[9])\n\n p3=TLorentzVector(px3_l1,py3_l1,pz3_l1,e3_l1)\n p4=TLorentzVector(px4_l1,py4_l1,pz4_l1,e4_l1)\n #h1 constructed from aa\n pb1=p3+p4\n m_1_H1_l1.append(pb1.M())\n eta_a_l1.append(p3.Eta())\n pt_a_l1.append(p3.Pt())\n eta_a2_l1.append(p4.Eta())\n pt_a2_l1.append(p4.Pt())\n phi_a_l1.append(p3.Phi())\n phi_a2_l1.append(p4.Phi())\n\n px5_l1= float (b1[0].split()[6])\n py5_l1= float (b1[0].split()[7])\n pz5_l1= float (b1[0].split()[8])\n e5_l1= float (b1[0].split()[9])\n\n px6_l1= float (bbar1[0].split()[6])\n py6_l1= float (bbar1[0].split()[7])\n pz6_l1= float (bbar1[0].split()[8])\n e6_l1= float (bbar1[0].split()[9])\n\n p5=TLorentzVector(px5_l1,py5_l1,pz5_l1,e5_l1)\n p6=TLorentzVector(px6_l1,py6_l1,pz6_l1,e6_l1)\n #h2 constructed from bb~\n pb2=p5+p6\n m_1_H2_l1.append(pb2.M())\n eta_b_l1.append(p5.Eta())\n eta_bbar_l1.append(p6.Eta())\n pt_b_l1.append(p5.Pt())\n pt_bbar_l1.append(p6.Pt())\n phi_b_l1.append(p5.Phi())\n phi_bbar_l1.append(p6.Phi())\n\nfor child in root2:\n if(child.tag=='event'):\n lines=child.text.strip().split('\\n')\n event_header=lines[0].strip()\n num_part=int(event_header.split()[0].strip())\n\n a1_1=[s for s in lines if s.split()[0]=='22']\n a1=a1_1[1::2]\n a2=a1_1[0::2]\n b1=[s for s in lines if s.split()[0]=='5']\n bbar1=[s for s in lines if s.split()[0]=='-5']\n\n px3_l2= float (a1[0].split()[6])\n py3_l2= float (a1[0].split()[7])\n pz3_l2= float (a1[0].split()[8])\n e3_l2= float (a1[0].split()[9])\n\n px4_l2= float (a2[0].split()[6])\n py4_l2= float (a2[0].split()[7])\n pz4_l2= float (a2[0].split()[8])\n e4_l2= float (a2[0].split()[9])\n\n p3=TLorentzVector(px3_l2,py3_l2,pz3_l2,e3_l2)\n p4=TLorentzVector(px4_l2,py4_l2,pz4_l2,e4_l2)\n #h2 constructed from aa\n pb1=p3+p4\n m_1_H2_l2.append(pb1.M())\n eta_a_l2.append(p3.Eta())\n pt_a_l2.append(p3.Pt())\n eta_a2_l2.append(p4.Eta())\n pt_a2_l2.append(p4.Pt())\n phi_a_l2.append(p3.Phi())\n phi_a2_l2.append(p4.Phi())\n\n px5_l2= float (b1[0].split()[6])\n py5_l2= float (b1[0].split()[7])\n pz5_l2= float (b1[0].split()[8])\n e5_l2= float (b1[0].split()[9])\n\n px6_l2= float (bbar1[0].split()[6])\n py6_l2= float (bbar1[0].split()[7])\n pz6_l2= float (bbar1[0].split()[8])\n e6=float (bbar1[0].split()[9])\n\n p5=TLorentzVector(px5_l2,py5_l2,pz5_l2,e5_l2)\n p6=TLorentzVector(px6_l2,py6_l2,pz6_l2,e6_l2)\n #h1 constructed from bb~\n pb2=p5+p6\n m_1_H1_l2.append(pb2.M())\n eta_b_l2.append(p5.Eta())\n eta_bbar_l2.append(p6.Eta())\n pt_b_l2.append(p5.Pt())\n pt_bbar_l2.append(p6.Pt())\n phi_b_l2.append(p5.Phi())\n phi_bbar_l2.append(p6.Phi())\n\n\n\nc.SetLogy()\n\nh1_l1=TH1F('Invariant Mass of H1 (#gamma #gamma)',\"\",1000,0,1200)\nfor i in m_1_H1_l1:\n h1_l1.Fill(i)\n\nh14_l1=TH1F('Invariant Mass of H2 (bb~)',\"\",1000,0,1200)\nfor i in m_1_H2_l1:\n h14_l1.Fill(i)\n\n\nh2_l1=TH1F('#eta_{#gamma1}',\"\",100,-5,5)\nfor i in eta_a_l1:\n h2_l1.Fill(i)\n\nh9_l1=TH1F('#eta_{#gamma2}',\"\",100,-5,5)\nfor i in eta_a2_l1:\n h9_l1.Fill(i)\n\nh3_l1=TH1F('#eta_{b}',\"\",100,-5,5)\nfor i in eta_b_l1:\n h3_l1.Fill(i)\n\nh7_l1=TH1F('#eta_{b~}',\"\",100,-5,5)\nfor i in eta_bbar_l1:\n h7_l1.Fill(i)\n\nh4_l1=TH1F('P_{T#gamma1}',\"\",100,0,1000)\nfor i in pt_a_l1:\n h4_l1.Fill(i)\n\nh8_l1=TH1F('P_{T#gamma2}',\"\",100,0,1000)\nfor i in pt_a2_l1:\n h8_l1.Fill(i)\n\nh5_l1=TH1F('Pt of b',\"\",100,0,1000)\nfor i in pt_b_l1:\n h5_l1.Fill(i)\n\nh6_l1=TH1F('Pt of bbar',\"\",100,0,1000)\nfor i in pt_bbar_l1:\n h6_l1.Fill(i)\n\nh10_l1=TH1F('Phi of a',\"\",10,-4,4)\nfor i in phi_a_l1:\n h10_l1.Fill(i)\n\nh11_l1=TH1F('Phi of a2',\"\",10,-4,5)\nfor i in phi_a2_l1:\n h11_l1.Fill(i)\n\nh12_l1=TH1F('Phi of b',\"\",10,-4,4)\nfor i in phi_b_l1:\n h12_l1.Fill(i)\nh13_l1=TH1F('Phi of bbar',\"\",10,-4,4)\nfor i in phi_bbar_l1:\n h13_l1.Fill(i)\n\n\n\n\nh1_l2=TH1F('Invariant Mass of H1 (bb~)',\"\",1000,0,1200)\nfor i in m_1_H1_l2:\n h1_l2.Fill(i)\n\nh14_l2=TH1F('Invariant Mass of H2 (#gamma #gamma)',\"\",1000,0,1200)\nfor i in m_1_H2_l2:\n h14_l2.Fill(i)\n\n\nh2_l2=TH1F('#eta_{#gamma1}',\"\",100,-5,5)\nfor i in eta_a_l2:\n h2_l2.Fill(i)\n\nh9_l2=TH1F('#eta_{#gamma2}',\"\",100,-5,5)\nfor i in eta_a2_l2:\n h9_l2.Fill(i)\n\nh3_l2=TH1F('#eta_{b}',\"\",100,-5,5)\nfor i in eta_b_l2:\n h3_l2.Fill(i)\n\nh7_l2=TH1F('#eta_{b~}',\"\",100,-5,5)\nfor i in eta_bbar_l2:\n h7_l2.Fill(i)\n\nh4_l2=TH1F('P_{T#gamma1}',\"\",100,0,1000)\nfor i in pt_a_l2:\n h4_l2.Fill(i)\n\nh8_l2=TH1F('P_{T#gamma2}',\"\",100,0,1000)\nfor i in pt_a2_l2:\n h8_l2.Fill(i)\n\nh5_l2=TH1F('Pt of b',\"\",100,0,1000)\nfor i in pt_b_l2:\n h5_l2.Fill(i)\n\nh6_l2=TH1F('Pt of bbar',\"\",100,0,1000)\nfor i in pt_bbar_l2:\n h6_l2.Fill(i)\n\nh10_l2=TH1F('Phi of a',\"\",10,-4,4)\nfor i in phi_a_l2:\n h10_l2.Fill(i)\n\n#h11_l2=TH1F('Phi of a2',\"\",10,-4,5)\n#for i in phi_a2_l2:\n# h11_l2.Fill(i)\n\nh12_l2=TH1F('Phi of b',\"\",10,-4,4)\nfor i in phi_b_l2:\n h12_l2.Fill(i)\nh13_l2=TH1F('Phi of bbar',\"\",10,-4,4)\nfor i in phi_bbar_l2:\n h13_l2.Fill(i)\n\n\n\n'''\ntps1=TPaveStats()\nh1.FindObject(\"stats\")\ntps1.SetName(\"Hist1 Stats\")\nX1=tps1.GetX1NDC()\nY1=tps1.GetY1NDC()\nX2=tps1.GetX2NDC()\nY2=tps1.GetY2NDC()\n\ntps2=TPaveStats()\nh14.FindObject(\"stats\")\ntps2.SetTextColor(kRed)\ntps2.SetLineColor(kRed)\ntps2.SetX1NDC(X1)\ntps2.SetX2NDC(X2)\ntps2.SetY1NDC(Y1-(Y2-Y1))\ntps2.SetY2NDC(Y1)\n'''\n'''\nlegend=TLegend(0.1,0.1,0.3,0.3)\nlegend.SetHeader(\"Legend\")\nlegend.AddEntry(h2,\"#eta_{#gamma1}\",\"l\")\nlegend.AddEntry(h9,\"#eta_{#gamma2}\",\"l\")\nlegend.AddEntry(h3,\"#eta_{b}\",\"l\")\nlegend.AddEntry(h7,\"#eta_{b~}\",\"l\")\nlegend.AddEntry(h4,\"pt_{#gamma1}\",\"l\")\nlegend.AddEntry(h8,\"pt_{#gamma2}\",\"l\")\nlegend.AddEntry(h4,\"pt_{#gamma1}\",\"l\")\nlegend.AddEntry(h8,\"pt_{#gamma2}\",\"l\")\n'''\n\nh1_l1.SetXTitle(\"M_h1_aa [GeV]\")\nh1_l1.SetYTitle(\"Events\")\nh1_l1.SetLineColor(6)\nh1_l2.SetXTitle(\"M_h1_bb [GeV]\")\nh1_l2.SetYTitle(\"events\")\nh1_l2.SetLineColor(4)\nh1_l1.DrawNormalized(\"hist\")\nh1_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"Mass_combine_h1.png\")\nc.SaveAs(\"Mass_combine_h1.root\")\n\nh14_l1.SetXTitle(\"M_h2_bb [GeV]\")\nh14_l1.SetYTitle(\"Events\")\nh14_l1.SetLineColor(6)\nh14_l2.SetXTitle(\"M_h1_aa [GeV]\")\nh14_l2.SetYTitle(\"events\")\nh14_l2.SetLineColor(4)\nh14_l1.DrawNormalized(\"hist\")\nh14_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"Mass_combine_h2.png\")\nc.SaveAs(\"Mass_combine_h2.root\")\n\nh2_l1.SetXTitle(\"#eta_{#gamma}\")\nh2_l1.SetYTitle(\"Events\")\nh2_l1.SetLineColor(6)\nh2_l2.SetXTitle(\"#eta_{#gamma}\")\nh2_l2.SetYTitle(\"events\")\nh2_l2.SetLineColor(4)\nh2_l1.DrawNormalized(\"hist\")\nh2_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"eta_combine_gamma.png\")\nc.SaveAs(\"eta_combine_gamma.root\")\n\nh3_l1.SetXTitle(\"#eta_{b}\")\nh3_l1.SetYTitle(\"Events\")\nh3_l1.SetLineColor(6)\nh3_l2.SetXTitle(\"#eta_{b}\")\nh3_l2.SetYTitle(\"events\")\nh3_l2.SetLineColor(4)\nh3_l1.DrawNormalized(\"hist\")\nh3_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"eta_combine_b.png\")\nc.SaveAs(\"eta_combine_b.root\")\n\nh4_l1.SetXTitle(\"p_{T#gamma} \")\nh4_l1.SetYTitle(\"Events\")\nh4_l1.SetLineColor(6)\nh4_l2.SetXTitle(\"p_{T#gamma}\")\nh4_l2.SetYTitle(\"events\")\nh4_l2.SetLineColor(4)\nh4_l1.DrawNormalized(\"hist\")\nh4_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"pT_combine_gamma.png\")\nc.SaveAs(\"pT_combine_gamma.root\")\n\nh5_l1.SetXTitle(\"#p_{T}_b\")\nh5_l1.SetYTitle(\"Events\")\nh5_l1.SetLineColor(6)\nh5_l2.SetXTitle(\"#p_{T}_b\")\nh5_l2.SetYTitle(\"events\")\nh5_l2.SetLineColor(4)\nh5_l1.DrawNormalized(\"hist\")\nh5_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"pT_combine_b.png\")\nc.SaveAs(\"pT_combine_b.root\")\n\nh6_l1.SetXTitle(\"#p_{T}_b~\")\nh6_l1.SetYTitle(\"Events\")\nh6_l1.SetLineColor(6)\nh6_l2.SetXTitle(\"#p_{T}_b~\")\nh6_l2.SetYTitle(\"events\")\nh6_l2.SetLineColor(4)\nh6_l1.DrawNormalized(\"hist\")\nh6_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"pT_combine_b~.png\")\nc.SaveAs(\"pT_combine_b~.root\")\n\nh7_l1.SetXTitle(\"#eta_{b~}\")\nh7_l1.SetYTitle(\"Events\")\nh7_l1.SetLineColor(6)\nh7_l2.SetXTitle(\"#eta_{b~}\")\nh7_l2.SetYTitle(\"events\")\nh7_l2.SetLineColor(4)\nh7_l1.DrawNormalized(\"hist\")\nh7_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"eta_combine_b~.png\")\nc.SaveAs(\"eta_combine_b~.root\")\n\nh10_l1.SetXTitle(\"#phi_{#gamma2}\")\nh10_l1.SetYTitle(\"Events\")\nh10_l1.SetLineColor(6)\nh10_l2.SetXTitle(\"#phi_{#gamma2}\")\nh10_l2.SetYTitle(\"events\")\nh10_l2.SetLineColor(4)\nh10_l1.DrawNormalized(\"hist\")\nh10_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"phi_combine_gamma.png\")\nc.SaveAs(\"phi_combine_gamma.root\")\n\nh12_l1.SetXTitle(\"#phi_{b}\")\nh12_l1.SetYTitle(\"Events\")\nh12_l1.SetLineColor(6)\nh12_l2.SetXTitle(\"#phi_{b}\")\nh12_l2.SetYTitle(\"events\")\nh12_l2.SetLineColor(4)\nh12_l1.DrawNormalized(\"hist\")\nh12_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"phi_combine_b.png\")\nc.SaveAs(\"phi_combine_b.root\")\n\nh13_l1.SetXTitle(\"#phi_{b~}\")\nh13_l1.SetYTitle(\"Events\")\nh13_l1.SetLineColor(6)\nh13_l2.SetXTitle(\"#phi_{b~}\")\nh13_l2.SetYTitle(\"events\")\nh13_l2.SetLineColor(4)\nh13_l1.DrawNormalized(\"hist\")\nh13_l2.DrawNormalized(\"hist&SAMES\")\nc.SaveAs(\"phi_combine_b~.png\")\nc.SaveAs(\"phi_combine_b~.root\")\n","sub_path":"pp_h3_h1h2_h1aa_h2bb_lhapdf/combined.py","file_name":"combined.py","file_ext":"py","file_size_in_byte":11081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"289425729","text":"import collections\nimport itertools\nimport heapq\n\nclass Maze:\n \"\"\" Class finding its way through the maze. \"\"\"\n\n def __init__(self,fileName, multi_robots = False):\n self.grid = self.read_map(fileName)\n self.y, self.x, self.total_keys = self.find_start_and_keys()\n self.pos = self.initialize_position(multi_robots)\n\n def compute_shortest_path(self):\n \"\"\" Traverse the grid by first looking for the reachable keys and select\n nodes with shortest distance while traversing.\"\"\"\n\n # Initial node - depth, position, collection of keys\n q = [(0, self.pos, frozenset())]\n\n # Visited nodes\n visited = set()\n\n while q:\n\n # Obtain shortest the node\n depth, current_pos, keys = heapq.heappop(q)\n\n # We are done if all keys are found\n if keys == self.total_keys:\n return depth\n\n # Skip node if visited before\n if (current_pos, keys) in visited:\n continue\n\n # Update visited node\n visited.add( (current_pos, keys) )\n\n # Go through positions\n for i, (current_y, current_x) in enumerate(current_pos):\n # Go through the reachable keys for each position\n for d, y, x, key in self.reachable_keys(current_y,current_x,keys):\n # Update positions list\n new_pos = current_pos[0:i] + ((y,x,),) + current_pos[i+1:]\n # Push to heap new depth, new position, and collected keys\n heapq.heappush(q, (depth+d, new_pos, keys | frozenset([key])))\n\n def reachable_keys(self, y_, x_, keys):\n \"\"\" Given start position y_,x_, and keys find other reachable keys \"\"\"\n\n # Initialize node to go through\n q = collections.deque( [(y_, x_, 0)] )\n\n # Initialize visited nodes\n visited = set()\n\n # Search directions\n directions = ( (1,0), (-1, 0), (0,1), (0, -1))\n\n while q:\n\n # Get the node\n y, x, depth = q.popleft()\n\n # If we reach a key which we do not have, yield it\n if self.grid[y][x].islower() and self.grid[y][x] not in keys:\n yield depth, y, x, self.grid[y][x]\n continue\n\n # Search neighbors\n for dy, dx in directions:\n y_new, x_new = y + dy, x + dx\n\n # Skip if we have visited the node\n if ((y_new,x_new)) in visited:\n continue\n\n # Add to visited node\n visited.add((y_new,x_new))\n\n value = self.grid[y_new][x_new]\n\n if value != '#' and (not value.isupper() or value.lower() in keys):\n q.append( (y_new, x_new, depth + 1) )\n\n def initialize_position(self, multi_robots):\n \"\"\" Set the initial position depending on part one or part two \"\"\"\n if multi_robots:\n y, x = self.y, self.x\n self.grid[y-1] = self.grid[y-1][:x] + '#' + self.grid[y-1][x+1:]\n self.grid[y ] = self.grid[y][:x-1] + '###' + self.grid[y][x+2:]\n self.grid[y+1] = self.grid[y+1][:x] + '#' + self.grid[y+1][x+1:]\n return ( (self.y-1, self.x-1), (self.y-1, self.x+1), \\\n (self.y+1, self.x-1), (self.y+1, self.x+1), )\n else:\n return ( (self.y,self.x),)\n\n def find_start_and_keys(self):\n \"\"\" Figure out middle of the map and how many keys are present \"\"\"\n # Flatten grid\n linear_grid = list(itertools.chain.from_iterable(self.grid))\n\n # Width and height of grid\n height, width = len(self.grid), len(self.grid[0])\n start_index = linear_grid.index('@')\n\n # Divide index with length and width\n y, x = start_index // width, start_index % width\n \n # If the key is a lower case letter then include\n total_keys = set(key for key in linear_grid if key.islower())\n\n return y, x, total_keys\n\n def read_map(self,fileName):\n \"\"\" Read the map \"\"\"\n with open(fileName) as f: return f.read().splitlines()\n def print_map(self):\n \"\"\" Print the map \"\"\"\n for row in self.grid: print(\"\".join(row))","sub_path":"2019/day18/python/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"337912116","text":"def send_request(self, data, **message_kwargs):\n data = to_list(data)\n become = self._become\n if become:\n self.connection.queue_message('vvvv', 'firing event: on_become')\n data.insert(0, {\n 'cmd': 'enable',\n 'input': self._become_pass,\n })\n output = message_kwargs.get('output', 'text')\n request = request_builder(data, output)\n headers = {\n 'Content-Type': 'application/json-rpc',\n }\n (response, response_data) = self.connection.send('/command-api', request, headers=headers, method='POST')\n try:\n response_data = json.loads(to_text(response_data.getvalue()))\n except ValueError:\n raise ConnectionError('Response was not valid JSON, got {0}'.format(to_text(response_data.getvalue())))\n results = handle_response(response_data)\n if become:\n results = results[1:]\n if (len(results) == 1):\n results = results[0]\n return results","sub_path":"Data Set/bug-fixing-5/84d9b3e58986d70ca64539e816e342a9d7d0b888--fix.py","file_name":"84d9b3e58986d70ca64539e816e342a9d7d0b888--fix.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"464049159","text":"# -*- coding: utf-8 -*-\nimport time\nimport numpy as np\nimport geatpy as ea # 导入geatpy库\nfrom sys import path as paths\nfrom os import path as currentPath\npaths.append(currentPath.split(currentPath.realpath(__file__))[0])\nfrom updateNDSet import updateNDSet # 导入该算法模板所需的外部函数\n\nclass moea_awGA_templet(ea.MoeaAlgorithm):\n \n \"\"\"\nmoea_awGA_templet : class - 多目标进化优化awGA算法模板\n \n算法描述:\n 采用awGA进行多目标优化。\n\n模板使用注意:\n 本模板调用的目标函数形如:aimFunc(pop), \n 其中pop为Population类的对象,代表一个种群,\n pop对象的Phen属性(即种群染色体的表现型)等价于种群所有个体的决策变量组成的矩阵,\n 该函数根据该Phen计算得到种群所有个体的目标函数值组成的矩阵,并将其赋值给pop对象的ObjV属性。\n 若有约束条件,则在计算违反约束程度矩阵CV后赋值给pop对象的CV属性(详见Geatpy数据结构)。\n 该函数不返回任何的返回值,求得的目标函数值保存在种群对象的ObjV属性中,\n 违反约束程度矩阵保存在种群对象的CV属性中。\n 例如:population为一个种群对象,则调用aimFunc(population)即可完成目标函数值的计算,\n 此时可通过population.ObjV得到求得的目标函数值,population.CV得到违反约束程度矩阵。\n 若不符合上述规范,则请修改算法模板或自定义新算法模板。\n \n参考文献:\n [1] Gen M,CHeng R. Genetic Algorithms and Engineering Optimization[M]. \n New York: John Wiley & Sons,2000\n \n \"\"\"\n \n def __init__(self, problem, population):\n ea.MoeaAlgorithm.__init__(self, problem, population) # 先调用父类构造方法\n if str(type(population)) != \"\":\n raise RuntimeError('传入的种群对象必须为Population类型')\n self.name = 'awGA'\n self.selFunc = 'tour' # 选择方式,采用锦标赛选择\n if population.Encoding == 'P':\n self.recFunc = 'xovpmx' # 部分匹配交叉\n self.mutFunc = 'mutinv' # 染色体片段逆转变异\n elif population.Encoding == 'BG':\n self.recFunc = 'xovud' # 均匀交叉\n self.mutFunc = 'mutbin' # 二进制变异\n elif population.Encoding == 'RI':\n self.recFunc = 'xovud' # 均匀交叉\n self.mutFunc = 'mutuni' # 均匀变异\n else:\n raise RuntimeError('编码方式必须为''BG''、''RI''或''P''.')\n self.pc = 1 # 重组概率\n self.pm = 1 # 整条染色体的变异概率\n self.MAXSIZE = population.sizes # 非支配解集大小限制\n\n def run(self):\n #==========================初始化配置===========================\n problem = self.problem\n population = self.population\n NIND = population.sizes\n MAXSIZE = self.MAXSIZE\n if MAXSIZE is None: # 检查MAXSIZE,默认取2倍的种群规模\n MAXSIZE = 2 * NIND\n self.initialization() # 初始化算法模板的一些动态参数\n #===========================准备进化============================\n if population.Chrom is None:\n population.initChrom(NIND) # 初始化种群染色体矩阵(内含解码,详见Population类的源码)\n else:\n population.Phen = population.decoding() # 染色体解码\n self.problem.aimFunc(population) # 计算种群的目标函数值\n NDSet = updateNDSet(population, problem.maxormins, MAXSIZE) # 计算适应度和得到全局非支配种群\n self.evalsNum = population.sizes # 记录评价次数\n #===========================开始进化============================\n while self.terminated(population) == False:\n uniChrom = np.unique(NDSet.Chrom, axis = 0)\n repRate = 1 - uniChrom.shape[0] / NDSet.sizes # 计算NDSet中的重复率\n # 选择个体去进化形成子代\n offspring = population[ea.selecting(self.selFunc, population.FitnV, NIND)]\n offspring.Chrom = ea.recombin(self.recFunc, offspring.Chrom, self.pc) #重组\n offspring.Chrom = ea.mutate(self.mutFunc, offspring.Encoding, offspring.Chrom, offspring.Field, self.pm) # 变异\n if population.Encoding != 'BG' and repRate > 0.1:\n offspring.Chrom = ea.mutate('mutgau', offspring.Encoding, offspring.Chrom, offspring.Field, self.pm, False, 3) # 高斯变异,对标准差放大3倍。\n offspring.Phen = offspring.decoding() # 染色体解码\n self.problem.aimFunc(offspring) # 求进化后个体的目标函数值\n self.evalsNum += offspring.sizes # 更新评价次数\n # 父代种群和育种种群合并\n population = population + offspring\n NDSet = updateNDSet(population, problem.maxormins, MAXSIZE, NDSet) # 计算合并种群的适应度及更新NDSet\n # 保留个体到下一代\n population = population[ea.selecting('dup', population.FitnV, NIND)] # 选择,保留NIND个个体\n NDSet = NDSet[np.where(np.all(NDSet.CV <= 0, 1))[0]] # 最后要彻底排除非可行解\n self.passTime += time.time() - self.timeSlot # 更新用时记录\n #=========================绘图及输出结果=========================\n if self.drawing != 0:\n ea.moeaplot(NDSet.ObjV, 'Pareto Front', True)\n # 返回帕累托最优集\n return NDSet\n ","sub_path":"geatpy/templates/moeas/awGA/moea_awGA_templet.py","file_name":"moea_awGA_templet.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"310043710","text":"import urllib.request\nimport os.path\n\nurl_base = 'http://yann.lecun.com/exdb/mnist/'\nkey_file = {\n 'train_img':'train-images-idx3-ubyte.gz',\n 'train_label':'train-labels-idx1-ubyte.gz',\n 'test_img':'t10k-images-idx3-ubyte.gz',\n 'test_label':'t10k-labels-idx1-ubyte.gz'\n}\ndataset_dir = os.path.dirname(os.path.abspath(__file__))\n\ndef _download(filename):\n file_path = dataset_dir + '/' + filename\n if os.path.exists(file_path):\n return print('already exist')\n print('Downloading ' + filename + ' ...')\n urllib.request.urlretrieve(url_base + filename, file_path)\n print('Done')\n\ndef download_mnist():\n for v in key_file.values():\n _download(v)\n\ndownload_mnist()\n","sub_path":"intelligentSystemTraining/MnistDownload.py","file_name":"MnistDownload.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"98246711","text":"import tensorflow as tf\n\n\"\"\"\ntfrecord_list : a list of tfrecord file\nparse_function: A function with a signature parse_function( example_proto )\nbatch_size : an integer denoting the size of the batch\nparser function is supplied by client and therefore this\nprepare_dataset is independent of the task in hand.\nReturns the Dataset\n\"\"\"\n\n\n#########################################\n# gets an input list of tfrecord file names\n# and prepares a datset\n#\n#########################################\n\n\ndef prepare_dataset(tfrecord_list, parse_function, batch_size ):\n\n dataset = tf.data.TFRecordDataset(tfrecord_list)\n\n dataset = dataset.shuffle(buffer_size=5000)\n\n dataset = dataset.map(parse_function)\n\n dataset = dataset.batch(batch_size)\n\n dataset = dataset.repeat()\n\n return dataset","sub_path":"tfread/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"544079400","text":"\"\"\"\n Module that defines the `NetworkGroup` object and methods to read, write and manipulate it\n\"\"\"\n\nfrom collections.abc import Collection\nfrom typing import Any, Dict, Iterator, List, Union\n\nimport networkx as nx\nimport simplejson\n\nfrom .network import Network\n\nDType = List[Dict[str, Any]]\n\n\nclass NetworkGroup(Collection):\n \"\"\"\n Class that represents a group of network objects\n These network objects are intended to be visualized together\n\n Parameters\n ----------\n networks : List[Network]\n The collection of networks to be grouped\n key = context-id, value = Network\n\n Attributes\n ----------\n graph : Union[nx.MultiGraph, nx.MultiDiGraph]\n The networkx multi-graph representation of the network\n nodes: DType\n The list of nodes in the network group\n links: DType\n The list of links in the network group\n contexts: DType\n The list of all contexts in the network group\n \"\"\"\n\n def __init__(self, networks: List[Network]) -> None:\n self.nodeid_map: Dict[int, Dict[str, str]] = dict()\n self._networks = networks\n if not networks or [n for n in networks if not isinstance(n, Network)]:\n raise ValueError(\n \"The networks parameter must be a list of one or more networks\"\n )\n self.graph = self._combine_networks(networks)\n\n def __contains__(self, key) -> bool:\n if key in range(len(self)):\n return True\n return False\n\n def __len__(self) -> int:\n return len(self._networks)\n\n def __iter__(self) -> Iterator:\n return iter(self._networks)\n\n def __repr__(self) -> str:\n n_nodes = len(self.nodes)\n n_links = len(self.links)\n n_contexts = len(self.contexts)\n return f\"\"\n\n def _combine_nodes(self, all_nodes: Dict[int, DType]) -> DType:\n \"\"\" Combine nodes of individual networks into a single list \"\"\"\n nodes: DType = []\n node_hash: Dict[int, int] = dict() # taxid => nodes.index\n if len(all_nodes) == 1:\n return all_nodes[0]\n for cid, network_nodes in all_nodes.items():\n self.nodeid_map[cid] = dict()\n for node in network_nodes:\n if node[\"taxid\"] not in node_hash:\n id_ = len(nodes)\n id_old = node[\"id\"]\n id_new = f\"id{id_}\"\n nodes.append(\n {**node, **{\"id\": id_new, \"children\": [], \"abundance\": None}}\n )\n node_hash[node[\"taxid\"]] = id_\n self.nodeid_map[cid][id_old] = id_new\n else:\n id_old = node[\"id\"]\n ind = node_hash[node[\"taxid\"]]\n id_new = nodes[ind][\"id\"]\n self.nodeid_map[cid][id_old] = id_new\n return nodes\n\n def _combine_links(self, all_links: Dict[int, DType]) -> DType:\n \"\"\" Combine links of individual networks into a single list \"\"\"\n links = []\n if len(all_links) == 1:\n for link in all_links[0]:\n links.append({**link, \"context_index\": 0})\n return links\n for cid, network_links in all_links.items():\n for link in network_links:\n source, target = link[\"source\"], link[\"target\"]\n new_source = self.nodeid_map[cid][source]\n new_target = self.nodeid_map[cid][target]\n links.append(\n {\n **link,\n **{\n \"source\": new_source,\n \"target\": new_target,\n \"context_index\": cid,\n },\n }\n )\n return links\n\n def _combine_networks(\n self, networks: List[Network]\n ) -> Union[nx.MultiGraph, nx.MultiDiGraph]:\n \"\"\"\n Combine networks into a network group\n\n Parameters\n ----------\n networks : List[Network]\n The list of networks to be grouped\n\n Returns\n -------\n Union[nx.MultiGraph, nx.MultiDiGraph]\n The networkx graph of the network\n \"\"\"\n nodes_dict = dict()\n links_dict = dict()\n contexts = []\n for cid, network in enumerate(networks):\n nodes_dict[cid] = network.nodes\n links_dict[cid] = network.links\n contexts.append(network.metadata)\n merged_nodes = self._combine_nodes(nodes_dict)\n merged_links = self._combine_links(links_dict)\n if all([n.graph.is_directed() for n in networks]):\n graph = nx.MultiDiGraph(contexts=contexts)\n else:\n graph = nx.MultiGraph(contexts=contexts)\n for node in merged_nodes:\n graph.add_node(node[\"id\"], **node)\n for link in merged_links:\n graph.add_edge(link[\"source\"], link[\"target\"], **link)\n return graph\n\n @property\n def nodes(self) -> DType:\n \"\"\" The list of nodes in the `NetworkGroup` and their corresponding properties \"\"\"\n return [data for _, data in self.graph.nodes(data=True)]\n\n @property\n def links(self) -> DType:\n \"\"\" The list of links in the `NetworkGroup` and their corresponding properties \"\"\"\n return [data for _, _, data in self.graph.edges(data=True)]\n\n @property\n def contexts(self) -> DType:\n \"\"\" The contexts for the group of networks \"\"\"\n return self.graph.graph[\"contexts\"]\n\n def filter_links(self, pvalue_filter: bool, interaction_filter: bool) -> DType:\n \"\"\"\n The links of the networks after applying filtering\n\n Parameters\n ----------\n pvalue_filter : bool\n If True will use `pvalue_threshold` for filtering\n interaction_filter : bool\n If True will use `interaction_threshold` for filtering\n\n Returns\n -------\n DType\n The list of links in the network after applying thresholds\n \"\"\"\n filtered_links_dict = dict()\n for cid, network in enumerate(self._networks):\n filtered_links_dict[cid] = network.filter_links(\n pvalue_filter=pvalue_filter, interaction_filter=interaction_filter\n )\n merged_filtered_links = self._combine_links(filtered_links_dict)\n return merged_filtered_links\n\n def json(\n self, pvalue_filter: bool = False, interaction_filter: bool = False\n ) -> str:\n \"\"\"\n Returns the network as a `JSON` string\n\n Parameters\n ----------\n pvalue_filter : bool\n If True will use `pvalue_threshold` for filtering\n Default value is False\n interaction_filter : bool\n If True will use `interaction_threshold` for filtering\n Default value is False\n\n Returns\n -------\n str\n The `JSON` string representation of the network\n \"\"\"\n nodes = self.nodes\n links = self.filter_links(\n pvalue_filter=pvalue_filter, interaction_filter=interaction_filter\n )\n contexts = self.contexts\n network = {\"contexts\": contexts, \"nodes\": nodes, \"links\": links}\n return simplejson.dumps(network, indent=2, sort_keys=True, ignore_nan=True)\n\n def write(\n self, fpath: str, pvalue_filter: bool = False, interaction_filter: bool = False\n ) -> None:\n \"\"\"\n Write network to file as JSON\n\n Parameters\n ----------\n fpath : str\n The path to the `JSON` file\n pvalue_filter : bool\n If True will use `pvalue_threshold` for filtering\n Default value is False\n interaction_filter : bool\n If True will use `interaction_threshold` for filtering\n Default value is False\n \"\"\"\n with open(fpath, \"w\") as fid:\n fid.write(\n self.json(\n pvalue_filter=pvalue_filter, interaction_filter=interaction_filter\n )\n )\n\n @classmethod\n def load_json(cls, fpath: str) -> \"NetworkGroup\":\n \"\"\"\n Create a `NetworkGroup` object from network `JSON` file\n\n Parameters\n ----------\n fpath : str\n The path to the network `JSON` file\n\n Returns\n -------\n NetworkGroup\n The instance of the `NetworkGroup` class\n \"\"\"\n with open(fpath, \"r\") as fid:\n raw_data = simplejson.load(fid)\n n_networks = len(raw_data[\"contexts\"])\n all_node_dict = {n[\"id\"]: n for n in raw_data[\"nodes\"]}\n data_dict: Dict[int, dict] = {\n n: {\"nodes\": [], \"links\": [], \"metadata\": {}} for n in range(n_networks)\n }\n unique_node_dict: Dict[int, dict] = {n: set() for n in range(n_networks)}\n for cid in range(n_networks):\n data_dict[cid][\"metadata\"] = {**raw_data[\"contexts\"][cid]}\n for link in raw_data[\"links\"]:\n link_cid = link[\"context_index\"]\n source = all_node_dict[link[\"source\"]]\n source_name = link[\"source\"]\n target = all_node_dict[link[\"target\"]]\n target_name = link[\"target\"]\n data_dict[link_cid][\"links\"].append(link)\n if source_name not in unique_node_dict[link_cid]:\n data_dict[link_cid][\"nodes\"].append(source)\n unique_node_dict[link_cid].add(source_name)\n if target_name not in unique_node_dict[link_cid]:\n data_dict[link_cid][\"nodes\"].append(target)\n unique_node_dict[link_cid].add(target_name)\n networks: List[Network] = []\n for cid in range(n_networks):\n metadata = data_dict[cid][\"metadata\"]\n nodes = data_dict[cid][\"nodes\"]\n links = data_dict[cid][\"links\"]\n network_raw_data = {**metadata, \"nodes\": nodes, \"links\": links}\n networks.append(Network.load_json(raw_data=network_raw_data))\n return cls(networks)\n\n def combine_pvalues(self, method: str) -> np.array:\n \"\"\"\n Combine pvalues of links in the network group using Empirical Brown's Method\n\n Parameters\n ----------\n method : str\n\n Returns\n -------\n np.array\n \"\"\"\n pass\n","sub_path":"mindpipe/main/network_group.py","file_name":"network_group.py","file_ext":"py","file_size_in_byte":10740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"29849027","text":"import preprocessing \nimport numpy as np\nimport cv2\n\ndef open_image2(filename, scale_to=[64, 64]):\n \"\"\"Opens an image, returns the preprocessed image (scaled, masked)\"\"\"\n #img = cv2.imread(filename) * cv2.imread(filename.replace('Bmp', 'Msk'))/255\n img = cv2.imread(filename)/255\n #processed_img = np.zeros(list(scale_to)+[3])\n\n # scaling\n # img_w, img_h = img.shape[1], img.shape[0]\n # target_w, target_h = scale_to[1], scale_to[0]\n # factor = target_w / img_w if img_w/img_h > target_w/target_h else target_h / img_h\n # img = cv2.resize(img, None, fx=factor, fy=factor)\n img = cv2.resize(img, tuple(scale_to))\n\n # centering image\n # x, y = int(target_w/2 - img.shape[1]/2), int(target_h/2 - img.shape[0]/2)\n # processed_img[y:y+img.shape[0], x:x+img.shape[1]] = img\n\n # normalising\n processed_img = img.astype(np.float32)\n for c in range(3):\n processed_img[:,:,c] /= np.max(processed_img[:,:,c])\n\n # to grayscale\n processed_img = cv2.cvtColor(\n (processed_img*255).astype(np.uint8), cv2.COLOR_RGB2GRAY)\n processed_img = np.expand_dims(processed_img, -1)\n\n # new_image = cv2.adaptiveThreshold(processed_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \\\n # \tcv2.THRESH_BINARY, 11, 2)\n\n blur = cv2.GaussianBlur(processed_img, (5,5), 0)\n _, new_image = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n new_image = np.expand_dims(new_image, -1)\n #new_image = cv2.Laplacian(new_image, cv2.CV_64F)\n\n return new_image\n\n\ncv2.imshow(\"Test Image\", open_image2(\"English/Img/GoodImg/Bmp/Sample021/img021-00061.png\"))\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","sub_path":"image_viewing.py","file_name":"image_viewing.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"150209897","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.1.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\nimport pandas as pd\nfrom requests import get\nfrom bs4 import BeautifulSoup\nfrom datetime import date\n\n\n# +\ndef get_page(url):\n response = get(url)\n html = response.content\n soup = BeautifulSoup(html, \"html.parser\")\n return soup\n\nbase_ff_url = 'https://www.fleaflicker.com/mlb/leagues/'\nleague_ids = ['21579', '21581', '21580', '21582', '21583', '21584', '21585', '21586', '21587', '21588', '21589', \n '21590', '21591', '21592', '21593', '21594', '21595', '21596']\n\nall_teams = []\nfor l in league_ids:\n url = base_ff_url + l\n soup = get_page(url)\n trs = soup.find_all('tr')\n raw_headers = trs[1].find_all('th')\n player_data = trs[2:]\n headers = []\n for header in raw_headers:\n if header.text:\n headers.append(header.text)\n exp_headers = headers + ['league_id', 'league_name', 'team_id'] \n league_name = soup.find_all('li', {'class': 'active'})[1].text.strip()\n for row in player_data:\n d_dict = dict.fromkeys(exp_headers)\n d_dict['league_id'] = l\n d_dict['league_name'] = league_name\n d_dict['Team'] = row.find('td', {'class': 'left'}).text\n d_dict['Owner'] = row.find('td', {'class': 'right'}).text\n d_dict['team_id'] = row.find('a', href=True).get('href')[-6:]\n try:\n d_dict['Rank'] = row.find_all('td', {'class': 'right text-center'})[-1].text\n except IndexError:\n d_dict['Rank'] = row.find_all('td', {'class': 'bottom right text-center'})[-1].text\n heads = exp_headers[2:14]\n if d_dict['Owner'] == 'Take Over':\n stats = row.find_all('span', {'class': 'nowrap'})\n else:\n stats = row.find_all('span', {'class': 'nowrap'})[1:]\n for h, s in zip(heads, stats):\n d_dict[h] = s.text\n all_teams.append(d_dict)\n# -\n\nall_df = pd.DataFrame(all_teams, columns=exp_headers)\nall_df.HR = all_df.HR.astype(int)\nall_df.R = all_df.R.astype(int)\nall_df.RBI = all_df.RBI.astype(int)\nall_df.SB = all_df.SB.astype(int)\nall_df.OBP = all_df.OBP.astype(float)\nall_df.OPS = all_df.OPS.astype(float)\nall_df.SO = all_df.SO.astype(int)\nall_df.SV = all_df.SV.astype(int)\nall_df.HD = all_df.HD.astype(int)\nall_df.ERA = all_df.ERA.astype(float)\nall_df.WHP = all_df.WHP.astype(float)\nall_df.QS = all_df.SV.astype(int)\n\nrank_headers = ['HR', 'R','RBI','SB','OBP','OPS','SO','SV','HD','ERA','WHP','QS']\nfor r in rank_headers:\n if r in ['ERA', 'WHP']:\n all_df[r+'_Points'] = all_df[r].rank(ascending=False)\n else:\n all_df[r+'_Points'] = all_df[r].rank()\n\nall_df['Total_Points'] = all_df.iloc[:,-12:].sum(axis=1)\nall_df['Overall_Rank'] = all_df.Total_Points.rank(ascending=False)\n\nall_df.head()\n\nall_df[all_df.Owner == 'xacex']\n\nt_date = str(date.today())\nall_df.to_csv('current_rankings_'+t_date+'.csv')\n\n\n","sub_path":"FleaFlicker/.ipynb_checkpoints/FleaFlicker Scrape-checkpoint.py","file_name":"FleaFlicker Scrape-checkpoint.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"457995891","text":"# 打印斐波那契(Fibonacci)数列:1,1,2,3,5,8,13 ......\n# a,b=0,1\n# while b<100:\n# print(b,end=' ')\n# a,b=b,a+b\n\n\n# 我们来写一个程序计算幂级数:e^x = 1 + x + x^2 / 2! + x^3 / 3! + ... + x^n / n! (0 < x < 1)。\nprint(\"please input a number:\")\nx = float(input())\nn = result = term = 1\n\nwhile n < 100:\n term *= x / n\n result += term\n if term < 0.0001:\n break\n n += 1\n\nprint(\"result is {:.10f}\".format(result))\n","sub_path":"01.新手入门课/循环/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"602120168","text":"import pygame\nfrom settings import SOUND_PATH, skill_PATH\nimport os\n\nclass RequestSubject:\n def __init__(self, model):\n self.__observers = []\n self.model = model\n\n def register(self, observer):\n self.__observers.append(observer)\n\n def notify(self, user_request):\n for o in self.__observers:\n o.update(user_request, self.model)\n\n\nclass EnemyGenerator:\n def __init__(self, subject):\n subject.register(self)\n self.cd = 900\n self.max_cd = 900\n self.boss_generate_flag = 1\n\n def update(self, user_request: str, model):\n if(self.cd >= self.max_cd and user_request == \"start new wave\"):\n if model.checkpoint == 1 or model.checkpoint == 2:\n model.enemies.add(self.en_num(model.checkpoint),model)\n self.cd = 0\n elif model.checkpoint == 3 and self.boss_generate_flag == 1:\n model.enemies.add(self.en_num(model.checkpoint),model)\n self.cd = 0\n self.boss_generate_flag = 0\n else:\n self.cd += 1\n \n def en_num(self, checkpoint):\n if checkpoint == 1:\n return 3\n elif checkpoint == 2:\n return 4\n else:\n return 1\n \n\n\nclass Music:\n def __init__(self, subject):\n subject.register(self)\n\n def update(self, user_request: str, model):\n if user_request == \"music\":\n pygame.mixer.music.unpause()\n model.sound.play()\n\n\nclass Muse:\n def __init__(self, subject):\n subject.register(self)\n\n def update(self, user_request: str, model):\n if user_request == \"mute\":\n pygame.mixer.music.pause()\n model.sound.play()\n\n\nclass Hero_howhow:\n def __init__(self, subject):\n subject.register(self)\n self.howhow_music = pygame.mixer.Sound(os.path.join(SOUND_PATH,\"howhow_sound.mp3\"))\n def update(self, user_request: str, model):\n if user_request == \"howhow\":\n if model.money >= 70:\n model.money -= 70\n model.heros.add('howhow', model.hero_level)\n self.howhow_music.set_volume(0.4)\n pygame.mixer.Channel(2).play(self.howhow_music)\n print('summon howhow')\n\nclass Hero_godtone:\n def __init__(self, subject):\n subject.register(self)\n self.godtone_music = pygame.mixer.Sound(os.path.join(SOUND_PATH,\"tone_sound.mp3\"))\n def update(self, user_request: str, model):\n if user_request == \"godtone\":\n if model.money >= 50:\n model.money -= 50\n model.heros.add(\"godtone\", model.hero_level)\n self.godtone_music.set_volume(0.03)\n pygame.mixer.Channel(2).play(self.godtone_music)\n print('summon godtone')\n\n\nclass Hero_p:\n def __init__(self, subject):\n subject.register(self)\n self.p_music = pygame.mixer.Sound(os.path.join(SOUND_PATH,\"p_sound.mp3\"))\n def update(self, user_request: str, model):\n if user_request == \"p\":\n if model.money >= 200:\n model.money -= 200\n model.heros.add(\"p\", model.hero_level)\n self.p_music.set_volume(0.8)\n pygame.mixer.Channel(2).play(self.p_music)\n print('summon p')\n\nclass Hero_brian:\n def __init__(self, subject):\n subject.register(self)\n self.brian_music = pygame.mixer.Sound(os.path.join(SOUND_PATH,\"brian_sound.mp3\"))\n def update(self, user_request: str, model):\n if user_request == \"brian\":\n if model.money >= 70:\n model.money -= 70\n model.heros.add(\"brian\", model.hero_level)\n self.brian_music.set_volume(0.4)\n pygame.mixer.Channel(2).play(self.brian_music)\n print('summon brian')\n\n\n\n\nclass Special:\n def __init__(self, subject):\n subject.register(self)\n self.skill_music = pygame.mixer.Sound(os.path.join(SOUND_PATH,\"rising.mp3\"))\n def update(self, user_request: str, model):\n if user_request == \"special\" and model.en.expedition:\n if model.money >= 200:\n model.money -= 200\n model.skill_animation = True\n self.skill_music.set_volume(0.6)\n pygame.mixer.Channel(3).play(self.skill_music)\n for en in model.en.expedition:\n en.health = en.health // 2\n\n\nclass Upgrade:\n def __init__(self, subject):\n subject.register(self)\n self.upgrade_music = pygame.mixer.Sound(os.path.join(SOUND_PATH,\"upgradesound.wav\"))\n def update(self, user_request: str, model):\n hero_update_cost = [100, 150, 200]\n if user_request == \"upgrade\":\n if model.money >= hero_update_cost[model.hero_level] and model.hero_level < 3:\n model.money -= hero_update_cost[model.hero_level]\n self.upgrade_music.set_volume(0.6)\n pygame.mixer.Channel(3).play(self.upgrade_music)\n \n\n\n","sub_path":"game/user_request.py","file_name":"user_request.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"298812943","text":"# coding: utf-8\n\nimport urllib.parse\nimport http.cookiejar\nimport urllib.request\nimport re\nimport http.client\n\n\nfrom bs4 import BeautifulSoup\n\n\n# 我们需要的网址\nurl = \"http://www.baidu.com\"\n\n\nprint(\">>> 第一种方式,最基本方式\")\nresp = urllib.request.urlopen(url)\nresult = resp.read()\n# 需要解码为我们需要的编码\nprint(len(result.decode(\"utf-8\")))\nresp.close()\n\n\nprint(\">>> 第二种方式,携带数据\")\nheaders = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }\nvalues = { 'name' : 'test', 'pwd' : 'test' }\n# encoding\ndata = urllib.parse.urlencode(values).encode(\"utf-8\")\n# 新建请求\nreq = urllib.request.Request(url, data, headers)\n# 打开连接\nresp = urllib.request.urlopen(req)\n# 得到结果\nprint(resp.readline())\nresp.close()\n\n\nprint(\">>> 第三种方式\")\n# urlopen 是使用 opener 对象处理请求的, opener 内包含一系列 handler,用于处理不同类型的请求\n# 默认情况下, urlopen 内会调用 build_opener() 方法创建默认的 opener\n# 我们也可以通过手动的方式,创建自己的 opener,并 build_opener 指定使用我们的 opener\n# 下面是为请求增加 Cookie 支持的方法\njaropener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor())\njaropener.addheaders = [('User-agent',\n 'Mozilla/5.0 (Windows NT 6.3; WOW64) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/31.0.1650.63 Safari/537.36')];\nresp = urllib.request.install_opener(jaropener)\n\n# 头部和参数\nheaders = {}\nparameters = {'a':'b'}\n# 编码\nparameters = urllib.parse.urlencode(parameters).encode()\n# 获取 req\nreq = urllib.request.Request(url, parameters, headers)\n# 获得 resp\nresp = urllib.request.urlopen(req)\n# 最终结果\nprint(resp.getcode())\nprint(resp.info())\nprint(resp.readline())\nhtml = resp.read()\n\nbs = BeautifulSoup(html, 'html.parser', from_encoding='utf-8')\nprint(bs.find_all(\"a\", href=re.compile(\"more\")))\nnode = bs.find(\"a\")\nprint(node.name)\n\n\nresp.close()\n\n\n\n'''\n# 下面是 python2 中网络连接的例子\n\nurl = \"http://www.baidu.com\"\n\nprint '连接的第一种办法:'\nresp1 = urllib2.urlopen(url)\nprint resp1.getcode(), len(resp1.read())\n\n\nprint '连接的第二种办法:'\nreq = urllib2.Request(url)\nreq.add_header(\"user-agent\", \"Mozilla/5.0\")\nresp2 = urllib2.urlopen(req)\nprint resp2.getcode(), len(resp2.read())\n\n\nprint '连接的第三种办法:'\ncj = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\nurllib2.install_opener(opener)\nresp3 = urllib2.urlopen(url)\nbaiduhtml = resp3.read()\nprint resp3.getcode(), cj, baiduhtml\n\n\n# BS4 的使用\nsoup = BeautifulSoup(baiduhtml, 'html.parser', from_encoding='utf-8')\n\nprint '获取所有连接:'\nlinks = soup.find_all('a')\nfor link in links:\n print link.name, link['href'], link.get_text()\n\nprint '获取news连接:'\nlink = soup.find('a', href='http://news.baidu.com')\nprint link.name, link['href'], link.get_text()\n\nprint '获取正则表达式连接:'\nlink = soup.find('a', href=re.compile(r'news'))\nprint link.name, link['href'], link.get_text()\n\n'''\n\n\n","sub_path":"basic/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"455450041","text":"#coding:utf-8\n\"\"\"\n Time : 2020-02-23 07:32:54\n Author : Vincent\n FileName: server.py\n Software: PyCharm\n Last Modified by: Vincent\n Last Modified time: 2020-02-23 07:32:54\n\"\"\"\nimport json\nimport logging\nimport base64\nfrom spyne import Application, rpc, ServiceBase\nfrom spyne import String, Integer\nfrom spyne.protocol.soap import Soap11\nfrom spyne.server.django import DjangoApplication\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .xml_envelope import XmlEnvelopeTree\nfrom .handle import request_base64_decode\nfrom .map.mysql_orm import init_db, get_session, makeorder_to_db, saveaddr_to_db\n\n\n# Create your views here.\nlogging.basicConfig(level=logging.DEBUG, filename='my_server.log',\n format=\"%(asctime)s %(name)s:%(levelname)s:%(module)s:%(funcName)s:\"\n \"%(processName)s:%(process)d:%(message)s\")\nlogging.getLogger(__name__).setLevel(logging.DEBUG)\n\n\nclass OrderServices(ServiceBase):\n \"\"\"声明服务的类,类的方法,就是客户端访问的服务,业务逻辑,操作都在这里面\"\"\"\n\n @rpc(String, _returns=String)\n def saveOrderInfo(self, request):\n '''\n 保存订单接口\n :param request: 接收的请求\n :return: 订单保存结果\n '''\n logging.info('接收到请求:%s' % request)\n rq_decode = request_base64_decode(request)\n logging.info('请求参数:%s' % rq_decode)\n env_tree = XmlEnvelopeTree(rq_decode)\n dict_data = env_tree.xml_to_dict()\n logging.info('请求体字典数据:%s' % dict_data)\n result = makeorder_to_db(dict_data)\n xml_tree = XmlEnvelopeTree(result)\n logging.info('响应数据:%s' % xml_tree.envelope_encode())\n return base64.b64encode(xml_tree.envelope_encode().encode('utf-8')).decode()\n\n @rpc(String, _returns=String)\n def acceptUserAddrInfo(self, request):\n '''\n 保存推送过来的地址信息接口\n :param request: 接收的请求\n :return: 地址保存结果\n '''\n logging.info('接收到请求:%s' % request)\n rq_decode = request_base64_decode(request)\n logging.info('请求参数:%s' % rq_decode)\n env_tree = XmlEnvelopeTree(rq_decode)\n dict_data = env_tree.xml_to_dict()\n logging.info('请求体字典数据:%s' % dict_data)\n result = saveaddr_to_db(dict_data)\n xml_tree = XmlEnvelopeTree(result)\n logging.info('响应数据:%s' % xml_tree.envelope_encode())\n return base64.b64encode(xml_tree.envelope_encode().encode('utf-8')).decode()\n\n\nsoap_app = Application([OrderServices],\n tns='webservice_test.myservice.views',\n # in_protocol=HttpRpc(validator='soft'),\n # 'SampleServices',\n in_protocol=Soap11(validator=\"lxml\"),\n out_protocol=Soap11())\ndjango_app = DjangoApplication(soap_app)\nsum_app = csrf_exempt(django_app)\nes = get_session()\ninit_db(es[0])\nlogging.info(\"listening to http://127.0.0.1:8000\")\nlogging.info(\"wsdl is at: http://localhost:8000/OrderServices?wsdl\")","sub_path":"dj_webservice/myservices/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96832299","text":"# -*- coding: utf-8 -*-\n#create by jelly\n#2016.07.01\n\nimport re\nimport os\nimport subprocess\nimport time\nimport sys\nsys.path.append(\"..\")\nfrom system.osi import (run_command)\nhdoarm = \"hdparm\"\nsmart_ctl = \"smartctl\"\n\ndef smart_info(disk):\n disk_info = {}\n disk_info[\"name\"] = disk\n cmd = [smart_ctl, \"-i\", \"/dev/%s\" % disk]\n o, e, rc = run_command(cmd)\n for l in o:\n if (re.match('smartctl', l) is not None):\n if (re.match('smartctl database', l) is None):\n line = l.split(\"[\")\n disk_info[\"version\"] = line[0].split(\"smartctl\")[1].strip()\n\n if (re.match('Device Model', l) is not None):\n line = l.split(\":\")\n disk_info[\"device_model\"] = line[1].strip()\n\n if (re.match('Serial Number', l) is not None):\n line = l.split(\":\")\n disk_info[\"serial_number\"] = line[1].strip()\n\n if (re.match('Firmware Version', l) is not None):\n line = l.split(\":\")\n disk_info[\"firmware_version\"] = line[1].strip()\n\n if (re.match('User Capacity', l) is not None):\n line = l.split(\":\")\n disk_info[\"capacity\"] = line[1].strip()\n\n if (re.match('Sector Size', l) is not None):\n line = l.split(\":\")\n disk_info[\"sector_size\"] = line[1].strip()\n\n if (re.match('Rotation Rate', l) is not None):\n line = l.split(\":\")\n disk_info[\"rotation_rate\"] = line[1].strip()\n\n if (re.match('ATA Version is', l) is not None):\n line = l.split(\":\")\n disk_info[\"ata_version\"] = line[1].strip()\n\n if (re.match('SATA Version is', l) is not None):\n line = l.split(\":\")\n disk_info[\"sata_version\"] = line[1].strip()\n\n if (re.match('SMART support is', l) is not None):\n if (re.match('Available', l) is None):\n line = l.split(\":\")\n disk_info[\"enabled\"] = line[1].strip()\n\n cmd = [smart_ctl, \"-H\", \"/dev/%s\" % disk]\n o, e, rc = run_command(cmd)\n for l in o:\n if(re.match(\"test result\",l) is not None):\n line = l.split(\":\")\n disk_info[\"assessment\"] = line[1].strip()\n break\n return disk_info,rc\n\n#print smart_info(\"sdb\")\n\n#test begin\ndef smart_test(disk_info):\n #disk info must include disk name and test style(short and long)\n line = {\"status\":\"fail\",\"description\":\"\"}\n disk = disk_info[\"disk\"]\n style = disk_info[\"style\"]\n cmd = [smart_ctl, \"-t\", style, \"/dev/%s\" % disk]\n o, e, rc = run_command(cmd)\n for l in o:\n if (re.match(\"Testing has begun\",l) is not None):\n line[\"status\"] = \"success\"\n if(re.match(\"Please wait\",l) is not None):\n line[\"description\"] = l\n break\n if line[\"status\"] == \"fail\":\n #return {\"error\":\"smart test fail\"}\n return {\"error\":\"SMART测试失败\"}\n else:\n return line\n#abort smart test disk\ndef abort_smart_test(disk):\n #disk = sdx\n line = {\"status\":\"fail\"}\n cmd = [smart_ctl,\"-X\", \"/dev/%s\" % disk]\n o, e, rc = run_command(cmd)\n for l in o:\n if (re.match(\"Self-testing aborted\",l) is not None):\n line[\"status\"] = \"abort success\"\n break\n if line[\"status\"] == \"fail\":\n #return {\"error\":\"abort test fail\"}\n return {\"error\":\"停止SMART测试失败\"}\n else:\n return line\n\n#get smart test status,status is completed and processing\ndef get_smart_status(disk):\n dict = {\"remain\":\"\",\"status\":\"\"}\n line = \"\"\n key = 0\n cmd = [smart_ctl,\"-c\",\"/dev/%s\" % disk]\n o, e, rc = run_command(cmd)\n if rc == 0:\n for l in o:\n if(\"Total time to complete Offline\" in l):\n break\n if(key):\n line = line + \" \" + l\n if(\"Self-test execution status:\" in l):\n line = l\n key = 1\n #print line\n if(\"The previous self-test routine completed\" in line):\n dict[\"remain\"] = \"0\"\n dict[\"status\"] = \"completed\"\n else:\n dict[\"remain\"] = str((re.findall(r'(\\w*[0-9]+)\\w*',line))[1]) + \"%\"\n dict[\"status\"] = \"processing\"\n return dict\n else:\n #return {\"error\":\"get smart test status fail\"}\n return {\"error\":\"获取SMART测试状态失败\"}\n\n#self samrt test log\ndef smart_test_log(disk):\n #out put logs\n cmd = [smart_ctl, \"-l\", \"selftest\", \"/dev/%s\" % disk]\n o, e, rc = run_command(cmd)\n smart_log = []\n for l in o:\n log = {}\n if(re.match(\"#\",l) is not None):\n li = l.split()\n if (len(li) == 9):\n log[\"num\"] = li[1]\n log[\"Description\"] = li[2]\n log[\"Status\"] = li[3] + \" \" + li[4] + \" \" + li[5]\n log[\"Remain\"] = li[6]\n log[\"LifeTime\"] = li[7]\n log[\"LBA_of_first_error\"] = li[8]\n smart_log.append(log)\n continue\n return smart_log\n\ndef smart_error_log(disk):\n #out put error logs\n error_log = {}\n cmd = [smart_ctl, \"-l\", \"error\", \"/dev/%s\" % disk]\n o, e, rc = run_command(cmd)\n error = True\n for l in o:\n if(re.match(\"No Errors Logged\",l) is not None):\n error = False\n if (error == True):\n error_log[\"error\"] = True\n #code........\n else:\n error_log[\"error\"] = False\n return error_log\n\ndef smartproperty(disk):\n key = 0\n list = []\n cmd = [smart_ctl,\"-a\",\"/dev/%s\" % disk]\n o, e, rc = run_command(cmd)\n if rc == 0:\n for l in o:\n if(\"SMART Error Log\" in l):\n break\n if(key and len(l)>0):\n l = l.split()\n dict = {}\n dict[\"id\"] = l[0]\n dict[\"name\"] = l[1]\n dict[\"flag\"] = l[2]\n dict[\"normed_value\"] = l[3]\n dict[\"worst\"] = l[4]\n dict[\"threshold\"] = l[5]\n dict[\"type\"] = l[6]\n dict[\"updated\"] = l[7]\n dict[\"failed\"] = l[8]\n if(len(l) == 10):\n dict[\"raw_value\"] = l[9]\n else:\n value = \"\"\n for i in range(len(l)-9):\n value = value + \" \" + l[9+i]\n dict[\"raw_value\"] = value\n list.append(dict)\n #print l\n if(\"ID# ATTRIBUTE_NAME\" in l):\n key = 1\n return list\n else:\n #return [{\"error\":\"smart property error\"}]\n return [{\"error\":\"获取SMART信息错误\"}]\n\n\ndef smartcapability(disk):\n list = []\n relist = []\n i = 0\n j = 0\n key = 0\n line = \"\"\n cmd = [smart_ctl,\"-c\",\"/dev/%s\" % disk]\n o, e, rc = run_command(cmd)\n #print o\n if rc == 0:\n for l in o:\n if(key and len(l)>0):\n if(\":\" in l and l[0]!=\"\\t\"):\n if(j == 0):\n i = i + 1\n if(i>1):\n i = 0\n list.append(line)\n #line = \" \"\n line = l\n else:\n line = l\n else:\n i = i + 1\n j = 0\n line = line + \" \" + l\n elif(l[0]==\"\\t\"):\n i = i + 1\n line = line + \" \" + l.strip(\"\\t\")\n else:\n i = 0\n j = 1\n list.append(line)\n line = l\n if(\"General SMART Values:\" in l):\n key = 1\n if line != \"\":\n list.append(line)\n for l in list:\n dict = {}\n l = l.split(\":\")\n dict[\"name\"] = l[0]\n dict[\"flag\"] = l[1].split(\")\")[0].split(\"(\")[-1].strip()\n dict[\"capability\"] = l[1].split(\")\")[1].strip(\"\\t\")\n relist.append(dict)\n return relist\n else:\n return [{\"name\":\"none\",\"flag\":\"none\",\"capability\":\"none\"}]\n else:\n #return [{\"error\":\"smart capability error\"}]\n return [{\"error\":\"获取SMART信息错误\"}]\n#print smartcapability(\"sda\")\n\n#bcache disk function\n#disk = {\"cache_disk\":\"sdb\",\"data_disk\":[\"sdc\",\"sdd\"]}\ndef add_bcache_backing(disk):\n disk_data = \"\"\n history = 0\n cache_disk = disk[\"cache_disk\"]\n cache_disk = \"/dev/%s\" % cache_disk\n cmd1 = [\"bcache-super-show\",\"-f\",cache_disk]\n o,e,rc = run_command(cmd1)\n if(len(o) > 5):\n history = 1\n data_disk = disk[\"data_disk\"]\n if(history == 0):\n for i in range((len(data_disk))):\n data_disk_path = \"/dev/%s\" % data_disk[i]\n cmd2 = [\"bcache-super-show\",\"-f\",data_disk_path]\n o,e,rc = run_command(cmd2)\n if(len(o) > 5):\n history = 1\n break\n cmd = [\"make-bcache\",\"-C\",cache_disk,\"-B\",\"--writeback\"]\n for i in range(len(data_disk)):\n disk_data = \"/dev/%s\" % data_disk[i]\n cmd.insert(5,disk_data)\n if(history == 1):\n cmd.insert(len(cmd),\"--wipe-bcache\")\n o,e,rc = run_command(cmd)\n if(rc == 0):\n return {\"status\": \"add bcache method success\"}\n else:\n #return {\"error\": \"add bcache method fail\"}\n return {\"error\": \"增加cache功能盘失败\"}\n#disk = {\"set_uuid\":\"fafaa-7777979cascasdb\"}\ndef delete_bcache(disk):\n key = 1\n i = 0\n disk_cache = disk[\"set_uuid\"]\n list_cache = os.listdir(\"/sys/fs/bcache\")\n if disk_cache in list_cache:\n list_link = os.listdir(\"/sys/fs/bcache/%s\" % disk_cache)\n for link in list_link:\n if os.path.islink(\"/sys/fs/bcache/%s/%s\" % (disk_cache,link)):\n i = i + 1\n if(i > 1):\n key = 0\n break\n else:\n key = 0\n if(key):\n path_register = \"/sys/fs/bcache/%s/unregister\" % disk_cache\n #cmd = [\"echo\",\"1\",\">\",path_register]\n #run_command(cmd)\n os.system(\"echo 1 > %s\" % path_register)\n return {\"status\": \"delete cache disk success\"}\n else:\n #return {\"error\": \"The backing disk is exists, please delete backing disk first or the cache disk not exists\"}\n return {\"error\": \"数据盘还存在, 请先删除数据盘然后再次删除cache盘\"}\n#disk = {\"name\":\"sdc\"}\ndef delete_backing(disk):\n data_disk = disk[\"name\"]\n path_discon = \"/sys/block/%s/bcache/detach\" % data_disk\n if os.path.exists(path_discon):\n #cmd = [\"echo\",\"1\",\">\",path_discon]\n #run_command(cmd)\n os.system(\"echo 1 > %s\" % path_discon)\n path_stop = \"/sys/block/%s/bcache/stop\" % data_disk\n #cmd = [\"echo\",\"1\",\">\",path_stop]\n #o,e,rc =run_command(cmd)\n if os.path.exists(path_stop):\n os.system(\"echo 1 > %s\" % path_stop)\n return {\"status\": \"delete data disk success\"}\n #else:\n else:\n #return {\"error\": \"delete data disk fail\"}\n return {\"error\": \"删除数据盘失败\"}\n else:\n return {\"error\": \"删除数据盘失败\"}\ndef get_cache_uuid():\n uuid_back = []\n if os.path.exists(\"/sys/fs/bcache/\"):\n uuid = os.listdir(\"/sys/fs/bcache/\")\n for i in range(len(uuid)):\n if uuid[i] != \"register_quiet\" and uuid[i] != \"register\":\n uuid_back.append(uuid[i])\n return uuid_back\n return uuid_back\n\n#disk = \"bcache0\"\ndef get_bcachedisk(disk):\n data = \"\"\n path_bcache = \"/sys/block/%s/\" % disk\n cmd = [\"ls\",\"-l\",path_bcache]\n o,e,rc = run_command(cmd)\n for l in o:\n l = l.split(\"/\")\n if len(l) > 8:\n data = l[-2]\n break\n return data\n","sub_path":"services/storage/fs/disks.py","file_name":"disks.py","file_ext":"py","file_size_in_byte":11782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"298129739","text":"from setuptools import setup, find_packages\n\npackages = find_packages()\n\nsetup(name='baybars',\n version='0.0.15',\n setup_requires=['pbr==5.1.1'],\n copyright='Copyright 2019 Jet.com',\n url='http://pypi.org/project/baybars/',\n packages=packages,\n install_requires=[\n 'python-consul==1.1.0',\n 'azure-storage-blob==1.4.0',\n 'azure-storage-queue==1.4.0',\n 'confluent-kafka==0.11.6',\n 'azure-cosmos==3.0.2',\n 'pysftp==0.2.9',\n 'requests==2.20.1',\n 'numpy==1.15.4',\n 'pandas==0.23.4',\n 'python-consul==1.1.0',\n 'PyHive==0.6.1',\n 'elasticsearch==6.3.1',\n 'azure-cosmosdb-table==1.0.5'\n ],\n keywords='azure kafka blob documentdb cosmosdb queue tar',\n python_requires='>=3.5',\n zip_safe=False,\n pbr=True)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"303525442","text":"from typing import List\nimport numpy as np\nimport os\nimport settings\nfrom Mdp.transition_counting_translator import TransitionCountingTranslator\nfrom transition_counting.heatmap_plotter import plot_count_heatmap\nfrom transition_counting.transition_counter import TransitionCounter\n\n\nclass ConversationComparer:\n def compare_and_save_plots(\n self,\n file_name: str,\n original_conversation: List[dict],\n calculated_conversation: List[dict],\n frame_step: int,\n file_metadata: dict,\n show: bool\n ):\n base = os.path.basename(file_name)\n # get file name without extention\n name = os.path.splitext(base)[0]\n original_results = self.__count(\n original_conversation, file_metadata, frame_step\n )\n calculated_results = self.__count(\n calculated_conversation, file_metadata, frame_step\n )\n\n self.__save_plots(original_results, name, \"original\", show)\n self.__save_plots(calculated_results, name, \"calculated\", show)\n\n def __save_plots(self, results, file_name, original_or_not: str, show: bool):\n file_name_counts = os.path.join(\n settings.COMPARISON_PLOTS_FOLDER_PATH,\n f\"{file_name}_{original_or_not}_plot_counts.png\",\n )\n file_name_probs = os.path.join(\n settings.COMPARISON_PLOTS_FOLDER_PATH,\n f\"{file_name}_{original_or_not}_plot_probs.png\",\n )\n\n translator = TransitionCountingTranslator(results)\n\n probabilities_matrix = translator.transform_to_4x4_probabilities_matrix()\n\n plot_count_heatmap(np.round(probabilities_matrix, decimals=3), file_name_probs, show)\n\n def __count(self, conversation, file_metadata: dict, frame_step: int) -> np.ndarray:\n result = np.zeros((2, 2, 2, 2))\n starting_points = np.arange(0, frame_step)\n counter = TransitionCounter()\n\n for i in starting_points:\n file_result = counter.count_transitions(\n conversation, frame_step, i, file_metadata\n )\n result += file_result\n\n return result\n\n","sub_path":"src/inverse_reinforcement_learning/conversation_comperar.py","file_name":"conversation_comperar.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"342179665","text":"# MIT License\n#\n# Copyright (c) 2021 Soohwan Kim\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom lightning_asr.vocabs.vocab import Vocabulary\n\n\nclass LibriSpeechVocabulary(Vocabulary):\n \"\"\"\n Converts label to string for librispeech dataset.\n\n Args:\n model_path (str): path of sentencepiece model\n vocab_size (int): size of vocab\n \"\"\"\n def __init__(self, model_path: str, vocab_size: int):\n super(LibriSpeechVocabulary, self).__init__()\n try:\n import sentencepiece as spm\n except ImportError:\n raise ImportError(\"Please install sentencepiece: `pip install sentencepiece`\")\n\n self.sp = spm.SentencePieceProcessor()\n self.sp.Load(model_path)\n self.pad_id = self.sp.PieceToId(\"\")\n self.sos_id = self.sp.PieceToId(\"\")\n self.eos_id = self.sp.PieceToId(\"\")\n self.blank_id = self.sp.PieceToId(\"\")\n self.vocab_size = vocab_size\n\n def label_to_string(self, labels):\n if len(labels.shape) == 1:\n return self.sp.DecodeIds([l.item() for l in labels])\n\n elif len(labels.shape) == 2:\n sentences = list()\n\n for label in labels:\n sentence = self.sp.DecodeIds([l for l in label])\n sentences.append(sentence)\n return sentences\n else:\n raise ValueError(\"Unsupported label's shape\")\n","sub_path":"lightning_asr/vocabs/librispeech.py","file_name":"librispeech.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"65956326","text":"class StoreEngine:\n\n def __init__(self, db):\n self.db = db\n\n def store(self, inter):\n data = {\n 'name': inter.name,\n 'region': inter.region,\n 'templates': self._convert_entities(inter.templates),\n 'functions': self._convert_entities(inter.funcs),\n }\n self.db['interfaces'].update({'name': inter.name}, data, True)\n\n def _convert_entities(self, entities):\n result = []\n\n for ent in entities:\n data = {\n 'name': ent.name,\n 'params': self._convert_params(ent.params)\n }\n\n result.append(data)\n\n return result\n\n def _convert_params(self, params):\n result = []\n\n for p in params:\n position = p.pos + 1 if p.pos is not None else None\n\n data = {\n 'name': p.name,\n 'position': position,\n 'type': str(p.type)\n }\n\n result.append(data)\n\n return result\n\n","sub_path":"xsl_stat/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"297765797","text":"import argparse\nfrom utils_db.db_cassandra import CassandraDatabaseHandler\n\ndef _parse_options():\n argParser = argparse.ArgumentParser( 'Sample Cassandra BCP import utility' )\n argParser.add_argument( '-config', dest='config', help='Config section name in db_example.py' )\n argParser.add_argument( '-source', dest='source', help='File name of the data source' )\n argParser.add_argument( '-target', dest='target', help='Target table name in Cassandra' )\n argParser.add_argument( '-log', dest='log', help='Logging file name' )\n argParser.add_argument( '-env', dest='env', help='Required environment variables',\n action='append', type=lambda kv:kv.split( '=', 1 ) )\n argParser.add_argument( '-bcp_opt', dest='options', help='Optional CQLSH copyutil options: \\\n http://docs.datastax.com/en/cql/3.1/cql/cql_reference/copy_r.html',\n action='append', type=lambda kv:kv.split( '=', 1 ) )\n return argParser.parse_args()\n\ndef main():\n \"\"\"\n Below command line options serve as an example to run this script:\n -config FMNA_DEV -target tbl_poc_fund_returns -source e:\\dev\\cass\\data\\out\\DMRI_FE_USA_short_bcp.csv\n -log e:\\dev\\cass\\data\\stdout.txt\n -env CASSANDRA_HOME=c:\\FAST\\apache-cassandra-3.10 -env PYTHON_HOME=c:\\FAST\\Python\\2.7.12\n -bcp_opt MAXBATCHSIZE=20 -bcp_opt HEADER=False\n \"\"\"\n\n argResults = _parse_options()\n status= 1\n\n with CassandraDatabaseConnection( argResults.config, argResults.target ) as dbSession:\n if dbSession.validateTableExistence():\n status = dbSession.runBcpIn(\n argResults.source, argResults.target, verbose=True,\n stdoutFile=argResults.log, stderrFile=argResults.log,\n envVars=dict( argResults.env ),\n options=dict( argResults.options ) )\n\n print( \"Cassandra BCP import status: %s\" % status )\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/cassandra_bcp_example.py","file_name":"cassandra_bcp_example.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"178227671","text":"# Autor: Cecilia Daniela Olivares Hernández, a01745727\r\n# Descripcion: Conversión de temperatura de escala Fahrenheit a la escala Celsius\r\n\r\n# Escribe tu programa después de esta línea.\r\n\r\nF = int(input(\"Inserta la temperatura en Fahrenheits: \"))\r\n\r\nC = (F - 32) / 1.8\r\n\r\nprint(\"La tenperatura Fahrenheit en Celsius es: \"'%.4f' % C)\r\n","sub_path":"extraTemperatura.py","file_name":"extraTemperatura.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"311022235","text":"# -*- coding: utf-8 -*-\n#\n\nfrom airflow.operators import PythonOperator\nfrom airflow.models import DAG\nfrom datetime import datetime, timedelta\nfrom airflow.models import Variable\nimport logging\n\nargs = {\n 'owner': 'systems',\n 'start_date': datetime.now() - timedelta(minutes=10),\n}\n\ndag = DAG(\n dag_id='apple',\n default_args=args,\n schedule_interval=\"2 * * * *\")\n\ndef print_context(*args, **kwargs):\n print('lol')\n\n\nrun_this = PythonOperator(\n task_id='do_it_for_the_lolz',\n provide_context=True,\n python_callable=print_context,\n dag=dag)\n\n\n# Generate 2 chill tasks, chilling from 0 to 1 seconds?\nfor i in range(2):\n task = PythonOperator(\n task_id='sleeping_on_job_for_' + str(i),\n python_callable=print_context,\n op_kwargs={'random_base': float(i)},\n dag=dag)\n\n run_this.set_downstream(task)\n\n\n\n","sub_path":"dags/test/troll.py","file_name":"troll.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"504296875","text":"import csv,os\nfrom google.cloud import bigquery\n\nimport get_hive_schema,get_bq_schema\n# Imports required variables from Initialization script\nfrom init_script import *\n# Imports required functions from the Utilities script\nfrom utilities import *\n\ndef get_metrics_table_schema():\n \"\"\"Creates schema for the Bigquery comparison metrics table\n \n Returns:\n list -- list of google.cloud.bigquery.schema.SchemaField objects\n \"\"\"\n schema = [\n bigquery.SchemaField('operation', 'STRING', mode='REQUIRED',description='operation'),\n bigquery.SchemaField('table_name', 'STRING', mode='REQUIRED',description='Table name'),\n bigquery.SchemaField('Column_count', 'STRING', mode='REQUIRED',description='Number of columns'),\n ]\n for col in columns_list:\n schema.append(bigquery.SchemaField(str(col), 'STRING', mode='REQUIRED'))\n return schema\n\ndef create_bq_metrics_table(hive_bq_comparison_table):\n \"\"\"Creates Bigquery comparison metrics table\n \n Arguments:\n hive_bq_comparison_table {str} -- Bigquery table name to be created\n \"\"\"\n\n dataset_ref = bq_client.dataset(dataset_id)\n table_ref = dataset_ref.table(hive_bq_comparison_table)\n table = bigquery.Table(table_ref, schema=get_metrics_table_schema())\n table = bq_client.create_table(table)\n\n# Reads the validation rules to a variable\ndef read_validations():\n \"\"\"Reads the validation rules\n \n Returns:\n list -- Validation rules list\n \"\"\"\n\n global validations_list\n file=open('validations.csv','rb')\n reader=csv.reader(file)\n validations_list = [row for row in reader]\n return validations_list\n\ndef analyze_bq_table(dataset_id,bq_table_name,schema):\n \"\"\"Gets metadata about the bigquery table\n \n Arguments:\n dataset_id {str} -- Bigquery dataset id\n bq_table_name {str} -- Bigquery table name\n schema {dict} -- Schema of the BQ table\n \n Returns:\n dict -- Bigquery Table metadata\n \"\"\"\n\n table_analysis={}\n dataset_ref =bq_client.dataset(dataset_id)\n table_ref = dataset_ref.table(bq_table_name)\n table = bq_client.get_table(table_ref)\n table_analysis['operation']=\"BQ\"\n table_analysis['table_name']=bq_table_name\n table_analysis['num_cols']=str(len(table.schema))\n table_analysis['schema']=schema\n # for col in columns_list:\n # for key,value in schema.iteritems():\n # table_analysis[str(col)]=str(schema[col])\n return table_analysis\n\n# Analyzes HIVE table for metrics\ndef analyze_hive_table(database,table_name,schema):\n \"\"\"Gets metadata about the Hive table\n \n Arguments:\n database {str} -- Hive database name\n table_name {str} -- Hive table name\n schema {dict} -- Schema of the Hive table\n \n Returns:\n dict -- Hive table metadata\n \"\"\"\n\n num_cols=0\n table_description = get_description(database,table_name)\n for j in range(len(table_description)):\n if table_description[j][0]=='LOCATION':\n location=table_description[j+1][0]\n for i in table_description:\n if i[0]=='ROW FORMAT SERDE ':\n break\n if 'CREATE TABLE' in i[0] or 'PARTITIONED BY' in i[0]:\n pass\n else:\n num_cols+=1\n table_analysis={}\n table_analysis['operation']=\"HIVE\"\n table_analysis['table_name']=table_name\n table_analysis['num_cols']=str(num_cols)\n table_analysis['schema']=schema\n return table_analysis\n\n# Inserts comparison data to a CSV file\ndef append_row_to_metrics_table(row_data):\n \"\"\"Writes comparison metrics data to csv file\n \n Arguments:\n row_data {dict} -- Metadata to write\n \"\"\"\n\n global is_csv_file_created\n data=[row_data['operation'],row_data['table_name'],row_data['num_cols']]\n for item in columns_list:\n data.append(row_data['schema'][item])\n with open(hive_bq_comparison_csv, 'a+') as csvFile:\n writer = csv.writer(csvFile)\n print(data)\n writer.writerow(data)\n csvFile.close()\n is_csv_file_created = True\n\n\n\ndef do_health_checks(hive_table_analysis,bq_table_analysis,schema):\n \"\"\"Populates the Health checks values from the comparison\n \n Arguments:\n hive_table_analysis {dict} -- Hive table metadata\n bq_table_analysis {dict} -- Bigquery table metadata\n schema {dict} -- Bigquery schema\n \n Returns:\n dict -- Health checks\n \"\"\"\n\n healths={\n \"operation\":\"Health Check\",\n \"table_name\":\"NA\",\n \"num_cols\":\"Fail\",\n \"schema\":schema\n }\n if (hive_table_analysis['num_cols']==bq_table_analysis['num_cols']):\n healths[\"num_cols\"]=\"Pass\"\n\n for item in columns_list:\n if 'array_' in hive_table_analysis['schema'][item]:\n hive_table_analysis['schema'][item] = '_'.join(hive_table_analysis['schema'][item].split('_')[-2:])\n \n \n if ([hive_table_analysis['schema'][item],bq_table_analysis['schema'][item]] in validations_list):\n healths['schema'][str(item)]=\"Pass\"\n else:\n healths['schema'][str(item)]=\"Fail\"\n return healths\n\ndef write_csv_to_gcs(filename):\n \"\"\"Writes comparison csv to GCS bucket\n \n Arguments:\n filename {str} -- Comparison metrics csv filename\n \n Returns:\n str -- GCS URI of filepath\n \"\"\"\n\n bucket=gcs_client.get_bucket(gcs_bucket_name)\n blob = bucket.blob(filename)\n blob.upload_from_filename(filename)\n uri = 'gs://'+gcs_bucket_name+'/'+filename\n return uri\n\ndef delete_blob(blob_name):\n \"\"\"Deletes file from GCS bucket\n \n Arguments:\n blob_name {str} -- GCS blob name to be deleted\n \"\"\"\n\n storage_client = storage.Client()\n bucket = storage_client.get_bucket(gcs_bucket_name)\n blob = bucket.blob(blob_name)\n blob.delete()\n print('File {} deleted.'.format(blob_name))\n\n# Loads CSV metrics data to BQ comparison table\ndef load_csv_to_bigquery(csv_uri,bq_table_name):\n \"\"\"Loads metrics CSV data to BQ comparison table\n \n Arguments:\n csv_uri {str} -- GCS URI of the metrics file\n bq_table_name {str} -- BQ comparison metrics table name\n \"\"\"\n\n dataset_ref = bq_client.dataset(dataset_id)\n job_config = bigquery.LoadJobConfig()\n job_config.schema = get_metrics_table_schema()\n job_config.source_format = bigquery.SourceFormat.CSV\n\n load_job = bq_client.load_table_from_uri(csv_uri,dataset_ref.table(bq_table_name),job_config=job_config)\n printOutput('Loading metrics data to BigQuery... Job {}'.format(load_job.job_id))\n\n load_job.result()\n\n destination_table = bq_client.get_table(dataset_ref.table(bq_table_name))\n printOutput('Loaded {} rows in metrics table'.format(destination_table.num_rows))\n printOutput('Migrated data successfully from hive to BigQuery')\n printOutput('Comparison metrics of tables available in BQ table '+bq_table_name)\n\n# Main function for creating the comparison metrics table\ndef write_metrics_to_bigquery(csv_name,table_name):\n \"\"\"Main function to be called to write comparison metrics to Bigquery\"\"\"\n\n global is_csv_file_written\n global is_csv_file_created\n global columns_list\n global hive_bq_comparison_csv,hive_bq_comparison_table\n hive_bq_comparison_csv=csv_name\n hive_bq_comparison_table = table_name\n\n printOutput(\"Analyzing the hive and BQ tables...\")\n\n bq_schema = get_bq_schema.get_schema(dataset_id,bq_table)\n # print(bq_schema)\n\n hive_schema,columns_list = get_hive_schema.get_schema(hive_database,hive_table_name)\n # print(hive_schema)\n # print(columns_list)\n\n hive_table_analysis = analyze_hive_table(hive_database,hive_table_name,hive_schema)\n # print(hive_table_analysis)\n append_row_to_metrics_table(hive_table_analysis)\n is_csv_file_created = True\n bq_table_analysis=analyze_bq_table(dataset_id,bq_table,bq_schema)\n # print(bq_table_analysis)\n append_row_to_metrics_table(bq_table_analysis)\n\n validations_list = read_validations()\n healths=do_health_checks(hive_table_analysis,bq_table_analysis,bq_schema)\n # print(healths)\n append_row_to_metrics_table(healths)\n\n create_bq_metrics_table(hive_bq_comparison_table)\n # print(bq_table_analysis)\n\n csv_uri = write_csv_to_gcs(hive_bq_comparison_csv)\n is_csv_file_written = True\n\n load_csv_to_bigquery(csv_uri,hive_bq_comparison_table)\n os.remove(hive_bq_comparison_csv)\n delete_blob(hive_bq_comparison_csv)\n","sub_path":"examples/hive-bq/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":8423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"156389264","text":"import itertools\nimport json\nimport os\n\nfrom django.http import HttpResponse\n\nfrom django.db.utils import IntegrityError\n\nfrom django.contrib.sessions.backends.db import SessionStore\n\nfrom .tesseract import convert_tiff_path_to_text\nfrom .highlighter import convert_string_to_html\nfrom .decisioner import HmsTreeGenerator\nfrom .decisioner import Cursor\nfrom ..models import UserComplaintClassification\nfrom .cfpb_db import update_database\nfrom .analyzer import classify\n\n\nclass AjaxFielder(object):\n '''Static methods for ajax requests.'''\n\n @classmethod\n def input_ajax(cls, request):\n '''Takes ajax request and routes data to the appropriate routine.'''\n # Delay makes animations look nicer.\n print(request.POST.dict())\n function_dict = {'load_tiff': cls.load_tiff,\n 'choice': cls.choice,\n 'backup': cls.backup,\n 'db_refresh': cls.db_refresh,\n 'analyze_tiff': cls.analyze_tiff,\n 'analyze_text': cls.analyze_text}\n try:\n function_string = request.POST.dict()['function']\n target_function = function_dict[function_string]\n except KeyError:\n return False\n result_list = target_function(request)\n return json.dumps(result_list)\n\n @classmethod\n def load_tiff(cls, request):\n '''Take a tiff, turn it into text, and return a response.'''\n response = {}\n sent_file = request.FILES['file']\n if sent_file.size > 10000000:\n return 'No files over 10 megabytes.'\n temporary_path = os.path.join(os.path.expanduser(\"~\"),\n 'hms_tempfile.tiff')\n with open(temporary_path, 'wb+') as f:\n f.write(sent_file.read())\n # Get text\n extracted_text = convert_tiff_path_to_text(temporary_path).decode()\n highlighted_text = convert_string_to_html(extracted_text)\n os.remove(temporary_path)\n # Store extracted and highlighted text in session.\n request.session['highlighted_text'] = highlighted_text\n request.session['extracted_text'] = extracted_text\n tree = HmsTreeGenerator().get_tree()\n request.session['decision_tree'] = tree\n request.session['cursor'] = Cursor(tree.get_root(),\n extracted_text)\n request.session.save()\n if extracted_text:\n panel_1_text = request.session['cursor'].get_node_criterion()\n panel_1_text += '

        '\n for item in request.session['cursor'].get_node_options():\n panel_1_text += ''.join([''])\n panel_1_text += '   '\n response['#panel_1'] = panel_1_text\n response['#panel_2'] = highlighted_text\n sess = request.session\n response['#panel_3'] = sess['cursor'].get_node_description()\n response['#panel_4'] = sess['cursor'].get_tags()\n else:\n response['#panel_2'] = 'No text found'\n return response\n\n @classmethod\n def choice(cls, request):\n '''Takes a choice and response.'''\n choice_string = request.POST.dict()['arguments']\n choice = cls.string_to_class(choice_string)\n response = {}\n # Store extracted and highlighted text in session.\n cursor = request.session['cursor']\n cursor.choose(choice)\n # If cursor complete, write to database.\n if cursor.complete:\n tags = [item for item\n in set(cursor.get_tags())\n if item is not None]\n response['#panel_1'] = ' '\n response['#panel_3'] = ' '\n response['#panel_4'] = ' '\n response['#panel_2'] = 'Analysis complete. Tags:\\n'\n response['#panel_2'] += '
        '.join(tags)\n sans_tags = [item.replace('#','')\n for item in tags]\n argument_dict = {key: True for key in sans_tags}\n UCC = UserComplaintClassification\n complaint = UCC(categorizer=request.user.username,\n complaint_text=str(cursor._inspected_item_data),\n tag_string=''.join(tags),\n **argument_dict)\n complaint.save()\n\n else:\n panel_1_text = cursor.get_node_criterion()\n panel_1_text += '

        '\n for item in cursor.get_node_options():\n panel_1_text += ''.join([''])\n panel_1_text += '   '\n panel_1_text += '

        '\n panel_1_text += ''])\n panel_1_text += '   '\n # If can back up further, add backup button\n if cursor._current_node.parent_node is not None:\n panel_1_text += '

        '\n panel_1_text += '