diff --git "a/240.jsonl" "b/240.jsonl" new file mode 100644--- /dev/null +++ "b/240.jsonl" @@ -0,0 +1,685 @@ +{"seq_id":"225833403","text":"# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack import *\n\n\nclass Httpie(PythonPackage):\n \"\"\"Modern command line HTTP client.\"\"\"\n\n homepage = \"https://httpie.io/\"\n pypi = \"httpie/httpie-2.5.0.tar.gz\"\n\n version('2.5.0', sha256='fe6a8bc50fb0635a84ebe1296a732e39357c3e1354541bf51a7057b4877e47f9')\n version('0.9.9', sha256='f1202e6fa60367e2265284a53f35bfa5917119592c2ab08277efc7fffd744fcb')\n version('0.9.8', sha256='515870b15231530f56fe2164190581748e8799b66ef0fe36ec9da3396f0df6e1')\n\n variant('socks', default=True,\n description='Enable SOCKS proxy support')\n\n depends_on('py-setuptools', type=('build', 'run'))\n depends_on('py-defusedxml', type=('build', 'run'))\n depends_on('py-pygments', type=('build', 'run'))\n depends_on('py-requests', type=('build', 'run'))\n depends_on('py-requests-toolbelt', type=('build', 'run'))\n depends_on('py-pysocks', type=('build', 'run'), when=\"+socks\")\n # Concretization problem breaks this. Unconditional for now...\n # https://github.com/spack/spack/issues/3628\n # depends_on('py-argparse@1.2.1:', type=('build', 'run'),\n # when='^python@:2.6,3.0:3.1')\n depends_on('py-argparse@1.2.1:', type=('build', 'run'), when='^python@:2.6')\n","sub_path":"docs/packaging/spack/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"341097354","text":"\"\"\" requerimientos\ninstalar python3-tk\nLinux: \n - sudo apt-get install python3-tk\n\"\"\"\nimport turtle \n\n# sets window to 200x200 pixels, in upper left of screen\nturtle.setup(width=400, height=400, startx=0, starty=0)\nturtle.colormode(255)\n\nfor x in range(1, 210):\n turtle.forward(x/2)\n turtle.left(64)\n r = x % 255\n g = 2 * x % 255\n b = 3 * x % 255\n turtle.pencolor(r, g, b)\n turtle.title(\"x={} r={}, g={}, b={}\".format(x, r, g, b))\n\nturtle.done()","sub_path":"code/dibujando-con-turtle/draw4.py","file_name":"draw4.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"120881934","text":"# -*- coding: utf-8 -*-\n\n\nclass Movie(object):\n \"\"\"\n Holds movie attributes.\n\n Attributes:\n title: Movie title\n poster_image_url: Absolute url of image in format for browser.\n trailer_youtube_id: Short video identifying string found at the\n end of a youtube url. For example 'CDdvReNKKuk'\n summary: Variable length string.\n uk_rating: No validation done, but valid choices found at\n http://www.bbfc.co.uk/\n review_url: Any valid url. Usually http://rottentomatoes.com/\n\n \"\"\"\n\n # list of class properties taken from the functions open_movie_pages and\n # create_movie_tiles_content in sample\n def __init__(self, title, poster_image_url, trailer_youtube_id,\n summary, uk_rating, review_url):\n \"\"\"Creates Movie instance.\n\n Returns:\n An instance of `Movie`.\n\n Note:\n These fields are populated 1:1 from the json document found at\n data/movies.json. See module documentation for more information.\n\n \"\"\"\n self.title = title\n self.poster_image_url = poster_image_url\n self.trailer_youtube_id = trailer_youtube_id\n self.summary = summary\n self.uk_rating = uk_rating\n self.review_url = review_url\n","sub_path":"freshtomatoes/media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"305715139","text":"\"\"\"Plot mean absolute error (MAE) figures.\n\nTwo types of plots are done:\n - MAE versus the chronological age,\n - MAE of one modality versus MAE of another modality.\n\"\"\"\nfrom itertools import combinations\nimport os\nimport shutil\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\nFIG_OUT_PATH = '../../data/figures/'\nPREDICTIONS = '../../data/age_prediction_exp_data.h5'\nOUT_FTYPE = 'png'\n\ndata = pd.read_hdf(PREDICTIONS, key='predictions')\n# Plot errors of predictions from different modalities versus subject's age\nkeys = data.columns\n# remove column with the original age\nkeys = keys[1:]\n\nylim = (-2, 55)\nxlim = None\nout_folder = os.path.join(FIG_OUT_PATH, 'ae_vs_age')\n\nif os.path.exists(out_folder):\n shutil.rmtree(out_folder)\n os.mkdir(out_folder)\nelse:\n os.mkdir(out_folder)\n\nfor key1 in keys:\n data_slice = data[key1].dropna()\n age = data.loc[data_slice.index, 'age'].values\n abs_errors = np.abs(data_slice.values - age)\n plt.close()\n plt.figure()\n plt.scatter(age, abs_errors, edgecolors='black')\n plt.title(key1)\n plt.xlabel('Age (Years)')\n plt.ylabel('Absolute Error (Years)')\n plt.grid()\n\n if xlim is not None:\n plt.xlim(xlim)\n if ylim is not None:\n plt.ylim(ylim)\n\n name = f'AE_vs_age_{key1.replace(\" \", \"-\")}.{OUT_FTYPE}'\n plt.savefig(os.path.join(out_folder, name), bbox_inches='tight')\n\n# Plot errors of predictions from different modalities versus each other\ndata = data.dropna()\nfold_idx = data['fold_idx']\ndata = data.drop(['fold_idx'], axis=1)\nage = data.age.values\nkeys = data.columns\n# remove column with the original age\nkeys = keys[1:]\n\nxlim = (0, 55)\nylim = (0, 55)\nout_folder = os.path.join(FIG_OUT_PATH, 'ae_predictor_vs_predictor')\n\nif os.path.exists(out_folder):\n shutil.rmtree(out_folder)\n os.mkdir(out_folder)\nelse:\n os.mkdir(out_folder)\n\ntitle = 'Absolute Error Correlation'\nfor key1, key2 in combinations(keys, r=2):\n plt.close()\n fig, ax = plt.subplots()\n x_values = np.abs(data[key1].values - age)\n y_values = np.abs(data[key2].values - age)\n plt.scatter(x_values, y_values, edgecolors='black',\n c=age, cmap=plt.cm.viridis_r)\n plt.title(title)\n plt.xlabel(key1 + ', AE (Years)')\n plt.ylabel(key2 + ', AE (Years)')\n\n if xlim is not None:\n xlim_ = (xlim[0] - 1, xlim[1] + 1)\n else:\n xlim_ = (data[key1].min() - 1, data[key1].max() + 1)\n\n if ylim is not None:\n ylim_ = (ylim[0] - 1, ylim[1] + 1)\n else:\n ylim_ = (data[key2].min() - 1, data[key2].max() + 1)\n\n ax.set(xlim=xlim_, ylim=ylim_)\n ax.plot(ax.get_xlim(), ax.get_ylim(), ls='--', c='.3')\n plt.grid()\n plt.colorbar()\n\n name = f'AE_{key1.replace(\" \", \"-\")}_vs_{key2.replace(\" \", \"-\")}'\\\n f'.{OUT_FTYPE}'\n plt.savefig(os.path.join(out_folder, name), bbox_inches='tight')\n","sub_path":"scripts/plotting/error_plots.py","file_name":"error_plots.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"203663599","text":"#! /usr/bin/env python\n# encoding: utf-8\n\nimport zipfile\nimport argparse\nimport time\nimport os\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"directory\", help=\"path to directory containing csvs to be zipped\")\n\nSTART_TIME = time.time()\n\nargs = parser.parse_args()\nos.chdir(args.directory)\n\nfor csv in [x for x in os.listdir(args.directory) if \".csv\" in x]:\n filename = csv.split(\".\")[0] + \".zip\"\n zip_file = zipfile.ZipFile(filename, \"w\")\n zip_file.write(csv)\n zip_file.close()\n os.remove(csv)\n\nprint(time.time() - START_TIME)\n","sub_path":"quickzip/quickzip.py","file_name":"quickzip.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"522119466","text":"#!/usr/bin/env python\n\n# wxPython module\nimport wx\n\n# Matplotlib Figure object\nfrom matplotlib.figure import Figure\n# Numpy functions for image creation\nimport numpy as np\n\n# import the WxAgg FigureCanvas object, that binds Figure to\n# WxAgg backend. In this case, this is a wxPanel\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\n\n\nclass MplCanvasFrame(wx.Frame):\n \"\"\"Class to represent a Matplotlib Figure as a wxFrame\"\"\"\n def __init__(self):\n # initialize the superclass, the wx.Frame\n wx.Frame.__init__(self, None, wx.ID_ANY,\n title='Matplotlib in Wx', size=(600, 400))\n\n # usual Matplotlib functions\n self.figure = Figure(figsize=(6, 4), dpi=100)\n self.axes = self.figure.add_subplot(111)\n x = np.arange(0, 6, .01)\n y = np.sin(x**2)*np.exp(-x)\n self.axes.plot(x, y)\n\n # initialize the FigureCanvas, mapping the figure to \n # the Wx backend\n self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)\n\n\n# Create a wrapper wxWidgets application\napp = wx.PySimpleApp()\n# instantiate the Matplotlib wxFrame\nframe = MplCanvasFrame()\n# show it\nframe.Show(True)\n# start wxWidgets mainloop\napp.MainLoop()\n","sub_path":"CG/SciPy/7900_07_01_embedding_in_wx.py","file_name":"7900_07_01_embedding_in_wx.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"7045056","text":"### $1=map file, $2=mongo dbase, $3=mongo collection\nimport sys\nparams=sys.argv\ndiagnosesMapFile = open(params[1])\n\n\nfrom pymongo import *\nclient = MongoClient('localhost', 27017)\ndiagnosesMap = client[params[2]]['diagnosesMap']\nfor diagnosis in diagnosesMapFile:\n\tcode, name = diagnosis.strip().split(',')\n\tdiagnosesMap.insert_one({'code':code.strip(), 'diagnosis':name.strip()})\n\ndiagnosesMapFile.close()\n","sub_path":"ETL/College_Park_Data/push_diagnoses_map_toMongo.py","file_name":"push_diagnoses_map_toMongo.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"378595371","text":"# coding:utf-8\n\nimport os\nimport sys\nfrom datetime import *\nfrom logging import (\n getLogger,\n StreamHandler,\n Formatter,\n INFO\n)\n\nimport boto3\nimport dataset\nimport psycopg2\nimport yaml\nfrom pytz import timezone\nfrom linebot import LineBotApi\nfrom linebot.models import TextSendMessage\nfrom linebot.exceptions import LineBotApiError\n\nfrom utils.holidays import Holiday\n\n\ndef lambda_handler(event, context):\n # Set up logging\n logger = getLogger()\n logger.setLevel(INFO)\n\n # Get the current time\n time = datetime.now(timezone('Asia/Tokyo'))\n\n # Check if it is holiday today\n holiday = Holiday()\n if holiday.is_holiday(time):\n logger.info('It is a national holiday today.')\n return 'OK'\n\n # Round the current time in case a few minutes passed\n rtime = round_time(time, 15)\n\n # Get the users and message_id from message_schedules table\n try:\n db = dataset.connect(os.environ.get('DATABASE_INFO'))\n users = db['users'].find(date=rtime.date(),\n timing=rtime.time(),\n active=True)\n if db['users'].count(date=rtime.date(),\n timing=rtime.time(),\n active=True) == 0:\n return 'OK'\n except Exception as err:\n logger.exception('Getting schedule Error.\\n %s', err)\n return 'NG'\n\n # Instantiate Line Bot\n line_bot = LineBotApi(os.environ.get('LINE_CHANNEL_ACCESS_TOKEN'))\n\n # Load messages\n try:\n messages = load_messages()\n except Exception as err:\n logger.exception('Loading messages Error.\\n %s', err)\n return 'NG'\n\n # Push messages to each user\n try:\n for user in users:\n message_id = user['message_id']\n message_text = messages['weather_notice'][message_id]\n # Push message if \"message_text\" is not None\n if message_text is not None:\n message = TextSendMessage(text=message_text)\n line_bot.push_message(user['id'], message)\n except Exception as err:\n logger.exception('Push message Error.\\n %s', err)\n return 'NG'\n\n return 'Successfully Completed.'\n\n\ndef round_time(time, minute):\n \"\"\"\n Round time each the specified minute.\n params: time(datetime), minute(int)\n return: rounded time (datetime)\n \"\"\"\n minute = round(time.minute/minute)*minute\n rtime = datetime(time.year, time.month, time.day,\n time.hour, minute, 0)\n return rtime\n\n\ndef load_messages():\n \"\"\"\n Load LINE messages from YAML file on S3\n params: None\n return: messages (dict)\n \"\"\"\n try:\n client = boto3.client('s3')\n BUCKET_NAME = os.environ.get('BUCKET_NAME')\n MESSAGE_OBJ_KEY = os.environ.get('MESSAGE_OBJ_KEY')\n\n obj = client.get_object(Bucket=BUCKET_NAME, Key=MESSAGE_OBJ_KEY)\n return yaml.load(obj['Body'])\n except:\n raise\n\n\nif __name__ == '__main__':\n from pprint import pprint\n lambda_handler(None, None)\n","sub_path":"lambda_functions/push_notice/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"354135103","text":"import re\nfrom pyspark.sql import SQLContext\nfrom pyspark.sql import SparkSession\nimport sys,os\nimport RDD.Config as config\nimport areaInfo as info\n\njava8_location = config.java8_location\nsys.path.append(config.syspath)\nos.environ['SPARK_HOME'] = config.spark_home\n\nspark =SparkSession.builder.appName(\"Saled_HouseModel\").master(\"local[*]\").getOrCreate()\nsc = spark.sparkContext\n\ncur = config.cur\ncurcompute = config.curcompute\nconncompute = config.conncompute\n\nsqlContext = SQLContext(sc)\ndataframe_mysql = sqlContext.read.format(\"jdbc\").options(\n url=config.url, driver=\"com.mysql.jdbc.Driver\", dbtable=config.dbtable2, user=config.user, password=config.password).load()\ndataframe_mysql.show()\n\ndef compute(row):\n key = row[0]\n sumtotal = 0\n sumunit = 0\n count = len(row[1])\n for e in row[1]:\n sumunit = sumunit + e[0]\n sumtotal = sumtotal + e[1]\n averageunit = round((sumunit / count), 2)\n averagetotal = round((sumtotal / count), 2)\n return (count,(key,count,averageunit,averagetotal))\n\n# 将dataframe转化为rdd\npairRDD = dataframe_mysql.rdd\n# 清洗不存在的数据\npairRDD1 = pairRDD.filter(lambda row:row[14] != '不存在该项' and row[14].replace(\" \",\"\") != '车位' and row[14].replace(\" \",\"\") != '--室--厅')\n# 初步提取数据,汇集成元组\npairRDD2 = pairRDD1.map(lambda row:(row[14].replace(\" \",\"\"), (row[7] , row[6])))\n# 对数据进行聚合\npairRDD3 = pairRDD2.groupByKey()\n# 对数据进行计算\npairRDD4 = pairRDD3.map(lambda row:compute(row))\n# 对数据进行排序\npairRDD5 = pairRDD4.sortByKey(ascending=False)\n\n# 使用collect()函数转化\nresult = pairRDD5.collect()\n\n# 获得每一个数据项的值\nID = []; Saled_HouseModel = []; Saled_HouseModel_Number = []\nidcount = 0\ncount_other = 0\nfor index,element in result:\n if element[1] < 500:\n count_other = count_other + element[1]\n else:\n ID.append(idcount)\n Saled_HouseModel.append(element[0])\n Saled_HouseModel_Number.append(element[1])\n idcount = idcount + 1\nID.append(idcount)\nSaled_HouseModel.append(\"其他\")\nSaled_HouseModel_Number.append(count_other)\nidcount = idcount + 1\n# 将获得的值存入数据库中\nfor i in range(0,idcount):\n sql = \"INSERT INTO Saled_HouseModel VALUES ({},'{}',{})\"\\\n .format(ID[i],Saled_HouseModel[i],Saled_HouseModel_Number[i])\n try:\n curcompute.execute(sql)\n conncompute.commit()\n except:\n conncompute.rollback()\n print(\"插入失败\")\n\n\n\n\n","sub_path":"RDD/Saled_HouseModel_RDD.py","file_name":"Saled_HouseModel_RDD.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"639403991","text":"import numpy.random as rnd\nfrom numpy.testing import assert_almost_equal, assert_equal, assert_raises\n\nfrom alns import ALNS, State\nfrom alns.criteria import HillClimbing, SimulatedAnnealing\nfrom .states import One, Zero\n\n\n# HELPERS ----------------------------------------------------------------------\n\n\ndef get_alns_instance(repair_operators=None, destroy_operators=None, seed=None):\n \"\"\"\n Test helper method.\n \"\"\"\n alns = ALNS(rnd.RandomState(seed))\n\n if repair_operators is not None:\n for repair_operator in repair_operators:\n alns.add_repair_operator(repair_operator)\n\n if destroy_operators is not None:\n for destroy_operator in destroy_operators:\n alns.add_destroy_operator(destroy_operator)\n\n return alns\n\n\nclass ValueState(State):\n \"\"\"\n Helper state for testing random values.\n \"\"\"\n\n def __init__(self, value):\n self._value = value\n\n def objective(self):\n return self._value\n\n\n# OPERATORS --------------------------------------------------------------------\n\n\ndef test_add_destroy_operator():\n \"\"\"\n Tests if adding a destroy operator correctly updates the number of\n operators available on the ALNS instance.\n \"\"\"\n alns = ALNS()\n\n for count in [1, 2]:\n alns.add_destroy_operator(lambda state, rnd: None)\n assert_equal(len(alns.destroy_operators), count)\n\n\ndef test_add_repair_operator():\n \"\"\"\n Tests if adding a repair operator correctly updates the number of\n operators available on the ALNS instance.\n \"\"\"\n alns = ALNS()\n\n for count in [1, 2]:\n alns.add_repair_operator(lambda state, rnd: None)\n assert_equal(len(alns.repair_operators), count)\n\n\n# PARAMETERS -------------------------------------------------------------------\n\n\ndef test_raises_missing_destroy_operator():\n \"\"\"\n Tests if the algorithm raises when no destroy operators have been set.\n \"\"\"\n alns = get_alns_instance([lambda state, rnd: None])\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 1, 1], 0.95, HillClimbing())\n\n\ndef test_raises_missing_repair_operator():\n \"\"\"\n Tests if the algorithm raises when no repair operators have been set.\n \"\"\"\n alns = get_alns_instance(destroy_operators=[lambda state, rnd: None])\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 1, 1], 0.95, HillClimbing())\n\n\ndef test_raises_negative_operator_decay():\n \"\"\"\n Tests if the algorithm raises when a negative operator decay parameter is\n passed.\n \"\"\"\n alns = get_alns_instance([lambda state, rnd: None],\n [lambda state, rnd: None])\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 1, 1], -0.5, HillClimbing())\n\n\ndef test_raises_explosive_operator_decay():\n \"\"\"\n Tests if the algorithm raises when an explosive operator decay parameter is\n passed.\n \"\"\"\n alns = get_alns_instance([lambda state, rnd: None],\n [lambda state, rnd: None])\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 1, 1], 1.2, HillClimbing())\n\n\ndef test_raises_boundary_operator_decay():\n \"\"\"\n The boundary cases, zero and one, should both raise.\n \"\"\"\n alns = get_alns_instance([lambda state, rnd: None],\n [lambda state, rnd: None])\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 1, 1], 0, HillClimbing())\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 1, 1], 1, HillClimbing())\n\n\ndef test_raises_insufficient_weights():\n \"\"\"\n We need (at least) four weights to be passed-in, one for each updating\n scenario.\n \"\"\"\n alns = get_alns_instance([lambda state, rnd: None],\n [lambda state, rnd: None])\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 1], .5, HillClimbing())\n\n\ndef test_raises_non_positive_weights():\n \"\"\"\n The passed-in weights should all be strictly positive.\n \"\"\"\n alns = get_alns_instance([lambda state, rnd: None],\n [lambda state, rnd: None])\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 0, 1], .5, HillClimbing())\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, -5, 1], .5, HillClimbing())\n\n\ndef test_raises_non_positive_iterations():\n \"\"\"\n The number of iterations should be strictly positive.\n \"\"\"\n alns = get_alns_instance([lambda state, rnd: None],\n [lambda state, rnd: None])\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 1, 1], .5, HillClimbing(), 0)\n\n with assert_raises(ValueError):\n alns.iterate(One(), [1, 1, 1, 1], .5, HillClimbing(), -1)\n\n\ndef test_does_not_raise():\n \"\"\"\n This set of parameters, on the other hand, should work correctly.\n \"\"\"\n alns = get_alns_instance([lambda state, rnd: One()],\n [lambda state, rnd: One()])\n\n alns.iterate(Zero(), [1, 1, 1, 1], .5, HillClimbing(), 100)\n\n\n# EXAMPLES ---------------------------------------------------------------------\n\n\ndef test_trivial_example():\n \"\"\"\n This tests the ALNS algorithm on a trivial example, where the initial\n solution is zero, and any other operator returns one.\n \"\"\"\n alns = get_alns_instance([lambda state, rnd: Zero()],\n [lambda state, rnd: Zero()])\n\n result = alns.iterate(One(), [1, 1, 1, 1], .5, HillClimbing(), 100)\n\n assert_equal(result.best_state.objective(), 0)\n\n\ndef test_fixed_seed_outcomes():\n \"\"\"\n Tests if fixing a seed results in deterministic outcomes even when using a\n 'random' acceptance criterion (here SA).\n \"\"\"\n outcomes = [0.00469, 0.00011, 0.04312]\n\n for seed, desired in enumerate(outcomes): # idx is seed\n alns = get_alns_instance(\n [lambda state, rnd: ValueState(rnd.random_sample())],\n [lambda state, rnd: None],\n seed)\n\n simulated_annealing = SimulatedAnnealing(1, .25, 1 / 100)\n\n result = alns.iterate(One(), [1, 1, 1, 1], .5, simulated_annealing, 100)\n\n assert_almost_equal(result.best_state.objective(), desired, decimal=5)\n\n\n# TODO test more complicated examples?\n# TODO test select_operator?\n","sub_path":"alns/tests/test_alns.py","file_name":"test_alns.py","file_ext":"py","file_size_in_byte":6315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"591139154","text":"import socket\nimport json\nimport sys\n\nport = int(sys.argv[1])\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ns.bind(('localhost', port))\ns.listen(5)\n\nwhile True:\n clientSock, clientAddr = s.accept()\n fullRequest = clientSock.recv(4096).decode()\n\n # Same header parsing as the curl clone\n header = {}\n firstLine = fullRequest.split('\\n')[0].split(' ')\n header['HTTP-Command'] = firstLine[0]\n header['Path'] = firstLine[1]\n header['HTTP-Type'] = firstLine[2]\n for line in fullRequest.split('\\n\\r\\n')[0].split('\\n'):\n if ':' in line:\n x, y = line.split(':', 1)\n header[x] = y.strip()\n\n if len(fullRequest) == 4096:\n try:\n while len(fullRequest) < int(header['Content-Length']):\n request = clientSock.recv(4096) # recieve the request with max of 4096 bits(?) at once\n fullRequest += request.decode()\n except Exception as e:\n while True:\n request = clientSock.recv(4096)\n fullRequest += request.decode()\n if len(request.decode()) < 10:\n break\n\n # Controlling all the request stuff here, pretty self explanatory\n if header['HTTP-Command'] != 'GET':\n response = 'HTTP/1.1 400 Bad Request\\r\\nContent-Length: 0\\r\\nContent-Type: application/json\\r\\n\\r\\n'\n clientSock.send(response.encode())\n elif header['Path'][:8] != '/product':\n response = 'HTTP/1.1 404 Not Found\\r\\nContent-Length: 0\\r\\nContent-Type: application/json\\r\\n\\r\\n'\n clientSock.send(response.encode())\n\n try:\n productList = header['Path'][9:].split('&')\n except:\n response = 'HTTP/1.1 400 Bad Request\\r\\nContent-Length: 0\\r\\nContent-Type: application/json\\r\\n\\r\\n'\n clientSock.send(response.encode())\n\n answer = 1\n operands = []\n for item in productList:\n try:\n answer = answer * float(item.split('=')[1])\n operands.append(float(item.split('=')[1]))\n except:\n response = 'HTTP/1.1 400 Bad Request\\r\\nContent-Length: 0\\r\\nContent-Type: application/json\\r\\n\\r\\n'\n clientSock.send(response.encode())\n break\n\n responsebody = json.dumps({'operation': 'product', 'operands': operands, 'result': answer}, indent=4)\n responseLength = len(responsebody)\n\n fullResponse = 'HTTP/1.1 200 OK\\r\\nContent-Length: ' + str(responseLength) + '\\r\\nContent-Type: application/json\\r\\n\\r\\n' + responsebody\n clientSock.send(fullResponse.encode())\n\n clientSock.close()\n","sub_path":"http_server3.py","file_name":"http_server3.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"386308769","text":"# coding:utf-8\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl=[]\nfilm_url_list=[]\nfor i in range(10):\n url.append(\"https://movie.douban.com/top250?start=%(i)s\" %{\"i\":i*25})\n film_web=BeautifulSoup(requests.get(url[i]).text)\n film_list=film_web.find(name=\"ol\",attrs={\"class\":\"grid_view\"}).findChildren(name=\"li\")\n for k in range(25):\n film_list2=film_list[k].find(name=\"div\",attrs={\"class\":\"pic\"}).find(name=\"a\")[\"href\"]\n film_url_list.append(film_list2)\n\n#film_url_list 储存TOP250电影各自页面的url\n#/home/katyusha/katyusha_dictionary/Internet_crawler/douban_spider\nrank=1\nfor t in film_url_list:\n try:\n film_intro=BeautifulSoup(requests.get(url=t).text)\n film_name=film_intro.find(name=\"span\",attrs={\"property\":\"v:itemreviewed\"}).contents[0]\n film_year=film_intro.find(name=\"span\",attrs={\"class\":\"year\"}).contents[0]\n film_rating=film_intro.find(name=\"strong\",attrs={\"property\":\"v:average\"}).contents[0]\n #film_director = film_intro.find(attrs={\"rel\": \"directedBy\"}).contents[0]\n film_actor=\"\"\n for l in film_intro.find_all(name=\"a\",attrs={\"rel\":\"v:starring\"}):\n film_actor+=\"/\"\n film_actor+=(l.string)\n film_rdata=film_intro.find(name=\"span\",attrs={\"property\":\"v:initialReleaseDate\"})[\"content\"]\n film_runtime=film_intro.find(name=\"span\",attrs={\"property\":\"v:runtime\"})[\"content\"]\n\n print(\"Top:%s\\n 影片名称:%s\\n 影片时间:%s\\n 影片评分:%s\\n 影片主演:%s\\n 影片片长:%s\\n\" %(rank,film_name,film_year,film_rating,film_actor,film_runtime))\n\n file_succese=open(\"/home/katyusha/katyusha_dictionary/Internet_crawler/douban_spider/douban_movie_top250.txt\",\"a\")\n file_succese.write(\"Top:%s\\n 影片名称:%s\\n 影片时间:%s\\n 影片评分:%s\\n 影片主演:%s\\n 影片片长:%s\\n\" %(rank,film_name,film_year,film_rating,film_actor,film_runtime))\n file_succese.write(\"========================\")\n except:\n print(\"top%s获取失败\\n\" %(rank))\n file_fail=open(\"/home/katyusha/katyusha_dictionary/Internet_crawler/douban_spider/douban_movie_top250.txt\",\"a\")\n file_fail.write(\"top%s写入失败\\n\" %(rank))\n file_fail.write(\"========================\")\n file_fail.close()\n rank += 1\n","sub_path":"spider/DouBan.py","file_name":"DouBan.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"200500479","text":"from asyncio import Queue\n\nfrom bocadillo import App, Templates, server_event\n\napp = App()\ntemplates = Templates(app)\n\nclients = set()\n\n\n@app.route(\"/events\")\nclass Events:\n async def get(self, req, res):\n client = Queue()\n clients.add(client)\n print(\"New client:\", id(client))\n\n @res.event_stream\n async def send_events():\n hello = {\"message\": \"hello\"}\n yield server_event(json=hello, name=\"hello\")\n try:\n while True:\n message = client.get_nowait()\n yield server_event(json=message, name=\"message\")\n print(\"Sent\", message, \"to client\", id(client))\n client.task_done()\n finally:\n print(\"Client disconnected:\", id(client))\n\n async def post(self, req, res):\n json = await req.json()\n for client in clients:\n await client.put(json)\n res.status_code = 201\n\n\n@app.route(\"/\")\nasync def index(req, res):\n res.html = await templates.render(\"index.html\")\n","sub_path":"docs/guides/http/sse_example/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"205437405","text":"'''\nserver.py: DIBS server definition.\n\nCopyright\n---------\n\nCopyright (c) 2021 by the California Institute of Technology. This code\nis open-source software released under a 3-clause BSD license. Please see the\nfile \"LICENSE\" for more information.\n'''\n\nfrom beaker.middleware import SessionMiddleware\nimport bottle\nfrom bottle import Bottle, HTTPResponse, static_file, template\nfrom bottle import request, response, redirect, route, get, post, error\nfrom datetime import datetime, timedelta\nfrom decouple import config\nimport functools\nfrom humanize import naturaldelta\nimport json\nimport os\nfrom os.path import realpath, dirname, join\nfrom peewee import *\nimport sys\nimport threading\nfrom topi import Tind\n\nfrom .database import Item, Loan, Recent\nfrom .date_utils import human_datetime\nfrom .email import send_email\nfrom .people import Person, check_password, person_from_session\nfrom .roles import role_to_redirect, has_required_role\n\nif __debug__:\n from sidetrack import log, logr, set_debug\n\n\f\n# General configuration and initialization.\n# .............................................................................\n\n# Begin by creating a Bottle object on which we will define routes. At the end\n# of this file, we will replace this object with the final exported application.\ndibs = Bottle()\n\n# Tell Bottle where to find templates. This is necessary for both the Bottle\n# template() command to work and also to get %include to work inside our .tpl\n# template files. Rather surprisingly, the only way to tell Bottle where to\n# find the templates is to set this Bottle package-level variable.\nbottle.TEMPLATE_PATH.append(join(realpath(dirname(__file__)), 'templates'))\n\n# Cooling-off period after a loan ends, before user can borrow same title again.\n_RELOAN_WAIT_TIME = timedelta(minutes = int(config('RELOAN_WAIT_TIME') or 30))\n\n# Where we send users to give feedback.\n_FEEDBACK_URL = config('FEEDBACK_URL') or '/'\n\n# The next constant is used to configure Beaker sessions. This is used at\n# the very end of this file in the call to SessionMiddleware.\n_SESSION_CONFIG = {\n # Use simple in-memory session handling. Ultimately we will only need\n # sessions for the admin pages, and we won't have many users.\n 'session.type' : 'memory',\n\n # Save session data automatically, without requiring us to call save().\n 'session.auto' : True,\n\n # Session cookies should be accessible only to the browser, not JavaScript.\n 'session.httponly' : True,\n\n # Clear sessions when the user restarts their browser.\n 'session.cookie_expires' : True,\n\n # The name of the session cookie.\n 'session.key' : config('COOKIE_NAME') or 'dibs',\n\n # Seconds until the session is invalidated.\n 'session.timeout' : config('SESSION_TIMEOUT', cast = int) or 604800,\n}\n\n\f\n# General-purpose utilities used later.\n# .............................................................................\n\ndef page(name, **kargs):\n '''Create a page using template \"name\" with some standard variables set.'''\n # Bottle is unusual in providing global objects like 'request'.\n session = request.environ['beaker.session']\n logged_in = bool(session.get('user', None))\n staff_user = has_required_role(person_from_session(session), 'library')\n return template(name, base_url = dibs.base_url, logged_in = logged_in,\n staff_user = staff_user, feedback_url = _FEEDBACK_URL, **kargs)\n\n\f\n# Bootle hooks -- functions that are run every time a route is invoked.\n# .............................................................................\n\n@dibs.hook('before_request')\ndef expired_loan_removing_wrapper():\n '''Clean up expired loans.'''\n for loan in Loan.select():\n if datetime.now() >= loan.endtime:\n barcode = loan.item.barcode\n if __debug__: log(f'loan for {barcode} by {loan.user} expired')\n Recent.create(item = loan.item, user = loan.user,\n nexttime = loan.endtime + timedelta(minutes = 1))\n loan.delete_instance()\n for recent in Recent.select():\n if datetime.now() >= recent.nexttime:\n barcode = recent.item.barcode\n if __debug__: log(f'expiring recent record for {barcode} by {recent.user}')\n recent.delete_instance()\n\n\f\n# Decorators -- functions that are run selectively on certain routes.\n# .............................................................................\n\ndef barcode_verified(func):\n '''Check if the given barcode (passed as keyword argument) exists.'''\n @functools.wraps(func)\n def barcode_verification_wrapper(*args, **kwargs):\n if 'barcode' in kwargs:\n barcode = kwargs['barcode']\n if not Item.get_or_none(Item.barcode == barcode):\n if __debug__: log(f'there is no item with barcode {barcode}')\n return page('error', summary = 'no such barcode',\n message = f'There is no item with barcode {barcode}.')\n return func(*args, **kwargs)\n return barcode_verification_wrapper\n\n\ndef authenticated(func):\n '''Check if the user is authenticated and redirect to /login if not.'''\n @functools.wraps(func)\n def authentication_check_wrapper(*args, **kwargs):\n if request.method == 'HEAD':\n # A Beaker session is not present when we get a HEAD. Unsure if\n # that's expected or just a Bottle or Beaker behavior. We can't\n # proceed with the request, but it's not an error either. I\n # haven't found a better alternative than simply returning nothing.\n if __debug__: log(f'returning empty HEAD on {request.path}')\n return\n session = request.environ['beaker.session']\n if not session.get('user', None):\n if __debug__: log(f'user not found in session object')\n redirect(f'{dibs.base_url}/login')\n else:\n if __debug__: log(f'user is authenticated: {session[\"user\"]}')\n return func(*args, **kwargs)\n return authentication_check_wrapper\n\n\f\n# Administrative interface endpoints.\n# .............................................................................\n\n# NOTE: there are three approaches for integrating SSO. First is always\n# require SSO before showing anything (not terribly useful here).\n# Second use existing end points (e.g. /login, /logout) this supports\n# everyone as SSO or not at all, third would be to support both\n# SSO via its own end points and allow the app based authentication\n# end points to remain for users who are defined in the system only.\n# This can be helpful in the case of admin users or service accounts.\n\n@dibs.get('/login')\ndef show_login_page():\n # NOTE: If SSO is implemented this should redirect to the\n # SSO end point with a return to /login on success.\n if __debug__: log('get /login invoked')\n return page('login')\n\n\n@dibs.post('/login')\ndef login():\n '''Handle performing the login action from the login page.'''\n # NOTE: If SSO is implemented this end point will handle the\n # successful login case applying role rules if necessary.\n email = request.forms.get('email').strip()\n password = request.forms.get('password')\n if __debug__: log(f'post /login invoked by {email}')\n # get our person obj from people.db for demo purposes\n user = (Person.get_or_none(Person.uname == email))\n if user != None:\n if check_password(password, user.secret) == False:\n if __debug__: log(f'wrong password -- rejecting {email}')\n return page('login')\n else:\n if __debug__: log(f'creating session for {email}')\n session = request.environ['beaker.session']\n session['user'] = email\n p = role_to_redirect(user.role)\n if __debug__: log(f'redirecting to \"{p}\"')\n redirect(f'{dibs.base_url}/{p}')\n return\n else:\n if __debug__: log(f'wrong password -- rejecting {email}')\n return page('login')\n\n\n@dibs.post('/logout')\ndef logout():\n '''Handle the logout action from the navbar menu on every page.'''\n session = request.environ['beaker.session']\n if not session.get('user', None):\n if __debug__: log(f'post /logout invoked by unauthenticated user')\n return\n user = session['user']\n if __debug__: log(f'post /logout invoked by {user}')\n del session['user']\n redirect(f'{dibs.base_url}/login')\n\n\n@dibs.get('/list')\n@authenticated\ndef list_items():\n '''Display the list of known items.'''\n person = person_from_session(request.environ['beaker.session'])\n if has_required_role(person, 'library') == False:\n redirect(f'{dibs.base_url}/notallowed')\n return\n if __debug__: log('get /list invoked')\n return page('list', items = Item.select())\n\n\n@dibs.get('/manage')\n@authenticated\ndef list_items():\n '''Display the list of known items.'''\n person = person_from_session(request.environ['beaker.session'])\n if has_required_role(person, 'library') == False:\n redirect(f'{dibs.base_url}/notallowed')\n return\n if __debug__: log('get /manage invoked')\n return page('manage', items = Item.select())\n\n\n@dibs.get('/add')\n@authenticated\ndef add():\n '''Display the page to add new items.'''\n person = person_from_session(request.environ['beaker.session'])\n if has_required_role(person, 'library') == False:\n redirect(f'{dibs.base_url}/notallowed')\n return\n if __debug__: log('get /add invoked')\n return page('edit', action = 'add', item = None)\n\n\n@dibs.get('/edit/')\n@barcode_verified\n@authenticated\ndef edit(barcode):\n '''Display the page to add new items.'''\n person = person_from_session(request.environ['beaker.session'])\n if has_required_role(person, 'library') == False:\n redirect(f'{dibs.base_url}/notallowed')\n return\n if __debug__: log(f'get /edit invoked on {barcode}')\n return page('edit', action = 'edit', item = Item.get(Item.barcode == barcode))\n\n\n@dibs.post('/update/add')\n@dibs.post('/update/edit')\n@authenticated\ndef update_item():\n '''Handle http post request to add a new item from the add-new-item page.'''\n person = person_from_session(request.environ['beaker.session'])\n if has_required_role(person, 'library') == False:\n redirect(f'{dibs.base_url}/notallowed')\n return\n if __debug__: log(f'post {request.path} invoked')\n if 'cancel' in request.POST:\n if __debug__: log(f'user clicked Cancel button')\n redirect(f'{dibs.base_url}/list')\n return\n\n # The HTML form validates the data types, but the POST might come from\n # elsewhere, so we always need to sanity-check the values.\n barcode = request.forms.get('barcode').strip()\n if not barcode.isdigit():\n return page('error', summary = 'invalid barcode',\n message = f'{barcode} is not a valid barcode')\n duration = request.forms.get('duration').strip()\n if not duration.isdigit() or int(duration) <= 0:\n return page('error', summary = 'invalid duration',\n message = f'Duration must be a positive number')\n num_copies = request.forms.get('num_copies').strip()\n if not num_copies.isdigit() or int(num_copies) <= 0:\n return page('error', summary = 'invalid copy number',\n message = f'# of copies must be a positive number')\n\n # Our current approach only uses items with barcodes that exist in TIND.\n # If that ever changes, the following needs to change too.\n tind = Tind('https://caltech.tind.io')\n try:\n rec = tind.item(barcode = barcode).parent\n except:\n if __debug__: log(f'could not find {barcode} in TIND')\n return page('error', summary = 'no such barcode',\n message = f'There is no item with barcode {barcode}.')\n return\n\n item = Item.get_or_none(Item.barcode == barcode)\n if '/update/add' in request.path:\n if item:\n if __debug__: log(f'{barcode} already exists in the database')\n return page('error', summary = 'duplicate entry',\n message = f'An item with barcode {{barcode}} already exists.')\n if __debug__: log(f'adding {barcode}, title {rec.title}')\n Item.create(barcode = barcode, title = rec.title, author = rec.author,\n tind_id = rec.tind_id, year = rec.year,\n edition = rec.edition, thumbnail = rec.thumbnail_url,\n num_copies = num_copies, duration = duration)\n else:\n if not item:\n if __debug__: log(f'there is no item with barcode {barcode}')\n return page('error', summary = 'no such barcode',\n message = f'There is no item with barcode {barcode}.')\n if __debug__: log(f'updating {barcode} from {rec}')\n\t#FIXME: Need to validate these values.\n item.barcode = barcode\n item.num_copies = num_copies\n item.duration = duration\n\t# NOTE: Since we don't have these fields in the edit form we don't\n\t# go anything with them.\n #for field in ['title', 'author', 'year', 'edition', 'tind_id', 'thumbnail']:\n # setattr(item, field, getattr(rec, field, ''))\n\t# NOTE: We only update the specific editable fields.\n item.save(only=[Item.barcode, Item.num_copies, Item.duration])\n redirect(f'{dibs.base_url}/list')\n\n\n@dibs.post('/ready')\n@barcode_verified\n@authenticated\ndef toggle_ready():\n '''Set the ready-to-loan field.'''\n barcode = request.POST.barcode.strip()\n ready = (request.POST.ready.strip() == 'True')\n if __debug__: log(f'post /ready invoked on barcode {barcode}')\n item = Item.get(Item.barcode == barcode)\n # The status we get is the availability status as it currently shown,\n # meaning the user's action is to change the status.\n item.ready = not ready\n #NOTE: We only save the ready value we toggled.\n item.save(only=[Item.ready])\n if __debug__: log(f'readiness of {barcode} is now {item.ready}')\n # If the readiness state is changed after the item is let out for loans,\n # then there may be outstanding loans right now. Delete them.\n if list(Loan.select(Loan.item == item)):\n if __debug__: log(f'loans for {barcode} have been deleted')\n Loan.delete().where(Loan.item == item).execute()\n redirect(f'{dibs.base_url}/list')\n\n\n@dibs.post('/remove')\n@barcode_verified\n@authenticated\ndef remove_item():\n '''Handle http post request to remove an item from the list page.'''\n person = person_from_session(request.environ['beaker.session'])\n if has_required_role(person, 'library') == False:\n redirect(f'{dibs.base_url}/notallowed')\n return\n barcode = request.POST.barcode.strip()\n if __debug__: log(f'post /remove invoked on barcode {barcode}')\n\n item = Item.get(Item.barcode == barcode)\n item.ready = False\n # Don't forget to delete any loans involving this item.\n if list(Loan.select(Loan.item == item)):\n Loan.delete().where(Loan.item == item).execute()\n Item.delete().where(Item.barcode == barcode).execute()\n redirect(f'{dibs.base_url}/manage')\n\n\f\n# User endpoints.\n# .............................................................................\n\n@dibs.get('/')\n@dibs.get('/')\ndef general_page(name = '/'):\n '''Display the welcome page.'''\n if __debug__: log(f'get {name} invoked')\n if name == 'about':\n return page('about')\n elif name == 'thankyou':\n return page('thankyou')\n else:\n return page('info', reloan_wait_time = naturaldelta(_RELOAN_WAIT_TIME))\n\n\n#FIXME: We need an item status which returns a JSON object\n# so the item page can update itself without reloading the whole page.\n@dibs.get('/item-status/')\n@authenticated\ndef item_status(barcode):\n '''Returns an item summary status as a JSON string'''\n user = request.environ['beaker.session'].get('user')\n if __debug__: log(f'get /item-status invoked on barcode {barcode} and {user}')\n\n obj = {\n 'barcode': barcode,\n 'ready': False,\n 'available': False,\n 'explanation': '',\n 'endtime' : None,\n 'base_url': dibs.base_url\n }\n item = Item.get_or_none(Item.barcode == barcode)\n if (item != None) and (user != None):\n obj['ready'] = item.ready\n user_loans = list(Loan.select().where(Loan.user == user))\n recent_history = list(Recent.select().where(Recent.item == item))\n endtime = None\n # First check if the user has recently loaned out this same item.\n if any(loan for loan in recent_history if loan.user == user):\n if __debug__: log(f'{user} recently borrowed {barcode}')\n recent = next(loan for loan in recent_history if loan.user == user)\n endtime = recent.nexttime\n obj['available'] = False\n obj['explanation'] = 'It is too soon after the last time you borrowed this book.'\n elif any(user_loans):\n # The user has a current loan. If it's for this title, redirect them\n # to the viewer; if it's for another title, block the loan button.\n if user_loans[0].item == item:\n if __debug__: log(f'{user} already has {barcode}; redirecting to uv')\n obj['explanation'] = 'You currently have borrowed this book.'\n else:\n if __debug__: log(f'{user} already has a loan on something else')\n obj['available'] = False\n endtime = user_loans[0].endtime\n loaned_item = user_loans[0].item\n obj['explanation'] = ('You have another item on loan'\n + f' (\"{loaned_item.title}\" by {loaned_item.author})'\n + ' and it has not yet been returned.')\n else:\n if __debug__: log(f'{user} is allowed to borrow {barcode}')\n loans = list(Loan.select().where(Loan.item == item))\n obj['available'] = item.ready and (len(loans) < item.num_copies)\n if item.ready and not obj['available']:\n endtime = min(loan.endtime for loan in loans)\n obj['explanation'] = 'All available copies are currently on loan.'\n elif not item.ready:\n endtime = None\n obj['explanation'] = 'This item is not currently available through DIBS.'\n else:\n # It's available and they can have it.\n endtime = None\n obj['explanation'] = ''\n if endtime != None:\n obj['endtime'] = human_datetime(endtime)\n else:\n obj['endtime'] == None\n return json.dumps(obj)\n\n\n@dibs.get('/item/')\n@barcode_verified\n@authenticated\ndef show_item_info(barcode):\n '''Display information about the given item.'''\n user = request.environ['beaker.session'].get('user')\n if __debug__: log(f'get /item invoked on barcode {barcode} by {user}')\n\n item = Item.get(Item.barcode == barcode)\n user_loans = list(Loan.select().where(Loan.user == user))\n recent_history = list(Recent.select().where(Recent.item == item))\n # First check if the user has recently loaned out this same item.\n if any(loan for loan in recent_history if loan.user == user):\n if __debug__: log(f'{user} recently borrowed {barcode}')\n recent = next(loan for loan in recent_history if loan.user == user)\n endtime = recent.nexttime\n available = False\n explanation = 'It is too soon after the last time you borrowed this book.'\n elif any(user_loans):\n # The user has a current loan. If it's for this title, redirect them\n # to the viewer; if it's for another title, block the loan button.\n if user_loans[0].item == item:\n if __debug__: log(f'{user} already has {barcode}; redirecting to uv')\n redirect(f'{dibs.base_url}/view/{barcode}')\n return\n else:\n if __debug__: log(f'{user} already has a loan on something else')\n available = False\n endtime = user_loans[0].endtime\n loaned_item = user_loans[0].item\n explanation = ('You have another item on loan'\n + f' (\"{loaned_item.title}\" by {loaned_item.author})'\n + ' and it has not yet been returned.')\n else:\n if __debug__: log(f'{user} is allowed to borrow {barcode}')\n loans = list(Loan.select().where(Loan.item == item))\n available = item.ready and (len(loans) < item.num_copies)\n if item.ready and not available:\n endtime = min(loan.endtime for loan in loans)\n explanation = 'All available copies are currently on loan.'\n elif not item.ready:\n endtime = None\n explanation = 'This item is not currently available through DIBS.'\n else:\n # It's available and they can have it.\n endtime = datetime.now()\n explanation = None\n return page('item', item = item, available = available,\n endtime = human_datetime(endtime), explanation = explanation)\n\n\n# Lock object used around some code to prevent concurrent modification.\n_THREAD_LOCK = threading.Lock()\n\n@dibs.post('/loan')\n@barcode_verified\n@authenticated\ndef loan_item():\n '''Handle http post request to loan out an item, from the item info page.'''\n user = request.environ['beaker.session'].get('user')\n barcode = request.POST.barcode.strip()\n if __debug__: log(f'post /loan invoked on barcode {barcode} by {user}')\n\n item = Item.get(Item.barcode == barcode)\n if not item.ready:\n # Normally we shouldn't see a loan request through our form in this\n # case, so either staff has changed the status after item was made\n # available or someone got here accidentally (or deliberately).\n if __debug__: log(f'{barcode} is not ready for loans')\n redirect(f'{dibs.base_url}/view/{barcode}')\n return\n\n # The default Bottle dev web server is single-thread, so we won't run into\n # the problem of 2 users simultaneously clicking on the loan button. Other\n # servers are multithreaded, and there's a risk that the time it takes us\n # to look through the loans introduces a window of time when another user\n # might click on the same loan button and cause another loan request to be\n # initiated before the 1st finishes. So, lock this block of code.\n with _THREAD_LOCK:\n if any(Loan.select().where(Loan.user == user)):\n if __debug__: log(f'{user} already has a loan on something else')\n return page('error', summary = 'only one loan at a time',\n message = ('Our policy currently prevents users from '\n 'borrowing more than one item at a time.'))\n loans = list(Loan.select().where(Loan.item == item))\n if any(loan.user for loan in loans if user == loan.user):\n # Shouldn't be able to reach this point b/c the item page shouldn't\n # make a loan available for this user & item combo. But if\n # something weird happens (e.g., double posting), we might.\n if __debug__: log(f'{user} already has a copy of {barcode} loaned out')\n if __debug__: log(f'redirecting {user} to /view for {barcode}')\n redirect(f'{dibs.base_url}/view/{barcode}')\n return\n if len(loans) >= item.num_copies:\n # This shouldn't be possible, but catch it anyway.\n if __debug__: log(f'# loans {len(loans)} >= num_copies for {barcode} ')\n redirect(f'{dibs.base_url}/item/{barcode}')\n return\n recent_history = list(Recent.select().where(Recent.item == item))\n if any(loan for loan in recent_history if loan.user == user):\n if __debug__: log(f'{user} recently borrowed {barcode}')\n recent = next(loan for loan in recent_history if loan.user == user)\n return page('error', summary = 'too soon',\n message = ('We ask that you wait at least '\n f'{naturaldelta(_RELOAN_WAIT_TIME)} before '\n 'requesting the same item again. Please try '\n f'after {human_datetime(recent.nexttime)}'))\n # OK, the user is allowed to loan out this item.\n start = datetime.now()\n end = start + timedelta(hours = item.duration)\n if __debug__: log(f'creating new loan for {barcode} for {user}')\n Loan.create(item = item, user = user, started = start, endtime = end)\n send_email(user, item, start, end, dibs.base_url)\n redirect(f'{dibs.base_url}/view/{barcode}')\n\n\n@dibs.post('/return')\n@barcode_verified\n@authenticated\ndef end_loan():\n '''Handle http post request to return the given item early.'''\n barcode = request.forms.get('barcode').strip()\n user = request.environ['beaker.session'].get('user')\n if __debug__: log(f'get /return invoked on barcode {barcode} by {user}')\n\n loans = list(Loan.select().join(Item).where(Loan.item.barcode == barcode))\n user_loans = [loan for loan in loans if user == loan.user]\n if len(user_loans) > 1:\n # Internal error -- users should not have more than one loan of an\n # item. Right now, we simply log it and move on.\n if __debug__: log(f'error: more than one loan for {barcode} by {user}')\n elif user_loans:\n # Normal case: user has loaned a copy of item. Delete the record and\n # add a new Recent loan record.\n if __debug__: log(f'deleting loan record for {barcode} by {user}')\n user_loans[0].delete_instance()\n Recent.create(item = Item.get(Item.barcode == barcode), user = user,\n nexttime = datetime.now() + _RELOAN_WAIT_TIME)\n else:\n # User does not have this item loaned out. Ignore the request.\n if __debug__: log(f'{user} does not have {barcode} loaned out')\n redirect(f'{dibs.base_url}/thankyou')\n\n\n@dibs.get('/view/')\n@barcode_verified\n@authenticated\ndef send_item_to_viewer(barcode):\n '''Redirect to the viewer.'''\n user = request.environ['beaker.session'].get('user')\n if __debug__: log(f'get /view invoked on barcode {barcode} by {user}')\n\n loans = list(Loan.select().join(Item).where(Loan.item.barcode == barcode))\n user_loans = [loan for loan in loans if user == loan.user]\n if user_loans:\n if __debug__: log(f'redirecting to viewer for {barcode} for {user}')\n return page('uv', barcode = barcode,\n endtime = human_datetime(user_loans[0].endtime),\n reloan_wait_time = naturaldelta(_RELOAN_WAIT_TIME))\n else:\n if __debug__: log(f'{user} does not have {barcode} loaned out')\n redirect(f'{dibs.base_url}/item/{barcode}')\n\n\n@dibs.get('/manifests/')\n@barcode_verified\n@authenticated\ndef return_manifest(barcode):\n '''Return the manifest file for a given item.'''\n user = request.environ['beaker.session'].get('user')\n if __debug__: log(f'get /manifests/{barcode} invoked by {user}')\n\n loans = list(Loan.select().join(Item).where(Loan.item.barcode == barcode))\n if any(loan.user for loan in loans if user == loan.user):\n if __debug__: log(f'returning manifest file for {barcode} for {user}')\n return static_file(f'{barcode}-manifest.json', root = 'manifests')\n else:\n if __debug__: log(f'{user} does not have {barcode} loaned out')\n redirect(f'{dibs.base_url}/notallowed')\n return\n\n\f\n# Universal viewer interface.\n# .............................................................................\n# The uv subdirectory contains generic html and css. We serve them as static\n# files to anyone; they don't need to be controlled. The multiple routes\n# are because the UV files themselves reference different paths.\n\n@dibs.route('/view/uv/')\n@dibs.route('/viewer/uv/')\ndef serve_uv_files(filepath):\n if __debug__: log(f'serving static uv file /viewer/uv/{filepath}')\n return static_file(filepath, root = 'viewer/uv')\n\n\n# The uv subdirectory contains generic html and css. Serve as static files.\n@dibs.route('/viewer/')\ndef serve_uv_files(filepath):\n if __debug__: log(f'serving static uv file /viewer/{filepath}')\n return static_file(filepath, root = 'viewer')\n\n\f\n# Error pages.\n# .............................................................................\n# Note: the Bottle session plugin does not seem to supply session arg to @error.\n\n@dibs.get('/notallowed')\n@dibs.post('/notallowed')\ndef not_allowed():\n if __debug__: log(f'serving /notallowed')\n return page('error', summary = 'access error',\n message = ('The requested method does not exist or you do not '\n 'not have permission to access the requested item.'))\n\n@error(404)\ndef error404(error):\n if __debug__: log(f'error404 called with {error}')\n return page('404', code = error.status_code, message = error.body)\n\n\n@error(405)\ndef error405(error):\n if __debug__: log(f'error405 called with {error}')\n return page('error', summary = 'method not allowed',\n message = ('The requested method does not exist or you do not '\n 'not have permission to perform the action.'))\n\n\f\n# Miscellaneous static pages.\n# .............................................................................\n\n@dibs.get('/favicon.ico')\ndef favicon():\n '''Return the favicon.'''\n if __debug__: log(f'returning favicon')\n return static_file('favicon.ico', root = 'dibs/static')\n\n\n@dibs.get('/static/')\ndef included_file(filename):\n '''Return a static file used with %include in a template.'''\n if __debug__: log(f'returning included file {filename}')\n return static_file(filename, root = 'dibs/static')\n\n\f\n# Main exported application.\n# .............................................................................\n# In the file above, we defined a Bottle application and its routes. Now we\n# take that application definition and hand it to a middleware layer for\n# session handling (using Beaker). The new \"dibs\" constitutes the final\n# application that is invoked by the WSGI server via ../adapter.wsgi.\n\ndibs = SessionMiddleware(dibs, _SESSION_CONFIG)\n","sub_path":"dibs/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":30539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"5897001","text":"# coding=utf-8\n\nimport re\nimport six\nimport time\nimport string\nimport random\nimport logging\n\nfrom avocado.utils import process\nfrom avocado.utils import wait\nfrom virttest import utils_misc\nfrom virttest import utils_disk\nfrom virttest import utils_test\nfrom virttest import error_context\nfrom virttest import virt_vm\nfrom virttest import qemu_monitor\nfrom provider.storage_benchmark import generate_instance\n\n\n@error_context.context_aware\ndef run(test, params, env):\n\n \"\"\"\n Special hardware test case.\n FC host: ibm-x3650m4-05.lab.eng.pek2.redhat.com\n Disk serial name: scsi-360050763008084e6e0000000000001a4\n # multipath -ll\n mpathb (360050763008084e6e0000000000001a8) dm-4 IBM,2145\n size=100G features='1 queue_if_no_path' hwhandler='1 alua' wp=rw\n |-+- policy='service-time 0' prio=50 status=active\n | `- 2:0:1:0 sde 8:64 active ready running\n `-+- policy='service-time 0' prio=10 status=enabled\n `- 2:0:0:0 sdd 8:48 active ready running\n mpatha (360050763008084e6e0000000000001a4) dm-3 IBM,2145\n size=100G features='1 queue_if_no_path' hwhandler='1 alua' wp=rw\n |-+- policy='service-time 0' prio=50 status=active\n | `- 1:0:1:0 sdc 8:32 active ready running\n `-+- policy='service-time 0' prio=10 status=enabled\n `- 1:0:0:0 sdb 8:16 active ready running\n Customer Bug ID: 1741937 1673546\n\n Test if VM paused/resume when fc storage offline/online.\n\n 1) pass-through /dev/mapper/mpatha\n 2) install guest on pass-through disk\n 3) Disconnect the storage during installation\n 4) Check if VM status is 'paused'\n 5) Connect the storage, Wait until the storage is accessible again\n 6) resume the vm\n 7) Check if VM status is 'running'\n 8) installation completed successfully\n 9) re-pass-through /dev/mapper/mpatha\n 10) fio test on pass-through disk\n 11) Disconnect any path of multipath during fio testing\n 12) Check if VM status is 'paused'\n 13) Connect the storage, Wait until the storage is accessible again\n 14) resume the vm\n 15) fio testing completed successfully\n\n :param test: kvm test object.\n :param params: Dictionary with the test parameters.\n :param env: Dictionary with test environment.\n \"\"\"\n\n def check_vm_status(vm, status):\n \"\"\"\n Check if VM has the given status or not.\n\n :param vm: VM object.\n :param status: String with desired status.\n :return: True if VM status matches our desired status.\n :return: False if VM status does not match our desired status.\n \"\"\"\n try:\n current_status = vm.monitor.get_status()\n vm.verify_status(status)\n except (virt_vm.VMStatusError, qemu_monitor.MonitorLockError):\n logging.info(\"Failed to check vm status, it is '%s' \"\n \"instead of '%s'\" % (current_status, status))\n return False\n except Exception as e:\n logging.info(\"Failed to check vm status: %s\" % six.text_type(e))\n logging.info(\"vm status is '%s' instead of\"\n \" '%s'\" % (current_status, status))\n return False\n else:\n logging.info(\"Check vm status successfully. It is '%s'\" % status)\n return True\n\n def get_multipath_disks(mpath_name=\"mpatha\"):\n\n \"\"\"\n Get all disks of multiple paths.\n multipath like below:\n mpatha (360050763008084e6e0000000000001a4) dm-3 IBM,2145\n size=100G features='1 queue_if_no_path' hwhandler='1 alua' wp=rw\n |-+- policy='service-time 0' prio=50 status=active\n | `- 1:0:1:0 sdc 8:32 active ready running\n `-+- policy='service-time 0' prio=10 status=enabled\n `- 1:0:0:0 sdb 8:16 active ready running\n\n :param mpath_name: multi-path name.\n :return: a list. if get disks successfully or raise a error\n \"\"\"\n logging.info(\"get_multipath_disks:\"+mpath_name)\n disks = []\n disk_str = []\n outputs = process.run(\"multipath -ll \"+mpath_name, shell=True).stdout.decode()\n outputs = outputs.split(mpath_name)[-1]\n disk_str.append(\"active ready running\")\n disk_str.append(\"active faulty offline\")\n disk_str.append(\"failed faulty offline\")\n disk_str.append(\"failed ready running\")\n for line in outputs.splitlines():\n if disk_str[0] in line or disk_str[1] in line or disk_str[2] \\\n in line or disk_str[3] in line:\n disks.append(line.split()[-5])\n if not disks:\n test.fail(\"Failed to get disks by 'multipath -ll'\")\n else:\n return disks\n\n def get_multipath_disks_status(mpath_name=\"mpatha\"):\n\n \"\"\"\n Get status of multiple paths.\n multipath like below:\n mpatha (360050763008084e6e0000000000001a4) dm-3 IBM,2145\n size=100G features='1 queue_if_no_path' hwhandler='1 alua' wp=rw\n |-+- policy='service-time 0' prio=50 status=active\n | `- 1:0:1:0 sdc 8:32 active ready running\n `-+- policy='service-time 0' prio=10 status=enabled\n `- 1:0:0:0 sdb 8:16 active ready running\n\n :param mpath_name: multi-path name.\n :return: a dict. e.g. {\"sdb\": \"running\", \"sdc\": \"running\"}\n \"\"\"\n disks = get_multipath_disks(mpath_name)\n disks_status = {}\n outputs = process.run(\"multipath -ll \" + mpath_name, shell=True).stdout.decode()\n outputs = outputs.split(mpath_name)[-1]\n for line in outputs.splitlines():\n for i in range(len(disks)):\n if disks[i] in line:\n disks_status[disks[i]] = line.strip().split()[-1]\n break\n if not disks_status or len(disks_status) != len(disks):\n logging.info(\"Failed to get disks status by 'multipath -ll'\")\n return {}\n else:\n return disks_status\n\n def compare_onepath_status(status, disk):\n\n \"\"\"\n Compare status whether equal to the given status.\n This function just focus on all paths are running or all are offline.\n\n :param status: the state of disks.\n :param disk: disk kname.\n :return: True, if equal to the given status or False\n \"\"\"\n status_dict = get_multipath_disks_status(mpath_name)\n logging.debug(\"compare_onepath_status disk:\",disk,status_dict,status)\n if disk in status_dict.keys() and status == status_dict[disk]:\n return True\n else:\n return False\n\n def compare_multipath_status(status, mpath_name=\"mpatha\"):\n\n \"\"\"\n Compare status whether equal to the given status.\n This function just focus on all paths are running or all are offline.\n\n :param status: the state of disks.\n :param mpath_name: multi-path name.\n :return: True, if equal to the given status or False\n \"\"\"\n status_dict = get_multipath_disks_status(mpath_name)\n logging.debug(\"compare_multipath_status mpath_name:\", mpath_name, status_dict, status)\n if len(set(status_dict.values())) == 1 and status in status_dict.values():\n return True\n else:\n return False\n\n def set_disk_status_to_online_offline(disk, status):\n\n \"\"\"\n set disk state to online/offline.\n multipath like below:\n mpatha (360050763008084e6e0000000000001a4) dm-3 IBM,2145\n size=100G features='1 queue_if_no_path' hwhandler='1 alua' wp=rw\n |-+- policy='service-time 0' prio=50 status=active\n | `- 1:0:1:0 sdc 8:32 active ready running\n `-+- policy='service-time 0' prio=10 status=enabled\n `- 1:0:0:0 sdb 8:16 failed faulty offline\n\n :param disk: disk name.\n :param status: the state of disk.\n :return: by default\n \"\"\"\n error_context.context(\"Set disk '%s' to status '%s'.\"\n % (disk, status), logging.info)\n process.run(\"echo %s > /sys/block/%s/device/state\"\n % (status, disk), shell=True)\n\n def set_multipath_disks_status(disks, status):\n\n \"\"\"\n set multiple paths to same status. all disks online or offline.\n multipath like below:\n mpatha (360050763008084e6e0000000000001a4) dm-3 IBM,2145\n size=100G features='1 queue_if_no_path' hwhandler='1 alua' wp=rw\n |-+- policy='service-time 0' prio=50 status=active\n | `- 1:0:1:0 sdc 8:32 active ready running\n `-+- policy='service-time 0' prio=10 status=enabled\n `- 1:0:0:0 sdb 8:16 failed faulty offline\n\n :param disks: disk list.\n :param status: the state of disk. online/offline\n :return: by default\n \"\"\"\n for disk in disks:\n set_disk_status_to_online_offline(disk, status)\n time.sleep(2)\n if len(disks) == 1:\n wait.wait_for(lambda: compare_onepath_status(status, disks[0]),\n first=wait_time, step=3, timeout=60)\n else:\n wait.wait_for(lambda: compare_multipath_status(status),\n first=wait_time, step=3, timeout=60)\n\n def get_lvm_dm_name(blkdevs_used):\n\n \"\"\"\n Get dm name for lvm. such as rhel_ibm--x3650m4--05-root in below\n NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT\n sda 8:0 0 278.9G 0 disk\n ├─sda1 8:1 0 1G 0 part /boot\n └─sda2 8:2 0 277.9G 0 part\n ├─rhel_ibm--x3650m4--05-root 253:0 0 50G 0 lvm /\n ├─rhel_ibm--x3650m4--05-swap 253:1 0 15.7G 0 lvm [SWAP]\n └─rhel_ibm--x3650m4--05-home 253:2 0 212.2G 0 lvm /home\n # ls /dev/mapper/* -l\n crw-------. 1 root root 10, 236 Oct 25 02:07 /dev/mapper/control\n lrwxrwxrwx. 1 root root 7 Oct 25 09:26 /dev/mapper/mpatha -> ../dm-3\n lrwxrwxrwx. 1 root root 7 Oct 25 09:26 /dev/mapper/mpatha1 -> ../dm-5\n lrwxrwxrwx. 1 root root 7 Oct 25 09:26 /dev/mapper/mpatha2 -> ../dm-6\n lrwxrwxrwx. 1 root root 7 Oct 25 06:49 /dev/mapper/mpathb -> ../dm-4\n lrwxrwxrwx. 1 root root 7 Oct 25 09:17 /dev/mapper/rhel_bootp--73--199--5-home -> ../dm-8\n lrwxrwxrwx. 1 root root 7 Oct 25 09:17 /dev/mapper/rhel_bootp--73--199--5-root -> ../dm-9\n lrwxrwxrwx. 1 root root 7 Oct 25 09:17 /dev/mapper/rhel_bootp--73--199--5-swap -> ../dm-7\n lrwxrwxrwx. 1 root root 7 Oct 25 02:07 /dev/mapper/rhel_ibm--x3650m4--05-home -> ../dm-2\n lrwxrwxrwx. 1 root root 7 Oct 25 02:07 /dev/mapper/rhel_ibm--x3650m4--05-root -> ../dm-0\n lrwxrwxrwx. 1 root root 7 Oct 25 02:07 /dev/mapper/rhel_ibm--x3650m4--05-swap -> ../dm-1\n -rw-r--r--. 1 root root 0 Oct 25 07:52 /dev/mapper/vg_raid10-lv_home\n # dmsetup info -c -o name,blkdevs_used\n Name BlkDevNamesUsed\n rhel_bootp--73--199--5-home dm-6\n mpathb sdd,sde\n mpatha sdb,sdc\n mpatha2 dm-3\n rhel_bootp--73--199--5-swap dm-6\n rhel_bootp--73--199--5-root dm-6\n mpatha1 dm-3\n rhel_ibm--x3650m4--05-home sda2\n rhel_ibm--x3650m4--05-swap sda2\n rhel_ibm--x3650m4--05-root sda2\n\n :param blkdevs_used: block name, e.g. sda2\n :return: a list contains all dm name for one blkdev\n \"\"\"\n dm_list = []\n logging.info(\"Get dm name for '%s'\" % blkdevs_used)\n output = process.run(\"ls /dev/mapper/* -l\",\n shell=True).stdout.decode()\n for line in output.splitlines():\n if blkdevs_used in line:\n dm_name = line.split(\"/\")[-1]\n break\n output = process.run(\"dmsetup info -c -o name,blkdevs_used\",\n shell=True).stdout.decode()\n for line in output.splitlines():\n if dm_name == line.split()[-1]:\n dm_list.append(line.split()[0])\n return dm_list\n\n def delete_lvm_on_multipath(mpath_name=\"mpatha\"):\n \"\"\"\n Delete lvm on the given multipath.\n\n :param mpath_name: multi-path name.\n :return: by default.\n \"\"\"\n output = process.run(\"pvscan\", shell=True).stdout.decode()\n pv_list = []\n vg_list = []\n lv_list = []\n for line in output.splitlines():\n if mpath_name in line:\n if line.split()[1] not in pv_list:\n pv_list.append(line.split()[1])\n if line.split()[3] not in vg_list:\n vg_list.append(line.split()[3])\n output = process.run(\"lvscan\", shell=True).stdout.decode()\n for line in output.splitlines():\n for vg in vg_list:\n lv = \"/dev/%s/\" % vg\n if lv in line and line.split(\"'\")[1] not in lv_list:\n lv_list.append(line.split(\"'\")[1])\n logging.info(\"pv list: %s\" % pv_list)\n logging.info(\"vg list: %s\" % vg_list)\n logging.info(\"lv list: %s\" % lv_list)\n for lv in lv_list:\n logging.info(\"Remove lvm '%s'.\" % lv)\n process.run(\"lvremove -y %s\" % lv, ignore_status=True, shell=True)\n for vg in vg_list:\n logging.info(\"Remove vg '%s'.\" % vg)\n process.run(\"vgremove -y %s\" % vg, ignore_status=True, shell=True)\n for pv in pv_list:\n pv_name = pv.split(\"/\")[-1]\n for dm in get_lvm_dm_name(pv_name):\n process.run(\"dmsetup remove %s\" % dm,\n ignore_status=True, shell=True)\n logging.info(\"Remove pv '%s'.\" % pv)\n process.run(\"pvremove -y %s\" % pv, ignore_status=True, shell=True)\n\n def delete_partition_on_host(did):\n \"\"\"\n Delete partitions on the given disk.\n\n :param did: disk ID. disk kname. e.g. 'sdb', 'nvme0n1'\n :return: by default.\n \"\"\"\n # process.run(\"partprobe /dev/%s\" % did, shell=True)\n list_disk_cmd = \"lsblk -o KNAME,MOUNTPOINT\"\n output = process.run(list_disk_cmd, shell=True).stdout.decode()\n regex_str = did + \"\\w*(\\d+)\"\n rm_cmd = 'parted -s \"/dev/%s\" rm %s'\n for line in output.splitlines():\n partition = re.findall(regex_str, line, re.I | re.M)\n if partition:\n if \"/\" in line.split()[-1]:\n process.run(\"umount %s\" % line.split()[-1], shell=True)\n list_partition_number = \"parted -s /dev/%s print|awk '/^ / {print $1}'\"\n partition_numbers = process.run(list_partition_number % did,\n ignore_status=True,\n shell=True).stdout.decode()\n ignore_err_msg = \"unrecognised disk label\"\n if ignore_err_msg in partition_numbers:\n logging.info(\"no partition to delete on %s\" % did)\n else:\n partition_numbers = partition_numbers.splitlines()\n for number in partition_numbers:\n logging.info(\"remove partition %s on %s\" % (number, did))\n process.run(rm_cmd % (did, number),\n ignore_status=True, shell=True)\n process.run(\"partprobe /dev/%s\" % did, shell=True)\n\n def delete_multipath_partition_on_host(mpath_name=\"mpatha\"):\n \"\"\"\n Delete partitions on the given multipath.\n\n :param mpath_name: multi-path name.\n :return: by default.\n \"\"\"\n # process.run(\"partprobe /dev/mapper/%s\" % mpath_name, shell=True)\n output = process.run(\"lsblk\", shell=True).stdout.decode()\n mpath_dict = {}\n pattern = r'%s(\\d+)' % mpath_name\n rm_cmd = 'parted -s \"/dev/mapper/%s\" rm %s'\n for line in output.splitlines():\n for part_num in re.findall(pattern, line, re.I | re.M):\n if part_num not in mpath_dict.keys():\n mpath_dict[part_num] = line.split()[-1]\n for key, value in mpath_dict.items():\n if \"/\" in value:\n process.run(\"umount %s\" % value, shell=True)\n logging.info(\"remove partition %s on %s\" % (key, mpath_name))\n process.run(rm_cmd % (mpath_name, key),\n ignore_status=True, shell=True)\n output = process.run(\"dmsetup ls\", shell=True).stdout.decode()\n for line in output.splitlines():\n for key in mpath_dict.keys():\n if (mpath_name + key) in line:\n process.run(\"dmsetup remove %s%s\" % (mpath_name, key),\n ignore_status=True,\n shell=True)\n process.run(\"partprobe /dev/mapper/%s\" % mpath_name, shell=True)\n\n def clean_partition_on_host(mpath_name=\"mpatha\"):\n \"\"\"\n Delete partitions on multi-path disks.\n\n :param mpath_name: multi-path name.\n :return: by default\n \"\"\"\n delete_multipath_partition_on_host(mpath_name)\n disks = get_multipath_disks(mpath_name)\n for disk in disks:\n delete_partition_on_host(disk)\n\n def _run_fio_background(session,filename):\n \"\"\"run fio testing by thread\"\"\"\n\n logging.info(\"Start fio in background.\")\n cmd=fio_multipath.cfg.fio_path + params['fio_options'] % filename\n logging.info(cmd)\n session.cmdline(cmd)\n # args = (params['fio_options'] % filename, 3600)\n # fio_thread = utils_misc.InterruptedThread(fio_multipath.run, args)\n # fio_thread.start()\n # if not utils_misc.wait_for(lambda: fio_thread.is_alive, 60):\n # test.fail(\"Failed to start fio thread.\")\n # return fio_thread\n # def _run_fio_background(filename):\n # \"\"\"run fio testing by thread\"\"\"\n #\n # logging.info(\"Start fio in background.\")\n # args = (params['fio_options'] % filename, 3600)\n # fio_thread = utils_misc.InterruptedThread(fio_multipath.run, args)\n # fio_thread.start()\n # if not utils_misc.wait_for(lambda: fio_thread.is_alive, 60):\n # test.fail(\"Failed to start fio thread.\")\n # return fio_thread\n\n def _get_windows_disks_index(session, image_size):\n \"\"\"\n Get all disks index which show in 'diskpart list disk'.\n except for system disk.\n in diskpart: if disk size < 8GB: it displays as MB\n else: it displays as GB\n\n :param session: session object to guest.\n :param image_size: image size. e.g. 40M\n :return: a list with all disks index except for system disk.\n \"\"\"\n disk = \"disk_\" + ''.join(random.sample(string.ascii_letters + string.digits, 4))\n disk_indexs = []\n list_disk_cmd = \"echo list disk > \" + disk\n list_disk_cmd += \" && echo exit >> \" + disk\n list_disk_cmd += \" && diskpart /s \" + disk\n list_disk_cmd += \" && del /f \" + disk\n disks = session.cmd_output(list_disk_cmd)\n size_type = image_size[-1] + \"B\"\n if size_type == \"MB\":\n disk_size = image_size[:-1] + \" MB\"\n elif size_type == \"GB\" and int(image_size[:-1]) < 8:\n disk_size = str(int(image_size[:-1]) * 1024) + \" MB\"\n else:\n disk_size = image_size[:-1] + \" GB\"\n regex_str = 'Disk (\\d+).*?%s' % disk_size\n for disk in disks.splitlines():\n if disk.startswith(\" Disk\"):\n o = re.findall(regex_str, disk, re.I | re.M)\n if o:\n disk_indexs.append(o[0])\n return disk_indexs\n\n def resume_vm_plus(vm, timeout=120):\n \"\"\"resume vm when it is paused.\n\n :param vm: VM object.\n :param timeout: re-try times, if it is still paused after resume\n :return: True or None.\n If resume successfully return True or return None\n \"\"\"\n logging.info(\"Try to resume vm within %s seconds.\" % timeout)\n try:\n vm_status = vm.resume(timeout=timeout)\n except Exception as e:\n logging.error(\"Failed to resume vm: %s\" % six.text_type(e))\n return vm_status\n\n def resume_vm(vm, n_repeat=2):\n \"\"\"resume vm when it is paused.\n\n :param vm: VM object.\n :param n_repeat: re-try times, if it is still paused after resume\n :return: True or False.\n If resume successfully return True or return False\n \"\"\"\n for i in range(1, n_repeat + 1):\n logging.info(\"Try to resume vm %s time(s)\" % i)\n try:\n vm.resume()\n time.sleep(wait_time * 15)\n except Exception as e:\n logging.error(\"Failed to resume vm: %s\" % six.text_type(e))\n finally:\n if check_vm_status(vm, \"running\"):\n return True\n if vm.is_paused() and i == 3:\n return False\n\n error_context.context(\"Get FC host name:\", logging.info)\n hostname = process.run(\"hostname\", shell=True).stdout.decode().strip()\n if hostname != params[\"special_host\"]:\n test.cancel(\"The special host is not '%s', cancel the test.\"\n % params[\"special_host\"])\n error_context.context(\"Get FC disk serial name:\", logging.info)\n outputs = process.run(\"multipath -ll\", shell=True).stdout.decode().splitlines()\n stg_serial_name = params[\"stg_serial_name\"]\n image_name_stg = params[\"image_name_stg\"]\n mpath_name = image_name_stg.split(\"/\")[-1]\n for output in outputs:\n if stg_serial_name in output and mpath_name in output:\n break\n else:\n test.cancel(\"The special disk is not '%s', cancel the test.\"\n % stg_serial_name)\n wait_time = float(params.get(\"sub_test_wait_time\", 0))\n repeat_times = int(params.get(\"repeat_times\", 2))\n multi_disks = get_multipath_disks(mpath_name)\n error_context.context(\"Get all disks for '%s': %s\"\n % (mpath_name, multi_disks), logging.info)\n error_context.context(\"Verify all paths are running for %s before\"\n \"start vm.\" % mpath_name, logging.info)\n if compare_multipath_status(\"running\", mpath_name):\n logging.info(\"All paths are running for %s.\" % mpath_name)\n else:\n logging.info(\"Not all paths are running for %s, set \"\n \"them to running.\" % mpath_name)\n set_multipath_disks_status(multi_disks, \"running\")\n error_context.context(\"Delete lvm on multipath disks on host \"\n \"before testing.\", logging.info)\n delete_lvm_on_multipath(mpath_name)\n error_context.context(\"Delete partitions on host before testing.\",\n logging.info)\n clean_partition_on_host(mpath_name)\n vm = env.get_vm(params[\"main_vm\"])\n try:\n if params.get(\"need_install\") == \"yes\":\n error_context.context(\"Install guest on passthrough disk:\",\n logging.info)\n args = (test, params, env)\n bg = utils_misc.InterruptedThread(utils_test.run_virt_sub_test, args,\n {\"sub_type\": \"unattended_install\"})\n bg.start()\n utils_misc.wait_for(bg.is_alive, timeout=10)\n time.sleep(random.uniform(60, 180))\n else:\n vm.create(params=params)\n session = vm.wait_for_login(timeout=int(params.get(\"timeout\", 240)))\n fio_multipath = generate_instance(params, vm, 'fio')\n image_size_stg = params[\"image_size_stg\"]\n image_num_stg = int(params[\"image_num_stg\"])\n os_type = params[\"os_type\"]\n except Exception as e:\n test.error(\"failed to create VM: %s\" % six.text_type(e))\n try:\n error_context.context(\"Make sure guest is running before test\",\n logging.info)\n if vm.is_paused():\n vm.resume()\n vm.verify_status(\"running\")\n if \"fio_multipath\" in locals().keys():\n if os_type == \"windows\":\n error_context.context(\"Get windows disk index that to \"\n \"be formatted\", logging.info)\n disks = _get_windows_disks_index(session, image_size_stg)\n if len(disks) != image_num_stg:\n test.fail(\"Failed to list all disks by image size. The expected \"\n \"is %s, actual is %s\" % (image_num_stg, len(disks)))\n error_context.context(\"Clear readonly for all disks and online \"\n \"them in windows guest.\", logging.info)\n if not utils_disk.update_windows_disk_attributes(session, disks):\n test.fail(\"Failed to update windows disk attributes.\")\n else:\n error_context.context(\"Get linux disk that to be \"\n \"formatted\", logging.info)\n disks = sorted(utils_disk.get_linux_disks(session).keys())\n if len(disks) != image_num_stg:\n test.fail(\"Failed to list all disks by image size. The expected \"\n \"is %s, actual is %s\" % (image_num_stg, len(disks)))\n file_system = [_.strip() for _ in params[\"file_system\"].split()]\n labeltype = params.get(\"labeltype\", \"gpt\")\n for n, disk in enumerate(disks):\n error_context.context(\"Format disk in guest: '%s'\" % disk,\n logging.info)\n # Random select one file system from file_system\n index = random.randint(0, (len(file_system) - 1))\n fstype = file_system[index].strip()\n partitions = utils_disk.configure_empty_disk(\n session, disk, image_size_stg, os_type,\n fstype=fstype, labeltype=labeltype)\n if not partitions:\n test.fail(\"Fail to format disks.\")\n fio_file_name = params[\"fio_file_name\"] % partitions[0]\n # fio_thread = _run_fio_background(fio_file_name)\n _run_fio_background(session,fio_file_name)\n # disk = random.sample(multi_disks, 1)\n for disk in multi_disks:\n error_context.context(\"Disable disk %s during guest running\"\n % disk, logging.info)\n set_multipath_disks_status([disk], \"offline\")\n time.sleep(wait_time * 15)\n if vm.is_paused():\n logging.info(\"vm is paused, will resume it.\")\n if not resume_vm(vm, repeat_times):\n test.fail(\"Failed to resume guest after disable one disk\")\n logging.info(\"Has resumed vm already. Then verify it running.\")\n if not utils_misc.wait_for(\n lambda: check_vm_status(vm, \"running\"), 60):\n test.fail(\"Guest is not running after disable one disk\")\n error_context.context(\"Enable disk %s during guest running\"\n % disk, logging.info)\n set_multipath_disks_status([disk], \"running\")\n time.sleep(wait_time * 15)\n error_context.context(\"Disable multipath '%s' during guest \"\n \"running.\" % mpath_name, logging.info)\n set_multipath_disks_status(multi_disks, \"offline\")\n time.sleep(wait_time * 15)\n error_context.context(\"Check if VM status is 'paused'\", logging.info)\n if not utils_misc.wait_for(lambda: check_vm_status(vm, \"paused\"), 120):\n test.fail(\"Guest is not paused after all disks offline\")\n error_context.context(\"Re-connect fc storage, wait until the \"\n \"storage is accessible again\", logging.info)\n set_multipath_disks_status(multi_disks, \"running\")\n time.sleep(wait_time * 15)\n error_context.context(\"vm is paused, resume it.\", logging.info)\n if not resume_vm(vm, repeat_times):\n test.fail(\"Failed to resume guest after enable multipath.\")\n logging.info(\"Has resumed vm already. Then verify it running.\")\n time.sleep(wait_time * 15)\n error_context.context(\"Check if VM status is 'running'\", logging.info)\n if not utils_misc.wait_for(lambda: check_vm_status(vm, \"running\"), 120):\n test.fail(\"Guest is not running after all disks online\")\n if \"bg\" in locals().keys() and bg.is_alive and not vm.is_paused():\n bg.join()\n # wq comment ,why need wait fio\n # if \"fio_thread\" in locals().keys() and fio_thread.is_alive \\\n # and not vm.is_paused():\n # fio_thread.join()\n error_context.context(\"Verify Host and guest kernel no error \"\n \"and call trace\", logging.info)\n vm.verify_kernel_crash()\n # except Exception as e:\n # logging.error(e)\n finally:\n logging.info(\"Finally, clean environment.\")\n # set_multipath_disks_status(multi_disks, \"running\")\n # error_context.context(\"Test end\")\n # wq comment do not need clean action\n # if \"session\" in locals().keys() and session:\n # session.close()\n # if \"fio_multipath\" in locals().keys() and fio_multipath \\\n # and not vm.is_paused():\n # fio_multipath.clean()\n # if vm.is_alive():\n # vm.destroy(gracefully=True)\n","sub_path":"internal_patch_fc/multipath_offline_running.py","file_name":"multipath_offline_running.py","file_ext":"py","file_size_in_byte":29570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"188182715","text":"\"\"\"\n.. module:: iec_model\n :synopsis: A useful module indeed.\n\"\"\"\n\nimport json\nimport os\nimport requests\n\nfrom pram_app.REST import rest_funcs\n\n# Set HTTP header\nhttp_headers = rest_funcs.setHTTPHeaders()\nurl_part1 = os.environ['UBERTOOL_REST_SERVER']\n\nclass iec(object):\n def __init__(self, set_variables=True,run_methods=True,run_type='single',dose_response=1,lc50=1,threshold=1,vars_dict=None):\n self.set_default_variables()\n self.jid = rest_funcs.gen_jid()\n if set_variables:\n if vars_dict is not None:\n self.__dict__.update(vars_dict)\n else:\n self.set_variables(run_type,dose_response,lc50,threshold)\n\n def __str__(self):\n string_rep = ''\n string_rep = string_rep + \"dose_response = {0:.2e}\".format(self.dose_response)\n string_rep = string_rep + \"lc50 = {0:.2e}\".format(self.lc50)\n string_rep = string_rep + \"threshold = {0:.2e}\".format(self.threshold)\n return string_rep\n\n\n def set_default_variables(self):\n self.run_type = \"single\"\n self.dose_response = 1\n self.lc50 = 1\n self.threshold = 1\n #\n #\"_out\" need to be added to ea. fun. as expection catching\n #\n\n def set_variables(self, run_type, dose_response, lc50, threshold):\n self.run_type = run_type\n self.dose_response = dose_response\n self.lc50 = lc50\n self.threshold = threshold\n\n all_dic = {\"dose_response\":self.dose_response, \"lc50\":self.lc50, \"threshold\":self.threshold}\n data = json.dumps(all_dic)\n\n self.jid = rest_funcs.gen_jid()\n url=url_part1 + '/iec/' + self.jid \n response = requests.post(url=url, data=data, headers=http_headers, timeout=60)\n output_val = json.loads(response.content)['result']\n for key, value in output_val.items():\n setattr(self, key, value)\n\n def set_unit_testing_variables(self):\n z_score_f_out_expected = None\n F8_f_out_expected = None\n chance_f_out_expected = None\n\n\n","sub_path":"models/iec/iec_model.py","file_name":"iec_model.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"99900317","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.http import JsonResponse, HttpResponseBadRequest\nfrom django.utils import timezone\n\nfrom main.models import Template, Stage, Case, Doc\nfrom main.utils import get_or_create_case\n\n\n# 查询案件阶段信息, 以树形结构输出\ndef tree(request):\n tree = Stage.objects.list_tree()\n return JsonResponse({\n 'status': 'ok',\n 'data': tree\n })\n\n\n# 输出案件阶段的 select 选项\ndef options(request):\n stages = Stage.objects.order_by('index').all().values('id', 'index', 'name')\n return JsonResponse({\n 'status': 'ok',\n 'data': list(stages)\n })\n\n\n# 查询案件阶段信息, 以级联选择框输出\ndef cascader(request):\n cascader = Stage.objects.list_cascader()\n return JsonResponse({'data': cascader})\n\n\n# 查询指定案件阶段下包含的模板列表\ndef templates(request, pk):\n stage = Stage.objects.filter(pk=pk).first()\n if not stage:\n return HttpResponseBadRequest('案件阶段不存在')\n\n template_objs = stage.template_set.exclude(status='deleted').all() \\\n .values('uid', 'pk', 'name', 'status', 'last_modified', 'version')\n\n tpls = [{\n 'uid': x['uid'],\n 'id': x['pk'],\n 'name': x['name'],\n 'status': x['status'],\n 'last_modified': timezone.localdate(x['last_modified']),\n 'version': x['version'],\n } for x in template_objs]\n\n return JsonResponse({'data': tpls})\n","sub_path":"backend/main/api/stages.py","file_name":"stages.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"277153134","text":"from django.contrib.auth.models import Permission\n\n\ndef get_permissions_from_ns_codenames(ns_codenames):\n '''\n Returns a list of Permission objects for the specified namespaced codenames\n '''\n splitnames = [ns_codename.split('.') for ns_codename in ns_codenames]\n return [\n Permission.objects.get(codename=codename,\n content_type__app_label=app_label)\n for app_label, codename in splitnames\n ]\n","sub_path":"hourglass/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"454402502","text":"import numpy as np\n\n#Algortim 2 for BAD\n\ndef azby_inverse(y):\n if len(y)%2==0:\n a=np.hstack((y[::2],y[::-2]))\n else:\n a=np.hstack((y[::2],y[len(y)-2::-2]))\n return a \n\ndef reverse(k):\n return np.arange(len(k))[::-1]+1\n\ndef inversion_number(k):\n return np.dot(k,reverse(k))-(np.sum(k)*(np.sum(k)+1))//2\n\ndef evenflipped(y):\n return y^np.arange(len(y))%2\n\ndef weight(y,k=0):\n a=evenflipped(y)\n return np.sum(a)\n\ndef remainder(a,n,m,y,k=0):\n return (a-inversion_number(azby_inverse(y)))%m\n\n\ndef flipped(b):\n if b==0:\n return 1\n elif b==1:\n return 0\n\ndef position1(y,r,k=0):\n arr=np.array(evenflipped(y))\n pos=np.count_nonzero(arr==1)\n if pos==r:\n return len(arr)\n for i in np.arange(len(arr))[::-1]:\n pos-=arr[i]\n if pos==r:\n return i\n\ndef position2(y,r,k=0):\n arr=np.array(evenflipped(y))\n pos=np.count_nonzero(arr==0)\n const=r-weight(y)-1\n if pos==const:\n return 0\n for i in np.arange(len(arr))+1:\n pos-=flipped(arr[i-1])\n if pos==const:\n return i\n\ndef deleted_seq1(p):\n if p%2==0:\n return [0,1]\n else:\n return [1,0]\n\ndef deleted_seq2(p):\n if p%2==0:\n return [1,0]\n else:\n return [0,1]\n\ndef I(y,p,b):\n return np.insert(y,p,b)\n\ndef dec_BAD(a,n,m,y,k=0):\n r=remainder(a,n,m,y)\n w=weight(y)\n if r<=w:\n p=position1(y,r)\n if p==None:\n return'failure'\n b=deleted_seq1(p)\n else: \n p=position2(y,r)\n if p==None:\n return 'failure'\n b=deleted_seq2(p)\n return I(y,p,b)\n\n#Algorithm for BAS\n\ndef position(r,n,m,y,k=0):\n return len(y)-min([r,m-r])\n\ndef Substituted(p,y):\n return np.insert(np.zeros(len(y)-2,dtype=\"int32\"),p-1,[1,1])^y\n\ndef dec_BAS(a,n,m,y,k=0):\n r=remainder(a,n,m,y)\n if (np.all(y==np.ones(len(y))))|(np.all(y==np.zeros(len(y)))):\n return 'failure'\n elif r==0:\n return np.array(y)\n else:\n p= position(r,n,m,y)\n if p==None:\n return 'failure'\n else:\n return Substituted(p,y)\n \n#Algorithm 2\ndef dec_alg2(a,n,m,y,k=0):\n if len(y)==n:\n return dec_BAS(a,n,m,y,k)\n elif len(y)==n-2:\n return dec_BAD(a,n,m,y,k)\n else:\n return 'failure'\n","sub_path":"Implementation_Algprithm2/Algorithm2.py","file_name":"Algorithm2.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"64299075","text":"from datetime import datetime\nfrom threading import Thread\n\nlogInitialized, logFile = None, None\n\ndef initLog(fileName=\"log.txt\"):\n global logInitialized, logFile\n logFile = open(fileName, \"w\")\n logInitialized = True\n\n\n#Print to log\ndef log(*printObj, pref=\">\"):\n def printToLog():\n if logInitialized:\n timeNow = \"[{hh}:{mm}:{ss}]\".format(\n hh=datetime.now().hour,\n mm=datetime.now().minute,\n ss=datetime.now().second\n )\n print(timeNow, pref, *printObj, sep=\" \", file=logFile)\n else:\n print(\"Log isn't initialized. Use initLog(fileName=\\\"log.txt\\\") to initialize log.\")\n\n thread = Thread(target=printToLog)\n thread.start()","sub_path":"GluckLog.py","file_name":"GluckLog.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"544311553","text":"import torch.utils.model_zoo as modelzoo\r\nfrom matplotlib import pyplot as plt\r\nfrom torchvision import transforms\r\nimport torch.nn.functional as F\r\nfrom torchvision import models\r\nfrom zipfile import ZipFile\r\nfrom pathlib import Path\r\nfrom PIL import Image\r\nfrom torch import nn\r\n\r\nimport typing as tp\r\nimport shutil\r\nimport random\r\nimport torch\r\nimport json\r\nimport os\r\n\r\n\r\ndef fit(batches, preprocessor, model, optimizer, loss_fn, epochs,\r\n ckpt_path:tp.Optional[str]=None, ckpt_per_iter:tp.Optional[int]=None,\r\n verbose_per_iter:tp.Optional[int]=None, history_path:tp.Optional[str]=None,\r\n meta_path: tp.Optional[str]=None):\r\n\r\n n_batches = len(batches)\r\n\r\n # GPU is preferred\r\n device = get_device()\r\n\r\n # Load model from checkpoint\r\n if is_loadable(ckpt_path):\r\n print(\"~ ~ ~ ~ ~ ~ ~ ~ ~ ~\")\r\n print(\"Checkpoint was found\")\r\n print(\"~ ~ ~ ~ ~ ~ ~ ~ ~ ~\")\r\n print()\r\n checkpoint = load_checkpoint(ckpt_path, device)\r\n model.load_state_dict(checkpoint['model'])\r\n optimizer.load_state_dict(checkpoint['optimizer'])\r\n loss_fn.load_state_dict(checkpoint['loss_fn'])\r\n\r\n # Load history\r\n if is_loadable(history_path):\r\n history = load_json(history_path)\r\n elif history_path is None:\r\n history = create_history()\r\n history_path = \"history.json\"\r\n else:\r\n history = create_history()\r\n\r\n # Load meta\r\n if is_loadable(meta_path):\r\n meta = load_json(meta_path)\r\n elif history_path is None:\r\n meta = create_meta()\r\n meta_path = \"meta.json\"\r\n else:\r\n meta = create_meta()\r\n\r\n # Read parameters\r\n start_epoch = meta[\"epoch\"]\r\n start_batch = meta[\"batch\"]\r\n\r\n # Switch to device\r\n model.to(device)\r\n optimizer_to(optimizer, device)\r\n\r\n for epoch in range(start_epoch, epochs):\r\n\r\n local_loss = []\r\n local_miou = []\r\n local_mpa = []\r\n\r\n for i in range(start_batch, len(batches)):\r\n \r\n batch = batches[i]\r\n\r\n # Data\r\n torch.cuda.empty_cache()\r\n model.train()\r\n loaded = Loader(batch)\r\n x, y = preprocessor(loaded[:])\r\n x = x.to(device).float()\r\n y = y.to(device).float()\r\n\r\n # Step\r\n pred = model(x)\r\n loss = loss_fn(pred, y)\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # Metrics\r\n miou = get_mean_iou(pred, y)\r\n mpa = get_mean_pixel_acc(pred, y)\r\n\r\n # Add to local buffer\r\n local_loss.append(loss.item())\r\n local_miou.append(miou)\r\n local_mpa.append(mpa)\r\n\r\n # Save to dict\r\n history['Loss'].append(loss.item())\r\n history['PixelAccuracy'].append(mpa)\r\n history['mIOU'].append(miou)\r\n\r\n # change meta batch\r\n meta[\"batch\"] += 1\r\n\r\n # Print state of a training\r\n if verbose_per_iter is not None:\r\n if (i+1) % verbose_per_iter == 0:\r\n show_state(epoch, i, local_loss, local_miou, local_mpa)\r\n local_loss = []\r\n local_miou = []\r\n local_mpa = []\r\n\r\n # Create checkpoint\r\n if (ckpt_path is not None) and (ckpt_per_iter is not None):\r\n if (i+1) % ckpt_per_iter == 0:\r\n save_json(meta_path, meta)\r\n save_json(history_path, history)\r\n create_checkpoint(ckpt_path, model, optimizer, loss_fn)\r\n\r\n # change meta epoch\r\n meta[\"epoch\"] += 1\r\n meta[\"batch\"] = 0\r\n start_batch = 0\r\n\r\nif __name__ == \"__main__\":\r\n\r\n ckpt_path = \"\"\r\n meta_path = \"\"\r\n history_path = \"\"\r\n\r\n resize = (480, 640)\r\n model = DeepLab()\r\n loss_fn = nn.BCEWithLogitsLoss()\r\n preprocessor = Preprocessor(resize)\r\n optimizer = torch.optim.Adam(model.parameters(), lr=0.00005)\r\n\r\n meta = load_json(meta_path)\r\n for i in range(meta[\"epoch\"], 5):\r\n if os.path.exists(\"Ego2Hand\"):\r\n shutil.rmtree(\"Ego2Hand\")\r\n extract_zip(subset_0_4, [8000*i, 8000*(i+1)])\r\n extract_zip(subset_5_10, [8000*i, 8000*(i+1)])\r\n extract_zip(subset_11_16, [8000*i, 8000*(i+1)])\r\n extract_zip(subset_17_21, [8000*i, 8000*(i+1)])\r\n \r\n gtea_paths = GTEAPaths(\"GTEA\")\r\n ego_hand_paths = EgoHandPaths(\"EgoHand\")\r\n ego_2_hand_paths = Ego2HandPaths(\"Ego2Hand\", \"backgrounds\")\r\n paths = AugmentationPaths([*gtea_paths[:], *ego_hand_paths[:], *ego_2_hand_paths[:]])\r\n batches = split_on_batches(paths, 8)\r\n\r\n fit(batches, preprocessor, model, optimizer, loss_fn, (i+1), \r\n ckpt_path, 25, 25, history_path, meta_path)","sub_path":"train/train_deeplab.py","file_name":"train_deeplab.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"570876350","text":"\"\"\" ATSSpider built for candidatecare.jobs. Built on top of existing\nATSSpider base. \n\nscrapy crawl candidatecare-jobs \\\n\t-a mining_job_id=9999 \\\n\t-a iteration=1 \\\n\t-a extract=1 \\\n\t-a url=\"https://amtci.candidatecare.jobs/\"\n\nsample url:\nhttps://alstar.candidatecare.jobs/\nhttps://amtci.candidatecare.jobs/\nhttps://eliteambulance.candidatecare.jobs/\n\"\"\"\nimport urllib\nimport re\n\nfrom urlparse import urljoin, urlparse, parse_qs\nfrom urllib import urlencode\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom scrapy.exceptions import CloseSpider, DropItem\nfrom scrapy.loader.processors import Join, Identity, TakeFirst\n\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.base.atsspiders import ATSSpider\n\nclass CandidatecareJobs(ATSSpider):\n\tname = 'candidatecare_jobs'\n\n\tdef parse(self, response):\n\t\tsel = Selector(response)\n\n\t\tcurrent_openings = sel.xpath(\"//h2/a/@href\").extract()\n\n\t\tif current_openings:\n\t\t\turl = urljoin(response.url, current_openings[0])\n\t\t\tyield Request(url=url, callback=self.parse_listings)\n\t\telse:\n\t\t\traise CloseSpider(\"No job openings!\")\n\n\tdef parse_listings(self, response):\n\t\tsel = Selector(response)\n\n\t\tlinks = sel.xpath(\"//div[contains(@class, 'positions')]/a\")\n\n\t\tfor link in links:\n\t\t\turl = urljoin(response.url, \n\t\t\t\tlink.xpath(\".//@href\").extract()[0])\n\t\t\tyield Request(url=url, callback=self.parse_job_callback())\n\n\tdef parse_job(self, response):\n\t\tsel = Selector(response)\n\n\t\tb_item = BrightcorpItemLoader(selector=sel)\n\t\tb_dict = {}\n\n\t\t# essentials: title, desc, ref #, location\n\t\tb_dict[\"title\"] = b_item.get_xpath(\n\t\t\t\"//b[contains(text(), 'Title')]/../following-sibling::td/text()\",\n\t\t\tTakeFirst(), Join())\n\t\tb_dict[\"location\"] = b_item.get_xpath(\n\t\t\t\"//b[contains(text(), 'Location')]/../following-sibling::td/text()\",\n\t\t\tTakeFirst(), Join())\n\t\t# ref number processing\n\t\tref_number = response.url.split(\"/\")[-1]\n\t\tb_dict[\"referencenumber\"] = \"%s-%s\" % (self.name, ref_number)\n\t\t# desc has multiple variations\n\t\tdesc_paths = [\n\t\t\t\"//strong[contains(text(), 'SUMMARY')]/following-sibling::text()\",\n\t\t\t\"//strong[contains(text(), 'SUMMARY')]/../following-sibling::p[1]//text()\",\n\t\t\t\"//strong[contains(text(), 'SUMMARY')]/../../following-sibling::p/text()\"\n\t\t]\n\t\tb_item.add_xpath('description', desc_paths, TakeFirst())\n\n\t\t# optional fields\n\t\tedu_paths = [\n\t\t\t\"//strong[contains(text(), 'PERFORMANCE REQUIREMENTS')]/../following-sibling::p/text()\",\n\t\t\t\"//strong[contains(text(), 'EDUCATION')]/../../following-sibling::p[1]/text()\",\n\t\t\t\"//strong[contains(text(), 'MINIMUM REQUIREMENTS')]/../following-sibling::ul[1]//text()\",\n\t\t\t\"//strong[contains(text(), 'TRAINING AND EXPERIENCE')]/../../following-sibling::ul//text()\"\n\t\t]\n\t\tb_item.add_xpath('educationrequirements', edu_paths, TakeFirst())\n\n\t\treturn b_item.load_item()\n\n\tdef set_custom_item(self, response):\n\t\tparts = response.url.split(\"/\")[-1]\n\t\tself.loader.add_value(\"referencenumber\", \"%s-%s\" % (self.name, parts))\n","sub_path":"brightcorp/brightcorp/spiders/candidatecare_jobs.py","file_name":"candidatecare_jobs.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"317843460","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn import linear_model\n\n\n# load dataset\n\ndata = pd.read_csv('./test.csv')\nprint(data)\n\n# data.corr() # correlation coefficient\n\ndata.plot(kind='scatter', x = 'Age', y = 'Salary')\ndata.plot(kind='line', x = 'Age', y = 'Salary')\nplt.show()\n\nAge = pd.DataFrame(data['Age'])\nSalary = pd.DataFrame(data['Salary'])\n# print(Age)\n# print(Salary)\n\n\n# build linear regression model\n\nlm = linear_model.LinearRegression()\nmodel = lm.fit(Age, Salary)\n\n# print(model.coef_)\n# print(model.intercept_)\n# print(model.score(Age, Salary)) # evaluate the model\n\n# predict new value of Salary\nage_new = [[30], [35], [22]]\nsalary_prediction = model.predict(age_new)\nprint(salary_prediction)\n","sub_path":"mraasvel/example_lrm.py","file_name":"example_lrm.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"60266876","text":"import matplotlib.pylab as plt\r\nfrom form_file import *\r\nfrom commonLib import *\r\nfrom getPath import *\r\npardir = getparentdir()\r\ninterval = 1\r\n\r\ndistribution_path = pardir+\"/distribution/ideal_distribution.txt\"\r\n\r\ndef read_distribution():\r\n with open(distribution_path,'r') as f:\r\n next(f)\r\n for line in f:\r\n arr = line.split('|')\r\n label = arr[0]\r\n minacc = arr[1].split(';')\r\n minacc = [float(t) for t in minacc]\r\n plt.plot(minacc)\r\n maxacc = arr[2].split(';')\r\n maxacc = [float(t) for t in maxacc]\r\n plt.plot(maxacc)\r\n plt.title(label)\r\n plt.show()\r\n \r\nif __name__==\"__main__\":\r\n read_distribution()\r\n\r\n\r\n","sub_path":"plotinfo.py","file_name":"plotinfo.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"231288794","text":"import os\nfrom fabric.context_managers import shell_env\nfrom fabric.api import put, run, sudo\nfrom fabric.state import env\nfrom fabric.utils import puts\nfrom boto import ec2\n\n# APP_CLUSTER_NAME=logsearch-test1 fab githead\n\nenv.user = 'ubuntu'\n\n# optionally, auto-configure hosts from ec2\n\nif 0 == len(env.hosts):\n env.hosts = []\n\n conn = ec2.connect_to_region(os.environ['AWS_DEFAULT_REGION'])\n\n reservations = conn.get_all_instances(filters = { 'tag:logsearch-cluster' : os.environ['APP_CLUSTER_NAME'] });\n\n for reservation in reservations:\n for instance in reservation.instances:\n env.hosts.append(instance.ip_address)\n\n# tasks\n\ndef pushfile(path):\n put(\n os.path.dirname(__file__) + '/' + path,\n '/app/app/' + path,\n mirror_local_mode=True\n )\n\ndef githead():\n run('cd /app/app/ && git rev-parse HEAD')\n\ndef up2date():\n run('cd /app/app/ && git pull --ff-only')\n\ndef uploadstats(bucket, start, stop, path = \"report-stats/\"):\n with shell_env(AWS_ACCESS_KEY = os.environ['AWS_ACCESS_KEY_ID'], AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']):\n run('cd /app/app ; ./bin/upload-stats \"{0}\" \"{1}\" \"{2}\" \"{3}\"'.format(bucket, path, start, stop))\n\ndef uptime():\n run('uptime')\n\ndef whoami():\n run('whoami')\n","sub_path":"example/fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"326487544","text":"#!/usr/bin/env python3.4\n# This lambda is for ingest\n\nimport sys\nimport json\nimport time\n\nfrom spdb.spatialdb import Cube, SpatialDB, SpdbError\nfrom spdb.project import BossResourceBasic\nfrom spdb.c_lib.ndtype import CUBOIDSIZE\nfrom spdb.c_lib.ndlib import XYZMorton\n\nfrom ndingest.settings.bosssettings import BossSettings\nfrom ndingest.ndingestproj.bossingestproj import BossIngestProj\nfrom ndingest.nddynamo.boss_tileindexdb import BossTileIndexDB\nfrom ndingest.ndqueue.ingestqueue import IngestQueue\nfrom ndingest.ndbucket.tilebucket import TileBucket\nfrom ndingest.util.bossutil import BossUtil\n\nfrom io import BytesIO\nfrom PIL import Image\nimport numpy as np\nimport math\nimport boto3\n\nprint(\"$$$ IN INGEST LAMBDA $$$\")\n# Load settings\nSETTINGS = BossSettings.load()\n\n# Parse input args passed as a JSON string from the lambda loader\njson_event = sys.argv[1]\nevent = json.loads(json_event)\n\n# Load the project info from the chunk key you are processing\nproj_info = BossIngestProj.fromSupercuboidKey(event[\"chunk_key\"])\nproj_info.job_id = event[\"ingest_job\"]\n\n# Handle up to 2 messages before quitting (helps deal with making sure all messages get processed)\nrun_cnt = 0\nwhile run_cnt < 1: # Adjusted count down to 1 as lambda is crashing with full memory when pulling off more than 1.\n # Get message from SQS flush queue, try for ~2 seconds\n rx_cnt = 0\n msg_data = None\n msg_id = None\n msg_rx_handle = None\n while rx_cnt < 6:\n ingest_queue = IngestQueue(proj_info)\n msg = [x for x in ingest_queue.receiveMessage()]\n if msg:\n msg = msg[0]\n print(\"MESSAGE: {}\".format(msg))\n print(len(msg))\n msg_id = msg[0]\n msg_rx_handle = msg[1]\n msg_data = json.loads(msg[2])\n print(\"MESSAGE DATA: {}\".format(msg_data))\n break\n else:\n rx_cnt += 1\n print(\"No message found. Try {} of 6\".format(rx_cnt))\n time.sleep(1)\n\n if not msg_id:\n # Nothing to flush. Exit.\n sys.exit(\"No ingest message available\")\n\n # Get the write-cuboid key to flush\n chunk_key = msg_data['chunk_key']\n print(\"Ingesting Chunk {}\".format(chunk_key))\n\n # Setup SPDB instance\n sp = SpatialDB(msg_data['parameters'][\"KVIO_SETTINGS\"],\n msg_data['parameters'][\"STATEIO_CONFIG\"],\n msg_data['parameters'][\"OBJECTIO_CONFIG\"])\n\n # Get tile list from Tile Index Table\n tile_index_db = BossTileIndexDB(proj_info.project_name)\n # tile_index_result (dict): keys are S3 object keys of the tiles comprising the chunk.\n tile_index_result = tile_index_db.getCuboid(msg_data[\"chunk_key\"], int(msg_data[\"ingest_job\"]))\n if tile_index_result is None:\n # Remove message so it's not redelivered.\n ingest_queue.deleteMessage(msg_id, msg_rx_handle)\n sys.exit(\"Aborting due to chunk key missing from tile index table\")\n\n # Sort the tile keys\n print(\"Tile Keys: {}\".format(tile_index_result[\"tile_uploaded_map\"]))\n tile_key_list = [x.rsplit(\"&\", 2) for x in tile_index_result[\"tile_uploaded_map\"].keys()]\n tile_key_list = sorted(tile_key_list, key=lambda x: int(x[1]))\n tile_key_list = [\"&\".join(x) for x in tile_key_list]\n print(\"Sorted Tile Keys: {}\".format(tile_key_list))\n\n # Augment Resource JSON data so it will instantiate properly that was pruned due to S3 metadata size limits\n resource_dict = msg_data['parameters']['resource']\n _, exp_name, ch_name = resource_dict[\"boss_key\"].split(\"&\")\n\n resource_dict[\"channel\"][\"name\"] = ch_name\n resource_dict[\"channel\"][\"description\"] = \"\"\n resource_dict[\"channel\"][\"sources\"] = []\n resource_dict[\"channel\"][\"related\"] = []\n resource_dict[\"channel\"][\"default_time_sample\"] = 0\n resource_dict[\"channel\"][\"downsample_status\"] = \"NOT_DOWNSAMPLED\"\n\n resource_dict[\"experiment\"][\"name\"] = exp_name\n resource_dict[\"experiment\"][\"description\"] = \"\"\n resource_dict[\"experiment\"][\"num_time_samples\"] = 1\n resource_dict[\"experiment\"][\"time_step\"] = None\n resource_dict[\"experiment\"][\"time_step_unit\"] = None\n\n resource_dict[\"coord_frame\"][\"name\"] = \"cf\"\n resource_dict[\"coord_frame\"][\"name\"] = \"\"\n resource_dict[\"coord_frame\"][\"x_start\"] = 0\n resource_dict[\"coord_frame\"][\"x_stop\"] = 100000\n resource_dict[\"coord_frame\"][\"y_start\"] = 0\n resource_dict[\"coord_frame\"][\"y_stop\"] = 100000\n resource_dict[\"coord_frame\"][\"z_start\"] = 0\n resource_dict[\"coord_frame\"][\"z_stop\"] = 100000\n resource_dict[\"coord_frame\"][\"voxel_unit\"] = \"nanometers\"\n\n # Setup the resource\n resource = BossResourceBasic()\n resource.from_dict(resource_dict)\n dtype = resource.get_numpy_data_type()\n\n # read all tiles from bucket into a slab\n tile_bucket = TileBucket(proj_info.project_name)\n data = []\n num_z_slices = 0\n for tile_key in tile_key_list:\n try:\n image_data, message_id, receipt_handle, _ = tile_bucket.getObjectByKey(tile_key)\n except KeyError:\n print('Key: {} not found in tile bucket, assuming redelivered SQS message and aborting.'.format(\n tile_key))\n # Remove message so it's not redelivered.\n ingest_queue.deleteMessage(msg_id, msg_rx_handle)\n sys.exit(\"Aborting due to missing tile in bucket\")\n\n tile_img = np.asarray(Image.open(BytesIO(image_data)), dtype=dtype)\n data.append(tile_img)\n num_z_slices += 1\n\n # Make 3D array of image data. It should be in XYZ at this point\n chunk_data = np.array(data)\n del data\n tile_dims = chunk_data.shape\n\n # Break into Cube instances\n print(\"Tile Dims: {}\".format(tile_dims))\n print(\"Num Z Slices: {}\".format(num_z_slices))\n num_x_cuboids = int(math.ceil(tile_dims[2] / CUBOIDSIZE[proj_info.resolution][0]))\n num_y_cuboids = int(math.ceil(tile_dims[1] / CUBOIDSIZE[proj_info.resolution][1]))\n\n print(\"Num X Cuboids: {}\".format(num_x_cuboids))\n print(\"Num Y Cuboids: {}\".format(num_y_cuboids))\n\n # Cuboid List\n cuboids = []\n chunk_key_parts = BossUtil.decode_chunk_key(chunk_key)\n t_index = chunk_key_parts['t_index']\n for x_idx in range(0, num_x_cuboids):\n for y_idx in range(0, num_y_cuboids):\n # TODO: check time series support\n cube = Cube.create_cube(resource, CUBOIDSIZE[proj_info.resolution])\n cube.zeros()\n\n # Compute Morton ID\n # TODO: verify Morton indices correct!\n print(chunk_key_parts)\n morton_x_ind = x_idx + (chunk_key_parts[\"x_index\"] * num_x_cuboids)\n morton_y_ind = y_idx + (chunk_key_parts[\"y_index\"] * num_y_cuboids)\n print(\"Morton X: {}\".format(morton_x_ind))\n print(\"Morton Y: {}\".format(morton_y_ind))\n morton_index = XYZMorton([morton_x_ind, morton_y_ind, int(chunk_key_parts['z_index'])])\n\n # Insert sub-region from chunk_data into cuboid\n x_start = x_idx * CUBOIDSIZE[proj_info.resolution][0]\n x_end = x_start + CUBOIDSIZE[proj_info.resolution][0]\n x_end = min(x_end, tile_dims[2])\n y_start = y_idx * CUBOIDSIZE[proj_info.resolution][1]\n y_end = y_start + CUBOIDSIZE[proj_info.resolution][1]\n y_end = min(y_end, tile_dims[1])\n z_end = CUBOIDSIZE[proj_info.resolution][2]\n # TODO: get sub-array w/o making a copy.\n print(\"Yrange: {}\".format(y_end - y_start))\n print(\"Xrange: {}\".format(x_end - x_start))\n print(\"X start: {}\".format(x_start))\n print(\"X stop: {}\".format(x_end))\n cube.data[0, 0:num_z_slices, 0:(y_end - y_start), 0:(x_end - x_start)] = chunk_data[0:num_z_slices,\n y_start:y_end, x_start:x_end]\n\n # Create object key\n object_key = sp.objectio.generate_object_key(resource, proj_info.resolution, t_index, morton_index)\n print(\"Object Key: {}\".format(object_key))\n\n # Put object in S3\n sp.objectio.put_objects([object_key], [cube.to_blosc()])\n\n # Add object to index\n sp.objectio.add_cuboid_to_index(object_key, ingest_job=int(msg_data[\"ingest_job\"]))\n\n # Update id indices if this is an annotation channel\n if resource.data['channel']['type'] == 'annotation':\n try:\n sp.objectio.update_id_indices(\n resource, proj_info.resolution, [object_key], [cube.data])\n except SpdbError as ex:\n sns_client = boto3.client('sns')\n topic_arn = msg_data['parameters'][\"OBJECTIO_CONFIG\"][\"prod_mailing_list\"]\n msg = 'During ingest:\\n{}\\nCollection: {}\\nExperiment: {}\\n Channel: {}\\n'.format(\n ex.message,\n resource.data['collection']['name'],\n resource.data['experiment']['name'],\n resource.data['channel']['name'])\n sns_client.publish(\n TopicArn=topic_arn,\n Subject='Object services misuse',\n Message=msg)\n\n # Delete message since it was processed successfully\n ingest_queue.deleteMessage(msg_id, msg_rx_handle)\n\n # Delete Tiles\n for tile in tile_key_list:\n for try_cnt in range(0, 4):\n try:\n time.sleep(try_cnt)\n print(\"Deleting tile: {}\".format(tile))\n tile_bucket.deleteObject(tile)\n break\n except:\n print(\"failed\")\n\n # Delete Entry in tile table\n for try_cnt in range(0, 4):\n try:\n time.sleep(try_cnt)\n tile_index_db.deleteCuboid(chunk_key, int(msg_data[\"ingest_job\"]))\n break\n except:\n print(\"failed\")\n\n # Increment run counter\n run_cnt += 1\n","sub_path":"lambda/ingest_lambda.py","file_name":"ingest_lambda.py","file_ext":"py","file_size_in_byte":9971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"412516490","text":"import numpy as np\nimport numpy.linalg as linalg\nimport random\nfrom utils import safe_mkdir, get_fold\nfrom config import Config\n\nconfig = Config()\n\n\nclass FisherClassifier(object):\n\n def __init__(self):\n self.omiga = None\n self.g = None\n self.w = None\n\n def train_step(self, data, label, omiga):\n E3 = data[label == 0] # shape = (n_E3, n_feats)\n E5 = data[label == 1] # shape = (n_E5, n_feats)\n m_E3 = np.mean(E3, axis=0) # shape = (n_feats, )\n m_E5 = np.mean(E5, axis=0) # shape = (n_feats, )\n\n S_E3 = np.matmul(np.expand_dims(E3 - m_E3, 2), np.expand_dims(E3 - m_E3, 1)).sum(axis=0)\n # shape = (n_feats, n_feats)\n S_E5 = np.matmul(np.expand_dims(E5 - m_E5, 2), np.expand_dims(E5 - m_E5, 1)).sum(axis=0)\n # shape = (n_feats, n_feats)\n\n S_w_inv = linalg.inv(S_E3 + S_E5) # shape = (n_feats, n_feats)\n w = np.matmul(S_w_inv, m_E3 - m_E5) # shape = (n_feats, )\n\n self.g = lambda x: (np.dot(w, x) + omiga) < 0\n self.w = w\n\n def train(self, train_data, train_label, low, high, cv):\n\n best_acc = 0\n\n if not cv:\n for omiga in np.linspace(low, high, 500):\n self.train_step(train_data, train_label, omiga)\n n_true, n_all, acc = self.eval(train_data, train_label)\n if acc > best_acc:\n best_acc = acc\n self.omiga = omiga\n self.train_step(train_data, train_label, self.omiga)\n\n return best_acc\n\n else: # Cross Validation.\n n_train = train_data.shape[0]\n ix = list(range(n_train))\n random.shuffle(ix)\n fold_l = int(n_train / 10)\n\n for omiga in np.linspace(low, high, 500):\n\n accs = []\n for fold_ix in range(10):\n if fold_ix != 9:\n cvtrain_data, cvtrain_label, cvtest_data, cvtest_label = \\\n get_fold(train_data, train_label, ix[fold_ix * fold_l: ((fold_ix + 1) * fold_l)])\n else:\n cvtrain_data, cvtrain_label, cvtest_data, cvtest_label = \\\n get_fold(train_data, train_label, ix[fold_ix * fold_l:])\n\n self.train_step(cvtrain_data, cvtrain_label, omiga)\n _, _, acc = self.eval(cvtest_data, cvtest_label)\n accs.append(acc)\n acc = sum(accs) / 10.\n\n if acc > best_acc:\n best_acc = acc\n self.omiga = omiga\n\n # Train with the best omiga.\n self.train_step(train_data, train_label, self.omiga)\n return best_acc\n\n def eval(self, data, label):\n\n preds = np.apply_along_axis(self.g, 1, data)\n n_true = np.sum(preds == label)\n n_all = preds.shape[0]\n acc = n_true / float(n_all)\n\n return n_true, n_all, acc","sub_path":"PR2018-Assignment1/Modules/Fisher.py","file_name":"Fisher.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"205274435","text":"import csv\nfrom bs4 import BeautifulSoup\nimport requests\nimport csv\n\nsource = requests.get('https://www.newegg.ca/GIGABYTE-AMD-Motherboards/BrandSubCat/ID-1314-22')\nsoup = BeautifulSoup(source.text,'html.parser')\n\ncsv_file = open('scraped.csv','w')\ncsv_writer = csv.writer(csv_file)\ncsv_writer.writerow(['Motherboard_Name','Old_Price','New_Price'])\n\nfor title in soup.find_all('div',class_='item-container'):\n\n label = title.find('a',class_='item-title').text\n\n print(label)\n\n try:\n old_price = title.find('li',class_='price-was').span.text\n except:\n old_price = None\n \n print(old_price)\n\n new_price = title.find('li',class_='price-current').text.split('(')[0]\n\n print(new_price)\n\n csv_writer.writerow([label,old_price,new_price])\n\ncsv_file.close()\n\n\n","sub_path":"Web Scraping - Python/scrapnewegg/scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"146809619","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2010 - 2020 Detlev Offenbach \n#\n\n\"\"\"\nModule implementing the CxFreeze plugin.\n\"\"\"\n\nimport os\nimport platform\n\nfrom PyQt5.QtCore import QObject, QTranslator, QCoreApplication, QProcess\nfrom PyQt5.QtWidgets import QDialog\n\nfrom E5Gui import E5MessageBox\nfrom E5Gui.E5Action import E5Action\nfrom E5Gui.E5Application import e5App\n \nimport Utilities\n\n# Start-of-Header\nname = \"CxFreeze Plugin\"\nauthor = \"Detlev Offenbach \"\nautoactivate = True\ndeactivateable = True\nversion = \"7.0.0\"\nclassName = \"CxFreezePlugin\"\npackageName = \"CxFreeze\"\nshortDescription = \"Show the CxFreeze dialogs.\"\nlongDescription = (\n \"\"\"This plugin implements the CxFreeze dialogs.\"\"\"\n \"\"\" CxFreeze is used to generate a distribution package.\"\"\"\n)\nneedsRestart = False\npyqtApi = 2\n# End-of-Header\n\nerror = \"\"\n\nexePy3 = []\n\n\ndef exeDisplayDataList():\n \"\"\"\n Public method to support the display of some executable info.\n \n @return dictionary containing the data to query the presence of\n the executable\n \"\"\"\n dataList = []\n data = {\n \"programEntry\": True,\n \"header\": QCoreApplication.translate(\n \"CxFreezePlugin\", \"Packagers - cx_freeze\"),\n \"exe\": 'dummyfreeze',\n \"versionCommand\": '--version',\n \"versionStartsWith\": 'dummyfreeze',\n \"versionPosition\": -1,\n \"version\": \"\",\n \"versionCleanup\": None,\n }\n \n if _checkProgram():\n for exePath in exePy3:\n data[\"exe\"] = exePath\n data[\"versionStartsWith\"] = \"cxfreeze\"\n dataList.append(data.copy())\n else:\n dataList.append(data)\n return dataList\n\n\ndef _findExecutable(majorVersion):\n \"\"\"\n Restricted function to determine the names of the executable.\n \n @param majorVersion major python version of the executables (int)\n @return names of the executable (list)\n \"\"\"\n # Determine Python Version\n if majorVersion == 3:\n minorVersions = range(10)\n else:\n return []\n \n executables = set()\n if Utilities.isWindowsPlatform():\n #\n # Windows\n #\n try:\n import winreg\n except ImportError:\n import _winreg as winreg # __IGNORE_WARNING__\n \n def getExePath(branch, access, versionStr):\n try:\n software = winreg.OpenKey(branch, 'Software', 0, access)\n python = winreg.OpenKey(software, 'Python', 0, access)\n pcore = winreg.OpenKey(python, 'PythonCore', 0, access)\n version = winreg.OpenKey(pcore, versionStr, 0, access)\n installpath = winreg.QueryValue(version, 'InstallPath')\n exe = os.path.join(installpath, 'Scripts', 'cxfreeze.bat')\n if os.access(exe, os.X_OK):\n return exe\n except WindowsError: # __IGNORE_WARNING__\n return None\n return None\n \n versionSuffixes = [\"\", \"-32\", \"-64\"]\n for minorVersion in minorVersions:\n for versionSuffix in versionSuffixes:\n versionStr = '{0}.{1}{2}'.format(majorVersion, minorVersion,\n versionSuffix)\n exePath = getExePath(\n winreg.HKEY_CURRENT_USER,\n winreg.KEY_WOW64_32KEY | winreg.KEY_READ, versionStr)\n if exePath is not None:\n executables.add(exePath)\n \n exePath = getExePath(\n winreg.HKEY_LOCAL_MACHINE,\n winreg.KEY_WOW64_32KEY | winreg.KEY_READ, versionStr)\n if exePath is not None:\n executables.add(exePath)\n \n # Even on Intel 64-bit machines it's 'AMD64'\n if platform.machine() == 'AMD64':\n exePath = getExePath(\n winreg.HKEY_CURRENT_USER,\n winreg.KEY_WOW64_64KEY | winreg.KEY_READ, versionStr)\n if exePath is not None:\n executables.add(exePath)\n \n exePath = getExePath(\n winreg.HKEY_LOCAL_MACHINE,\n winreg.KEY_WOW64_64KEY | winreg.KEY_READ, versionStr)\n if exePath is not None:\n executables.add(exePath)\n \n if not executables and majorVersion >= 3:\n # check the PATH environment variable if nothing was found\n # Python 3 only\n path = Utilities.getEnvironmentEntry('PATH')\n if path:\n dirs = path.split(os.pathsep)\n for directory in dirs:\n for suffix in (\".bat\", \".exe\"):\n exe = os.path.join(directory, \"cxfreeze\" + suffix)\n if os.access(exe, os.X_OK):\n executables.add(exe)\n else:\n #\n # Linux, Unix ...\n cxfreezeScript = 'cxfreeze'\n scriptSuffixes = [\"\", \"-python{0}\".format(majorVersion)]\n for minorVersion in minorVersions:\n scriptSuffixes.append(\n \"-python{0}.{1}\".format(majorVersion, minorVersion))\n # There could be multiple cxfreeze executables in the path\n # e.g. for different python variants\n path = Utilities.getEnvironmentEntry('PATH')\n # environment variable not defined\n if path is None:\n return []\n \n # step 1: determine possible candidates\n exes = []\n dirs = path.split(os.pathsep)\n for directory in dirs:\n for suffix in scriptSuffixes:\n exe = os.path.join(directory, cxfreezeScript + suffix)\n if os.access(exe, os.X_OK):\n exes.append(exe)\n \n # step 2: determine the Python variant\n _exePy3 = set()\n versionArgs = [\"-c\", \"import sys; print(sys.version_info[0])\"]\n for exe in exes:\n try:\n f = open(exe, \"r\")\n line0 = f.readline()\n program = line0.replace(\"#!\", \"\").strip()\n process = QProcess()\n process.start(program, versionArgs)\n process.waitForFinished(5000)\n # get a QByteArray of the output\n versionBytes = process.readAllStandardOutput()\n versionStr = str(versionBytes, encoding='utf-8').strip()\n if versionStr == \"3\":\n _exePy3.add(exe)\n finally:\n f.close()\n \n executables = _exePy3\n \n # sort items, the probably newest topmost\n executables = list(executables)\n executables.sort(reverse=True)\n return executables\n\n\ndef _checkProgram():\n \"\"\"\n Restricted function to check the availability of cxfreeze.\n \n @return flag indicating availability (boolean)\n \"\"\"\n global error, exePy3\n \n exePy3 = _findExecutable(3)\n if exePy3 == []:\n if Utilities.isWindowsPlatform():\n error = QCoreApplication.translate(\n \"CxFreezePlugin\",\n \"The cxfreeze.bat executable could not be found.\"\n \"Did you run the cxfreeze-postinstall script?\")\n else:\n error = QCoreApplication.translate(\n \"CxFreezePlugin\",\n \"The cxfreeze executable could not be found.\")\n return False\n else:\n return True\n\n\nclass CxFreezePlugin(QObject):\n \"\"\"\n Class implementing the CxFreeze plugin.\n \"\"\"\n def __init__(self, ui):\n \"\"\"\n Constructor\n \n @param ui reference to the user interface object (UI.UserInterface)\n \"\"\"\n QObject.__init__(self, ui)\n self.__ui = ui\n self.__initialize()\n _checkProgram()\n \n self.__translator = None\n self.__loadTranslator()\n \n def __initialize(self):\n \"\"\"\n Private slot to (re)initialize the plugin.\n \"\"\"\n self.__projectAct = None\n self.__projectSeparator = None\n \n def activate(self):\n \"\"\"\n Public method to activate this plugin.\n \n @return tuple of None and activation status (boolean)\n \"\"\"\n global error\n \n # There is already an error, don't activate\n if error:\n return None, False\n \n # cxfreeze is only activated if it is available\n if not _checkProgram():\n return None, False\n \n project = e5App().getObject(\"Project\")\n menu = project.getMenu(\"Packagers\")\n if menu:\n self.__projectAct = E5Action(\n self.tr('Use cx_freeze'),\n self.tr('Use cx_&freeze'), 0, 0,\n self, 'packagers_cxfreeze')\n self.__projectAct.setStatusTip(\n self.tr('Generate a distribution package using cx_freeze'))\n self.__projectAct.setWhatsThis(self.tr(\n \"\"\"Use cx_freeze\"\"\"\n \"\"\"

Generate a distribution package using cx_freeze.\"\"\"\n \"\"\" The command is executed in the project path. All\"\"\"\n \"\"\" files and directories must be given absolute or\"\"\"\n \"\"\" relative to the project directory.

\"\"\"\n ))\n self.__projectAct.triggered.connect(self.__cxfreeze)\n project.addE5Actions([self.__projectAct])\n self.__projectSeparator = menu.addSeparator()\n menu.addAction(self.__projectAct)\n project.showMenu.connect(self.__projectShowMenu)\n \n error = \"\"\n return None, True\n\n def deactivate(self):\n \"\"\"\n Public method to deactivate this plugin.\n \"\"\"\n menu = e5App().getObject(\"Project\").getMenu(\"Packagers\")\n if menu:\n if self.__projectAct:\n menu.removeAction(self.__projectAct)\n e5App().getObject(\"Project\").removeE5Actions(\n [self.__projectAct])\n if self.__projectSeparator:\n menu.removeAction(self.__projectSeparator)\n \n self.__initialize()\n \n def __projectShowMenu(self, menuName, menu):\n \"\"\"\n Private slot called, when the the project menu or a submenu is\n about to be shown.\n \n @param menuName name of the menu to be shown (string)\n @param menu reference to the menu (QMenu)\n \"\"\"\n if menuName == \"Packagers\":\n if self.__projectAct is not None:\n self.__projectAct.setEnabled(\n e5App().getObject(\"Project\").getProjectLanguage() ==\n \"Python3\"\n )\n \n def __loadTranslator(self):\n \"\"\"\n Private method to load the translation file.\n \"\"\"\n if self.__ui is not None:\n loc = self.__ui.getLocale()\n if loc and loc != \"C\":\n locale_dir = os.path.join(os.path.dirname(__file__),\n \"CxFreeze\", \"i18n\")\n translation = \"cxfreeze_{0}\".format(loc)\n translator = QTranslator(None)\n loaded = translator.load(translation, locale_dir)\n if loaded:\n self.__translator = translator\n e5App().installTranslator(self.__translator)\n else:\n print(\"Warning: translation file '{0}' could not be\"\n \" loaded.\".format(translation))\n print(\"Using default.\")\n \n def __cxfreeze(self):\n \"\"\"\n Private slot to handle the cxfreeze execution.\n \"\"\"\n project = e5App().getObject(\"Project\")\n if not project.getMainScript():\n # no main script defined\n E5MessageBox.critical(\n self.__ui,\n self.tr(\"cxfreeze\"),\n self.tr(\n \"\"\"There is no main script defined for the current\"\"\"\n \"\"\" project.\"\"\"),\n E5MessageBox.StandardButtons(E5MessageBox.Abort))\n return\n \n majorVersionStr = project.getProjectLanguage()\n exe = {\"Python3\": exePy3}.get(majorVersionStr)\n if exe == []:\n E5MessageBox.critical(\n self.__ui,\n self.tr(\"cxfreeze\"),\n self.tr(\"\"\"The cxfreeze executable could not be found.\"\"\"))\n return\n\n # check if all files saved and errorfree before continue\n if not project.checkAllScriptsDirty(reportSyntaxErrors=True):\n return\n\n from CxFreeze.CxfreezeConfigDialog import CxfreezeConfigDialog\n parms = project.getData('PACKAGERSPARMS', \"CXFREEZE\")\n dlg = CxfreezeConfigDialog(project, exe, parms)\n if dlg.exec_() == QDialog.Accepted:\n args, parms = dlg.generateParameters()\n project.setData('PACKAGERSPARMS', \"CXFREEZE\", parms)\n \n # now do the call\n from CxFreeze.CxfreezeExecDialog import CxfreezeExecDialog\n dia = CxfreezeExecDialog(\"cxfreeze\")\n dia.show()\n res = dia.start(args, parms, project.ppath,\n project.getMainScript())\n if res:\n dia.exec_()\n\n#\n# eflag: noqa = M801\n","sub_path":"PluginCxFreeze.py","file_name":"PluginCxFreeze.py","file_ext":"py","file_size_in_byte":13430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"511885406","text":"\ndef print_board(game_matrix): # Print the game board to the screen\n\n game_board = \"\"\"\n 0 1 2\n 0 {} | {} | {}\n ----+----+----\n 1 {} | {} | {}\n ----+----+----\n 2 {} | {} | {}\n \"\"\".format(game_matrix[0][0],game_matrix[0][1],game_matrix[0][2],\n game_matrix[1][0],game_matrix[1][1],game_matrix[1][2],\n game_matrix[2][0],game_matrix[2][1],game_matrix[2][2])\n\n print(game_board)\n\ndef check_win_conditions(game_matrix, turn_counter): # call to check conditions & return False to quit game\n\n first_column = [row[0] for row in game_matrix] # define columns & diagonals for win_configurations\n second_column = [row[1] for row in game_matrix]\n third_column = [row[2] for row in game_matrix]\n diagonal1 = [game_matrix[0][0], game_matrix[1][1], game_matrix[2][2]]\n diagonal2 = [game_matrix[0][2], game_matrix[1][1], game_matrix[2][0]]\n win_conditions = [[\"X\", \"X\", \"X\"], [\"O\", \"O\", \"O\"]]\n win_configs = [first_column, second_column, third_column, game_matrix[0], game_matrix[1], game_matrix[2], diagonal1, diagonal2]\n\n if turn_counter % 2 != 0:\n player = \"1\"\n else:\n player = \"2\"\n\n for item in win_configs: # Check all 8 win configurations\n if item in win_conditions:\n print(\"GAME OVER\")\n print(\"Good job Player {}! YOU WIN!!! \".format(player))\n return False\n\ndef play_again(): # Ask to play again, if not return False\n\n print(\"Do you want to play again? (Y/n) \")\n if input(\"> \") == \"y\":\n game()\n else:\n return False\n\ndef player_move(game_matrix, turn_counter): # Player choice & assign letter to correct matrix cell\n\n if turn_counter % 2 != 0:\n player = \"1\"\n player_letter = \"X\"\n else:\n player = \"2\"\n player_letter = \"O\"\n\n print(\"Player {}, it's your turn. Where do you want to move? \".format(player))\n\n good_moves = [\"0\", \"1\", \"2\"]\n row = input(\"Row \")\n column = input(\"Column \")\n\n if row not in good_moves:\n print(\"That is an invalid choice. \")\n return False\n elif column not in good_moves:\n print(\"That is an invalid choice. \")\n return False\n elif game_matrix[int(row)][int(column)] != \" \":\n print(\"You cannot make that move! \")\n return False\n else:\n game_matrix[int(row)][int(column)] = player_letter\n return True\n\ndef game(): # Game function\n\n game_matrix = [[\" \",\" \",\" \"],[\" \",\" \",\" \"],[\" \",\" \",\" \"]] # Matrix to accept player moves\n\n turn_counter = 0\n\n while True: # Game loop\n\n print_board(game_matrix) # Print current game board state\n\n if check_win_conditions(game_matrix, turn_counter) == False: # If win conditions met, ask to play again\n if play_again() == False:\n break\n elif turn_counter == 9: # The board is full if count gets to 9\n print(\"The game is a DRAW! \")\n if play_again() == False:\n break\n else:\n turn_counter += 1\n\n while not player_move(game_matrix, turn_counter): # Player one's turn, if invalid move go again\n pass\n\n print_board(game_matrix) # Print current game board state\n\n if check_win_conditions(game_matrix, turn_counter) == False: # If win conditions met, ask to play again\n if play_again() == False:\n break\n elif turn_counter == 9: # The board is full is the count gets to 9\n print(\"The game is a DRAW! \")\n if play_again() == False:\n break\n else:\n turn_counter += 1\n\n while not player_move(game_matrix, turn_counter): # Player two's turn, if invalid move go again\n pass\n\ngame()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"606110912","text":"import voluptuous as vol\n\nfrom esphome import pins\nfrom esphome.components import display, spi\nfrom esphome.components.spi import SPIComponent\nimport esphome.config_validation as cv\nfrom esphome.const import CONF_CS_PIN, CONF_DC_PIN, CONF_EXTERNAL_VCC, CONF_ID, CONF_LAMBDA, \\\n CONF_MODEL, CONF_PAGES, CONF_RESET_PIN, CONF_SPI_ID\nfrom esphome.cpp_generator import Pvariable, add, get_variable, process_lambda\nfrom esphome.cpp_helpers import gpio_output_pin_expression, setup_component\nfrom esphome.cpp_types import App, PollingComponent, void\n\nDEPENDENCIES = ['spi']\n\nSSD1306 = display.display_ns.class_('SSD1306', PollingComponent, display.DisplayBuffer)\nSPISSD1306 = display.display_ns.class_('SPISSD1306', SSD1306, spi.SPIDevice)\nSSD1306Model = display.display_ns.enum('SSD1306Model')\n\nMODELS = {\n 'SSD1306_128X32': SSD1306Model.SSD1306_MODEL_128_32,\n 'SSD1306_128X64': SSD1306Model.SSD1306_MODEL_128_64,\n 'SSD1306_96X16': SSD1306Model.SSD1306_MODEL_96_16,\n 'SSD1306_64X48': SSD1306Model.SSD1306_MODEL_64_48,\n 'SH1106_128X32': SSD1306Model.SH1106_MODEL_128_32,\n 'SH1106_128X64': SSD1306Model.SH1106_MODEL_128_64,\n 'SH1106_96X16': SSD1306Model.SH1106_MODEL_96_16,\n 'SH1106_64X48': SSD1306Model.SH1106_MODEL_64_48,\n}\n\nSSD1306_MODEL = cv.one_of(*MODELS, upper=True, space=\"_\")\n\nPLATFORM_SCHEMA = vol.All(display.FULL_DISPLAY_PLATFORM_SCHEMA.extend({\n cv.GenerateID(): cv.declare_variable_id(SPISSD1306),\n cv.GenerateID(CONF_SPI_ID): cv.use_variable_id(SPIComponent),\n vol.Required(CONF_CS_PIN): pins.gpio_output_pin_schema,\n vol.Required(CONF_DC_PIN): pins.gpio_output_pin_schema,\n vol.Required(CONF_MODEL): SSD1306_MODEL,\n vol.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,\n vol.Optional(CONF_EXTERNAL_VCC): cv.boolean,\n}).extend(cv.COMPONENT_SCHEMA.schema), cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA))\n\n\ndef to_code(config):\n spi_ = yield get_variable(config[CONF_SPI_ID])\n cs = yield gpio_output_pin_expression(config[CONF_CS_PIN])\n dc = yield gpio_output_pin_expression(config[CONF_DC_PIN])\n\n rhs = App.make_spi_ssd1306(spi_, cs, dc)\n ssd = Pvariable(config[CONF_ID], rhs)\n add(ssd.set_model(MODELS[config[CONF_MODEL]]))\n\n if CONF_RESET_PIN in config:\n reset = yield gpio_output_pin_expression(config[CONF_RESET_PIN])\n add(ssd.set_reset_pin(reset))\n if CONF_EXTERNAL_VCC in config:\n add(ssd.set_external_vcc(config[CONF_EXTERNAL_VCC]))\n if CONF_LAMBDA in config:\n lambda_ = yield process_lambda(config[CONF_LAMBDA],\n [(display.DisplayBufferRef, 'it')], return_type=void)\n add(ssd.set_writer(lambda_))\n\n display.setup_display(ssd, config)\n setup_component(ssd, config)\n\n\nBUILD_FLAGS = '-DUSE_SSD1306'\n","sub_path":"esphome/components/display/ssd1306_spi.py","file_name":"ssd1306_spi.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"20707404","text":"from OpenGL.GL import *\nfrom OpenGL.GL.shaders import compileProgram,compileShader\nimport pygame as pg\nimport numpy as np\n\npg.init()\n#display\npg.display.set_mode((640,480),pg.OPENGL|pg.DOUBLEBUF|pg.RESIZABLE)\nglClearColor(0.2, 0.3, 0.3, 1.0)\n\n#timer\nclock = pg.time.Clock()\n\n#define data\nvertices = [ 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0,\n 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0,\n -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,\n -0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0] \nindices = [0, 1, 3,\n 1, 2, 3]\n\nvertices = np.array(vertices,dtype=np.float32)\nindices = np.array(indices,dtype=np.uint32)\nVBO = glGenBuffers(1)\nEBO = glGenBuffers(1)\nVAO = glGenVertexArrays(1)\nglBindVertexArray(VAO)\nglBindBuffer(GL_ARRAY_BUFFER,VBO)\nglBufferData(GL_ARRAY_BUFFER,vertices.nbytes,vertices,GL_STATIC_DRAW)\n#vertex attributes\n#position\nglVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,vertices.itemsize*8,ctypes.c_void_p(0))\nglEnableVertexAttribArray(0)\n#colour\nglVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,vertices.itemsize*8,ctypes.c_void_p(12))\nglEnableVertexAttribArray(1)\n#texture (s,t) coords\nglVertexAttribPointer(2,2,GL_FLOAT,GL_FALSE,vertices.itemsize*8,ctypes.c_void_p(24))\nglEnableVertexAttribArray(2)\n\n#texture\ntexture = glGenTextures(1)\nglBindTexture(GL_TEXTURE_2D,texture)\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\nimage = pg.image.load(\"textures/crate-texture.jpg\").convert()\nimage_width,image_height = image.get_rect().size\nimg_data = pg.image.tostring(image,'RGBA')\nglTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,image_width,image_height,0,GL_RGBA,GL_UNSIGNED_BYTE,img_data)\nglGenerateMipmap(GL_TEXTURE_2D)\n\nglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)\nglBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)\n\n#shaders\nwith open(\"shaders/texturedVertex2.txt\",'r') as f:\n vertex_src = f.readlines()\nwith open(\"shaders/texturedFragment2.txt\",'r') as f:\n fragment_src = f.readlines()\nshader = compileProgram(compileShader(vertex_src,GL_VERTEX_SHADER),\n compileShader(fragment_src,GL_FRAGMENT_SHADER))\nglUseProgram(shader)\nrunning = True\n\nwhile running:\n for event in pg.event.get():\n if event.type==pg.QUIT:\n running = False\n if event.type==pg.VIDEORESIZE:\n glViewport(0,0,event.w,event.h)\n\n glClear(GL_COLOR_BUFFER_BIT)\n glBindVertexArray(VAO)\n glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)\n \n pg.display.flip()\n clock.tick()\n fps = clock.get_fps()\n pg.display.set_caption(\"Running at \"+str(int(fps))+\" fps\")\n\npg.quit()","sub_path":"texturePygame.py","file_name":"texturePygame.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"532281517","text":"import requests\nimport time\nimport datetime\nimport json\nimport constants\nimport pandas as pd\nimport pickle\nimport db_manager\n\ndef get_response(query):\n \"\"\"\n Access wunderground API to do a get request\n \"\"\"\n try:\n response = requests.get(constants.BASE_URL + query+ \".json\")\n return response.json() if response.ok else None\n except Exception as e:\n raise e\n\n\ndef collect_forecast_coords(coords, city):\n \"\"\"\n Stores the json object corresponding to the weather forecast of city in a file.\n Parameters:\n coords: dictionary with the city names as keys, and tuple of coordinates as value\n city: name of the city in a string format \n \"\"\"\n latitude, longitude= constants.coordinates.get(city)\n location = str(latitude)+ \",\" + str(longitude)\n response = get_response(location)\n simple_forecast = response.get(\"hourly_forecast\")\n filename = str(time.time()) + \"_\" + city + \"_\" + constants.FILENAME\n f = open(filename, 'w')\n json.dump(simple_forecast, f)\n f.close()\n\ndef extract_parameters(hourly_forecast, city, data):\n fcttime = hourly_forecast.get('FCTTIME')\n year, month, day, hour = fcttime.get('year'), fcttime.get('mon_padded'), fcttime.get('mday_padded'), fcttime.get('hour_padded')\n temperature = hourly_forecast.get('temp').get('metric')\n wind_speed = hourly_forecast.get('wspd').get('metric')\n humidity = hourly_forecast.get('humidity')\n precipitation_per = hourly_forecast.get('qpf').get('metric') #convert\n wind_direction = hourly_forecast.get('wdir').get('dir')\n condition = hourly_forecast.get('condition')\n snow = hourly_forecast.get('snow').get('metric')\n UVI = hourly_forecast.get('uvi')\n precipitation_l = None\n website = 'The Weather Channel'\n\n data['website'].append(website)\n data['city'].append(city)\n data['date_of_acquisition'].append(datetime.datetime.now().strftime('%Y%m%d%H'))\n data['date_for_which_weather_is_predicted'].append(year + month + day + hour)\n data['temperature'].append(temperature)\n data['wind_speed'].append(wind_speed)\n data['humidity'].append(humidity)\n data['precipitation_per'].append(precipitation_per )\n data['precipitation_l'].append(precipitation_l)\n data['wind_direction'].append(wind_direction)\n data['condition'].append(condition)\n data['snow'].append(snow)\n data['uvi'].append(UVI)\n return data\n #df = pd.DataFrame(data, index=[0])\n\ndef gather_hourly_city(city, data):\n latitude, longitude= constants.coordinates.get(city)\n location = str(latitude)+ \",\" + str(longitude)\n response = get_response(location)\n iterations = 100\n while(response == None and iterations > 0):\n response = get_response(location)\n iterations -= 1\n time.sleep(10)\n if(response == None):\n return data\n\n hourly_forecasts = response.get(\"hourly_forecast\")\n\n for hourly_forecast in hourly_forecasts:\n data = extract_parameters(hourly_forecast, city, data)\n return data\n\ndef gather_hourly_information():\n data = {\n 'website' : [],\n 'city' : [],\n 'date_of_acquisition' : [],\n 'date_for_which_weather_is_predicted' : [],\n 'temperature' : [],\n 'wind_speed' : [],\n 'humidity' : [],\n 'precipitation_per' : [],\n 'precipitation_l' : [],\n 'wind_direction' : [],\n 'condition' : [],\n 'snow' : [],\n 'uvi' : [],\n }\n for city in constants.coordinates.keys():\n data = gather_hourly_city(city, data)\n\n df = pd.DataFrame(data)\n df.date_for_which_weather_is_predicted = df.date_for_which_weather_is_predicted.apply(lambda x: datetime.datetime.strptime(x, '%Y%m%d%H'))\n df.date_of_acquisition = df.date_of_acquisition.apply(lambda x: datetime.datetime.strptime(x, '%Y%m%d%H'))\n return df\n\ndf = gather_hourly_information()\n\ntry:\n if(df.size > 0):\n db_manager.insert_df(\"HourlyPrediction\", df)\nfinally:\n if(df.size > 0): \n timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M')\n filename = \"/home/danielv/Documents/webscraping_2018/data_hourly/\" + timestamp + \".pkl\"\n df.to_pickle(filename)\n","sub_path":"hourly_db.py","file_name":"hourly_db.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"466849017","text":"from flask import Blueprint\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import url_for\n\nfrom flask_login import login_required\n\nfrom blog.auth import UserAwareMethodView\nfrom blog.admin.forms import NewPostForm\nfrom blog.admin.forms import NewProjectForm\nfrom blog.posts.models import Post\nfrom blog.projects.models import Project\n\n\nadmin = Blueprint('admin', __name__, template_folder='templates')\n\n\nclass AdminIndexView(UserAwareMethodView):\n decorators = [login_required]\n active_nav = 'admin_index'\n\n def get(self):\n context = self.get_context()\n context['posts'] = Post.objects.all()\n context['projects'] = Project.objects().all()\n return render_template(\"admin/index.html\", **context)\n\n\nclass EditPostView(UserAwareMethodView):\n decorators = [login_required]\n active_nav = 'admin_edit_post'\n\n def get(self, slug):\n context = self.get_context()\n context['post'] = Post.objects.get_or_404(slug=slug)\n return render_template(\"admin/edit-post.html\", **context)\n\n def post(self, slug):\n post = Post.objects.get_or_404(slug=slug)\n title = request.form['post-title']\n body = request.form['post-body']\n post.title = title\n post.body = body\n post.save()\n return redirect(url_for('posts.detail', slug=post.slug))\n\n\nclass EditProjectView(UserAwareMethodView):\n decorators = [login_required]\n active_nav = 'admin_edit_project'\n\n def get(self, slug):\n context = self.get_context()\n context['project'] = Project.objects.get_or_404(slug=slug)\n return render_template(\"admin/edit-project.html\", **context)\n\n def post(self, slug):\n project = Project.objects.get_or_404(slug=slug)\n title = request.form['title']\n body = request.form['body']\n project.title = title\n project.body = body\n project.save()\n return redirect(url_for('posts.detail', slug=project.slug))\n\n\nclass AddPostView(UserAwareMethodView):\n decorators = [login_required]\n active_nav = 'admin_add_post'\n\n def get(self):\n context = self.get_context()\n context['form'] = NewPostForm()\n return render_template(\"admin/add-post.html\", **context)\n\n def post(self):\n post = Post(\n title=request.form.get('post-title', None),\n body=request.form.get('post-body', None),\n slug=request.form.get('post-slug', None),\n category=\"blog\",\n )\n post.save()\n return redirect(url_for('posts.detail', slug=post.slug))\n\n\nclass AddProjectView(UserAwareMethodView):\n decorators = [login_required]\n active_nav = 'admin_add_project'\n\n def get(self):\n context = self.get_context()\n context['form'] = NewProjectForm()\n return render_template(\"admin/add-project.html\", **context)\n\n def post(self):\n project = Project(\n title=request.form.get('title', None),\n subtitle=request.form.get('subtitle', None),\n body=request.form.get('body', None),\n slug=request.form.get('slug', None),\n category=\"project\",\n )\n project.save()\n return redirect(url_for('projects.detail', slug=project.slug))\n\n\n# Register the urls\nadmin.add_url_rule('/admin/', view_func=AdminIndexView.as_view('index'))\nadmin.add_url_rule('/admin/blog/', view_func=AddPostView.as_view('add-post'))\nadmin.add_url_rule('/admin/blog//', view_func=EditPostView.as_view('edit-post'))\nadmin.add_url_rule('/admin/project/', view_func=AddProjectView.as_view('add-project'))\nadmin.add_url_rule('/admin/project/', view_func=EditProjectView.as_view('edit-project'))\n","sub_path":"blog/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"377305545","text":"from transformers import BartConfig\nfrom transformers.modeling_bart_efficient_decoder import SelfAttention\nfrom transformers.modeling_bart_efficient_decoder import _prepare_bart_decoder_inputs, _filter_out_falsey_values\nfrom transformers.modeling_utils import BeamHypotheses, calc_banned_ngram_tokens\n\nfrom models.lobart import LoBART\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass HierSelfAttention(SelfAttention):\n def __init__(\n self,\n embed_dim,\n num_heads,\n dropout=0.0,\n bias=True,\n encoder_decoder_attention=True, # otherwise self_attention\n ):\n super().__init__(embed_dim, num_heads, dropout, bias, encoder_decoder_attention)\n\n # sent-level projection\n self.sent_k_proj = nn.Linear(in_features=embed_dim, out_features=embed_dim, bias=bias)\n self.sent_q_proj = nn.Linear(in_features=embed_dim, out_features=embed_dim, bias=bias)\n\n def forward(\n self, query, key,\n boundary=None, # where [EOS] tokens are in the key\n key_padding_mask = None,\n layer_state = None,\n attn_mask = None,\n need_weights=False,\n ):\n \"\"\"Input shape: Time(SeqLen) x Batch x Channel\"\"\"\n static_kv: bool = self.encoder_decoder_attention\n tgt_len, bsz, embed_dim = query.size()\n assert embed_dim == self.embed_dim\n assert list(query.size()) == [tgt_len, bsz, embed_dim]\n # get here for encoder decoder cause of static_kv\n if layer_state is not None: # reuse k,v and encoder_padding_mask\n saved_state = layer_state.get(self.cache_key, {})\n if \"prev_key\" in saved_state:\n # previous time steps are cached - no need to recompute key and value if they are static\n if static_kv:\n key = None\n else:\n saved_state = None\n layer_state = {}\n\n q = self.q_proj(query) * self.scaling\n if static_kv:\n if key is None:\n k = v = None\n else:\n k = self.k_proj(key)\n v = self.v_proj(key)\n else:\n k = self.k_proj(query)\n v = self.v_proj(query)\n q = self._shape(q, tgt_len, bsz) # making multiple heads\n if k is not None:\n k = self._shape(k, -1, bsz) # making multiple heads\n if v is not None:\n v = self._shape(v, -1, bsz) # making multiple heads\n\n\n if saved_state is not None:\n k, v, key_padding_mask = self._use_saved_state(k, v, saved_state, key_padding_mask, static_kv, bsz)\n\n # Update cache\n layer_state[self.cache_key] = {\n \"prev_key\": k.view(bsz, self.num_heads, -1, self.head_dim),\n \"prev_value\": v.view(bsz, self.num_heads, -1, self.head_dim),\n \"prev_key_padding_mask\": key_padding_mask if not static_kv else None,\n }\n\n assert k is not None\n src_len = k.size(1)\n\n # here is normal attention mechanism\n attn_weights = torch.bmm(q, k.transpose(1, 2))\n assert attn_weights.size() == (bsz * self.num_heads, tgt_len, src_len)\n\n if attn_mask is not None:\n attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_mask\n attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n # This is part of a workaround to get around fork/join parallelism not supporting Optional types.\n if key_padding_mask is not None and key_padding_mask.dim() == 0:\n key_padding_mask = None\n assert key_padding_mask is None or key_padding_mask.size()[:2] == (bsz, src_len,)\n\n if key_padding_mask is not None: # don't attend to padding symbols\n attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)\n reshaped = key_padding_mask.unsqueeze(1).unsqueeze(2)\n attn_weights = attn_weights.masked_fill(reshaped, float(\"-inf\"))\n attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n # attn_weights = F.softmax(attn_weights, dim=-1)\n # attn_probs = F.dropout(attn_weights, p=self.dropout, training=self.training,)\n\n _attn_weights = F.softmax(attn_weights, dim=-1)\n boundary_matrix = boundary['boundary']\n sent_outputs = boundary['sent_outputs']\n sentid2wordid = boundary['sentid2wordid']\n num_sentences_kept = 30\n\n exact_sent_attn_weights = torch.bmm(_attn_weights.squeeze(0), boundary_matrix)\n # sent-level\n sent_q = self.sent_q_proj(query) * self.scaling\n sent_q = self._shape(sent_q, tgt_len, bsz) # making multiple heads\n\n sent_k = self.sent_k_proj(sent_outputs)\n sent_k = sent_k.reshape(self.num_heads, -1, self.head_dim)\n rnn_sent_attn_weights = F.softmax(torch.bmm(sent_q, sent_k.transpose(1, 2)), dim=-1)\n\n # selection\n # exact_sent_attn_weights | rnn_sent_attn_weights\n # attn_scores.shape => (num_head, decoder_timesteps, num_sentences)\n if boundary['use_exact_scores']:\n attn_scores = exact_sent_attn_weights\n else: # i.e. use_approximated_scores\n attn_scores = rnn_sent_attn_weights\n\n decoder_timesteps = attn_scores.size(1)\n k_min = min(num_sentences_kept, boundary_matrix.size(-1))\n selection_mask = float('-inf') * torch.ones(attn_weights.shape, device=attn_weights.device)\n for t in range(decoder_timesteps):\n phi_prod_topk = torch.topk(attn_scores[:,t,:].mean(dim=[0]), k=k_min, dim=-1)[-1]\n for sentid in phi_prod_topk:\n kept_wordids = sentid2wordid[sentid]\n selection_mask[:, t, kept_wordids] = 0.0\n\n attn_weights = F.softmax(attn_weights + selection_mask, dim=-1)\n attn_probs = F.dropout(attn_weights, p=self.dropout, training=self.training)\n\n # assume batch_size is 1\n exact_sent_attn_weights = exact_sent_attn_weights.unsqueeze(0)\n rnn_sent_attn_weights = rnn_sent_attn_weights.unsqueeze(0)\n\n assert v is not None\n attn_output = torch.bmm(attn_probs, v)\n assert attn_output.size() == (bsz * self.num_heads, tgt_len, self.head_dim)\n attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)\n attn_output = self.out_proj(attn_output)\n return attn_output, {'exact_sent_attn_weights': exact_sent_attn_weights, 'rnn_sent_attn_weights': rnn_sent_attn_weights}\n\n\nclass SentLevelNN(nn.Module):\n def __init__(self, config, num_layers=2):\n super().__init__()\n # add a RNN head\n self.rnn_head = nn.GRU(input_size=config.d_model, hidden_size=config.d_model,\n num_layers=num_layers, bias=True, batch_first=True,\n dropout=config.dropout, bidirectional=True)\n # add linear layer\n self.linear = nn.Linear(2*config.d_model, config.d_model)\n\nclass BartEfficientLoBART(LoBART):\n def __init__(self, config: BartConfig):\n super().__init__(config)\n num_encoder_sent_nn_layers = 2\n print(\"------------------------------------------------\")\n print(\"num_encoder_sent_nn_layers:\", num_encoder_sent_nn_layers)\n print(\"------------------------------------------------\")\n self.encoder_sent_nn = SentLevelNN(self.config, num_layers=num_encoder_sent_nn_layers)\n\n # initiliazation\n for name, p in self.encoder_sent_nn.named_parameters():\n if p.dim() > 1: nn.init.xavier_normal_(p)\n else:\n if 'bias' in name: nn.init.zeros_(p)\n\n # override\n def forward(\n self,\n input_ids,\n attention_mask=None,\n encoder_outputs=None,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n decoder_cached_states=None,\n lm_labels=None,\n use_cache=False,\n boundary=None,\n **unused\n ):\n\n # ----------------------- BART Model ----------------------- #\n if not use_cache:\n decoder_input_ids, decoder_padding_mask, causal_mask = _prepare_bart_decoder_inputs(\n self.model.config,\n input_ids,\n decoder_input_ids=decoder_input_ids,\n decoder_padding_mask=decoder_attention_mask,\n causal_mask_dtype=self.model.shared.weight.dtype,\n )\n else:\n decoder_padding_mask, causal_mask = None, None\n\n assert decoder_input_ids is not None\n if encoder_outputs is None:\n encoder_outputs = self.model.encoder(input_ids=input_ids, attention_mask=attention_mask)\n assert isinstance(encoder_outputs, tuple)\n\n\n\n ## computing sent-level representation ##\n _encoder_outputs = encoder_outputs[0]\n num_sentences = len(boundary['sentid2wordid'])\n batch_size = _encoder_outputs.size(0)\n assert batch_size == 1, \"batch_size == 1 only!!\"\n sent_outputs = torch.zeros((batch_size, num_sentences, self.config.d_model), device=_encoder_outputs.device)\n for k in range(num_sentences):\n word_i1 = boundary['sentid2wordid'][k][0]\n word_i2 = boundary['sentid2wordid'][k][-1]\n sent_len = word_i2-word_i1+1\n\n h_this_sent = _encoder_outputs[:, word_i1:word_i2+1]\n rnn_outputs = self.encoder_sent_nn.rnn_head(h_this_sent)\n rnn_output = rnn_outputs[0].view(1, sent_len, 2, -1) # get output [0]\n fw_output = rnn_output[:, -1, 0, :]\n bw_output = rnn_output[:, 0, 1, :]\n sent_output = self.encoder_sent_nn.linear(torch.cat([fw_output, bw_output], dim=-1))\n sent_outputs[:, k, :] = sent_output\n\n boundary['sent_outputs'] = sent_outputs\n ## ------------------------------------ ##\n\n # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n decoder_outputs = self.model.decoder(\n decoder_input_ids,\n encoder_outputs[0],\n attention_mask,\n decoder_padding_mask,\n decoder_causal_mask=causal_mask,\n decoder_cached_states=decoder_cached_states,\n use_cache=use_cache,\n boundary=boundary,\n )\n # Attention and hidden_states will be [] or None if they aren't needed\n decoder_outputs: Tuple = _filter_out_falsey_values(decoder_outputs)\n assert isinstance(decoder_outputs[0], torch.Tensor)\n encoder_outputs: Tuple = _filter_out_falsey_values(encoder_outputs)\n outputs = decoder_outputs + encoder_outputs\n # ------------------------------------------------------------ #\n\n\n lm_logits = F.linear(outputs[0], self.model.shared.weight, bias=self.final_logits_bias)\n outputs = (lm_logits,) + outputs[1:] # Add cache, hidden states and attention if they are here\n if lm_labels is not None:\n loss_fct = nn.CrossEntropyLoss()\n # TODO(SS): do we need to ignore pad tokens in lm_labels?\n masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), lm_labels.view(-1))\n outputs = (masked_lm_loss,) + outputs\n\n return outputs\n\n\n def swap_crossattn_to_hier(self, num_layers=12):\n print(\"Start Swapping Cross-Attention\")\n # copy weights\n for l in range(num_layers):\n embed_dim = self.model.decoder.layers[l].encoder_attn.embed_dim\n num_heads = self.model.decoder.layers[l].encoder_attn.num_heads\n dropout = self.model.decoder.layers[l].encoder_attn.dropout\n hier_cross_attention = HierSelfAttention(embed_dim, num_heads, dropout,\n bias=True, encoder_decoder_attention=True)\n hier_cross_attention.k_proj.weight.data = self.model.decoder.layers[l].encoder_attn.k_proj.weight.data\n hier_cross_attention.v_proj.weight.data = self.model.decoder.layers[l].encoder_attn.v_proj.weight.data\n hier_cross_attention.q_proj.weight.data = self.model.decoder.layers[l].encoder_attn.q_proj.weight.data\n hier_cross_attention.out_proj.weight.data = self.model.decoder.layers[l].encoder_attn.out_proj.weight.data\n self.model.decoder.layers[l].encoder_attn = hier_cross_attention\n print(\"End Swapping Cross-Attention\")\n\n\n\n @torch.no_grad()\n def generate(\n self, input_ids = None,\n max_length = None, min_length = None,\n do_sample = None, early_stopping = None, num_beams = None,\n temperature = None, top_k = None, top_p = None, repetition_penalty = None,\n bad_words_ids = None, bos_token_id = None, pad_token_id = None, eos_token_id = None,\n length_penalty = None, no_repeat_ngram_size = None,\n num_return_sequences = None, attention_mask = None, decoder_start_token_id = None,\n use_cache = None, **model_specific_kwargs\n ) -> torch.LongTensor:\n\n # We cannot generate if the model does not have a LM head\n if self.get_output_embeddings() is None:\n raise AttributeError(\n \"You tried to generate sequences with a model that does not have a LM Head.\"\n \"Please use another model class (e.g. `OpenAIGPTLMHeadModel`, `XLNetLMHeadModel`, `GPT2LMHeadModel`, `CTRLLMHeadModel`, `T5WithLMHeadModel`, `TransfoXLLMHeadModel`, `XLMWithLMHeadModel`, `BartForConditionalGeneration` )\"\n )\n\n max_length = max_length if max_length is not None else self.config.max_length\n min_length = min_length if min_length is not None else self.config.min_length\n do_sample = do_sample if do_sample is not None else self.config.do_sample\n early_stopping = early_stopping if early_stopping is not None else self.config.early_stopping\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n num_beams = num_beams if num_beams is not None else self.config.num_beams\n temperature = temperature if temperature is not None else self.config.temperature\n top_k = top_k if top_k is not None else self.config.top_k\n top_p = top_p if top_p is not None else self.config.top_p\n repetition_penalty = repetition_penalty if repetition_penalty is not None else self.config.repetition_penalty\n bos_token_id = bos_token_id if bos_token_id is not None else self.config.bos_token_id\n pad_token_id = pad_token_id if pad_token_id is not None else self.config.pad_token_id\n eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id\n length_penalty = length_penalty if length_penalty is not None else self.config.length_penalty\n no_repeat_ngram_size = (\n no_repeat_ngram_size if no_repeat_ngram_size is not None else self.config.no_repeat_ngram_size\n )\n bad_words_ids = bad_words_ids if bad_words_ids is not None else self.config.bad_words_ids\n num_return_sequences = (\n num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences\n )\n decoder_start_token_id = (\n decoder_start_token_id if decoder_start_token_id is not None else self.config.decoder_start_token_id\n )\n\n if input_ids is not None:\n batch_size = input_ids.shape[0] # overriden by the input batch_size\n else:\n batch_size = 1\n\n assert isinstance(max_length, int) and max_length > 0, \"`max_length` should be a strictly positive integer.\"\n assert isinstance(min_length, int) and min_length >= 0, \"`min_length` should be a positive integer.\"\n assert isinstance(do_sample, bool), \"`do_sample` should be a boolean.\"\n assert isinstance(early_stopping, bool), \"`early_stopping` should be a boolean.\"\n assert isinstance(use_cache, bool), \"`use_cache` should be a boolean.\"\n assert isinstance(num_beams, int) and num_beams > 0, \"`num_beams` should be a strictly positive integer.\"\n assert temperature > 0, \"`temperature` should be strictly positive.\"\n assert isinstance(top_k, int) and top_k >= 0, \"`top_k` should be a positive integer.\"\n assert 0 <= top_p <= 1, \"`top_p` should be between 0 and 1.\"\n assert repetition_penalty >= 1.0, \"`repetition_penalty` should be >= 1.\"\n assert input_ids is not None or (\n isinstance(bos_token_id, int) and bos_token_id >= 0\n ), \"If input_ids is not defined, `bos_token_id` should be a positive integer.\"\n assert pad_token_id is None or (\n isinstance(pad_token_id, int) and (pad_token_id >= 0)\n ), \"`pad_token_id` should be a positive integer.\"\n assert (eos_token_id is None) or (\n isinstance(eos_token_id, int) and (eos_token_id >= 0)\n ), \"`eos_token_id` should be a positive integer.\"\n assert length_penalty > 0, \"`length_penalty` should be strictly positive.\"\n assert (\n isinstance(no_repeat_ngram_size, int) and no_repeat_ngram_size >= 0\n ), \"`no_repeat_ngram_size` should be a positive integer.\"\n assert (\n isinstance(num_return_sequences, int) and num_return_sequences > 0\n ), \"`num_return_sequences` should be a strictly positive integer.\"\n assert (\n bad_words_ids is None or isinstance(bad_words_ids, list) and isinstance(bad_words_ids[0], list)\n ), \"`bad_words_ids` is either `None` or a list of lists of tokens that should not be generated\"\n\n if input_ids is None:\n assert isinstance(bos_token_id, int) and bos_token_id >= 0, (\n \"you should either supply a context to complete as `input_ids` input \"\n \"or a `bos_token_id` (integer >= 0) as a first token to start the generation.\"\n )\n input_ids = torch.full(\n (batch_size, 1), bos_token_id, dtype=torch.long, device=next(self.parameters()).device,\n )\n else:\n assert input_ids.dim() == 2, \"Input prompt should be of shape (batch_size, sequence length).\"\n\n # not allow to duplicate outputs when greedy decoding\n if do_sample is False:\n if num_beams == 1:\n # no_beam_search greedy generation conditions\n assert (\n num_return_sequences == 1\n ), \"Greedy decoding will always produce the same output for num_beams == 1 and num_return_sequences > 1. Please set num_return_sequences = 1\"\n\n else:\n # beam_search greedy generation conditions\n assert (\n num_beams >= num_return_sequences\n ), \"Greedy beam search decoding cannot return more sequences than it has beams. Please set num_beams >= num_return_sequences\"\n\n # create attention mask if necessary\n # TODO (PVP): this should later be handled by the forward fn() in each model in the future see PR 3140\n if (attention_mask is None) and (pad_token_id is not None) and (pad_token_id in input_ids):\n attention_mask = input_ids.ne(pad_token_id).long()\n elif attention_mask is None:\n attention_mask = input_ids.new_ones(input_ids.shape)\n\n # set pad_token_id to eos_token_id if not set. Important that this is done after\n # attention_mask is created\n if pad_token_id is None and eos_token_id is not None:\n logger.warning(\n \"Setting `pad_token_id` to {} (first `eos_token_id`) to generate sequence\".format(eos_token_id)\n )\n pad_token_id = eos_token_id\n\n # current position and vocab size\n if hasattr(self.config, \"vocab_size\"):\n vocab_size = self.config.vocab_size\n elif (\n self.config.is_encoder_decoder\n and hasattr(self.config, \"decoder\")\n and hasattr(self.config.decoder, \"vocab_size\")\n ):\n vocab_size = self.config.decoder.vocab_size\n\n # set effective batch size and effective batch multiplier according to do_sample\n if do_sample:\n effective_batch_size = batch_size * num_return_sequences\n effective_batch_mult = num_return_sequences\n else:\n effective_batch_size = batch_size\n effective_batch_mult = 1\n\n if self.config.is_encoder_decoder:\n if decoder_start_token_id is None:\n decoder_start_token_id = bos_token_id\n\n assert (\n decoder_start_token_id is not None\n ), \"decoder_start_token_id or bos_token_id has to be defined for encoder-decoder generation\"\n assert hasattr(self, \"get_encoder\"), \"{} should have a 'get_encoder' function defined\".format(self)\n assert callable(self.get_encoder), \"{} should be a method\".format(self.get_encoder)\n\n # get encoder and store encoder outputs\n encoder = self.get_encoder()\n\n encoder_outputs: tuple = encoder(input_ids, attention_mask=attention_mask)\n\n # Expand input ids if num_beams > 1 or num_return_sequences > 1\n if num_return_sequences > 1 or num_beams > 1:\n input_ids_len = input_ids.shape[-1]\n input_ids = input_ids.unsqueeze(1).expand(batch_size, effective_batch_mult * num_beams, input_ids_len)\n attention_mask = attention_mask.unsqueeze(1).expand(\n batch_size, effective_batch_mult * num_beams, input_ids_len\n )\n\n input_ids = input_ids.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n attention_mask = attention_mask.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n\n if self.config.is_encoder_decoder:\n # create empty decoder_input_ids\n input_ids = torch.full(\n (effective_batch_size * num_beams, 1),\n decoder_start_token_id,\n dtype=torch.long,\n device=next(self.parameters()).device,\n )\n cur_len = 1\n\n assert (\n batch_size == encoder_outputs[0].shape[0]\n ), f\"expected encoder_outputs[0] to have 1st dimension bs={batch_size}, got {encoder_outputs[0].shape[0]} \"\n\n # expand batch_idx to assign correct encoder output for expanded input_ids (due to num_beams > 1 and num_return_sequences > 1)\n expanded_batch_idxs = (\n torch.arange(batch_size)\n .view(-1, 1)\n .repeat(1, num_beams * effective_batch_mult)\n .view(-1)\n .to(input_ids.device)\n )\n # expand encoder_outputs\n encoder_outputs = (encoder_outputs[0].index_select(0, expanded_batch_idxs), *encoder_outputs[1:])\n\n else:\n encoder_outputs = None\n cur_len = input_ids.shape[-1]\n\n if num_beams > 1:\n output = self._generate_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n early_stopping=early_stopping,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n bos_token_id=bos_token_id,\n pad_token_id=pad_token_id,\n decoder_start_token_id=decoder_start_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n num_return_sequences=num_return_sequences,\n length_penalty=length_penalty,\n num_beams=num_beams,\n vocab_size=vocab_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n else:\n output = self._generate_no_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n bos_token_id=bos_token_id,\n pad_token_id=pad_token_id,\n decoder_start_token_id=decoder_start_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n\n return output\n\n def _generate_beam_search(\n self,\n input_ids,\n cur_len,\n max_length,\n min_length,\n do_sample,\n early_stopping,\n temperature,\n top_k,\n top_p,\n repetition_penalty,\n no_repeat_ngram_size,\n bad_words_ids,\n bos_token_id,\n pad_token_id,\n eos_token_id,\n decoder_start_token_id,\n batch_size,\n num_return_sequences,\n length_penalty,\n num_beams,\n vocab_size,\n encoder_outputs,\n attention_mask,\n use_cache,\n model_specific_kwargs,\n ):\n \"\"\" Generate sequences for each example with beam search.\n \"\"\"\n\n # generated hypotheses\n generated_hyps = [\n BeamHypotheses(num_beams, max_length, length_penalty, early_stopping=early_stopping)\n for _ in range(batch_size)\n ]\n\n # scores for each sentence in the beam\n beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)\n\n # for greedy decoding it is made sure that only tokens of the first beam are considered to avoid sampling the exact same tokens three times\n if do_sample is False:\n beam_scores[:, 1:] = -1e9\n beam_scores = beam_scores.view(-1) # shape (batch_size * num_beams,)\n\n # cache compute states\n past = encoder_outputs # defined for encoder-decoder models, None for decoder-only models\n\n # done sentences\n done = [False for _ in range(batch_size)]\n\n while cur_len < max_length:\n model_inputs = self.prepare_inputs_for_generation(\n input_ids, past=past, attention_mask=attention_mask, use_cache=use_cache, **model_specific_kwargs\n )\n if 'boundary' in model_specific_kwargs:\n model_inputs['boundary'] = model_specific_kwargs['boundary']\n outputs = self(**model_inputs) # (batch_size * num_beams, cur_len, vocab_size)\n next_token_logits = outputs[0][:, -1, :] # (batch_size * num_beams, vocab_size)\n\n # if model has past, then set the past variable to speed up decoding\n if self._use_cache(outputs, use_cache):\n past = outputs[1]\n\n # repetition penalty (from CTRL paper https://arxiv.org/abs/1909.05858)\n if repetition_penalty != 1.0:\n self.enforce_repetition_penalty_(\n next_token_logits, batch_size, num_beams, input_ids, repetition_penalty,\n )\n\n if temperature != 1.0:\n next_token_logits = next_token_logits / temperature\n\n if self.config.is_encoder_decoder and do_sample is False:\n # TODO (PVP) still a bit hacky here - there might be a better solution\n next_token_logits = self.prepare_logits_for_generation(\n next_token_logits, cur_len=cur_len, max_length=max_length\n )\n\n scores = F.log_softmax(next_token_logits, dim=-1) # (batch_size * num_beams, vocab_size)\n\n # set eos token prob to zero if min_length is not reached\n if eos_token_id is not None and cur_len < min_length:\n scores[:, eos_token_id] = -float(\"inf\")\n\n if no_repeat_ngram_size > 0:\n # calculate a list of banned tokens to prevent repetitively generating the same ngrams\n num_batch_hypotheses = batch_size * num_beams\n # from fairseq: https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345\n banned_batch_tokens = calc_banned_ngram_tokens(\n input_ids, num_batch_hypotheses, no_repeat_ngram_size, cur_len\n )\n for i, banned_tokens in enumerate(banned_batch_tokens):\n scores[i, banned_tokens] = -float(\"inf\")\n\n if bad_words_ids is not None:\n # calculate a list of banned tokens according to bad words\n banned_tokens = calc_banned_bad_words_ids(input_ids, bad_words_ids)\n\n for i, banned_tokens in enumerate(banned_tokens):\n scores[i, banned_tokens] = -float(\"inf\")\n\n assert scores.shape == (batch_size * num_beams, vocab_size), \"Shapes of scores: {} != {}\".format(\n scores.shape, (batch_size * num_beams, vocab_size)\n )\n\n if do_sample:\n _scores = scores + beam_scores[:, None].expand_as(scores) # (batch_size * num_beams, vocab_size)\n # Top-p/top-k filtering\n _scores = top_k_top_p_filtering(\n _scores, top_k=top_k, top_p=top_p, min_tokens_to_keep=2\n ) # (batch_size * num_beams, vocab_size)\n # re-organize to group the beam together to sample from all beam_idxs\n _scores = _scores.contiguous().view(\n batch_size, num_beams * vocab_size\n ) # (batch_size, num_beams * vocab_size)\n\n # Sample 2 next tokens for each beam (so we have some spare tokens and match output of greedy beam search)\n probs = F.softmax(_scores, dim=-1)\n next_tokens = torch.multinomial(probs, num_samples=2 * num_beams) # (batch_size, num_beams * 2)\n # Compute next scores\n next_scores = torch.gather(_scores, -1, next_tokens) # (batch_size, num_beams * 2)\n # sort the sampled vector to make sure that the first num_beams samples are the best\n next_scores, next_scores_indices = torch.sort(next_scores, descending=True, dim=1)\n next_tokens = torch.gather(next_tokens, -1, next_scores_indices) # (batch_size, num_beams * 2)\n\n else:\n next_scores = scores + beam_scores[:, None].expand_as(scores) # (batch_size * num_beams, vocab_size)\n\n # re-organize to group the beam together (we are keeping top hypothesis accross beams)\n next_scores = next_scores.view(\n batch_size, num_beams * vocab_size\n ) # (batch_size, num_beams * vocab_size)\n\n next_scores, next_tokens = torch.topk(next_scores, 2 * num_beams, dim=1, largest=True, sorted=True)\n\n assert next_scores.size() == next_tokens.size() == (batch_size, 2 * num_beams)\n\n # next batch beam content\n next_batch_beam = []\n\n # for each sentence\n for batch_idx in range(batch_size):\n\n # if we are done with this sentence\n if done[batch_idx]:\n assert (\n len(generated_hyps[batch_idx]) >= num_beams\n ), \"Batch can only be done if at least {} beams have been generated\".format(num_beams)\n assert (\n eos_token_id is not None and pad_token_id is not None\n ), \"generated beams >= num_beams -> eos_token_id and pad_token have to be defined\"\n next_batch_beam.extend([(0, pad_token_id, 0)] * num_beams) # pad the batch\n continue\n\n # next sentence beam content\n next_sent_beam = []\n\n # next tokens for this sentence\n for beam_token_rank, (beam_token_id, beam_token_score) in enumerate(\n zip(next_tokens[batch_idx], next_scores[batch_idx])\n ):\n # get beam and token IDs\n beam_id = beam_token_id // vocab_size\n token_id = beam_token_id % vocab_size\n\n effective_beam_id = batch_idx * num_beams + beam_id\n # add to generated hypotheses if end of sentence or last iteration\n if (eos_token_id is not None) and (token_id.item() == eos_token_id):\n # if beam_token does not belong to top num_beams tokens, it should not be added\n is_beam_token_worse_than_top_num_beams = beam_token_rank >= num_beams\n if is_beam_token_worse_than_top_num_beams:\n continue\n generated_hyps[batch_idx].add(\n input_ids[effective_beam_id].clone(), beam_token_score.item(),\n )\n else:\n # add next predicted token if it is not eos_token\n next_sent_beam.append((beam_token_score, token_id, effective_beam_id))\n\n # the beam for next step is full\n if len(next_sent_beam) == num_beams:\n break\n\n # Check if were done so that we can save a pad step if all(done)\n done[batch_idx] = done[batch_idx] or generated_hyps[batch_idx].is_done(\n next_scores[batch_idx].max().item(), cur_len=cur_len\n )\n\n # update next beam content\n assert len(next_sent_beam) == num_beams, \"Beam should always be full\"\n next_batch_beam.extend(next_sent_beam)\n assert len(next_batch_beam) == num_beams * (batch_idx + 1)\n\n # stop when we are done with each sentence\n if all(done):\n break\n\n # sanity check / prepare next batch\n assert len(next_batch_beam) == batch_size * num_beams\n beam_scores = beam_scores.new([x[0] for x in next_batch_beam])\n beam_tokens = input_ids.new([x[1] for x in next_batch_beam])\n beam_idx = input_ids.new([x[2] for x in next_batch_beam])\n\n # re-order batch and update current length\n input_ids = input_ids[beam_idx, :]\n input_ids = torch.cat([input_ids, beam_tokens.unsqueeze(1)], dim=-1)\n cur_len = cur_len + 1\n\n # re-order internal states\n if past is not None:\n past = self._reorder_cache(past, beam_idx)\n\n # extend attention_mask for new generated input if only decoder\n if self.config.is_encoder_decoder is False:\n attention_mask = torch.cat(\n [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1\n )\n\n # finalize all open beam hypotheses and end to generated hypotheses\n for batch_idx in range(batch_size):\n if done[batch_idx]:\n continue\n\n # test that beam scores match previously calculated scores if not eos and batch_idx not done\n if eos_token_id is not None and all(\n (token_id % vocab_size).item() is not eos_token_id for token_id in next_tokens[batch_idx]\n ):\n assert torch.all(\n next_scores[batch_idx, :num_beams] == beam_scores.view(batch_size, num_beams)[batch_idx]\n ), \"If batch_idx is not done, final next scores: {} have to equal to accumulated beam_scores: {}\".format(\n next_scores[:, :num_beams][batch_idx], beam_scores.view(batch_size, num_beams)[batch_idx],\n )\n\n # need to add best num_beams hypotheses to generated hyps\n for beam_id in range(num_beams):\n effective_beam_id = batch_idx * num_beams + beam_id\n final_score = beam_scores[effective_beam_id].item()\n final_tokens = input_ids[effective_beam_id]\n generated_hyps[batch_idx].add(final_tokens, final_score)\n\n # depending on whether greedy generation is wanted or not define different output_batch_size and output_num_return_sequences_per_batch\n output_batch_size = batch_size if do_sample else batch_size * num_return_sequences\n output_num_return_sequences_per_batch = 1 if do_sample else num_return_sequences\n\n # select the best hypotheses\n sent_lengths = input_ids.new(output_batch_size)\n best = []\n\n # retrieve best hypotheses\n for i, hypotheses in enumerate(generated_hyps):\n sorted_hyps = sorted(hypotheses.beams, key=lambda x: x[0])\n for j in range(output_num_return_sequences_per_batch):\n effective_batch_idx = output_num_return_sequences_per_batch * i + j\n best_hyp = sorted_hyps.pop()[1]\n sent_lengths[effective_batch_idx] = len(best_hyp)\n best.append(best_hyp)\n\n # shorter batches are filled with pad_token\n if sent_lengths.min().item() != sent_lengths.max().item():\n assert pad_token_id is not None, \"`Pad_token_id` has to be defined\"\n sent_max_len = min(sent_lengths.max().item() + 1, max_length)\n decoded = input_ids.new(output_batch_size, sent_max_len).fill_(pad_token_id)\n\n # fill with hypothesis and eos_token_id if necessary\n for i, hypo in enumerate(best):\n decoded[i, : sent_lengths[i]] = hypo\n if sent_lengths[i] < max_length:\n decoded[i, sent_lengths[i]] = eos_token_id\n else:\n # none of the hypotheses have an eos_token\n assert (len(hypo) == max_length for hypo in best)\n decoded = torch.stack(best).type(torch.long).to(next(self.parameters()).device)\n\n return decoded\n","sub_path":"lobart_work/models/efficient_lobart_expC_integrated.py","file_name":"efficient_lobart_expC_integrated.py","file_ext":"py","file_size_in_byte":38527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"559550971","text":"def main():\n from ROOT import TFile\n import configurations as config\n\n infile = TFile(\"Templates.root\", \"READ\")\n infileCL = TFile(\"MI.root\", \"READ\")\n\n\n for Nmin in config.inclusive_multiplicities:\n\n texfile = open(\"latex/tableModelIndependentLimits_N%d.tex\" % Nmin, \"w\")\n #texfile.write(\"\\\\begin{table}\\n\")\n #texfile.write(\"\\\\centering\\n\")\n #texfile.write(\"\\\\begin{tabular}{*{6}r}\\n\")\n #texfile.write(\"\\\\hline\\n\")\n #texfile.write(\"$N^\\\\mathrm{min}$ & $S_T^{\\\\mathrm{min}}$ (TeV)\")\n #texfile.write(\"& $n^\\mathrm{data}$ & $n^\\\\mathrm{bkg}$ &\")\n #texfile.write(\"$\\\\sigma^{95}$ (pb)& $\\\\sigma^{95}_\\\\mathrm{exp.}$ (pb)\\\\\\\\\")\n #texfile.write(\"\\\\hline\\n\")\n\n hData = infile.Get(\"IntegralData_N%dup\" % Nmin)\n hBkg = infile.Get(\"IntegralBackground_N%dup\" % Nmin)\n\n gCL95 = infileCL.Get(\"CL95_N%dup\" % Nmin)\n gCLA = infileCL.Get(\"CLA_N%dup\" % Nmin)\n\n firstbin = hData.FindBin(1000)\n lastbin = hData.FindBin(config.MI_maxST)\n\n for i in range(firstbin, lastbin):\n STmin = hData.GetBinLowEdge(i)\n nData = hData.GetBinContent(i)\n nBkg = hBkg.GetBinContent(i)\n nBkgErr = hBkg.GetBinError(i)\n cl95 = gCL95.Eval(STmin)\n cla = gCLA.Eval(STmin)\n\n if nBkgErr > nBkg:\n texfile.write(\"%d & %.1f & %d & $%.2f ^{+%.2f}_{-%.2f}$ & %.4f & %.4f \\\\\\\\\\n\"\\\n % (Nmin, STmin/1000., nData, nBkg, nBkgErr, nBkg, cl95, cla))\n\n else:\n texfile.write(\"%d & %.1f & %d & $%.2f \\pm %.2f$ & %.4f & %.4f \\\\\\\\\\n\"\\\n % (Nmin, STmin/1000.0, nData, nBkg, nBkgErr, cl95, cla))\n\n #texfile.write(\"\\\\hline\\n\")\n #texfile.write(\"\\\\end{tabular}\\n\")\n #texfile.write(\"\\\\end{table}\")\n texfile.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"BHScripts_8TeV_postICHEP_Final_WithRun2012C_NewFitRange/genLatexTable.py","file_name":"genLatexTable.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"223613541","text":"def preprocess(book):\n ht = {} # hashtable\n for word in book.split():\n word = word.lower()\n if word == '':\n continue\n elif word not in ht:\n ht[word] = 1\n else:\n ht[word] += 1\n return ht\n\ndef get_frequency(word, ht):\n if ht == {} or word == None:\n return 0\n elif word.lower() not in ht:\n return 0\n else:\n return ht[word.lower()]\n\nbook = 'Once upon a time there was this book. \\\n This is a sentence. This is a much longer sentence. \\\n This is a terribly short example. But you get the idea. \\\n You should see the word this 6 times in this example text.'\n\nht = preprocess(book)\n\nword = 'this'\n\nprint('The word \"' + word + '\" appears ' + str(get_frequency(word, ht)) + ' times.')\n","sub_path":"Chapter16/16_2_WordFrequencies/16_2_RepetitiveQueries.py","file_name":"16_2_RepetitiveQueries.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"95880970","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport math\n\nz = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0]\nz_exp = [math.exp(i) for i in z]\nprint(z_exp)\nsum_z_exp = sum(z_exp)\nprint(sum_z_exp)\nsoftmax_z = [round(i / sum_z_exp, 3) for i in z_exp]\nprint(softmax_z)\nsum_softmax_z = sum(softmax_z)\nprint(sum_softmax_z)\n","sub_path":"softmax/softmax.py","file_name":"softmax.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"113929984","text":"import numpy as np\nfrom uncertainties import ufloat\nimport uncertainties.unumpy as unp\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\nn,w,t=np.genfromtxt('Messwerte_diffWirkungsquerschnitt.txt',unpack=True)\n\nrate=n/t\nFehler=np.sqrt(1/n)\nprint('Winkel',w)\nprint('Rate',rate)\nprint('Fehler der Rate',Fehler)\n#Konstanten\nEalpha=5.486\nmalpha=3727.38\neps0=8.85*(10**(-12))\n#eps0=1\nme=0.51\ne=1.602*(10**(-19))\n#e=1\nI=790\nc=3*(10**8)\n#Gold\nZ=79\nz=2\nAkt=330000\nrad=np.pi/180\n\n\nplt.plot(w,rate,'bx',label='Messwerte')\n\n\n#Raumwinkel\n\n#Blende\nx=0.002\ny=0.01\nl=0.45\nA=x*y\nR=4*np.arctan(x/(2*l))*np.arctan(y/(2*l))\nprint('Raumwinkel',R,'°^2')\n#R=32.29\n\n#RutherExp=\n\n\n#Theorie\nw=w*rad\nRutherford=R*(1/(4*3.141*eps0)**2)*(((z*Z*(e**2))/(4*Ealpha))**2)*(1/((np.sin(w/2))**4))\n\nwi=np.linspace(6,20)\nwi=wi*np.pi/180\nThe=(10**(-3))*1.3*(((z*Z)/Ealpha)**2)*(1/(np.sin(wi/2)**4))*R\n#print(The)\nplt.plot(wi*(180/np.pi),The,'r-',label='Theorie Kurve')\n#print('Theorie Werte',Rutherford)\n\n\n\nplt.legend(loc=\"best\")\nplt.xlim(-0.5,21)\nplt.xlabel(\"Streuwinkel in °\")\nplt.ylabel(\"Zählrate in 1/s\")\n\nplt.show()\n","sub_path":"fp/Rutherford_Experiment/Auswertung/DiffWirkungsquerschnitt.py","file_name":"DiffWirkungsquerschnitt.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"19503383","text":"import cv2\nimport numpy as np\nimport face_recognition\nimport os\n\nclass faceRec:\n def encodeImages(self,path):\n images = []\n classnames = []\n mylist = os.listdir(path)\n # print(mylist)\n\n for cl in mylist:\n curimg = cv2.imread(f'{path}/{cl}')\n images.append(curimg)\n classnames.append(os.path.splitext(cl)[0])\n # print(classnames)\n\n encodelist = []\n for img in images:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n encode = face_recognition.face_encodings(img)[0]\n encodelist.append(encode)\n # return encodelist,classnames\n np.save(\"./trained/encodelist.npy\", encodelist)\n np.save(\"./trained/classnames.npy\", classnames)\n\n def detectAndRecognize(self,encodelistpath,classnamepath):\n encodlistknown = np.load(encodelistpath)\n classnames = np.load(classnamepath)\n names = []\n cap = cv2.VideoCapture(0)\n while True:\n success,img = cap.read()\n imgS = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n facesCurrFrame = face_recognition.face_locations(imgS)\n encodesCurrFrame = face_recognition.face_encodings(imgS,facesCurrFrame)\n\n for encodeFace, faceloc in zip(encodesCurrFrame, facesCurrFrame):\n matches = face_recognition.compare_faces(encodlistknown, encodeFace)\n faceDis = face_recognition.face_distance(encodlistknown, encodeFace)\n # print(faceDis)\n matchIndex = np.argmin(faceDis)\n\n if matches[matchIndex]:\n name = classnames[matchIndex]\n y1, x2, y2, x1 = faceloc\n y1, x2, y2, x1 = y1, x2, y2, x1\n cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_DUPLEX, 1, (255, 255, 255), 2)\n else:\n print(\"NEW GUEST PLEASE REGISTER\")\n return 0\n cv2.imshow(\"Frame\", img)\n key = cv2.waitKey(1)\n if key == 27:\n break\n cap.release()\n cv2.destroyAllWindows()\n","sub_path":"module 2/facerecognition.py","file_name":"facerecognition.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"495185886","text":"from flask import (\n Blueprint, render_template, request, redirect, url_for, current_app, g, send_from_directory, flash\n)\nimport os\nimport re\nfrom werkzeug.utils import secure_filename\n\nbp = Blueprint('uploader', __name__, url_prefix='/')\nALLOWED_EXTENSIONS = set(['jpg', 'jpeg'])\n\ndef allowed_file(filename):\n \treturn '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@bp.route('/uploader_image_model')\ndef upload_model_page() :\n \n return render_template('uploader_image_model.html')\n\n@bp.route('/uploader_image_model', methods=['POST'])\ndef upload_image_model() :\n files = request.files.getlist(\"img_02[]\")\n\n for file in files:\n if file.filename == '' :\n flash('上傳檔案不能為空且檔案格式須為.jpg')\n return redirect(request.url)\n else:\n if file and allowed_file(file.filename):\n file_name = str(hash(g)) + file.filename\n file.save(os.path.join(current_app.config['INSTANCE_PATH']+\"/database\", file_name))\n flash(file_name)\n pass\n else:\n flash('上傳檔案不能為.png')\n return redirect(request.url)\n pass\n \n if len(files) >0:\n init_img_db_cmd()\n flash('File successfully uploaded')\n return redirect('/uploader_image_model')\n \ndef init_img_db_cmd() :\n # from ..widgts.IRE_Keras import index\n # index.init_img_db()\n # click.echo('Initialized the img database.')\n database = current_app.config['IMG_DATABASE_PATH']\n index = os.path.join(current_app.config['IMG_DATABASE_PATH'], 'imgset.file')\n command = current_app.config['CONDA_ACTIVATE'] + ' & python index.py -database %s -index %s' % (database, index)\n cwd = os.path.join(current_app.config['APP_ROOT'], 'widgts/IRE_Keras')\n\n import subprocess\n subprocess.run(command, cwd=cwd, shell=True)\n\ndef get_file_name(file_dir) :\n for root,dirs,files in os.walk(file_dir):\n return files\n \ndef get_filter_files_list(image_set):\n files =[]\n for image in image_set:\n if image.endswith('.jpg') != True :\n pass\n # elif image.endswith('.png') != True : #not sure png rank is ok?\n # pass\n else: \n files.append(image) \n \n return files\n\n\n@bp.route('/')\ndef upload_page() :\n results = get_filter_files_list(get_file_name(current_app.config['INSTANCE_PATH']+\"/database\"))\n \n return render_template('upload_page.html', results = results)\n\n@bp.route('/uploader', methods = [\"POST\"])\ndef uploader() :\n img_01_file = request.files['img_01']\n # if user does not select file, browser also submit an empty part without filename\n if img_01_file.filename == '' :\n return redirect(url_for(''))\n\n file_name = str(hash(g)) + img_01_file.filename\n img_01_file.save(os.path.join(current_app.config['INSTANCE_PATH'], file_name))\n\n # call query widget\n import subprocess\n query = os.path.join(current_app.config['INSTANCE_PATH'], file_name)\n index = os.path.join(current_app.config['IMG_DATABASE_PATH'], 'imgset.file')\n result = current_app.config['IMG_DATABASE_PATH']\n cwd = os.path.join(current_app.config['APP_ROOT'], 'widgts/IRE_Keras')\n command = current_app.config['CONDA_ACTIVATE'] + ' & python -m query_online -query %s -index %s -result %s' % (query, index, result)\n \n cp = subprocess.run(command, stdout=subprocess.PIPE, shell=True, cwd=cwd, text=True)\n # process return string to find target results\n results_str = re.findall('\\[\\'*.*\\'\\]', cp.stdout)[-1]\n \n results = list()\n \n for result_str in results_str.split(',') :\n result = dict()\n # get result pic file name and save it to result dict\n result_fname = result_str.strip('[]\\'\\n ')\n result['result'] = result_fname\n # find corresponding txt to get json string\n txt_match = re.search('\\..+$', result_fname)\n txt_fname = os.path.join(current_app.config['IMG_DATABASE_PATH'], result_fname[0 : txt_match.start()] + '.txt')\n try :\n with open(txt_fname) as f :\n result['result_json'] = f.read()\n f.close()\n except :\n result['result_json'] = None\n results.append(result)\n\n os.remove(os.path.join(current_app.config['INSTANCE_PATH'], file_name))\n return render_template('result.html', results = results)\n\n@bp.route('/image/', methods = [\"GET\",\"POST\"])\ndef img_render(img_name) :\n return send_from_directory(current_app.config['IMG_DATABASE_PATH'], img_name, mimetype='image/jpeg')","sub_path":"ImageTool/blueprints/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"566860429","text":"\"\"\" List Node implementation in Python with useful methods \"\"\"\n\nclass ListNode:\n def __init__(self, val=0):\n self.val = val\n self.next = None\n\n def to_ary(self):\n node = self\n result = []\n while node is not None:\n result.append(node.val)\n node = node.next\n return result\n\n @staticmethod\n def from_ary(lst):\n result = ListNode()\n node = result\n for nr in lst:\n node.next = ListNode()\n node.next.val = nr\n node = node.next\n return result.next\n\n @staticmethod\n def from_ary2(lst):\n result = None\n node = None\n for nr in lst:\n if node is None:\n node = ListNode()\n result = node\n else:\n node.next = ListNode()\n node = node.next\n node.val = nr\n return result\n\n def copy(self):\n result = ListNode()\n copy_node = result\n node = self\n while node is not None:\n copy_node.next = ListNode()\n copy_node = copy_node.next\n copy_node.val = node.val\n node = node.next\n return result.next\n\nif __name__ == '__main__':\n l1 = ListNode.from_ary([1,2,3,4])\n l2 = ListNode.from_ary2([1,2,3,4])\n print(l1.to_ary())\n print(l2.to_ary())\n print(l1.copy().to_ary())\n\n\"\"\"\nNote:\nWhen creating a linked list, there are 2 options:\n -Prepare the new node to add information and store on each iteration, but\n with this approach you end up with an empty node at the end that is \n hard to delete, one would need to go through all the list again\n -Create an initial dummy node and always store information on the next (best approach) (from_ary)\n -A variation (from_ary2) would be instead of creating a dummy node, check on each \n iteration the value of result and create a new one if it is None\n\"\"\"","sub_path":"linked_lists/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"528448185","text":"from django.contrib import admin\r\nfrom django_summernote.admin import SummernoteModelAdmin\r\nfrom adminsortable.admin import NonSortableParentAdmin, SortableStackedInline\r\n\r\nfrom .models import Post, Page, Category, MenuItem, GalleryPic, PageBlock\r\n\r\nadmin.site.site_header = 'Administrace stránek'\r\nadmin.site.site_title = 'ZŠ Bílá'\r\n\r\n\r\nclass PostAdmin(SummernoteModelAdmin):\r\n summernote_fields = '__all__'\r\n\r\n def save_model(self, request, obj, form, change):\r\n obj.post_long_text = obj.post_text.replace(\"
\", \"\")\r\n obj.post_short_text = obj.post_text.replace(obj.post_text.split('
')[-1], \"\").replace(\"
\", \"\")\r\n\r\n if obj.publisher is None:\r\n obj.publisher = request.user\r\n obj.save()\r\n\r\n\r\nclass PageBlockInline(SortableStackedInline):\r\n model = PageBlock\r\n extra = 0\r\n\r\n\r\nclass MenuItemInline(SortableStackedInline):\r\n model = MenuItem\r\n extra = 0\r\n\r\n\r\nclass PageAdmin(NonSortableParentAdmin):\r\n change_form_template_extends = 'zsbila/change_form.html'\r\n after_sorting_js_callback_name = 'after_sorting'\r\n inlines = [PageBlockInline]\r\n\r\n\r\nclass CategoryAdmin(NonSortableParentAdmin):\r\n inlines = [MenuItemInline]\r\n\r\n\r\nadmin.site.register(Category, CategoryAdmin)\r\nadmin.site.register(Post, PostAdmin)\r\nadmin.site.register(Page, PageAdmin)\r\nadmin.site.register(GalleryPic)\r\n","sub_path":"mysite/zsbila/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"629979568","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n#########\n#Copyright (C) 2014 Mark Spurgeon \n\t\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n#########\n\nfrom PyQt4 import QtGui,QtCore\nimport dbus\nimport dbus.service\nimport Config\nimport Main\nclass Window(QtGui.QMainWindow):\n\tdef __init__(self,parent=None):\n\t\tQtGui.QMainWindow.__init__(self, None,QtCore.Qt.WindowStaysOnTopHint|QtCore.Qt.FramelessWindowHint)#|QtCore.Qt.X11BypassWindowManagerHint)\n\t\tself.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n\t\tself.setAttribute(QtCore.Qt.WA_X11NetWmWindowTypeDock)\n\t\t#Values\n\t\td = QtGui.QDesktopWidget()\n\t\tself.top_pos= d.availableGeometry().y()\n\t\tself.parent=parent\n\t\tself.app={}\n\t\tself.conf=self.parent.conf\n\t\tself.drawButtonRect=False\n\t\tself.buttonRect=None\n\t\tself.width=200\n\t\tself.height=30*3\n\t\tself.y_pos=147\n\t\tself.size=int(Config.get()[\"size\"])\n\t\tself.r=int(Config.get()[\"r\"])\n\t\tself.g=int(Config.get()[\"g\"])\n\t\tself.b=int(Config.get()[\"b\"])\n\t\tself.move(self.size+10,self.y_pos+self.top_pos)\n\t\tself.resize(self.width+10,self.height+10)\n\tdef paintEvent(self,e):\n\t\tqp=QtGui.QPainter()\n\t\tqp.begin(self)\n\t\tqp.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform)\n\t\tqp.setPen(QtGui.QColor(int(self.r),int(self.g),int(self.b)))\n\t\tqp.setBrush(QtGui.QColor(int(self.r),int(self.g),int(self.b)))\n\t\tqp.drawRoundedRect(QtCore.QRectF(10,0,self.width-10,self.height),2,2)\n\t\tqp.setPen(QtGui.QColor(250,250,250,255))\n\t\tqp.setBrush(QtGui.QColor(250,250,250,255))\n\t\tqp.drawRect(9,0,5,self.height)\n\t\ticon=QtGui.QIcon(\"/usr/share/duck-launcher/icons/win.svg\")\n\t\ticon.paint(qp, -10,self.size/2-10, 20,20)\n\t\t#\n\t\tqp.setFont(QtGui.QFont(Config.get()[\"font\"],12))\n\t\tt_rect=QtCore.QRectF(10,0,self.width-10,30)\n\t\tqp.drawText(t_rect,QtCore.Qt.AlignCenter,self.app[\"name\"])\n\t\tqp.drawLine(26,30,self.width-20,30)\n\t\t#open\n\t\tif self.drawButtonRect==True and self.buttonRect!=None:\n\t\t\tqp.setPen(QtGui.QColor(0,0,0,0))\n\t\t\tqp.setBrush(QtGui.QColor(254,254,255,60))\n\t\t\tqp.drawRect(self.buttonRect)\n\t\t\t\n\t\tqp.setPen(QtGui.QColor(10,10,10,145))\n\t\tqp.setFont(QtGui.QFont(Config.get()[\"font\"],10))\n\t\to_rect=QtCore.QRectF(50,30,self.width-10,30)\n\t\tqp.drawText(o_rect,QtCore.Qt.AlignVCenter,\"Open\")\n\t\tremoveIcon=QtGui.QIcon(\"/usr/share/duck-launcher/icons/open.svg\")\n\t\tremoveIcon.paint(qp, 25,34,20,20)\n\t\t#remove\n\t\tqp.setPen(QtGui.QColor(12,10,10,140))\n\t\tr_rect=QtCore.QRectF(50,60,self.width-10,30)\n\t\tqp.drawText(r_rect, QtCore.Qt.AlignVCenter,\"Remove\")\n\t\tremoveIcon=QtGui.QIcon(\"/usr/share/duck-launcher/icons/remove.svg\")\n\t\tremoveIcon.paint(qp, 25,64,20,20)\n\tdef mouseMoveEvent(self,e):\n\t\tself.mousePressEvent(e)\n\tdef mousePressEvent(self,e):\n\t\tx_m,y_m=e.x(),e.y()\n\t\tself.drawButtonRect=False\n\t\tif 15 str:\n if noun[-1] == 's':\n return noun\n elif noun[0] in VOWELS:\n return f'an {noun}'\n else:\n return f'a {noun}'\n\n\ndef plural(noun: str) -> str:\n if noun[-1] == \"y\" and noun[-2] not in VOWELS:\n return f\"{noun[:-1]}ies\"\n elif noun[-2:] == \"is\":\n return f\"{noun[:-2]}es\"\n elif noun[-2:] == \"on\":\n return f\"{noun[:-2]}a\"\n elif noun.endswith((\"s\", \"ss\", \"sh\", \"ch\", \"x\", \"z\")):\n return f'{noun}es'\n else:\n return f\"{noun}s\"\n\n\n# Load irregular verbs\n# infinitive | simple past | past participle\nfile = open(\"irregular_verbs.csv\", \"r+\")\nheader = True\nirregular_verbs: Dict[str, Tuple[str, str, str]] = {}\nfor line in file:\n line = line.strip()\n if header:\n header = False\n continue\n if line != \"\":\n item = tuple(line.lower().split(\",\"))\n irregular_verbs[item[0]] = item\n\n\n# Verbs\ndef present_participle(verb: str) -> str:\n verb = verb.lower()\n if verb[-1] == 'e':\n return f'{verb[:-1]}ing'\n else:\n return f'{verb}ing'\n\n\ndef past_tense(verb: str) -> str:\n verb = verb.lower()\n if verb in irregular_verbs:\n return irregular_verbs[verb][1].split[\"/\"][0]\n elif verb[-1] == \"y\":\n return f\"{verb[:-1]}ied\"\n elif verb[-1] == 'e':\n return f\"{verb}d\"\n else:\n return f\"{verb}ed\"\n\n\ndef past_participle(verb: str) -> str:\n verb = verb.lower()\n if verb in irregular_verbs:\n return irregular_verbs[verb][2].split[\"/\"][0]\n elif verb[-1] == \"y\":\n return f\"{verb[:-1]}ied\"\n elif verb[-1] == 'e':\n return f\"{verb}d\"\n else:\n return f\"{verb}ed\"\n","sub_path":"grammar_checks.py","file_name":"grammar_checks.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"532596901","text":"'''Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.'''\n\n\na=17\nb=int(input(\"input the integer:\"))\nif b>a:\n c=b-a\n print(2*c)\nelse:\n print(a-b)","sub_path":"16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"115854946","text":"import argparse\r\nfrom datetime import datetime\r\nfrom pathlib import Path\r\nfrom typing import Tuple, Dict\r\n\r\nimport balance\r\nimport persistence\r\nimport price_fetcher as price\r\nfrom data_types import Security\r\n\r\n\r\ndef _set_argument_parser() -> argparse.ArgumentParser:\r\n default_data_directory = Path.home() / '.stock_balancer.data'\r\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\r\n\r\n parser.add_argument('-a', '--allocations_file',\r\n help='File containing the desired allocations of the securities to buy as tab-separated-values',\r\n default=str(default_data_directory / 'security_allocations.tsv'))\r\n parser.add_argument('-t', '--transactions_file',\r\n help='File containing the transactions of the current portfolio as tab-separated-values',\r\n default=str(default_data_directory / 'security_transactions.tsv'))\r\n\r\n subparsers = parser.add_subparsers(help='Subcommands')\r\n\r\n invest_parser = subparsers.add_parser('invest',\r\n description='Calculates the next investments that balance the portfolio',\r\n help='Additional help')\r\n invest_parser.add_argument('purchase_amount',\r\n help='Amount of money to be invested',\r\n type=float)\r\n invest_parser.add_argument('-n', '--max-count',\r\n help='Limit output to maximum of n purchases. Balancing will be approximate',\r\n type=int)\r\n invest_parser.set_defaults(which='invest')\r\n\r\n portfolio_parser = subparsers.add_parser('portfolio',\r\n description='Operations regarding the portfolio',\r\n help='Additional help')\r\n portfolio_parser.add_argument('--read',\r\n help='Reads the portfolio',\r\n action='store_true')\r\n portfolio_parser.add_argument('--get_historical_values',\r\n help='Gets the historical value of the portfolio',\r\n action='store_true')\r\n portfolio_parser.set_defaults(which='portfolio')\r\n\r\n return parser\r\n\r\n\r\ndef _read_persistence(args) -> Tuple[persistence.TransactionPersistence, persistence.AllocationPercentagesPersistence]:\r\n per = persistence\r\n transaction_persistence = per.TransactionPersistence(per.FileDataFrameIO(args.transactions_file))\r\n allocation_persistence = per.AllocationPercentagesPersistence(per.FileDataFrameIO(args.allocations_file))\r\n\r\n return transaction_persistence, allocation_persistence\r\n\r\n\r\ndef _get_portfolio_values(portfolio: Dict[Security, int]) -> Dict[Security, float]:\r\n return {\r\n sec: shares * price.get_price(security=sec, date=datetime.today()) for sec, shares in portfolio.items()\r\n }\r\n\r\n\r\ndef _print_security_dictionary(dictionary: dict):\r\n longest_security_name = max(dictionary.keys(), key=lambda sec: len(sec.identifier))\r\n longest_length = len(longest_security_name.identifier)\r\n\r\n for security, purchase in dictionary.items():\r\n security_name = (security.identifier + ':').ljust(longest_length + 2)\r\n print(f'{security_name}{purchase:.2f}')\r\n\r\n\r\ndef _process_invest_args(args):\r\n transaction_persistence, allocation_persistence = _read_persistence(args)\r\n purchase_amount = args.purchase_amount\r\n\r\n current_portfolio = transaction_persistence.read_portfolio()\r\n portfolio_values = _get_portfolio_values(current_portfolio)\r\n\r\n current_allocations = allocation_persistence.read_allocation_percentages()\r\n next_purchases = balance.calculate_next_purchases(portfolio_values, current_allocations, purchase_amount)\r\n\r\n if hasattr(args, 'max_count'):\r\n max_count = args.max_count\r\n next_purchases = balance.get_top_buy_purchases(next_purchases, max_count)\r\n\r\n print('Next purchases')\r\n print('--------------')\r\n _print_security_dictionary(next_purchases)\r\n\r\n\r\ndef _process_portfolio_args(args):\r\n transaction_persistence, allocation_persistence = _read_persistence(args)\r\n if args.read:\r\n portfolio = transaction_persistence.read_portfolio()\r\n portfolio_values = _get_portfolio_values(portfolio)\r\n\r\n print(' Portfolio')\r\n print('--------------')\r\n _print_security_dictionary(portfolio_values)\r\n\r\n if args.get_historical_values:\r\n historical_values = transaction_persistence.read_portfolio_history(price.get_price)\r\n print('Historical values')\r\n print('--------------')\r\n for date, value in historical_values.items():\r\n print(f'{date.strftime(\"%d.%m.%Y\")}: {value}')\r\n\r\n\r\ndef _main():\r\n parser = _set_argument_parser()\r\n args = parser.parse_args()\r\n if args.which == 'invest':\r\n _process_invest_args(args)\r\n elif args.which == 'portfolio':\r\n _process_portfolio_args(args)\r\n\r\n\r\nif __name__ == '__main__':\r\n _main()\r\n","sub_path":"stock_balancer.py","file_name":"stock_balancer.py","file_ext":"py","file_size_in_byte":5102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"140831750","text":"\"\"\"\nhttp://arxiv.org/abs/1504.00941\n\"\"\"\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport thu\n\n\ndef irnn_hook(nonlin=T.nnet.relu, scale=1):\n def identity_init(var):\n shape = var.get_value().shape\n assert len(shape) == 2\n assert shape[0] == shape[1]\n new_value = (scale * np.identity(shape[0])).astype(var.dtype)\n var.set_value(new_value)\n\n def replace_nonlinearity(hs):\n return nonlin(hs.kwargs[\"logit\"])\n\n def irnn_inner(hs):\n hs.hooks += [\n thu.inits.set_weight_init(\n identity_init,\n variable_scope=[\"simple_rnn\", \"h_to_h\"]),\n thu.filter_dsl(replace_nonlinearity,\n key=[\"nonlinearity\"],\n variable_scope=[\"simple_rnn\"]),\n ]\n return hs()\n\n return irnn_inner\n","sub_path":"thu/sandbox/irnn.py","file_name":"irnn.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"604236919","text":"# Try to implement the previous exercises using While loops.\n\nnumber = int(input(\"Enter a number to calculate the factorial: \"))\n\nfactorial = 1\ni = 1\n\nwhile i < number+1:\n factorial *= i\n i += 1\n\nprint(f\"The factorial value of !{number} is\", factorial)\n","sub_path":"Exercise 121. Use While Loops.py","file_name":"Exercise 121. Use While Loops.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"149307145","text":"#coding=utf-8\n\nfrom util import other_util as util\nimport Queue\nimport threading\nimport datetime\nimport time\n# import runtime\nimport socket\nimport re\nimport os\nimport traceback\nimport sys\n\n\nclass BaseTask(object):\n\n class PathConfig(object):\n result_file = os.path.join(os.getcwd(), '../data/etl_result.txt')\n etl_failids_file = os.path.join(os.getcwd(), '../data/etl_failids.txt')\n toc_failids_file = os.path.join(os.getcwd(), '../data/2c_failids.txt')\n\n def __init__(self, task_name, queue_size=200, thread_cnt=10):\n self._queue = Queue.Queue(queue_size)\n self._thread_cnt = thread_cnt\n self._end_mark = 0\n self._name = task_name\n self._start_timet = time.time()\n self._start_datetime = None\n self._running_count = 0\n self._worker_count = 0\n self._threads = []\n self._reporter = None\n self._dispatcher = None\n self.cur_jobid = 0\n self._mjob_count = 0\n self._mjob_all = '?'\n self._log_port = 9527\n\n self._tls = threading.local()\n self._r_locker = threading.RLock()\n\n def dispatcher(self, q):\n raise NotImplementedError(\"virtual function called\")\n\n def _job_runner(self, tid):\n with self._r_locker:\n self._worker_count += 1\n setattr(self._tls, 'tid', tid)\n end_this_thd = False\n while not end_this_thd:\n job, ismainjob = self._get_job()\n if job is None:\n self._dec_worker()\n return\n\n self.cur_jobid = job\n\n try:\n with self._r_locker:\n self._running_count += 1\n self.run_job(job)\n except Exception as e:\n util.Log.error(e)\n traceback.print_exc()\n finally:\n with self._r_locker:\n self._running_count -= 1\n\n self._dec_worker()\n\n def run_job(self, job):\n return False\n\n def _get_job(self):\n try:\n jobid = self._queue.get(True, 20)\n self._queue.task_done()\n if jobid is not None:\n with self._r_locker:\n self._mjob_count += 1\n return jobid, 0\n except Queue.Empty:\n return None, None\n\n def _dec_worker(self):\n with self._r_locker:\n self._worker_count -= 1\n if self._worker_count == 0:\n self._end_mark = 1\n\n def _load_data(self):\n return\n\n def start_operation(self, *args, **kwargs):\n return\n\n def run(self):\n\n self.start_operation()\n\n self._load_data()\n\n if (len(self._threads) > 0 or\n self._reporter is not None or\n self._dispatcher is not None):\n raise RuntimeError(\"already run??\")\n\n self._start_datetime = datetime.datetime.now()\n self._threads = []\n self.cur_jobid = 0\n self._end_mark = 0\n self._worker_count = 0\n\n self._job_count = 0\n self._mjob_count = 0\n self._mjob_all = '?'\n\n # 日志报告 udp查看\n self._reporter = threading.Thread(target=self.report)\n self._reporter.start()\n # runtime.Runtime.set_thread_name(self._reporter.ident, \"%s.job.reporter\" % self._name)\n\n # 任务分发\n self._dispatcher = threading.Thread(target=self.dispatcher, args=(self._queue, ))\n self._dispatcher.start()\n # runtime.Runtime.set_thread_name(self._dispatcher.ident, \"%s.job.dispatcher\" % self._name)\n\n for i in range(0, self._thread_cnt):\n t = threading.Thread(target=self._job_runner, args=(i,))\n t.start()\n # runtime.Runtime.set_thread_name(t.ident, \"%s.worker.%d\" % (self._name, i))\n self._threads.append(t)\n\n self.event_handler('STARTED', '')\n self.wait_run(True)\n\n self.end_operation()\n\n def wait_run(self, report=False):\n for t in self._threads:\n t.join()\n self._end_mark = 1\n self._dispatcher.join()\n self._reporter.join()\n self._dispatcher = None\n self._reporter = None\n self._end_mark = 0\n self._threads = []\n if report:\n endtime = datetime.datetime.now()\n timespan = str(endtime - self._start_datetime)\n reportstr = \"prog:%s\\nlast job is %s\\nDONE time used:%s\\n\" % (' '.join(sys.argv), str(self.cur_jobid), timespan)\n reportstr += \"mj: %d \" % (self._mjob_count)\n sys.stderr.write(reportstr)\n self.event_handler('DONE', reportstr)\n\n def event_handler(self, evt, msg, **kwargs):\n return\n\n def end_operation(self, *args, **kwargs):\n return\n\n def report(self):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n while 1:\n time.sleep(2)\n prog = \"mj:%d/%s\\n wc:%d \\n rc:%d\" % (self._mjob_count, self._mjob_all, self._worker_count, self._running_count)\n if isinstance(self.cur_jobid, dict) and 'url' in self.cur_jobid:\n cjstr = util.utf8str(self.cur_jobid['url'])\n else:\n cjstr = util.utf8str(self.cur_jobid)\n cjstr = re.sub(r'\\r|\\n', '', cjstr)\n if len(cjstr) > 100:\n cjstr = cjstr[0:100]\n\n message = \"[pid=%d]job:%s prog:%s\\n\" % (os.getpid(), cjstr, prog)\n try:\n s.sendto(message, (\"127.0.0.1\", self._log_port))\n except Exception as e:\n pass\n if self._end_mark:\n message = \"[pid=%d] DONE\\n\" % (os.getpid())\n try:\n s.sendto(message, (\"127.0.0.1\", self._log_port))\n except:\n pass\n return\n\n def wait_q(self):\n lt = 0\n while True:\n while not self._queue.empty():\n self._queue.join()\n if time.time() < lt + 1 and self._running_count==0:\n return True\n time.sleep(2)\n lt = time.time()\n\n\n\n\n\n\n\n\n\n","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"550920866","text":"#!/usr/bin/env python\n#\n# LSST Data Management System\n# Copyright 2008-2015 AURA/LSST.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\n\"\"\"\nSubtasks for creating the reference catalogs used in forced measurement.\n\"\"\"\n\nimport lsst.afw.geom\nimport lsst.pex.config\nimport lsst.pipe.base\n\n__all__ = (\"BaseReferencesTask\", \"CoaddSrcReferencesTask\")\n\n\nclass BaseReferencesConfig(lsst.pex.config.Config):\n removePatchOverlaps = lsst.pex.config.Field(\n doc=\"Only include reference sources for each patch that lie within the patch's inner bbox\",\n dtype=bool,\n default=True\n )\n filter = lsst.pex.config.Field(\n doc=\"Bandpass for reference sources; None indicates chi-squared detections.\",\n dtype=str,\n optional=True\n )\n\n\nclass BaseReferencesTask(lsst.pipe.base.Task):\n \"\"\"!\n Base class for forced photometry subtask that retrieves reference sources.\n\n BaseReferencesTask defines the required API for the references task, which includes:\n - getSchema(butler)\n - fetchInPatches(butler, tract, filter, patchList)\n - fetchInBox(self, butler, tract, filter, bbox, wcs)\n - the removePatchOverlaps config option\n\n It also provides the subset() method, which may be of use to derived classes when\n reimplementing fetchInBox.\n \"\"\"\n\n ConfigClass = BaseReferencesConfig\n\n def __init__(self, butler=None, schema=None, **kwargs):\n \"\"\"!Initialize the task.\n\n BaseReferencesTask and its subclasses take two keyword arguments beyond the usual Task arguments:\n - schema: the Schema of the reference catalog\n - butler: a butler that will allow the task to load its Schema from disk.\n At least one of these arguments must be present; if both are, schema takes precedence.\n \"\"\"\n lsst.pipe.base.Task.__init__(self, **kwargs)\n\n def getSchema(self, butler):\n \"\"\"!\n Return the schema for the reference sources.\n\n Must be available even before any data has been processed.\n \"\"\"\n raise NotImplementedError(\"BaseReferencesTask is pure abstract, and cannot be used directly.\")\n\n def getWcs(self, dataRef):\n \"\"\"!\n Return the WCS for reference sources. The given dataRef must include the tract in its dataId.\n \"\"\"\n raise NotImplementedError(\"BaseReferencesTask is pure abstract, and cannot be used directly.\")\n\n def fetchInBox(self, dataRef, bbox, wcs):\n \"\"\"!\n Return reference sources that overlap a region defined by a pixel-coordinate bounding box\n and corresponding Wcs.\n\n @param[in] dataRef ButlerDataRef; the implied data ID must contain the 'tract' key.\n @param[in] bbox a afw.geom.Box2I or Box2D that defines the region in pixel coordinates\n @param[in] wcs afw.image.Wcs that maps the bbox to sky coordinates\n\n @return an iterable of reference sources\n\n It is not required that the returned object be a SourceCatalog; it may be any Python iterable\n containing SourceRecords (including a lazy iterator).\n\n The returned set of sources should be complete and close to minimal.\n \"\"\"\n raise NotImplementedError(\"BaseReferencesTask is pure abstract, and cannot be used directly.\")\n\n def fetchInPatches(self, dataRef, patchList):\n \"\"\"!\n Return reference sources that overlap a region defined by one or more SkyMap patches.\n\n @param[in] dataRef ButlerDataRef; the implied data ID must contain the 'tract' key.\n @param[in] patchList list of skymap.PatchInfo instances for which to fetch reference sources\n\n @return an iterable of reference sources\n\n It is not required that the returned object be a SourceCatalog; it may be any Python sequence\n containing SourceRecords (including a lazy iterator).\n\n The returned set of sources should be complete and close to minimal. If\n config.removePatchOverlaps is True, only sources within each patch's \"inner\" bounding box\n should be returned.\n \"\"\"\n raise NotImplementedError(\"BaseReferencesTask is pure abstract, and cannot be used directly.\")\n\n def subset(self, sources, bbox, wcs):\n \"\"\"!\n Filter sources to contain only those within the given box, defined in the coordinate system\n defined by the given Wcs.\n\n @param[in] sources input iterable of SourceRecords\n @param[in] bbox bounding box with which to filter reference sources (Box2I or Box2D)\n @param[in] wcs afw.image.Wcs that defines the coordinate system of bbox\n\n Instead of filtering sources directly via their positions, we filter based on the positions\n of parent objects, then include or discard all children based on their parent's status. This\n is necessary to support ReplaceWithNoise in measurement, which requires all child sources have\n their parent present.\n\n @return an iterable of filtered reference sources\n\n This is not a part of the required BaseReferencesTask interface; it's a convenience function\n used in implementing fetchInBox that may be of use to subclasses.\n \"\"\"\n boxD = lsst.afw.geom.Box2D(bbox)\n # We're passed an arbitrary iterable, but we need a catalog so we can iterate\n # over parents and then children.\n catalog = lsst.afw.table.SourceCatalog(self.schema)\n catalog.extend(sources)\n # catalog must be sorted by parent ID for lsst.afw.table.getChildren to work\n catalog.sort(lsst.afw.table.SourceTable.getParentKey())\n # Iterate over objects that have no parent.\n parentSources = catalog.getChildren(0)\n skyCoordList = [source.getCoord() for source in parentSources]\n pixelPosList = wcs.skyToPixel(skyCoordList)\n for parent, pixel in zip(parentSources, pixelPosList):\n if boxD.contains(pixel):\n yield parent\n for child in catalog.getChildren(parent.getId()):\n yield child\n\n\nclass CoaddSrcReferencesConfig(BaseReferencesTask.ConfigClass):\n coaddName = lsst.pex.config.Field(\n doc=\"Coadd name: typically one of deep or goodSeeing.\",\n dtype=str,\n default=\"deep\",\n )\n skipMissing = lsst.pex.config.Field(\n doc=\"Silently skip patches where the reference catalog does not exist.\",\n dtype=bool,\n default=False\n )\n\n def validate(self):\n if (self.coaddName == \"chiSquared\") != (self.filter is None):\n raise lsst.pex.config.FieldValidationError(\n field=CoaddSrcReferencesConfig.coaddName,\n config=self,\n msg=\"filter may be None if and only if coaddName is chiSquared\"\n )\n\n\nclass CoaddSrcReferencesTask(BaseReferencesTask):\n \"\"\"!\n A references task implementation that loads the coadd_datasetSuffix dataset directly from\n disk using the butler.\n \"\"\"\n\n ConfigClass = CoaddSrcReferencesConfig\n datasetSuffix = \"src\" # Suffix to add to \"Coadd_\" for dataset name\n\n def __init__(self, butler=None, schema=None, **kwargs):\n \"\"\"! Initialize the task.\n Additional keyword arguments (forwarded to BaseReferencesTask.__init__):\n - schema: the schema of the detection catalogs used as input to this one\n - butler: a butler used to read the input schema from disk, if schema is None\n The task will set its own self.schema attribute to the schema of the output merged catalog.\n \"\"\"\n BaseReferencesTask.__init__(self, butler=butler, schema=schema, **kwargs)\n if schema is None:\n assert butler is not None, \"No butler nor schema provided\"\n schema = butler.get(\"{}Coadd_{}_schema\".format(self.config.coaddName, self.datasetSuffix),\n immediate=True).getSchema()\n self.schema = schema\n\n def getWcs(self, dataRef):\n \"\"\"Return the WCS for reference sources. The given dataRef must include the tract in its dataId.\n \"\"\"\n skyMap = dataRef.get(self.config.coaddName + \"Coadd_skyMap\", immediate=True)\n return skyMap[dataRef.dataId[\"tract\"]].getWcs()\n\n def fetchInPatches(self, dataRef, patchList):\n \"\"\"!\n An implementation of BaseReferencesTask.fetchInPatches that loads 'coadd_' + datasetSuffix\n catalogs using the butler.\n\n The given dataRef must include the tract in its dataId.\n \"\"\"\n dataset = \"{}Coadd_{}\".format(self.config.coaddName, self.datasetSuffix)\n tract = dataRef.dataId[\"tract\"]\n butler = dataRef.butlerSubset.butler\n for patch in patchList:\n dataId = {'tract': tract, 'patch': \"%d,%d\" % patch.getIndex()}\n if self.config.filter is not None:\n dataId['filter'] = self.config.filter\n\n if not butler.datasetExists(dataset, dataId):\n if self.config.skipMissing:\n continue\n raise lsst.pipe.base.TaskError(\"Reference %s doesn't exist\" % (dataId,))\n self.log.info(\"Getting references in %s\" % (dataId,))\n catalog = butler.get(dataset, dataId, immediate=True)\n if self.config.removePatchOverlaps:\n bbox = lsst.afw.geom.Box2D(patch.getInnerBBox())\n for source in catalog:\n if bbox.contains(source.getCentroid()):\n yield source\n else:\n for source in catalog:\n yield source\n\n def fetchInBox(self, dataRef, bbox, wcs, pad=0):\n \"\"\"!\n Return reference sources that overlap a region defined by a pixel-coordinate bounding box\n and corresponding Wcs.\n\n @param[in] dataRef ButlerDataRef; the implied data ID must contain the 'tract' key.\n @param[in] bbox a afw.geom.Box2I or Box2D that defines the region in pixel coordinates\n @param[in] wcs afw.image.Wcs that maps the bbox to sky coordinates\n @param[in] pad a buffer to grow the bounding box by after catalogs have been loaded, but\n before filtering them to include just the given bounding box.\n\n @return an iterable of reference sources\n \"\"\"\n skyMap = dataRef.get(self.config.coaddName + \"Coadd_skyMap\", immediate=True)\n tract = skyMap[dataRef.dataId[\"tract\"]]\n coordList = [wcs.pixelToSky(corner) for corner in lsst.afw.geom.Box2D(bbox).getCorners()]\n self.log.info(\"Getting references in region with corners %s [degrees]\" %\n \", \".join(\"(%s)\" % (coord.getPosition(lsst.afw.geom.degrees),) for coord in coordList))\n patchList = tract.findPatchList(coordList)\n # After figuring out which patch catalogs to read from the bbox, pad out the bbox if desired\n # But don't add any new patches while padding\n if pad:\n bbox.grow(pad)\n return self.subset(self.fetchInPatches(dataRef, patchList), bbox, wcs)\n\n\nclass MultiBandReferencesConfig(CoaddSrcReferencesTask.ConfigClass):\n\n def validate(self):\n if self.filter is not None:\n raise lsst.pex.config.FieldValidationError(\n field=MultiBandReferencesConfig.filter,\n config=self,\n msg=\"Filter should not be set for the multiband processing scheme\")\n # Delegate to ultimate base class, because the direct one has a check we don't want.\n BaseReferencesTask.ConfigClass.validate(self)\n\n\nclass MultiBandReferencesTask(CoaddSrcReferencesTask):\n \"\"\"Loads references from the multiband processing scheme\"\"\"\n ConfigClass = MultiBandReferencesConfig\n datasetSuffix = \"ref\"\n","sub_path":"python/lsst/meas/base/references.py","file_name":"references.py","file_ext":"py","file_size_in_byte":12431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"624733755","text":"#! /usr/bin/env python\n\nimport json, httplib\n\nclass Sender:\n def send(self, data):\n d = self.__chunks(data, 20)\n for r in d:\n j = {\"requests\" : r}\n self.__send(j)\n\n def __send(self, data):\n self.connection = httplib.HTTPSConnection('api.parse.com', 443)\n self.connection.connect()\n self.connection.request('POST', '/1/batch',\n json.dumps(data),\n {\n \"X-Parse-Application-Id\" : \"1IaZeSQCiWI0jkNoXNt1skvtnvKDYbnoCuj8zaLk\",\n \"X-Parse-REST-API-Key\" : \"YvL38iXOO287N3acjafpcOPZWtP7LX58XANjngzp\",\n \"X-Parse-Session-Token\" : \"jpu1u8kkfacjgngws1yikhwey\",\n \"Content-Type\" : \"application/json\"\n }\n )\n\n def __chunks(self, l, n):\n return [l[i:i+n] for i in range(0, len(l), n)]\n\n\n# j = []\n\n\n# for i in xrange(333):\n# s = str(i)\n# d = {\n# \"method\": \"POST\",\n# \"path\": \"/1/classes/Technology\",\n# \"body\": {\n# \"link\":\"http\" + s ,\n# \"title\":\"Sean\" + s,\n# \"body\":\"f\" + s\n# }\n# }\n# j.append(d)\n\n\n# #print j\n# Sender().send(j)\n","sub_path":"scrapers/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"7396931","text":"# TicTacToe\r\n\r\nthe_board = {7: ' ', 8: ' ', 9: ' ',\r\n 4: ' ', 5: ' ', 6: ' ',\r\n 1: ' ', 2: ' ', 3: ' '}\r\ntheBoard = the_board.copy()\r\n\r\n\r\ndef draw_board(board):\r\n print(f'''\r\n {board[7]}|{board[8]}|{board[9]}\r\n -+-+-\r\n {board[4]}|{board[5]}|{board[6]}\r\n -+-+-\r\n {board[1]}|{board[2]}|{board[3]}''')\r\n\r\ndef restart():\r\n if game_over:\r\n res = input('Restart?(y/n): ')\r\n if res.lower() == 'y':\r\n global theBoard\r\n theBoard = the_board.copy()\r\n game()\r\n else:\r\n print(\"thanks for playing!!!\".title())\r\n\r\n \r\n \r\ndef game():\r\n turn = 'O'\r\n count = 9\r\n global game_over\r\n game_over = False\r\n \r\n \r\n def tw(): # short for \"{turn} wins\"\r\n print(f\"\"\" _________ \r\n|{turn} wins!! |\r\n|Game Over|\r\n-----------\"\"\")\r\n\r\n global game_over\r\n game_over = True\r\n\r\n\r\n def check_winner():\r\n \r\n if theBoard[7] == theBoard[8] == theBoard[9] != ' ':\r\n tw()\r\n elif theBoard[4] == theBoard[5] == theBoard[6] != ' ':\r\n tw()\r\n elif theBoard[1] == theBoard[2] == theBoard[3] != ' ':\r\n tw()\r\n \r\n elif theBoard[7] == theBoard[4] == theBoard[1] != ' ':\r\n tw()\r\n elif theBoard[8] == theBoard[5] == theBoard[2] != ' ':\r\n tw()\r\n elif theBoard[9] == theBoard[6] == theBoard[3] != ' ':\r\n tw()\r\n \r\n elif theBoard[7] == theBoard[5] == theBoard[3] != ' ':\r\n tw()\r\n elif theBoard[1] == theBoard[5] == theBoard[9] != ' ':\r\n tw()\r\n\r\n# Game Loop\r\n\r\n while count > 0 and not game_over:\r\n \r\n draw_board(theBoard)\r\n inp = int(input(f\"{turn}'s turn. Where to move?: \"))\r\n \r\n if inp in theBoard and theBoard[inp] == ' ':\r\n theBoard[inp] = turn\r\n count -= 1\r\n\r\n check_winner()\r\n \r\n if turn == 'O':\r\n turn = 'X'\r\n else:\r\n turn = 'O'\r\n else:\r\n print(\"Invalid Move.\".upper())\r\n \r\n else:\r\n draw_board(theBoard)\r\n if count <= 0 and not game_over: \r\n print(\"It's a tie.\")\r\n restart()\r\n \r\n\r\nif __name__ == \"__main__\":\r\n game()\r\n \r\n","sub_path":"CLI.py","file_name":"CLI.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"25428537","text":"#!/usr/bin/python\n\n#import picamera\nfrom time import sleep\nimport cv2\nimport io\nimport numpy as np\nimport imutils\n\nimport os\nimport sys\nimport re\n\nfrom datetime import datetime\nfrom PIL import Image\nfrom pyzbar import pyzbar\n\nimport requests\nimport json\n######################\n### Initialization ###\n######################\n#camera = picamera.PiCamera()\ntray_ID_cache = ''\n\n##################\n### User Input ###\n##################\n#ID of this CVID/camera\nCVID_id=0\n# Motion detection sensitivity\nmin_area = 500\npast_frame= None\n\n\ncapture_delays = 0.1\n# Cooling time for Setting camera\ncooling_delays = 0.1\n# Saving path of captured ambience Raw img\ntray_img_path = '/home/pi/Desktop/YANG_XG/testimages/Video0_tray_img.jpg'\n# Saving path of QR captured Raw img\nQR_img_path = '/home/pi/Desktop/YANG_XG/testimages/Video0_QR_img.jpg'\n# Saving path of QR captured Binarized img\nQR_img_BIN_path = '/home/pi/Desktop/YANG_XG/testimages/Video0_Bin.jpg'\n# Saving path of stability analysis imgs\nsta_anls0_path = '/home/pi/Desktop/YANG_XG/testimages/Video0_sta_anls0.jpg'\nsta_anls1_path = '/home/pi/Desktop/YANG_XG/testimages/Video0_sta_anls1.jpg'\n#A set of binarization thresholds\n#lighter version\nthre_tab=[20,30,40,60,70,80,90,100,110,120,140,160,180,200,212]\n#darker version\n#thre_tab=[192,168,60,40,150,160,180,207,212]\n# URL of RTD-API\nurl = \"http://st-mct-vm31/tracking/api/container/update/camera/info\"\nheader = {}\ntxt_name = \"temp_log.txt\"\n\n#####################################\n### Func: Camera Setting by v4l2 ###\n#####################################\n\n# fps : min=15 max=30 default=30 \n# brightness 0x00980900 (int) : min=-64 max=64 step=1 default=0 value=0\n# contrast 0x00980901 (int) : min=0 max=95 step=1 default=32 value=32\n# saturation 0x00980902 (int) : min=0 max=128 step=1 default=55 value=55\n# white_balance_temperature_auto 0x0098090c (bool) : default=1 value=1\n# white_balance_temperature 0x0098091a (int) : min=2800 max=6500 step=1 default=4600 value=2800 flags=inactive\n# backlight_compensation 0x0098091c (int) : min=0 max=3 step=1 default=1 value=1\n# exposure_auto 0x009a0901 (menu) : min=0 max=3 default=3 value=3\n# exposure_absolute 0x009a0902 (int) : min=1 max=5000 step=1 default=179 value=179 flags=inactive\n# exposure_auto_priority 0x009a0903 (bool) : default=0 value=1\ndef Camera_Setting():\n #setting attributes\n fps = \"15\"\n brightness = \"64\"\n contrast = \"12\"\n saturation = \"55\"\n white_balance_temperature_auto = \"1\"\n white_balance_temperature = \"5000\"\n backlight_compensation = \"3\"\n exposure_auto = \"3\"\n exposure_absolute = \"179\"\n exposure_auto_priority = \"0\"\n #setting commands\n os.system(\"v4l2-ctl -d /dev/video0 --set-parm={}\".format(fps))\n os.system(\"v4l2-ctl -d /dev/video0 --set-ctrl={}={}\".format('brightness',brightness))\n os.system(\"v4l2-ctl -d /dev/video0 --set-ctrl={}={}\".format('contrast',contrast))\n os.system(\"v4l2-ctl -d /dev/video0 --set-ctrl={}={}\".format('saturation',saturation))\n os.system(\"v4l2-ctl -d /dev/video0 --set-ctrl={}={}\".format('white_balance_temperature_auto',white_balance_temperature_auto))\n os.system(\"v4l2-ctl -d /dev/video0 --set-ctrl={}={}\".format('white_balance_temperature',white_balance_temperature))\n os.system(\"v4l2-ctl -d /dev/video0 --set-ctrl={}={}\".format('backlight_compensation',backlight_compensation))\n os.system(\"v4l2-ctl -d /dev/video0 --set-ctrl={}={}\".format('exposure_auto',exposure_auto))\n os.system(\"v4l2-ctl -d /dev/video0 --set-ctrl={}={}\".format('exposure_absolute',exposure_absolute))\n os.system(\"v4l2-ctl -d /dev/video0 --set-ctrl={}={}\".format('exposure_auto_priority',exposure_auto_priority))\n print('Camera setting finished.')\n\n \n\n#################################\n### Func: Upload Information ###\n#################################\ndef RTD_API_Post(url,para,header):\n try:\n r = requests.post(url,data=para,headers=header)\n print(\"Status:\",r.status_code)\n json_r = r.json()\n print(json_r)\n except BaseException as e:\n print(\"RTD-API posting fails\",str(e))\n\n#############################\n##### Func: TXT Writing ####\n#############################\ndef Txt_Write(file_name,contents):\n while True:\n infos = str(datetime.now())+' '+contents+'\\n'\n try:\n with open (file_name,'a') as f:\n #f.write(now)\n f.write(infos)\n break\n except:\n print('Writing failed. Retrying...')\n break\n\n\n###############################\n###### uvc_camera capture #####\n###############################\ndef uvc_capture(filepath):\n #kindly notice command \"/dev/video0\" using physical address, do not use \"/dev/video0\" \n commands = \"fswebcam -d /dev/video0 --no-banner -r 1280x720 {}\".format(filepath)\n capture = os.system(commands)\n#if \"--- Opening /dev/device0... stat: No such file or directory\" means the device dedicated to incorrect USBports\n\n\n#####################################\n### Func: Preprocess & Decode QR ###\n#####################################\ndef decoder(threshold,file_path1,file_path2):#Input is the binarization threshold\n \n #Preprocessing\n img_tmp = Image.open(file_path1)\n img_tmp_BL = img_tmp.convert('L')#Convert to gray img\n\n table = []\n for i in range(256):\n if i < threshold:\n table.append(0)\n else:\n table.append(1)\n \n #Binarize the image\n img_tmp_BIN = img_tmp_BL.point(table,'1')\n img_tmp_BIN.save(file_path2)\n\n #Decode QR\n with open(file_path2,'rb') as image_file:\n image = Image.open(image_file)\n image.load()\n \n #this is for testing, to be removed and toggle another line \n #codes=pyzbar.decode(Image.open(file_path_static))\n codes=pyzbar.decode(Image.open(file_path2)) \n return(codes)\n\n###############################\n### Func: Top of Decode QR ###\n###############################\ndef decoder_top(thre_tab,QR_img_path,QR_img_BIN_path,flag):\n\n global tray_ID_cache\n# sta_anls()\n #Decoding by going thru all thres\n for thres in thre_tab:\n codes=decoder(thres,QR_img_path,QR_img_BIN_path)\n if codes!=[]:\n break\n \n # Print results\n if codes==[]:\n if flag == 0:\n print('Ambient Lights too low, CVID disabled')\n now = datetime.now()\n print(str(now))\n #contents={\"CameraId\":str(CVID_id),\"TrayId\":\"C0000\",\"Existance\":\"0\"}\n #RTD_API_Post(url,contents,header)\n \n elif flag == 1:\n print('Tray detected but no QR codes detected')\n now = datetime.now()\n print(str(now))\n contents={\"CameraId\":str(CVID_id),\"TrayId\":\"D0000\",\"Existance\":\"1\"}\n tray_ID_cache = 'D0000'\n RTD_API_Post(url,contents,header)\n #Refresh DataLog\n Txt_Write(txt_name,'Unknown Tray~\\n')\n\n else:\n if tray_ID_cache != '':\n print('Tray removed')\n now = datetime.now()\n print(str(now))\n contents={\"CameraId\":str(CVID_id),\"TrayId\":str(tray_ID_cache),\"Existance\":\"0\"}\n RTD_API_Post(url,contents,header)\n # Reset Tray_ID_cache\n tray_ID_cache = ''\n #Refresh DataLog\n Txt_Write(txt_name,'Tray removed~\\n')\n\n else:\n print('No tray detected, false alarm')\n now = datetime.now()\n print(str(now)) \n else:\n #To extract data from obj codes\n tmp=codes[0].data \n print('QR codes on Device0: %s' % tmp.decode('utf-8'))\n tray_ID_cache = tmp.decode('utf-8')\n now = datetime.now()\n print(str(now))\n contents={\"CameraId\":str(CVID_id),\"TrayId\":str(tmp.decode('utf-8')),\"Existance\":\"1\"}\n RTD_API_Post(url,contents,header)\n #Refresh DataLog\n Txt_Write(txt_name,str(tmp.decode('utf-8')))\n return tray_ID_cache\n\n#################################\n### Func: Stability analysis ###\n#################################\ndef sta_anls():\n while True:\n uvc_capture(sta_anls0_path)\n #convert image into a binary byte stream\n imageArr0 = CVTI2B(sta_anls0_path)\n data0 = np.frombuffer(imageArr0 , dtype=np.uint8)\n frame0 = cv2.imdecode(data0, 1)\n (h0, w0) = frame0.shape[:2]\n r0 = 500 / float(w0)\n dim0 = (500, int(h0 * r0))\n frame0 = cv2.resize(frame0, dim0, cv2.INTER_AREA) # We resize the frame\n gray0 = cv2.cvtColor(frame0, cv2.COLOR_BGR2GRAY) # We apply a black & white filter\n gray0 = cv2.GaussianBlur(gray0, (21, 21), 0) # Then we blur the picture\n\n uvc_capture(sta_anls1_path)\n #convert image into a binary byte stream\n imageArr1 = CVTI2B(sta_anls1_path)\n data1 = np.frombuffer(imageArr1 , dtype=np.uint8)\n frame1 = cv2.imdecode(data1, 1)\n (h1, w1) = frame1.shape[:2]\n r1 = 500 / float(w1)\n dim1 = (500, int(h1 * r1))\n frame1 = cv2.resize(frame1, dim1, cv2.INTER_AREA) # We resize the frame\n gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) # We apply a black & white filter\n gray1 = cv2.GaussianBlur(gray1, (21, 21), 0) # Then we blur the picture\n\n#if necessary??\n# (h_gray0, w_gray0) = gray0.shape[:2]\n# (h_gray1, w_gray1) = gray1.shape[:2]\n# if h_gray0 != h_gray1 or w_gray0 != w_gray1: # This shouldnt occur but this is error handling\n# print('Two frames do not have the same sizes {0} {1} {2} {3}'.format(h_gray0, w_gray0, h_gray1, w_gray1))\n# return\n\n # compute the absolute difference between the current frame and first frame\n frame_delta = cv2.absdiff(gray0, gray1)\n # then apply a threshold to remove camera motion and other false positives (like light changes)\n thresh = cv2.threshold(frame_delta, 50, 255, cv2.THRESH_BINARY)[1]\n # dilate the thresholded image to fill in holes, then find contours on thresholded image\n thresh = cv2.dilate(thresh, None, iterations=2)\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n # notice the opencv 4 returns variables in new sequence--Written by Yang Xinge 24/Feb/2020\n cnts = cnts[1] if imutils.is_cv2() else cnts[0]\n stability_flag = 1\n for c in cnts:\n # if the contour is too small, ignore it\n if cv2.contourArea(c) > min_area:\n stability_flag = 0\n if stability_flag == 1:\n print(\"The frame is stable!\")\n break\n else:\n print(\"The frame is unstable!\")\n\n\n\n###########################\n### Func: Tray sensing ###\n###########################\ndef Tray_sense(delays,file_path):\n# camera.start_preview()\n# camera.resolution = (1280, 960)\n# camera.brightness = 70\n# camera.contrast = 50\n# camera.iso = 200\n# camera.image_effect = 'denoise'\n sleep(delays)\n uvc_capture(file_path)\n# camera.capture(file_path)\n# camera.stop_preview()\n im = cv2.imread(file_path,0)\n (mean,stddv) = cv2.meanStdDev(im)\n #low gray_value means dark environment, cannot work\n if mean < 50:\n return 0\n #gray_value in the middle means tray existing\n elif mean < 100:\n return 1\n #high gray_value means no tray\n else:\n return 2\n\n##############################\n### Func: Frame Comparison ###\n##############################\ndef handle_new_frame(frame, past_frame, min_area,usbport_num):\n\n (h, w) = frame.shape[:2]\n r = 500 / float(w)\n dim = (500, int(h * r))\n frame = cv2.resize(frame, dim, cv2.INTER_AREA) # We resize the frame\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # We apply a black & white filter\n gray = cv2.GaussianBlur(gray, (21, 21), 0) # Then we blur the picture\n\n # if the first frame is None, initialize it because there is no frame for comparing the current one with a previous one\n if past_frame is None:\n past_frame = gray\n return past_frame\n\n # check if past_frame and current have the same sizes\n (h_past_frame, w_past_frame) = past_frame.shape[:2]\n (h_current_frame, w_current_frame) = gray.shape[:2]\n if h_past_frame != h_current_frame or w_past_frame != w_current_frame: # This shouldnt occur but this is error handling\n print('Past frame and current frame do not have the same sizes {0} {1} {2} {3}'.format(h_past_frame, w_past_frame, h_current_frame, w_current_frame))\n return\n\n # compute the absolute difference between the current frame and first frame\n frame_delta = cv2.absdiff(past_frame, gray)\n # then apply a threshold to remove camera motion and other false positives (like light changes)\n thresh = cv2.threshold(frame_delta, 50, 255, cv2.THRESH_BINARY)[1]\n # dilate the thresholded image to fill in holes, then find contours on thresholded image\n thresh = cv2.dilate(thresh, None, iterations=2)\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n # notice the opencv 4 returns variables in new sequence--Written by Yang Xinge 24/Feb/2020\n cnts = cnts[1] if imutils.is_cv2() else cnts[0]\n\n # loop over the contours\n for c in cnts:\n # if the contour is too small, ignore it\n if cv2.contourArea(c) < min_area:\n continue\n print(\"Motion detected on usbport{}!\".format(usbport_num))\n now2 = datetime.now()\n print(str(now2))\n #If there is already an existance of tray,\n #Then, make an advanced response.\n if tray_ID_cache != '':\n print('Tray removed.')\n now = datetime.now()\n print(str(now))\n contents={\"CameraId\":str(CVID_id),\"TrayId\":str(tray_ID_cache),\"Existance\":\"0\"}\n RTD_API_Post(url,contents,header)\n #Refresh DataLog\n Txt_Write(txt_name,'Tray removed~\\n')\n \n else:\n sta_anls()\n #Wait for motion still\n #sleep(capture_delays)\n #Judge existance of Tray\n tray_flag=Tray_sense(cooling_delays,tray_img_path)\n #QR Capture \n uvc_capture(QR_img_path)\n #Img_Capture(camera,brightness,contrast,iso,cooling_delays,QR_img_path) \n #Decode QR \n decoder_top(thre_tab,QR_img_path,QR_img_BIN_path,tray_flag)\n gray = None\n break\n #return gray to prevent to capturing a new frame\n return gray\n\n######################################\n###### Convert Image to BytesArr #####\n######################################\ndef CVTI2B(QR_img_path):\n ext = \"jpg\"\n im = Image.open(QR_img_path,mode = 'r')\n stream = io.BytesIO()\n imgformat = Image.registered_extensions()['.'+ext]\n im.save(stream,imgformat)\n imgByteArr = stream.getvalue()\n return imgByteArr\n\n######################\n###### Main Body #####\n######################\nif __name__ == '__main__':\n past_frame = None\n print(\"Starting motion detection\")\n Camera_Setting()\n now = datetime.now()\n get_usbport_num = os.popen(\"udevadm info --attribute-walk --name=/dev/video0 |grep KERNELS\")\n usbport_num = get_usbport_num.read()[18:19]\n print('USB Port'+usbport_num)\n print(str(now))\n try:\n while True:\n #capture an image by using os command\n #capture = os.system(\"fswebcam --no-banner -r 1280x720 testimages/imagetest1.jpg\")\n uvc_capture(QR_img_path)\n #convert image into a binary byte stream\n imageArr = CVTI2B(QR_img_path)\n data = np.frombuffer(imageArr , dtype=np.uint8)\n frame = cv2.imdecode(data, 1)\n\n if frame is not None:\n past_frame = handle_new_frame(frame, past_frame, min_area, usbport_num)\n #print(past_frame)\n else:\n print(\"No more frame\")\n finally:\n print(\"Exiting\")","sub_path":"UVC_Video0_CVID_RPi_for_RTD_V15.py","file_name":"UVC_Video0_CVID_RPi_for_RTD_V15.py","file_ext":"py","file_size_in_byte":16096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"450003085","text":"import os\nfrom .korpora import Korpus, SentencePairKorpusData\nfrom .utils import fetch, default_korpora_path, load_wikitext\n\n\nNAMUWIKI_FETCH_INFORMATION = [\n {\n 'url': 'https://github.com/lovit/namuwikitext/releases/download/v0.1/namuwikitext_20200302.v0.1.train.zip',\n 'destination': 'namiwiki/namuwikitext_20200302.train.zip',\n 'method': 'download & unzip'\n },\n {\n 'url': 'https://github.com/lovit/namuwikitext/releases/download/v0.1/namuwikitext_20200302.v0.1.test.zip',\n 'destination': 'namiwiki/namuwikitext_20200302.test.zip',\n 'method': 'download & unzip'\n },\n {\n 'url': 'https://github.com/lovit/namuwikitext/releases/download/v0.1/namuwikitext_20200302.v0.1.dev.zip',\n 'destination': 'namiwiki/namuwikitext_20200302.dev.zip',\n 'method': 'download & unzip'\n }\n]\n\ndescription = \"\"\" Author : Hyunjoong Kim lovit@github\n Repository : https://github.com/lovit/namuwikitext\n References :\n\n 나무위키의 덤프 데이터를 바탕을 제작한 wikitext 형식의 텍스트 파일입니다.\n 학습 및 평가를 위하여 위키페이지 별로 train (99%), dev (0.5%), test (0.5%) 로 나뉘어져있습니다.\n\"\"\"\n\nlicense = \" CC BY-NC-SA 2.0 KR which Namuwiki dump dataset is licensed\"\n\n\nclass NamuwikiTextKorpusData(SentencePairKorpusData):\n \"\"\"\n Args:\n description (str) : data description\n texts (list of str) : namuwiki contents including '\\n'\n pairs (list of str) : title\n \"\"\"\n def __init__(self, description, texts, pairs):\n super().__init__(description, texts, pairs)\n\n\nclass NamuwikiTextKorpus(Korpus):\n def __init__(self, root_dir=None, force_download=False):\n super().__init__(description, license)\n\n if root_dir is None:\n root_dir = default_korpora_path\n fetch_namuwikitext(root_dir, force_download)\n\n for information in NAMUWIKI_FETCH_INFORMATION:\n destination = information['destination']\n local_path = os.path.join(os.path.abspath(root_dir), destination[:-4])\n\n if 'train' in destination:\n response = input(\n 'NamuwikiText.train text file is large (5.3G).'\n 'If you want to load text in your memory, please insert `yes`').lower()\n if (len(response) == 1 and response == 'y') or (response == 'yes'):\n texts, titles = self.load(local_path)\n self.train = NamuwikiTextKorpusData(description, texts, titles)\n else:\n dirname = os.path.abspath(f'{root_dir}/namiwiki')\n self.train = f'Namuwikitext corpus is downloaded. Open local directory {dirname}'\n print('Continue to load `dev` and `test`')\n continue\n\n texts, titles = self.load(local_path)\n if 'dev' in destination:\n self.dev = NamuwikiTextKorpusData(description, texts, titles)\n elif 'test' in destination:\n self.test = NamuwikiTextKorpusData(description, texts, titles)\n else:\n raise ValueError(f'Check local files')\n\n def load(self, path):\n def split_title_text(wikitext):\n lines = wikitext.split('\\n')\n title = lines[0]\n text = '\\n'.join([line.strip() for line in lines[2:] if line.strip()])\n return title, text\n\n wikitexts = load_wikitext(path)\n wikitexts = [split_title_text(wikitext) for wikitext in wikitexts]\n titles, texts = zip(*wikitexts)\n # swap position\n return texts, titles\n\n\ndef fetch_namuwikitext(root_dir, force_download):\n for information in NAMUWIKI_FETCH_INFORMATION:\n url = information['url']\n destination = information['destination']\n local_path = os.path.join(os.path.abspath(root_dir), destination)\n fetch(url, local_path, 'namuwikitext', force_download, information['method'])\n","sub_path":"Korpora/korpus_namuwiki.py","file_name":"korpus_namuwiki.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"453087146","text":"SMALL_NUMBER = 1e-7\nBIG_NUMBER = 1e7\n\nBITS_PER_BYTE = 8\nMIN_PRECISION = 1\nMAX_PRECISION = 16\nMIN_WIDTH = 5\nSHIFT_BITS = 4\n\nMAX_SHIFT_GROUPS = 6\nMIN_SHIFT_GROUPS = 4\nMAX_SHIFT_GROUPS_FACTOR = 0.05\n\nLENGTH_SIZE = 2\nLENGTH_ORDER = 'little'\n\nPERIOD = 4\nBT_FRAME_SIZE = 20\n\nPOLICIES = ['random', 'uniform', 'adaptive_heuristic', 'adaptive_deviation', 'skip_rnn']\nENCODING = ['standard', 'group', 'group_unshifted', 'single_group', 'padded', 'pruned']\nENCRYPTION = ['stream', 'block']\nCOLLECTION = ['tiny', 'low', 'med', 'high']\n","sub_path":"adaptiveleak/utils/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"261754853","text":"import hoomd\nfrom hoomd.conftest import pickling_check\n\n\ndef test_attach(simulation_factory, two_particle_snapshot_factory):\n sim = simulation_factory(two_particle_snapshot_factory(dimensions=3, d=8))\n integrator = hoomd.md.Integrator(.05)\n integrator.methods.append(hoomd.md.methods.Langevin(hoomd.filter.All(), kT=0))\n integrator.forces.append(hoomd.md.force.Active(filter=hoomd.filter.All(), rotation_diff=0.01))\n sim.operations.integrator = integrator\n sim.operations._schedule()\n sim.run(10)\n\n\ndef test_pickling(simulation_factory, two_particle_snapshot_factory):\n sim = simulation_factory(two_particle_snapshot_factory())\n active = hoomd.md.force.Active(\n filter=hoomd.filter.All(), rotation_diff=0.01)\n pickling_check(active)\n integrator = hoomd.md.Integrator(\n .05,\n methods=[hoomd.md.methods.Langevin(hoomd.filter.All(), kT=0)],\n forces=[active]\n )\n sim.operations.integrator = integrator\n sim.run(0)\n pickling_check(active)\n","sub_path":"hoomd/md/pytest/test_active.py","file_name":"test_active.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"234895445","text":"from setuptools import setup, find_packages\r\n\r\nlong_desc = '''\r\nThis package is a Chisel domain for Sphinx.\r\n'''\r\n\r\nrequires = ['Sphinx>=0.6',\r\n 'sphinxcontrib-domaintools>=0.1']\r\n\r\nsetup(\r\n name='sphinx-chisel',\r\n version='0.1',\r\n author='John Andrews',\r\n description='Chisel domain for Sphinx',\r\n long_description=long_desc,\r\n zip_safe=False,\r\n platforms='any',\r\n packages=find_packages(exclude=['sample*']),\r\n include_package_data=False,\r\n install_requires=requires,\r\n namespace_packages=['chisel']\r\n)\r\n","sub_path":"sphinx-chisel-workspace/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"519252449","text":"'''\n同時併發 (concurrency) 執行 for-loop 搭配使用 async 來執行\n - asyncio.gather() 併發運行任務\n\n情境是有三個任務,分別為執行 10, 2, 4 次的 for-loop,三個任務會併發式執行處理完畢後,由return 的 task 接收。\n\nReference:\n - https://docs.python.org/zh-tw/3/library/asyncio-task.html\n\n'''\nimport asyncio\nimport time\n\n\nasync def sum(task_name, max_nums):\n start_time = time.time()\n \n for i in range(max_nums):\n print(f'task {task_name}: i={i}')\n await asyncio.sleep(1)\n \n end_time = time.time()\n total_time = end_time - start_time\n print(f'task {task_name} spend time: {total_time}')\n \n return total_time\n\n\nasync def main():\n start_time = time.time()\n \n task = await asyncio.gather(\n sum('1', 10),\n sum('2', 2),\n sum('3', 4),\n )\n \n end_time = time.time()\n total_time = end_time - start_time\n \n # 會將 task 內的任務執行完畢後的結果,存到 task list 裡面。\n print(task)\n \n # 原本三個任務,總共會需要 10 + 2 + 4 = 16秒,但使用 concurrency則加快速度僅需要 10秒多\n print('total_time', total_time)\n \nasyncio.run(main())","sub_path":"async_IO/coroutines/ex/for_loop_async.py","file_name":"for_loop_async.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"310898582","text":"import numpy as np\nimport emcee\nimport corner\nfrom astropy import constants\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import simps\nfrom astropy.coordinates import Distance\nimport os\nfrom scipy.integrate import quad\n\n\ndef lin_mod(m,c,mag):\n return m*mag + c\n\ndef lnlike(theta,mag,error,val):\n m,c = theta\n ll = 0\n diff = val - lin(m,c,mag)\n sig = (diff**2)/((error**2))\n ll = -1 * np.sum(sig)\n\n return ll\n\ndef fit_lin_model(theta0,mags,vals,errs,crange,mrange):\n m0,c0 = theta0\n mags = np.array(mags)\n vals = np.array(vals)\n errs = np.array(errs)\n nwalkers = 100\n minit = m0 + mrange*np.random.random(nwalkers)\n cinit = c0 + crange*np.random.random(nwalkers)\n ndim = np.shape(theta0)[0]\n \n pos = [np.array(x) for x in zip(minit,cinit)]\n \n sampler = emcee.EnsembleSampler(nwalkers,ndim,lnlike,args=(mags,errs,vals))\n \n sampler.run_mcmc(pos,600)\n \n samples = sampler.chain[:,100:,:].reshape(-1,ndim)\n \n m_mcmc,c_mcmc = map(lambda v: (v[1],v[2] - v[1],v[1]-v[0]),zip(*np.percentile(samples,[32,50,68],axis=0)))\n \n return m_mcmc,c_mcmc\n\n\ndef get_line(m_mcmc,c_mcmc,start_mag,stop_mag):\n \n mags = np.array(range(start_mag,stop_mag,0.01))\n \n mod_vals = lin_mod(m_mcmc[0],c_mcmc[0],mags)\n \n return mod_vals,mags\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"linear_fitter.py","file_name":"linear_fitter.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"592140104","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom swagger_server.models.base_model_ import Model\nfrom swagger_server import util\n\n\nclass History(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, email: str=None, _from: datetime=None, to: datetime=None): # noqa: E501\n \"\"\"History - a model defined in Swagger\n\n :param email: The email of this History. # noqa: E501\n :type email: str\n :param _from: The _from of this History. # noqa: E501\n :type _from: date\n :param to: The to of this History. # noqa: E501\n :type to: date\n \"\"\"\n self.swagger_types = {\n 'email': str,\n '_from': datetime,\n 'to': datetime\n }\n\n self.attribute_map = {\n 'email': 'email',\n '_from': 'from',\n 'to': 'to'\n }\n\n self._email = email\n self.__from = _from\n self._to = to\n\n @classmethod\n def from_dict(cls, dikt) -> 'History':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The History of this History. # noqa: E501\n :rtype: History\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def email(self) -> str:\n \"\"\"Gets the email of this History.\n\n\n :return: The email of this History.\n :rtype: str\n \"\"\"\n return self._email\n\n @email.setter\n def email(self, email: str):\n \"\"\"Sets the email of this History.\n\n\n :param email: The email of this History.\n :type email: str\n \"\"\"\n\n self._email = email\n\n @property\n def _from(self) -> datetime:\n \"\"\"Gets the _from of this History.\n\n\n :return: The _from of this History.\n :rtype: date\n \"\"\"\n return self.__from\n\n @_from.setter\n def _from(self, _from: datetime):\n \"\"\"Sets the _from of this History.\n\n\n :param _from: The _from of this History.\n :type _from: date\n \"\"\"\n\n self.__from = _from\n\n @property\n def to(self) -> datetime:\n \"\"\"Gets the to of this History.\n\n\n :return: The to of this History.\n :rtype: date\n \"\"\"\n return self._to\n\n @to.setter\n def to(self, to: datetime):\n \"\"\"Sets the to of this History.\n\n\n :param to: The to of this History.\n :type to: date\n \"\"\"\n\n self._to = to\n","sub_path":"swagger_server/models/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"326996561","text":"from .utils import init_experiment, make_session\n\n\ndef create_recording(model, simulator, dir_name):\n reward = 0.0\n while reward is not None:\n state = simulator.get_state()\n action = model.action(state)\n reward = simulator.take_action(action)\n\n simulator.save_recording(dir_name)\n\ndef record_mode(settings):\n session = make_session() # parallel session\n model, simulator = init_experiment(settings, session, record=True)\n create_recording(model, simulator, settings['__runtime__']['savedir'])\n","sub_path":"deeprl/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"59911966","text":"from __future__ import print_function\n\nimport config as cfg\nimport numpy as np\nimport tensorflow as tf\nfrom utils import no_op, nest_log, normalize\nfrom utils.tf_utils import axial_reshape, split_reshape, tf_shape, net_size\nfrom tensorflow.contrib.framework import nest\nimport sys\n\nslim = tf.contrib.slim\n\nimport os\n\nfn_repo = os.getenv('FN_REPO')\nsys.path.append(fn_repo)\nfrom correlation import correlation as xcor\n\ndef normalizer_no_op(x, *a, **k):\n \"\"\" passthrough normalization \"\"\"\n return x\n\ndef upsample(x):\n \"\"\" upsample source to 2x \"\"\"\n h, w = x.get_shape().as_list()[1:3]\n return tf.image.resize_images(x, (2*h,2*w), align_corners=True)\n\ndef upconv(x, f, *a, **k):\n \"\"\" simple up-convolution \"\"\"\n with tf.name_scope('upconv', [x]):\n x = upsample(x)\n x = f(x, *a, **k)\n return x\n\ndef epe(x, y):\n \"\"\" endpoint error \"\"\"\n with tf.name_scope('epe', [x,y]):\n e = tf.square(y-x)\n e = tf.reduce_sum(e, axis=-1, keepdims=True)\n e = tf.sqrt(e)\n return e\n\ndef xcor_feat(f,\n d=10,\n s_h=1,\n s_w=2,\n log=no_op\n ):\n \"\"\" compute feature-field cross-correlation \"\"\"\n with tf.name_scope('xcor_feat', [f]):\n h, w = tf_shape(f)[1:3]\n f_ab = split_reshape(f, 0, 2)\n fa, fb = tf.unstack(f_ab, axis=1)\n # a, b, kernel_size, max_disp, stride-1, stride_2, pad\n fxf = xcor(fa, fb, 1, d*2, s_h, s_w, d*2)\n fxf = tf.nn.elu(fxf)\n log('coverage : ({:.0%}x{:.0%})'.format(d/float(h), d/float(w)))\n log('shape : {}'.format(fxf.shape))\n return fxf\n\ndef merge_feat(f, log=no_op):\n \"\"\" merge 2x-stacked feature streams into channel axis \"\"\"\n f = split_reshape(f, 0, 2) # Nx2/2, 2, ...\n f = axial_reshape(f, [0,2,3,(4,1)])\n return f\n\nclass FlowNetBB(object):\n def __init__(self, step, learning_rate=None,\n img=None, lab=None,\n train=True, eval=True,\n reuse=None, log=print):\n self.img_ = img\n self.lab_ = lab\n\n self.col_ = [('train' if train else 'valid')]\n self.learning_rate_ = (cfg.LEARNING_RATE if (learning_rate is None) else learning_rate)\n self.step_ = step\n self.train_ = train\n self.eval_ = eval\n self.reuse_ = reuse\n self.log_ = log\n\n self.build(log=print)\n\n def _build_input(self, log=no_op):\n \"\"\" build input part \"\"\"\n with tf.name_scope('input'):\n img = tf.placeholder(tf.float32, \n [None, 2, cfg.IMG_HEIGHT, cfg.IMG_WIDTH, cfg.IMG_DEPTH], name='img')\n if self.eval_:\n lab = tf.placeholder(tf.float32,\n [None, cfg.IMG_HEIGHT, cfg.IMG_WIDTH, 3], name='lab') # flow label, (di,dj,mask)\n else:\n lab = None\n self.img_ = img\n self.lab_ = lab\n\n def _build_cnn(self, x, log=no_op):\n \"\"\" build contraction part \"\"\"\n log('- build-cnn -')\n # see vo_net.VONet for reference here\n\n with tf.name_scope('build_cnn', [x]):\n with tf.name_scope('format_in'):\n log('cnn-input', x.shape)\n x = axial_reshape(x, [(0,1), 2, 3, 4]) # (merge \"time\" with batch)\n log('cnn-format', x.shape)\n with tf.name_scope('cnn'):\n with slim.arg_scope(self._arg_scope()):\n with slim.arg_scope([slim.conv2d, slim.separable_conv2d],\n outputs_collections=['cnn-feats']):\n x = slim.conv2d(x, 64, 7, 2, scope='conv', padding='SAME')\n x = slim.stack(x,\n slim.separable_conv2d,\n [(128,3,1,2),(256,3,1,2),(196,1,1,1),(384,3,1,2),(256,1,1,1),(512,3,1,2),(512,1,1,1)],\n scope='sconv',\n padding='SAME',\n )\n log('post-sconv', x.shape) #NTx4x5\n\n log('-------------')\n xs = slim.utils.convert_collection_to_dict('cnn-feats')\n\n log('- feats -')\n for (k,v) in xs.items():\n log(k,v)\n log('---------')\n\n xs = [xs[s] for s in [\n 'vo/sconv/sconv_1', #48x64\n 'vo/sconv/sconv_3', #24x32\n 'vo/sconv/sconv_5', #12x16\n 'vo/sconv/sconv_7', #6x8\n ]]\n\n if cfg.FN_USE_XCOR:\n log('- xcor -')\n # d, s_h, s_w\n xcor_args = [\n (7, 1, 1), #48x64x ((2*7+1)**2 == 361), win ~ (0.1875 x 0.140625)\n (5, 1, 1), #24x32x ((2*5+1)**2 == 225), win ~ (0.2916' x 0.21875)\n (3, 1, 1), #12x16x ((2*3+1)**2 == 121), win ~ (0.416' x 0.3125)\n (3, 1, 1), #6x8x ((2*3+1)**2 == 49), win ~ (0.5x0.375)\n ]\n xs = [xcor_feat(x,*a,log=log) for (x,a) in zip(xs,xcor_args)]\n log('--------')\n else:\n log('- merge -')\n xs = [merge_feat(x) for x in xs]\n log('---------')\n\n log('- xs -')\n for x in xs:\n log(x.name, x.shape)\n log('------')\n return xs\n\n def _build_tcnn(self, xs, img, log=no_op):\n \"\"\" build expansion part \"\"\"\n # Nx1024 --> Nx240x320\n def to_flow(fx_in, pad='SAME', scope='flow'):\n return slim.conv2d(fx_in, 2, 3, padding=pad,\n activation_fn=None,\n normalizer_fn=normalizer_no_op,\n scope=scope,\n outputs_collections='flow'\n )\n\n log('- build-tcnn -')\n with tf.name_scope('build_tcnn', [xs]):\n with slim.arg_scope(self._arg_scope()):\n with slim.arg_scope([slim.conv2d, slim.separable_conv2d],\n outputs_collections=['tcnn-feats']):\n # objective : (15x20), (30x40), (60x80), (120x160), (240x320)\n #x = slim.separable_conv2d(x, 256, 1, stride=1, padding='SAME') # feat reduction\n #log('tcnn-rdc', x.shape)\n x = slim.separable_conv2d(xs[3], 1024, 3, stride=1, padding='SAME')\n f0 = to_flow(x, scope='flow_0')\n log('xs-0', x.shape)\n log('flow-0', f0.shape)\n\n #x = slim.conv2d_transpose(x, 128, 3, stride=2, padding='SAME')\n c, s = slim.conv2d, slim.separable_conv2d\n x = upconv(x, s, 512, 3, stride=1, padding='SAME')\n f0u = upconv(f0, c, 2, 3, stride=1, padding='SAME',\n activation_fn=None,\n normalizer_fn=normalizer_no_op\n )\n x = tf.concat([x, xs[2], f0u],axis=-1)\n f1 = to_flow(x, scope='flow_1')\n log('xs-1', x.shape)\n log('flow-1', f1.shape)\n\n x = upconv(x, s, 256, 3, stride=1, padding='SAME')\n f1u = upconv(f1, c, 2, 3, stride=1, padding='SAME',\n activation_fn=None,\n normalizer_fn=normalizer_no_op\n )\n x = tf.concat([x, xs[1], f1u], axis=-1)\n f2 = to_flow(x, scope='flow_2')\n log('xs-1', x.shape)\n log('flow-1', f2.shape)\n\n x = upconv(x, s, 128, 3, stride=1, padding='SAME')\n f2u = upconv(f2, c, 2, 3, stride=1, padding='SAME',\n activation_fn=None,\n normalizer_fn=normalizer_no_op\n )\n x = tf.concat([x, xs[0], f2u], axis=-1)\n f3 = to_flow(x, scope='flow_3')\n log('xs-2', x.shape)\n log('flow-2', f3.shape)\n\n x = upconv(x, s, 64, 3, stride=1, padding='SAME')\n f3u = upconv(f3, c, 2, 3, stride=1, padding='SAME',\n activation_fn=None,\n normalizer_fn=normalizer_no_op\n )\n x = tf.concat([x, f3u], axis=-1)\n f4 = to_flow(x, scope='flow_4')\n log('xs-3', x.shape)\n log('flow-3', f4.shape)\n\n x = upconv(x, s, 32, 3, stride=1, padding='SAME')\n f4u = upconv(f4, c, 2, 3, stride=1, padding='SAME',\n activation_fn=None,\n normalizer_fn=normalizer_no_op\n )\n img2 = axial_reshape(img, [0,2,3,(4,1)])\n x = tf.concat([x, f4u, img2], axis=-1)\n x = to_flow(x, pad='SAME', scope='flow_5')\n log('xs-4', x.shape)\n log('flow-4', x.shape)\n\n fs = slim.utils.convert_collection_to_dict('flow').values()\n log('--------------')\n return x, fs\n\n def _build_err(self, xs, y, log=no_op):\n \"\"\" build error part \"\"\"\n def err_x(f, y):\n with tf.name_scope('err_x', [f, y]):\n h0, w0 = y.get_shape().as_list()[1:3]\n h, w = f.get_shape().as_list()[1:3]\n y_rsz = tf.image.resize_images(y, (h,w), align_corners=True)\n flo, msk = tf.split(y_rsz, [2,1], axis=-1)\n\n # scale flow appropriately\n rsz_s = [tf.cast(w,tf.float32)/w0, tf.cast(h, tf.float32)/h0]\n rsz_s = tf.reshape(rsz_s, [1,1,1,2])\n flo_s = flo * rsz_s # scaled flow\n\n err = epe(f, flo_s)\n #err = tf.sqrt(tf.reduce_sum(tf.square(f-y_rsz),\n # axis=-1,keepdims=True))\n err = tf.reduce_sum(err * msk) / tf.reduce_sum(msk)\n return err\n\n log('- build-err -')\n errs = {}\n with tf.name_scope('build-err', [xs,y]):\n for f in xs:\n h, w = f.get_shape().as_list()[1:3]\n key = 'err_{}x{}'.format(w,h)\n errs[key] = err_x(f, y)\n ks = ['err_8x6', 'err_16x12','err_32x24', 'err_64x48', 'err_128x96', 'err_256x192']\n\n # decay weight per size of flow-image\n err_scale = tf.train.exponential_decay(cfg.FN_ERR_SCALE,\n self.step_, cfg.FN_ERR_SCALE_DECAY_STEPS, cfg.FN_ERR_SCALE_DECAY_FACTOR, staircase=False)\n\n # opt1 : dynamic error weight scaling (over step)\n\n ## using exp so that err_scale is always >= 1\n #err_scale = tf.exp(err_scale)\n #ws = tf.pow(err_scale, -tf.to_float(tf.range(len(ks))) )\n #ws = ws / tf.reduce_sum(ws) # normalize weights\n\n # opt1.2 : dynamic error with possible final \"topple\"\n # (numerically stable)\n ws = -tf.log(err_scale) * tf.to_float(tf.range(len(ks)))\n ws = tf.nn.softmax(ws)\n\n # opt2 : static error weight scaling\n # ws = np.float32([cfg.FN_ERR_DECAY**-e for e in range(len(ks))])\n # ws /= ws.sum() # normalize weights\n\n #err = tf.reduce_mean(errs.values())\n err = tf.losses.compute_weighted_loss(\n losses=[errs[k] for k in ks],\n weights=ws\n )\n log('err', err.shape)\n log('-------------')\n return err, errs, err_scale\n\n def _build_opt(self, c, log=no_op):\n \"\"\" build optimizer part \"\"\"\n log('- build-opt -')\n opt = tf.train.AdamOptimizer(learning_rate=self.learning_rate_)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = tf.contrib.layers.optimize_loss(c, self.step_,\n learning_rate=self.learning_rate_,\n optimizer='Adam',\n clip_gradients=None,\n summaries=['loss', 'learning_rate', 'global_gradient_norm', 'gradients'])\n log('-------------')\n return train_op\n\n def _build_log(self, log=no_op, **tensors):\n \"\"\" build log summaries part \"\"\"\n log('- build-log -')\n tf.summary.scalar('err', tensors['err'], collections=self.col_)\n tf.summary.scalar('err_scale', tensors['err_scale'], collections=self.col_)\n for (k,v) in tensors['errs'].items():\n tf.summary.scalar(k, v, collections=self.col_)\n log('-------------')\n return None\n\n def build(self, log=no_op):\n \"\"\" build everything \"\"\"\n # NTCHW\n if self.img_ is None:\n self._build_input()\n\n img = self.img_\n lab = self.lab_\n\n with tf.variable_scope('vo', reuse=self.reuse_):\n xs = self._build_cnn(img, log=log)\n tcnn, prds = self._build_tcnn(xs, img, log=log)\n\n if self.eval_:\n err_c, errs, err_scale = self._build_err(prds, lab, log=log)\n\n if self.train_:\n reg_c = tf.add_n(tf.losses.get_regularization_losses())\n tf.summary.scalar('err_loss', err_c)\n tf.summary.scalar('reg_loss', reg_c)\n cost = (err_c + reg_c)\n opt = self._build_opt(cost, log=log)\n self.opt_ = opt\n\n if self.eval_:\n _ = self._build_log(log=log, err=err_c, errs=errs,\n err_scale=err_scale\n )\n\n self.img_ = img\n self.pred_ = tcnn\n self.lab_ = lab\n\n if self.eval_:\n self.err_ = err_c\n else:\n self.err_ = None\n\n ns = net_size()\n log('- net size - ')\n log('total : {}'.format(ns))\n log('-------------')\n return\n\n def _arg_scope(self):\n \"\"\" function default arguments \"\"\"\n bn_params = {\n 'is_training' : self.train_,\n 'decay' : 0.92,\n 'fused' : True,\n 'scale' : True,\n 'reuse' : self.reuse_,\n 'data_format' : 'NHWC',\n 'scope' : 'batch_norm',\n }\n with slim.arg_scope(\n [slim.conv2d, slim.separable_conv2d],\n normalizer_fn=slim.batch_norm,\n normalizer_params=bn_params,\n ):\n with slim.arg_scope(\n [slim.conv2d, slim.separable_conv2d, slim.conv2d_transpose],\n padding='SAME',\n data_format='NHWC',\n activation_fn=tf.nn.elu,\n weights_regularizer=(slim.l2_regularizer(1e-6) if self.train_ else None),\n reuse=self.reuse_\n ):\n with slim.arg_scope(\n [slim.fully_connected],\n weights_regularizer=(slim.l2_regularizer(1e-6) if self.train_ else None),\n reuse=self.reuse_\n ) as sc:\n return sc\ndef main():\n net = FlowNetBB(step=tf.train.get_or_create_global_step())\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"robot_learning/scripts/flow_net_bb.py","file_name":"flow_net_bb.py","file_ext":"py","file_size_in_byte":15127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"388726804","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 22 23:32:33 2019\n\n@author: mrinalmanu\n\"\"\"\n\n\"\"\"Part I\n\n\"\"\"\n\nimport sys\nfrom Bio import Phylo\nfrom io import StringIO \nfrom ete3 import Tree, TreeStyle, NodeStyle\nimport matplotlib.pyplot as plt\nimport lxml.etree as ET\nimport random\nfrom pylab import savefig\nimport re\n\nwith open('/home/mrinalmanu/Documents/life.txt', 'r') as file:\n for item in file:\n treedata = ''.join('{}'.format(item))\n\nhandle = StringIO(treedata)\ntree = Phylo.read(handle, \"newick\")\n\n\"\"\"Saving an ascii tree to a file\"\"\"\n\nstdoutOrigin=sys.stdout \nsys.stdout = open('/home/mrinalmanu/Documents/output_phylo/ascii_phylo_life.txt', 'w')\nPhylo.draw_ascii(tree)\nsys.stdout.close()\nsys.stdout=stdoutOrigin\n\n####################\n\n\n''' Just right click and save'''\nPhylo.draw(tree)\nsavefig(path+'look.png', dpi = 600)\n\n\n\"\"\"Exporting tree as an XML file\"\"\"\n\nPath = '/home/mrinalmanu/Documents/output_phylo/'\n\nlines = tree_data\nroot = ET.Element(\"root\")\nfor l in lines:\n elems = l.split(\":\")\n if len(elems) == 2:\n elems = map(lambda x: x.strip(), elems)\n line = ET.SubElement(root, \"line\")\n item1 = ET.SubElement(line, \"item1\")\n item2 = ET.SubElement(line, \"item2\")\n item1.text = elems[0]\n item2.text = elems[1]\n\ntree = ET.ElementTree(root)\ntree.write(path+'life.xml', pretty_print=True)\n\n\n###########################################################################\n\nt = Tree('{}'.format(treedata), format =1)\ncircular_style = TreeStyle()\ncircular_style.show_branch_length = True # show branch length\ncircular_style.show_branch_support = True # show support\ncircular_style.mode = \"c\" # draw tree in circular mode\ncircular_style.scale = 100\n\n\nt.render(path+\"beautiful_life_tree.png\", w=3000, units=\"mm\", tree_style=circular_style)\nt.render(path+\"beautiful_life_tree.pdf\", w=3000, units=\"mm\", tree_style=circular_style)\n\nspecies = []\nfor node in t.get_leaf_names():\n species.append(node)\n\nrandom_nodes = []\n\ni = 0\nfor i in range(0, 42):\n random_nodes.append(str(random.choice(species)))\n i = i + 1\n \n\"\"\" For extreme situations use this to cleane the name and prune trees \"\"\"\n#clean_nodes = [re.sub(r'\\n--', '', elem) for elem in random_nodes]\n# new_t = t\n# for item in clean_nodes:\n# print('Pruning: {}{}{}'.format(\"'\",item,\"'\"))\n# new_t.prune('{}{}{}'.format(\"'\",item,\"'\"))\n \n\n# Creates an independent node style for each node, which is\n# initialized with a red foreground color.\nnew_t.prune(random_nodes)\n\n\"\"\" Getting this tree in some new style other than the basic \"\"\"\n# Basic tree style\nts = TreeStyle()\nts.show_leaf_name = True\n\nfor n in new_t.traverse():\n nstyle = NodeStyle()\n nstyle[\"fgcolor\"] = \"red\"\n nstyle[\"size\"] = 15\n n.set_style(nstyle)\n\n# Let's now modify the aspect of the root node\nnew_t.img_style[\"size\"] = 30\nnew_t.img_style[\"fgcolor\"] = \"blue\"\n\n \nnew_t.render(path+\"beautiful_pruned_life_tree.png\", w=3000, units=\"mm\", tree_style=circular_style)\nnew_t.render(path+\"beautiful_pruned_life_tree.pdf\", w=3000, units=\"mm\", tree_style=circular_style)\n\n\n\"\"\" End of code \"\"\"\n","sub_path":"Week 2/part_1.py","file_name":"part_1.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"246861688","text":"from rest_framework import serializers, fields\nfrom .models import Seller\nfrom product.models import Product\nfrom user.serializers import RegisterUserSerializer,UserSerializer\n\n# Seller Serializer\nclass SellerSerializer(serializers.ModelSerializer):\n user_id = fields.ReadOnlyField(source='user.id')\n name = fields.ReadOnlyField(source='user.name')\n mobile_no = fields.ReadOnlyField(source='user.mobile_no')\n email = fields.ReadOnlyField(source='user.email')\n active_products = serializers.SerializerMethodField()\n sold_products = serializers.SerializerMethodField()\n class Meta:\n model = Seller\n fields = ('id','user_id','name','mobile_no','email','active_products','sold_products')\n\n def get_active_products(self,obj):\n active_prod = Product.objects.filter(current_quantity__gt=0,seller=obj).count()\n return active_prod\n \n def get_sold_products(self,obj):\n sold_prod = Product.objects.filter(current_quantity=0,seller=obj).count()\n return sold_prod\n\n# Register Seller Serializer\nclass RegisterSellerSerializer(serializers.ModelSerializer):\n user = RegisterUserSerializer()\n class Meta:\n model = Seller\n fields = ('id','user')\n\n def create(self, validated_data):\n user_data = dict(validated_data['user'])\n user_serialize = RegisterUserSerializer(data=user_data)\n if user_serialize.is_valid():\n user = user_serialize.save()\n seller = Seller.objects.create(user=user)\n return seller\n","sub_path":"seller/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"567705744","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\n\nxl,yl = np.loadtxt('massa_mola_exp_laser.dat',unpack=True)\nA_laser = 3.850429058674\nB_laser = 0.05659480098019\nw_laser = 9.773472259004\nf_laser = 0.07016506012475\n\nxfit_laser = np.linspace(min(xl),max(xl),1000)\nyfit_laser = A_laser*np.exp(-B_laser*xfit_laser)*np.sin(w_laser*xfit_laser + f_laser)\n\nfig_size = [6.8,4.8]\n\nparams = {'backend': 'ps',\n 'axes.labelsize': 20,\n 'font.size': 10,\n 'legend.fontsize': 17,\n 'legend.fancybox': True,\n #'legend.frameon': False,\n 'xtick.labelsize': 17,\n 'ytick.labelsize': 17,\n 'text.usetex': True,\n 'font.family': 'serif',\n 'font.serif': 'Times',\n 'figure.figsize': fig_size}\n\nplt.rcParams.update(params)\n\nplt.figure(1)\nplt.clf()\nplt.axes([0.14,0.16,0.8,0.8])\n\nplt.plot(xfit_laser,yfit_laser,'-r',lw=1.)\nplt.plot(xl,yl,'ok',ms=3,label='Laser')\n\nplt.xlabel(r'$t(s)$',fontsize=24)\nplt.ylabel(r'$x(cm)$',fontsize=24)\n\nplt.xlim(0.,6.)\nplt.legend()\n\nplt.savefig('massa_mola_oscilacao_laser.png', format='png', dpi=900)\n","sub_path":"figuras/massa_mola/figura_oscilacao_massa_mola_laser.py","file_name":"figura_oscilacao_massa_mola_laser.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"448130214","text":"# Prompt: https://leetcode.com/problems/sort-colors/\n# Runtime: 24 ms, faster than 48.61% of Python online submissions for Sort Colors.\n# Memory Usage: 13.5 MB, less than 42.22% of Python online submissions for Sort Colors.\n\n\nclass Solution(object):\n \n def swap(self, arr, i, j):\n \"\"\"\n :type arr: List[int]\n :type i: int\n :type j: int\n :rtype: None Do not return anything; modify arr in-place instead.\n \"\"\"\n temp = arr[j]\n arr[j] = arr[i]\n arr[i] = temp\n \n def sortColors(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything; modify nums in-place instead.\n \"\"\"\n \n # bubble sort\n allSorted = False\n \n while not allSorted:\n allSorted = True\n \n for i in range(len(nums)-1):\n if nums[i] > nums[i+1]:\n self.swap(nums, i, i+1)\n allSorted = False\n \n return nums\n","sub_path":"1. Medium/75. Sort Colors/sort_colors.py","file_name":"sort_colors.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"36987736","text":"import multiprocessing\nimport time\n\n\n'''Passing arguments to identify or name the process\nis cumbersome, and unnecessary. Each Process instance\nhas a name with a default value that can be changed\nas the process is created. Naming processes is useful\nfor keeping track of them, especially in applications\nwith multiple types of processes running simultaneously.'''\n\n\ndef worker():\n name = multiprocessing.current_process().name\n print(name, ' Starting')\n time.sleep(2)\n print(name, ' Exiting')\n\ndef my_service():\n name = multiprocessing.current_process().name\n print(name, ' Starting')\n time.sleep(2)\n print(name, ' Exiting')\n\nif __name__ == '__main__':\n service = multiprocessing.Process(name='my_service', target=my_service)\n worker_1 = multiprocessing.Process(name='worker_1', target=worker)\n worker_2 = multiprocessing.Process(target=worker)\n\n worker_1.start()\n worker_2.start()\n service.start()\n\n\n'''The debug output includes the name\nof the current process on each line.\nThe lines with Process-3 in the name\ncolumn correspond to the unnamed\nprocess worker_1.'''","sub_path":"multiprocessing_test/determining_current_process.py","file_name":"determining_current_process.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"499584160","text":"\"\"\"\nYou are given an array A of size N. The array A consists of a permutation of the set {1, 2, 3, … , N} for some positive integer N. You have to start at the position which has 1 in the array and then travel to the position which has 2. Then from 2, you travel to 3 and so on till you reach the position which has N. When you travel from A[i] to A[j], the distance travelled is |i– j|.Your aim is to find the total distance you have to travel to reach N when you start from 1.\n\nInput:\nThe first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two lines of input. The first line contains an integer N, where N is the size of the array A[ ]. The second line contains N space separated integers which denote a permutation of the set {1, 2, 3, … , N}.\n\nOutput:\nFor each test case, print the total distance travelled.\n\nConstraints:\n1 <= T <= 100\n1 <= N <= 107\n1<= Ai <= 107\n\nExample :\nInput:\n2\n5\n5 1 4 3 2\n6\n6 5 1 2 4 3\n\nOutput :\n7\n8\n\nExplanation:\nTestcase1: The numbers and their respective indices are given below:\n1->1\n2->4\n3->3\n4->2\n5->0\nTotal distance =|4-1|+|3-4|+|2-3|+|0-2| = 3+1+1+2 = 7\n\"\"\"\n\n\ndef total_distance_travelled(arr, size):\n l1 = list(arr)\n for i in range(0, size):\n l1[arr[i] - 1] = i - 1\n\n sum = int(0)\n for i in range(1, size):\n sum = sum + abs(l1[i] - l1[i - 1])\n return sum\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n size = int(input())\n arr = [int(i) for i in input().split()][0:size]\n print(total_distance_travelled(arr, size))\n","sub_path":"practice/Basic/total_distance_travelled.py","file_name":"total_distance_travelled.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"637034146","text":"from jaratoolbox import celldatabase\n\nsubject = 'pinp019'\nexperiments = []\n\nexp0 = celldatabase.Experiment(subject,\n '2017-04-26',\n brainarea='rightThal',\n info=['medialDiI', 'facingLateral'])\nexperiments.append(exp0)\n\n# exp0.add_site(3125, tetrodes=range(1, 9))\n# exp0.add_session('14-19-08', None, 'noiseburst', 'am_tuning_curve') #Noise burst response\n# exp0.add_session('14-20-53', None, 'laserpulse', 'am_tuning_curve') #No laser response\n\n# exp0.add_site(3255, tetrodes=range(1, 9))\n# exp0.add_session('14-25-18', None, 'noiseburst', 'am_tuning_curve') #Noise burst response\n# exp0.add_session('14-27-03', None, 'laserpulse', 'am_tuning_curve') #No laser response\n\n# exp0.add_site(3353, tetrodes=range(1, 9))\n# exp0.add_session('14-29-48', None, 'noiseburst', 'am_tuning_curve') #Noise burst response\n# exp0.add_session('14-32-20', None, 'laserpulse', 'am_tuning_curve') #No laser response\n# exp0.add_session('14-34-20', None, 'laserpulse2.5mW', 'am_tuning_curve') #No laser response\n\n# exp0.add_site(3449, tetrodes=range(1, 9))\n# exp0.add_session('14-36-53', None, 'noiseburst', 'am_tuning_curve') #Noise burst response\n# exp0.add_session('14-38-32', None, 'laserpulse', 'am_tuning_curve') #No laser responses\n\n# exp0.add_site(3549, tetrodes=range(1, 9))\n# exp0.add_session('14-53-36', None, 'noiseburst', 'am_tuning_curve') #Noise burst response\n# exp0.add_session('14-55-14', None, 'laserpulse', 'am_tuning_curve') #No laser responses\n\n# exp0.add_site(3658, tetrodes=range(1, 9))\n# exp0.add_session('15-00-16', None, 'noiseburst', 'am_tuning_curve') #Noise burst response\n# exp0.add_session('15-01-30', None, 'laserpulse', 'am_tuning_curve') #No laser response\n\nexp0.add_site(3552, tetrodes=range(1, 9))\nexp0.add_session('15-07-21', None, 'noiseburst', 'am_tuning_curve') #Noise burst response\nexp0.add_session('15-09-22', None, 'laserpulse', 'am_tuning_curve') #No laser response\nexp0.add_session('15-11-03', None, 'lasertrain', 'am_tuning_curve') #No laser response\nexp0.add_session('15-12-59', 'a', 'am', 'am_tuning_curve')\nexp0.maxDepth = 3552\n\nexp1 = celldatabase.Experiment(subject,\n '2017-04-27',\n brainarea='rightThal',\n info=['DiD', 'facingLateral'])\nexperiments.append(exp1)\n\nexp1.add_site(3868, tetrodes=range(1, 9)).remove_tetrodes([6, 8])\nexp1.add_session('15-32-40', None, 'laserpulse', 'am_tuning_curve')\nexp1.add_session('15-33-59', None, 'noiseburst', 'am_tuning_curve')\nexp1.add_session('15-35-16', None, 'lasertrain', 'am_tuning_curve')\nexp1.add_session('15-37-25', 'a', 'tc', 'am_tuning_curve')\nexp1.add_session('16-13-57', 'b', 'am', 'am_tuning_curve')\n\nexp1.add_site(3925, tetrodes=range(1, 9))\nexp1.add_session('16-35-34', None, 'noiseburst', 'am_tuning_curve')\nexp1.add_session('16-37-07', None, 'laserpulse', 'am_tuning_curve')\nexp1.add_session('16-38-44', None, 'lasertrain', 'am_tuning_curve')\nexp1.add_session('16-41-01', 'c', 'tc', 'am_tuning_curve')\nexp1.add_session('17-14-41', 'd', 'am', 'am_tuning_curve')\n\nexp1.add_site(4003, tetrodes=range(1, 9))\nexp1.add_session('17-34-41', None, 'noiseburst', 'am_tuning_curve')\nexp1.add_session('17-36-24', None, 'laserpulse', 'am_tuning_curve')\nexp1.add_session('17-37-38', None, 'lasertrain', 'am_tuning_curve')\nexp1.add_session('17-39-34', 'e', 'tc', 'am_tuning_curve')\nexp1.add_session('18-12-29', 'f', 'am', 'am_tuning_curve')\nexp1.maxDepth = 4003\n\nexp2 = celldatabase.Experiment(subject,\n '2017-05-02',\n brainarea='rightThal',\n info=['lateralDiI', 'facingLateral'])\nexperiments.append(exp2)\n\n# exp2.add_site(3905, tetrodes=range(1, 9))\n# exp2.add_session('11-32-32', None, 'noiseburst', 'am_tuning_curve')\n# exp2.add_session('11-36-19', 'a', 'am', 'am_tuning_curve')\n#I got all the way here and no response to sounds. Too lateral??\nexp2.maxDepth = 3905\n\nexp3 = celldatabase.Experiment(subject,\n '2017-05-03',\n brainarea='rightThal',\n info=['anteriorDiD', 'facingPosterior'])\nexperiments.append(exp3)\n\nexp3.add_site(3452, tetrodes=range(1, 9)).remove_tetrodes([7])\nexp3.add_session('14-19-13', None, 'noiseburst', 'am_tuning_curve')\nexp3.add_session('14-21-47', None, 'laserpulse', 'am_tuning_curve')\nexp3.add_session('14-23-08', None, 'lasertrain', 'am_tuning_curve')\nexp3.add_session('14-25-11', 'a', 'am', 'am_tuning_curve')\nexp3.add_session('14-41-00', 'b', 'tc', 'am_tuning_curve')\nexp3.maxDepth = 3452\n","sub_path":"common/inforecordings/pinp019_inforec.py","file_name":"pinp019_inforec.py","file_ext":"py","file_size_in_byte":4654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"327479812","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport utils\nimport torchvision as tv\nimport math\nimport copy\nfrom pygcn import gcn\n\nclass resnet_modified_small(nn.Module):\n def __init__(self):\n super(resnet_modified_small, self).__init__()\n self.resnet = tv.models.resnet34(pretrained=True)\n self.dropout2d = nn.Dropout2d(.5)\n #probably want linear, relu, dropout\n '''self.linear = nn.Linear(7*7*512, 1024)\n self.dropout2d = nn.Dropout2d(.5)\n self.dropout = nn.Dropout(.5)\n self.relu = nn.LeakyReLU()\n utils.init_weight(self.linear)'''\n\n def base_size(self): return 512\n def rep_size(self): return 1024\n\n def forward(self, x):\n x = self.resnet.conv1(x)\n x = self.resnet.bn1(x)\n x = self.resnet.relu(x)\n x = self.resnet.maxpool(x)\n\n x = self.resnet.layer1(x)\n x = self.resnet.layer2(x)\n x = self.resnet.layer3(x)\n x = self.resnet.layer4(x)\n\n x = self.dropout2d(x)\n\n #return self.dropout(self.relu(self.linear(x.view(-1, 7*7*self.base_size()))))\n return x\n\nclass RelationNetworks(nn.Module):\n def __init__(\n self,\n encoder,\n gpu_mode,\n conv_hidden=24,\n embed_hidden=300,\n lstm_hidden=300,\n mlp_hidden=512\n ):\n super().__init__()\n\n self.normalize = tv.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n\n self.train_transform = tv.transforms.Compose([\n tv.transforms.Resize(224),\n tv.transforms.RandomCrop(224),\n tv.transforms.RandomHorizontalFlip(),\n tv.transforms.ToTensor(),\n self.normalize,\n ])\n\n self.dev_transform = tv.transforms.Compose([\n tv.transforms.Resize(224),\n tv.transforms.CenterCrop(224),\n tv.transforms.ToTensor(),\n self.normalize,\n ])\n\n self.encoder = encoder\n self.gpu_mode = gpu_mode\n self.n_roles = self.encoder.get_num_roles()\n self.n_verbs = self.encoder.get_num_verbs()\n self.vocab_size = self.encoder.get_num_labels()\n self.max_role_count = self.encoder.get_max_role_count()\n\n self.conv = resnet_modified_small()\n\n self.verb = nn.Sequential(\n nn.Linear(7*7*self.conv.base_size(), mlp_hidden),\n nn.ReLU(),\n nn.Linear(mlp_hidden, mlp_hidden*2),\n nn.ReLU(),\n nn.Dropout(),\n nn.Linear(mlp_hidden*2, self.n_verbs),\n )\n\n self.role_lookup = nn.Embedding(self.n_roles+1, embed_hidden, padding_idx=self.n_roles)\n self.verb_lookup = nn.Embedding(self.n_verbs, embed_hidden)\n\n\n self.n_concat = self.conv.base_size() * 2 + embed_hidden + 2 * 2\n\n self.g = nn.Sequential(\n nn.Linear(self.n_concat, mlp_hidden),\n nn.ReLU(),\n nn.Linear(mlp_hidden, mlp_hidden),\n nn.ReLU(),\n nn.Linear(mlp_hidden, mlp_hidden),\n nn.ReLU(),\n nn.Linear(mlp_hidden, mlp_hidden),\n nn.ReLU(),\n )\n\n self.role_graph = gcn.GCN(\n nfeat=mlp_hidden,\n nhid=256,\n nclass=self.vocab_size+1,\n dropout=0.5\n )\n\n self.conv_hidden = self.conv.base_size()\n self.lstm_hidden = lstm_hidden\n self.mlp_hidden = mlp_hidden\n\n coords = torch.linspace(-4, 4, 7)\n x = coords.unsqueeze(0).repeat(7, 1)\n y = coords.unsqueeze(1).repeat(1, 7)\n coords = torch.stack([x, y]).unsqueeze(0)\n self.register_buffer('coords', coords)\n\n def train_preprocess(self): return self.train_transform\n def dev_preprocess(self): return self.dev_transform\n\n def forward(self, image, verbs, roles):\n #print('came here')\n\n '''print('testing 123')\n x = torch.tensor([[1, 2, 3],[4,5,6]])\n print('original', x.size())\n x = x.repeat(1,2)\n print('xxxxxx', x, x.view(-1,3), x.size())'''\n\n conv = self.conv(image)\n\n #verb pred\n verb_pred = self.verb(conv.view(-1, 7*7*self.conv.base_size()))\n\n batch_size, n_channel, conv_h, conv_w = conv.size()\n n_pair = conv_h * conv_w\n\n verb_embd = self.verb_lookup(verbs)\n role_embd = self.role_lookup(roles)\n #print('verb embed :', verb_embd.size())\n #print('role embed :', role_embd)\n\n role_embed_reshaped = role_embd.transpose(0,1)\n verb_embed_expand = verb_embd.expand(self.max_role_count, verb_embd.size(0), verb_embd.size(1))\n role_verb_embd = verb_embed_expand * role_embed_reshaped\n role_verb_embd = role_verb_embd.transpose(0,1)\n role_verb_embd = role_verb_embd.contiguous().view(-1, self.lstm_hidden)\n #new batch size = batch_size*max_role\n #print(\"role_verb_embd\" , role_verb_embd)\n batch_size_updated = role_verb_embd.size(0)\n #print('new', batch_size_updated, n_pair, role_verb_embd.size())\n\n qst = torch.unsqueeze(role_verb_embd, 1)\n qst = qst.repeat(1,n_pair * n_pair,1)\n qst = torch.squeeze(qst)\n\n #print('qst size', qst.size())\n\n '''h_tile = role_verb_embd.permute(1, 0, 2).expand(\n batch_size_updated, n_pair * n_pair, self.lstm_hidden\n )'''\n\n\n #update conv to expand for all roles in 1 image\n conv = conv.repeat(1,self.max_role_count, 1, 1)\n #print('conv, size', conv.size())\n conv = conv.view(-1, n_channel, conv_h, conv_w)\n #print('after view', conv.size())\n conv = torch.cat([conv, self.coords.expand(batch_size_updated, 2, conv_h, conv_w)], 1)\n n_channel += 2\n conv_tr = conv.view(batch_size_updated, n_channel, -1).permute(0, 2, 1)\n conv1 = conv_tr.unsqueeze(1).expand(batch_size_updated, n_pair, n_pair, n_channel)\n conv2 = conv_tr.unsqueeze(2).expand(batch_size_updated, n_pair, n_pair, n_channel)\n conv1 = conv1.contiguous().view(-1, n_pair * n_pair, n_channel)\n conv2 = conv2.contiguous().view(-1, n_pair * n_pair, n_channel)\n #print('conv1 and 2 size :', conv1.size(), conv2.size())\n #print('no issue efore cat')\n #concat_vec = torch.cat([conv1, conv2, qst], 2).view(-1, self.n_concat)\n concat_vec = torch.cat([conv1, conv2, qst], 2)\n #apply mask\n concat_vec_masked = self.encoder.get_mask(verbs, concat_vec)\n #concat_vec_masked = concat_mask * concat_vec\n #print('concat vec size :', concat_vec_masked.size())\n cat = concat_vec_masked.view(-1, self.n_concat)\n g = self.g(cat)\n '''if self.gpu_mode >= 0:\n torch.cuda.empty_cache()'''\n #print('no issue after g')\n g = g.view(-1, n_pair * n_pair, self.mlp_hidden).sum(1).squeeze()\n #print('g after summing all elements in the image together :', g.size())\n g = g.contiguous().view(batch_size, -1, self.mlp_hidden)\n #print('g out size with separate roles :', g.size())\n #print('no issue after g view')\n adj_mtx = self.encoder.get_adj_matrix(verbs)\n if self.gpu_mode >= 0:\n adj_mtx = adj_mtx.to(torch.device('cuda'))\n #print('mask ', mask.size(),mask)\n role_predict = self.role_graph(g, adj_mtx)\n\n #role_predict = f.contiguous().view(batch_size, -1, self.vocab_size+1)\n #print('ffffff', f.size())\n\n #del f, g\n\n return verb_pred, role_predict\n\n def forward_eval(self, image):\n conv = self.conv(image)\n\n #verb pred\n verb_pred = self.verb(conv.view(-1, 7*7*self.conv.base_size()))\n #print('verb pred', verb_pred.size())\n sorted_idx = torch.sort(verb_pred, 1, True)[1]\n #print('sorted ', sorted_idx.size())\n verbs = sorted_idx[:,0]\n #todo:change for 5\n #print('top1 verbs', verbs)\n\n #print('verbs :', verbs.size(), verbs)\n\n roles = self.encoder.get_role_ids_batch(verbs)\n\n roles = roles.type(torch.LongTensor)\n verbs = verbs.type(torch.LongTensor)\n\n if self.gpu_mode >= 0:\n roles = roles.to(torch.device('cuda'))\n verbs = verbs.to(torch.device('cuda'))\n\n batch_size, n_channel, conv_h, conv_w = conv.size()\n n_pair = conv_h * conv_w\n\n verb_embd = self.verb_lookup(verbs)\n #print('verb embed :', verb_embd.size())\n role_embd = self.role_lookup(roles)\n #print('role embed :', role_embd.size())\n\n role_embed_reshaped = role_embd.transpose(0,1)\n verb_embed_expand = verb_embd.expand(self.max_role_count, verb_embd.size(0), verb_embd.size(1))\n role_verb_embd = verb_embed_expand * role_embed_reshaped\n role_verb_embd = role_verb_embd.transpose(0,1)\n role_verb_embd = role_verb_embd.contiguous().view(-1, self.lstm_hidden)\n #new batch size = batch_size*max_role\n batch_size_updated = role_verb_embd.size(0)\n #print('new', batch_size_updated, n_pair, role_verb_embd.size())\n\n qst = torch.unsqueeze(role_verb_embd, 1)\n qst = qst.repeat(1,n_pair * n_pair,1)\n qst = torch.squeeze(qst)\n\n #print('qst size', qst.size())\n\n '''h_tile = role_verb_embd.permute(1, 0, 2).expand(\n batch_size_updated, n_pair * n_pair, self.lstm_hidden\n )'''\n\n\n #update conv to expand for all roles in 1 image\n conv = conv.repeat(1,self.max_role_count, 1, 1)\n #print('conv, size', conv.size())\n conv = conv.view(-1, n_channel, conv_h, conv_w)\n #print('after view', conv.size())\n conv = torch.cat([conv, self.coords.expand(batch_size_updated, 2, conv_h, conv_w)], 1)\n n_channel += 2\n conv_tr = conv.view(batch_size_updated, n_channel, -1).permute(0, 2, 1)\n conv1 = conv_tr.unsqueeze(1).expand(batch_size_updated, n_pair, n_pair, n_channel)\n conv2 = conv_tr.unsqueeze(2).expand(batch_size_updated, n_pair, n_pair, n_channel)\n conv1 = conv1.contiguous().view(-1, n_pair * n_pair, n_channel)\n conv2 = conv2.contiguous().view(-1, n_pair * n_pair, n_channel)\n #print('size :', conv2.size())\n #print('no issue efore cat')\n concat_vec = torch.cat([conv1, conv2, qst], 2)\n #apply mask\n concat_vec_masked = self.encoder.get_mask(verbs, concat_vec)\n #concat_vec_masked = concat_mask * concat_vec\n #print('concat vec size :', concat_vec_masked.size())\n cat = concat_vec_masked.view(-1, self.n_concat)\n g = self.g(cat)\n '''if self.gpu_mode >= 0:\n torch.cuda.empty_cache()'''\n #print('no issue after g')\n g = g.view(-1, n_pair * n_pair, self.mlp_hidden).sum(1).squeeze()\n g = g.contiguous().view(batch_size, -1, self.mlp_hidden)\n #print('g out size :', g.size())\n #print('no issue after g view')\n adj_mtx = self.encoder.get_adj_matrix(verbs)\n if self.gpu_mode >= 0:\n adj_mtx = adj_mtx.to(torch.device('cuda'))\n #print('mask ', mask.size(),mask)\n role_predict = self.role_graph(g, adj_mtx)\n\n return verb_pred, role_predict\n\n\n\n\n\n def calculate_loss(self, verb_pred, gt_verbs, role_label_pred, gt_labels,args):\n\n batch_size = verb_pred.size()[0]\n if args.train_all:\n loss = 0\n for i in range(batch_size):\n for index in range(gt_labels.size()[1]):\n frame_loss = 0\n verb_loss = utils.cross_entropy_loss(verb_pred[i], gt_verbs[i])\n #frame_loss = criterion(role_label_pred[i], gt_labels[i,index])\n for j in range(0, self.max_role_count):\n frame_loss += utils.cross_entropy_loss(role_label_pred[i][j], gt_labels[i,index,j] ,None)\n #frame_loss = verb_loss + frame_loss/len(self.encoder.verb2_role_dict[self.encoder.verb_list[gt_verbs[i]]])\n frame_loss = verb_loss + frame_loss/self.max_role_count\n #print('frame loss', frame_loss, 'verb loss', verb_loss)\n loss += frame_loss\n else:\n #verb from pre-trained\n loss = 0\n for i in range(batch_size):\n for index in range(gt_labels.size()[1]):\n frame_loss = 0\n #verb_loss = utils.cross_entropy_loss(verb_pred[i], gt_verbs[i])\n #frame_loss = criterion(role_label_pred[i], gt_labels[i,index])\n for j in range(0, self.max_role_count):\n frame_loss += utils.cross_entropy_loss(role_label_pred[i][j], gt_labels[i,index,j] ,None)\n frame_loss = frame_loss/self.max_role_count\n #print('frame loss', frame_loss, 'verb loss', verb_loss)\n loss += frame_loss\n\n\n final_loss = loss/(batch_size)\n #final_loss = loss\n #print('loss :', final_loss, final_loss/batch_size)\n return final_loss\n\n","sub_path":"model_vsrl_finetune_gcn.py","file_name":"model_vsrl_finetune_gcn.py","file_ext":"py","file_size_in_byte":12978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"566171381","text":"import tornado.web\nimport tornado.ioloop\nfrom tornado.escape import json_decode\nimport json\nimport os \nimport pymysql as torndb\n\nconnect = torndb.connect('192.168.15.39',user='test',password='test',db='test')\ncursor = connect.cursor()\nconnect.autocommit(True)\nimport nginxparser\n\nclass WebApiHandler(tornado.web.RequestHandler):\n def post(self, *args, **kwargs):\n data=json_decode(self.request.body)\n print(data)\n k,v = data.popitem()\n v = json.dumps(v)\n cursor.execute(\"insert into proxy_info(ip,backstage) VALUES (%s,%s) on DUPLICATE key update backstage=VALUES(backstage)\",(k,v))\n '''\n for d in jdata:\n port = d['port']\n remote_ip = d['ip']\n remote_ip = ','.join(remote_ip)\n upstream_name = d['upstream']\n '''\n\nclass WebInfoHandler(tornado.web.RequestHandler):\n def get(self):\n\n data = {}\n cursor.execute(\"select * from proxy_info;\")\n res = cursor.fetchall()\n for info in res:\n k,v = info[0],info[1]\n data[k] = json_decode(v)\n\n self.render(r'web\\diagram\\nginx.html', data=data)\n\nclass DockerApiHandler(tornado.web.RequestHandler):\n def post(self, *args, **kwargs):\n data=json_decode(self.request.body)\n print(type(data))\n #cursor.execute(\"insert into proxy_info(ip,backstage) VALUES (%s,%s) on DUPLICATE key update backstage=VALUES(backstage)\",(k,v))\n\n\n\nif __name__ == \"__main__\":\n settings = {\n 'template_path': os.path.join(os.path.dirname(__file__),'templates'),\n 'static_path': os.path.join(os.path.dirname(__file__),'static')\n }\n app = tornado.web.Application([\n (r'/api/web', WebApiHandler),\n (r'/api/docker', DockerApiHandler),\n (r'/web/info', WebInfoHandler)\n ], **settings)\n app.listen(9999)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"Nginx配置文件生成/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"432743501","text":"import tensorflow as tf\r\n\r\n\r\nclass Linear(tf.keras.layers.Layer):\r\n\r\n # def __init__(self, units, input_dim):\r\n # super(Linear, self).__init__()\r\n # self.w = self.add_weight(shape=(input_dim, units),\r\n # initializer='random_normal',\r\n # trainable=True)\r\n # self.b = self.add_weight(shape=(units,),\r\n # initializer='zeros',\r\n # trainable=True)\r\n\r\n # def call(self, inputs):\r\n # return tf.matmul(inputs, self.w) + self.b\r\n\r\n# linear_layer = Linear(4,2)\r\n\r\n\r\n#In many cases, you may not know in advance the size of your inputs, and you would like to lazily create weights when that value becomes known, some time after instantiating the layer.\r\n def __init__(self, units=32):\r\n super(Linear, self).__init__()\r\n self.units = units\r\n\r\n def build(self, input_shape):\r\n self.w = self.add_weight(shape=(input_shape[-1], self.units),\r\n initializer='random_normal',\r\n trainable=True)\r\n self.b = self.add_weight(shape=(self.units,),\r\n initializer='random_normal',\r\n trainable=True)\r\n\r\n def call(self, inputs):\r\n return tf.matmul(inputs, self.w) + self.b\r\n\r\nlinear_layer = Linear(4)\r\nprint(linear_layer(tf.ones((2, 2))))\r\nprint(linear_layer.w)\r\nprint(linear_layer.b)\r\nprint('weights:', len(linear_layer.weights))\r\nprint('non-trainable weights:', len(linear_layer.non_trainable_weights))\r\n\r\n# It's not included in the trainable weights:\r\nprint('trainable_weights:', linear_layer.trainable_weights)\r\n\r\n'''\r\n** Layer output **\r\ntf.Tensor(\r\n[[ 0.00501864 0.01122843 0.04163956 -0.01085223]\r\n [ 0.00501864 0.01122843 0.04163956 -0.01085223]], shape=(2, 4), dtype=float32)\r\n\r\n** Weight matrix **\r\n\r\n\r\n** Biaa Vector **\r\n\r\n\r\n** 2 parameters are trained weights and bias since for both trainable=True **\r\nweights: 2\r\nnon-trainable weights: 0\r\n\r\n** Weight and Bias values combined **\r\ntrainable_weights: [, ]\r\n'''","sub_path":"tensorflow basics/custom_layer_with_biasV2.py","file_name":"custom_layer_with_biasV2.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"560983464","text":"#-*-coding:utf-8-*-\nimport requests\nimport re\nimport sys\n\nclass downloader(object):\n\n\tdef __init__(self):\n\t\tself.names = []\n\t\tself.prices=[]\n\t\tself.nums=[]\n\t\tself.url='https://s.taobao.com/search?q=iphonex&imgfile=&ie=utf8&app=detailproduct&through=1'\n\n\tdef get_data(self,url):\n\t\t#url = 'https://s.taobao.com/search?q=iphonex&imgfile=&ie=utf8&app=detailproduct&through=1'\n\t\thtml = requests.get(url)\n\t\thtml.encoding = 'utf-8'\n\t\tdata = html.text\n\t\tself.names = re.findall(r'\"raw_title\":\"([^\"]+)\"',data,re.I)\n\t\tself.prices = re.findall(r'\"view_price\":\"([^\"]+)\"',data,re.I)\n\t\tself.nums = len(self.prices)\n\n\tdef writer(self,name,path,price):\n\t\twith open(path,'a',encoding = 'utf-8') as f:\n\t\t\tf.write(name+'\\n')\n\t\t\tf.write(price)\n\t\t\tf.write('\\n\\n')\n\nif __name__ == '__main__':\n\tdl = downloader()\n\tdl.get_data(dl.url)\n\tprint('The information of IPhone X is downloading:')\n\tfor i in range(dl.nums):\n\t\tdl.writer(\"name:\" + dl.names[i],'iphonex.txt',\"the price is :\"+dl.prices[i])\n\t\tsys.stdout.write('Progress Status:%.1f%%' % float(i/dl.nums*100)+'\\r')\n\t\tsys.stdout.flush()\n\tprint('finish!!')\n","sub_path":"Iphonex.py","file_name":"Iphonex.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"367309553","text":"#!/usr/bin/env python3\ndef linearsearch(x, l):\n\tn = len(l);\n\tfound = False;\n\tfor index, value in enumerate(l):\n\t\tif x == value:\n\t\t\tfound = True;\n\t\t\treturn index;\n\t\n\tif found == False:\n\t\treturn -1;","sub_path":"Searching/linearsearch.py","file_name":"linearsearch.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"259697050","text":"#!/usr/bin/python\n#----------------------------------#\n# File name: rm.py\n# Author: Ricky Yu\n# Date Created: 31/01/2017\n# Python Version: Python2/Python3\n#----------------------------------#\n\"\"\"\nbuiltin => rm.py\n\nCurrent version: v0.1\nAuthor: Ricky Yu\n\"\"\"\nimport os\n\n\ndef rm(args):\n if len(args) == 0:\n print('Invalid arguments!')\n else:\n try:\n if len(args) == 1:\n target = args[0]\n if os.path.isdir(target):\n print(target + ' is not a file!')\n else:\n os.remove(target)\n elif len(args) == 2:\n try:\n if args[0] == '-rf':\n os.remove(args[1])\n else:\n print('Not recognised argument!')\n except PermissionError:\n print('Access is denied!')\n else:\n print('Not recognised argument!')\n except FileNotFoundError:\n print('Target file/dir not found!')","sub_path":"shell/builtin/rm.py","file_name":"rm.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"455692506","text":"\"\"\"\n463\neasy\nisland perimeter\n\n\"\"\"\n\nfrom typing import List\n\nclass Solution:\n def islandPerimeter(self, grid: List[List[int]]) -> int:\n\n m, n = len(grid), len(grid[0])\n\n def helper(x, y):\n count = 0\n for k, l in (-1, 0), (1, 0), (0, -1), (0, 1):\n if 0 <= x + k < m and 0 <= y + l < n and grid[x+k][y+l] == 1:\n count += 1\n\n return 4 - count\n\n total = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n total += helper(i, j)\n\n return total\n\ngrid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]\ngrid = [[1]]\nsol = Solution()\nprint(sol.islandPerimeter(grid))","sub_path":"Q463.py","file_name":"Q463.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"74862649","text":"from html.parser import HTMLParser\n\nhtmlstr = '''\n \n Test\n \n \n

Parse me!

\n \n

A paragraph.

\n

A paragraph with class.

\n \n
\n

A paragraph in div.

\n
\n \n'''\n\n#继承HTMLParser 重写方法\nclass Myparser(HTMLParser):\n #处理开始标签\n def handle_starttag(self,tag,attrs):\n return\n print(tag,'--',attrs)\n\n #处理结束标签\n def handle_endtag(self,tag):\n return\n print(tag)\n \n #处理标签里的内容\n def handle_data(self,data):\n return\n print(data)\n\n #处理开始和结束标签闭合的标签\n def handle_startendtag(self,tag,attrs):\n return\n print(tag,'--',attrs)\n\n #处理注释\n def handle_comment(self,data):\n return\n print(data)\n\n #处理全部p标签\n def handle_data(self,data):\n return\n #lasttag表示上一次操作的标签\n if self.lasttag == 'p':\n print(data)\n\n\n in_div = False\n #处理div标签下的p标签\n def __init___(self):\n HTMLParser.__init__(self)\n self.in_div = False\n\n def handle_starttag(self,tag,attrs):\n if tag == 'div':\n self.in_div = True\n\n def handle_data(self,data):\n if self.in_div == True and self.lasttag == 'p':\n print(data)\n\n#创建实例\nparser = Myparser()\n#添加html\nparser.feed(htmlstr)","sub_path":"008/parserlearn.py","file_name":"parserlearn.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"95639222","text":"import re\nfrom urllib.parse import urljoin\n\nfrom django.conf import settings\nfrom django.contrib import admin, messages\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib.auth.decorators import permission_required\nfrom django.shortcuts import get_object_or_404, render\nfrom django.template.defaultfilters import slugify, truncatechars\nfrom django.urls import path\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import format_html\nfrom django.views.decorators.cache import never_cache\n\nfrom exporter import views as exporter_views\nfrom importer.tasks import import_items_into_project_from_url\nfrom importer.utils.excel import slurp_excel\n\nfrom .forms import AdminItemImportForm, AdminProjectBulkImportForm\nfrom .models import (\n Asset,\n Campaign,\n Item,\n Project,\n Resource,\n Tag,\n Transcription,\n UserAssetTagCollection,\n)\nfrom .views import ReportCampaignView\n\n\ndef publish_action(modeladmin, request, queryset):\n \"\"\"\n Mark all of the selected objects as published\n \"\"\"\n\n count = queryset.filter(published=False).update(published=True)\n messages.add_message(request, messages.INFO, f\"Published {count} objects\")\n\n\npublish_action.short_description = \"Publish selected\"\n\n\ndef unpublish_action(modeladmin, request, queryset):\n \"\"\"\n Mark all of the selected objects as unpublished\n \"\"\"\n\n count = queryset.filter(published=True).update(published=False)\n messages.add_message(request, messages.INFO, f\"Unpublished {count} objects\")\n\n\nunpublish_action.short_description = \"Unpublish selected\"\n\n\n@never_cache\n@staff_member_required\n@permission_required(\"concordia.add_campaign\")\n@permission_required(\"concordia.change_campaign\")\n@permission_required(\"concordia.add_project\")\n@permission_required(\"concordia.change_project\")\n@permission_required(\"concordia.add_item\")\n@permission_required(\"concordia.change_item\")\ndef admin_bulk_import_view(request):\n # TODO: when we upgrade to Django 2.1 we can use the admin site override\n # mechanism (the old one is broken in 2.0): see\n # https://code.djangoproject.com/ticket/27887 in the meantime, this will\n # simply be a regular Django view using forms and just enough context to\n # reuse the Django admin template\n\n request.current_app = \"admin\"\n\n context = {\"title\": \"Bulk Import\"}\n\n if request.method == \"POST\":\n form = AdminProjectBulkImportForm(request.POST, request.FILES)\n\n if form.is_valid():\n context[\"import_jobs\"] = import_jobs = []\n\n rows = slurp_excel(request.FILES[\"spreadsheet_file\"])\n required_fields = [\n \"Campaign\",\n \"Campaign Short Description\",\n \"Campaign Long Description\",\n \"Project\",\n \"Project Description\",\n \"Import URLs\",\n ]\n for idx, row in enumerate(rows):\n missing_fields = [i for i in required_fields if i not in row]\n if missing_fields:\n messages.add_message(\n request,\n messages.WARNING,\n f\"Skipping row {idx}: missing fields {missing_fields}\",\n )\n continue\n\n campaign_title = row[\"Campaign\"]\n project_title = row[\"Project\"]\n import_url_blob = row[\"Import URLs\"]\n\n if not all((campaign_title, project_title, import_url_blob)):\n messages.add_message(\n request,\n messages.WARNING,\n f\"Skipping row {idx}: at least one required field (Campaign, Project, Import URLs) is empty\",\n )\n continue\n\n campaign, created = Campaign.objects.get_or_create(\n title=campaign_title,\n defaults={\n \"slug\": slugify(campaign_title),\n \"description\": row[\"Campaign Long Description\"] or \"\",\n \"short_description\": row[\"Campaign Short Description\"] or \"\",\n },\n )\n if created:\n messages.add_message(\n request, messages.INFO, f\"Created new campaign {campaign_title}\"\n )\n else:\n messages.add_message(\n request,\n messages.INFO,\n f\"Reusing campaign {campaign_title} without modification\",\n )\n\n project, created = campaign.project_set.get_or_create(\n title=project_title, defaults={\"slug\": slugify(project_title)}\n )\n if created:\n messages.add_message(\n request, messages.INFO, f\"Created new project {project_title}\"\n )\n else:\n messages.add_message(\n request,\n messages.INFO,\n f\"Reusing project {project_title} without modification\",\n )\n\n potential_urls = filter(None, re.split(r\"[\\s]+\", import_url_blob))\n for url in potential_urls:\n if not url.startswith(\"http\"):\n continue\n import_jobs.append(\n import_items_into_project_from_url(request.user, project, url)\n )\n messages.add_message(\n request,\n messages.INFO,\n f\"Queued {campaign_title} {project_title} import for {url}\",\n )\n else:\n form = AdminProjectBulkImportForm()\n\n context[\"form\"] = form\n\n return render(request, \"admin/bulk_import.html\", context)\n\n\nclass CustomListDisplayFieldsMixin:\n \"\"\"\n Mixin which provides some custom text formatters for list display fields\n used on multiple models\n \"\"\"\n\n def truncated_description(self, obj):\n return truncatechars(obj.description, 200)\n\n truncated_description.short_description = \"Description\"\n\n def truncated_metadata(self, obj):\n if obj.metadata:\n return format_html(\"{}\", truncatechars(obj.metadata, 200))\n else:\n return \"\"\n\n truncated_metadata.allow_tags = True\n truncated_metadata.short_description = \"Metadata\"\n\n\n@admin.register(Campaign)\nclass CampaignAdmin(admin.ModelAdmin, CustomListDisplayFieldsMixin):\n list_display = (\n \"id\",\n \"title\",\n \"slug\",\n \"short_description\",\n \"start_date\",\n \"end_date\",\n \"truncated_metadata\",\n \"published\",\n )\n list_display_links = (\"id\", \"title\", \"slug\")\n prepopulated_fields = {\"slug\": (\"title\",)}\n search_fields = [\"title\", \"description\"]\n list_filter = (\"published\",)\n\n actions = (publish_action, unpublish_action)\n\n def get_urls(self):\n urls = super().get_urls()\n\n app_label = self.model._meta.app_label\n model_name = self.model._meta.model_name\n\n custom_urls = [\n path(\n \"exportCSV/\",\n exporter_views.ExportCampaignToCSV.as_view(),\n name=f\"{app_label}_{model_name}_export-csv\",\n ),\n path(\n \"exportBagIt/\",\n exporter_views.ExportCampaignToBagit.as_view(),\n name=f\"{app_label}_{model_name}_export-bagit\",\n ),\n path(\n \"report/\",\n ReportCampaignView.as_view(),\n name=f\"{app_label}_{model_name}_report\",\n ),\n ]\n\n return custom_urls + urls\n\n\n@admin.register(Resource)\nclass ResourceAdmin(admin.ModelAdmin, CustomListDisplayFieldsMixin):\n list_display = (\"campaign\", \"sequence\", \"title\", \"resource_url\")\n\n\n@admin.register(Project)\nclass ProjectAdmin(admin.ModelAdmin, CustomListDisplayFieldsMixin):\n # todo: add foreignKey link for campaign\n list_display = (\n \"id\",\n \"title\",\n \"slug\",\n \"category\",\n \"campaign\",\n \"truncated_metadata\",\n \"published\",\n )\n\n list_display_links = (\"id\", \"title\", \"slug\")\n prepopulated_fields = {\"slug\": (\"title\",)}\n search_fields = [\"title\", \"campaign__title\"]\n list_filter = (\"published\", \"category\", \"campaign\")\n\n actions = (publish_action, unpublish_action)\n\n def get_urls(self):\n urls = super().get_urls()\n\n app_label = self.model._meta.app_label\n model_name = self.model._meta.model_name\n\n custom_urls = [\n path(\n \"/item-import/\",\n self.admin_site.admin_view(self.item_import_view),\n name=f\"{app_label}_{model_name}_item-import\",\n )\n ]\n\n return custom_urls + urls\n\n @method_decorator(permission_required(\"concordia.add_campaign\"))\n @method_decorator(permission_required(\"concordia.change_campaign\"))\n @method_decorator(permission_required(\"concordia.add_project\"))\n @method_decorator(permission_required(\"concordia.change_project\"))\n @method_decorator(permission_required(\"concordia.add_item\"))\n @method_decorator(permission_required(\"concordia.change_item\"))\n def item_import_view(self, request, object_id):\n\n project = get_object_or_404(Project, pk=object_id)\n\n if request.method == \"POST\":\n form = AdminItemImportForm(request.POST)\n\n if form.is_valid():\n import_url = form.cleaned_data[\"import_url\"]\n\n import_job = import_items_into_project_from_url(\n request.user, project, import_url\n )\n else:\n form = AdminItemImportForm()\n import_job = None\n\n media = self.media\n\n context = {\n **self.admin_site.each_context(request),\n \"app_label\": self.model._meta.app_label,\n \"add\": False,\n \"change\": False,\n \"save_as\": False,\n \"save_on_top\": False,\n \"opts\": self.model._meta,\n \"title\": f\"Import Items into “{project.title}”\",\n \"object_id\": object_id,\n \"original\": project,\n \"media\": media,\n \"preserved_filters\": self.get_preserved_filters(request),\n \"is_popup\": False,\n \"has_view_permission\": True,\n \"has_add_permission\": True,\n \"has_change_permission\": True,\n \"has_delete_permission\": False,\n \"has_editable_inline_admin_formsets\": False,\n \"project\": project,\n \"form\": form,\n \"import_job\": import_job,\n }\n\n return render(request, \"admin/concordia/project/item_import.html\", context)\n\n\n@admin.register(Item)\nclass ItemAdmin(admin.ModelAdmin):\n list_display = (\"title\", \"item_id\", \"campaign_title\", \"project\", \"published\")\n list_display_links = (\"title\", \"item_id\")\n search_fields = [\n \"title\",\n \"item_id\",\n \"item_url\",\n \"project__campaign__title\",\n \"project__title\",\n ]\n list_filter = (\"published\", \"project__campaign\", \"project\")\n\n actions = (publish_action, unpublish_action)\n\n readonly_fields = (\"project\",)\n\n def get_queryset(self, request):\n qs = super().get_queryset(request)\n qs = qs.select_related(\"project\", \"project__campaign\")\n return qs\n\n def campaign_title(self, obj):\n return obj.project.campaign.title\n\n\n@admin.register(Asset)\nclass AssetAdmin(admin.ModelAdmin, CustomListDisplayFieldsMixin):\n list_display = (\n \"published\",\n \"transcription_status\",\n \"item_id\",\n \"sequence\",\n \"truncated_media_url\",\n \"media_type\",\n \"truncated_metadata\",\n )\n list_display_links = (\"item_id\", \"sequence\")\n prepopulated_fields = {\"slug\": (\"title\",)}\n search_fields = [\n \"title\",\n \"media_url\",\n \"item__project__campaign__title\",\n \"item__project__title\",\n \"item__item_id\",\n ]\n list_filter = (\n \"published\",\n \"item__project__campaign\",\n \"item__project\",\n \"media_type\",\n \"transcription_status\",\n )\n actions = (publish_action, unpublish_action)\n\n readonly_fields = (\"item\",)\n\n ordering = (\"item__item_id\", \"sequence\")\n\n def get_queryset(self, request):\n qs = super().get_queryset(request)\n return qs.select_related(\"item\").order_by(\"item__item_id\", \"sequence\")\n\n def item_id(self, obj):\n return obj.item.item_id\n\n def truncated_media_url(self, obj):\n return format_html(\n '{}',\n urljoin(settings.MEDIA_URL, obj.media_url),\n truncatechars(obj.media_url, 100),\n )\n\n truncated_media_url.allow_tags = True\n truncated_media_url.short_description = \"Media URL\"\n\n def change_view(self, request, object_id, extra_context=None, **kwargs):\n if object_id:\n if extra_context is None:\n extra_context = {}\n extra_context[\"transcriptions\"] = (\n Transcription.objects.filter(asset__pk=object_id)\n .select_related(\"user\", \"reviewed_by\")\n .order_by(\"-pk\")\n )\n return super().change_view(\n request, object_id, extra_context=extra_context, **kwargs\n )\n\n\n@admin.register(Tag)\nclass TagAdmin(admin.ModelAdmin):\n list_display = (\"id\", \"value\")\n list_display_links = (\"id\", \"value\")\n\n search_fields = [\"value\"]\n\n\n@admin.register(UserAssetTagCollection)\nclass UserAssetTagCollectionAdmin(admin.ModelAdmin):\n list_display = (\"id\", \"asset\", \"user\", \"created_on\", \"updated_on\")\n list_display_links = (\"id\", \"asset\")\n date_hierarchy = \"created_on\"\n search_fields = [\"asset__title\", \"asset__campaign__title\", \"asset__project__title\"]\n list_filter = (\n \"asset__item__project__campaign\",\n \"asset__item__project\",\n \"user__is_staff\",\n )\n\n\n@admin.register(Transcription)\nclass TranscriptionAdmin(admin.ModelAdmin):\n list_display = (\n \"id\",\n \"asset\",\n \"user\",\n \"truncated_text\",\n \"created_on\",\n \"updated_on\",\n \"accepted\",\n \"rejected\",\n )\n list_display_links = (\"id\", \"asset\")\n\n search_fields = [\"text\"]\n\n readonly_fields = (\n \"asset\",\n \"user\",\n \"created_on\",\n \"updated_on\",\n \"submitted\",\n \"accepted\",\n \"rejected\",\n \"reviewed_by\",\n \"supersedes\",\n \"text\",\n )\n\n def truncated_text(self, obj):\n return truncatechars(obj.text, 100)\n\n truncated_text.short_description = \"Text\"\n","sub_path":"concordia/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":14900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"474781829","text":"from django.test import TestCase, Client\nfrom ventas import ventas_consumos\nfrom core import models\n\nimport json\nimport os\nimport pandas as pd\n\n\n\n\nclass VentasConsumosTests(TestCase):\n\n maxDiff = None\n\n def setUp(self):\n\n # Cliente\n self.operadora_magno = models.Cliente.objects.create(nombre='MAGNO BRASSERIE')\n # Sucursal\n self.magno_brasserie = models.Sucursal.objects.create(nombre='MAGNO-BRASSERIE', cliente=self.operadora_magno)\n # Almacen\n self.barra_1 = models.Almacen.objects.create(nombre='BARRA 1', numero=1, sucursal=self.magno_brasserie)\n # Caja\n self.caja_1 = models.Caja.objects.create(numero=1, nombre='CAJA 1', almacen=self.barra_1)\n\n #Categorías\n self.categoria_licor = models.Categoria.objects.create(nombre='LICOR')\n self.categoria_tequila = models.Categoria.objects.create(nombre='TEQUILA')\n self.categoria_whisky = models.Categoria.objects.create(nombre='WHISKY')\n\n # Ingredientes\n self.licor_43 = models.Ingrediente.objects.create(\n codigo='LICO001',\n nombre='LICOR 43',\n categoria=self.categoria_licor,\n factor_peso=1.05\n )\n self.herradura_blanco = models.Ingrediente.objects.create(\n codigo='TEQU001',\n nombre='HERRADURA BLANCO',\n categoria=self.categoria_tequila,\n factor_peso=0.95\n )\n self.jw_black = models.Ingrediente.objects.create(\n codigo='WHIS001',\n nombre='JOHNNIE WALKER BLACK',\n categoria=self.categoria_whisky,\n factor_peso=0.95\n )\n\n # Recetas\n self.trago_licor_43 = models.Receta.objects.create(\n codigo_pos='00081',\n nombre='LICOR 43 DERECHO',\n sucursal=self.magno_brasserie\n )\n self.trago_herradura_blanco = models.Receta.objects.create(\n codigo_pos='00126',\n nombre='HERRADURA BLANCO DERECHO',\n sucursal=self.magno_brasserie\n )\n self.trago_jw_black = models.Receta.objects.create(\n codigo_pos= '00167',\n nombre='JW BLACK DERECHO',\n sucursal=self.magno_brasserie\n )\n self.carajillo = models.Receta.objects.create(\n codigo_pos='00050',\n nombre='CARAJILLO',\n sucursal=self.magno_brasserie\n )\n\n # Ingredientes-Recetas\n self.ir_licor_43 = models.IngredienteReceta.objects.create(receta=self.trago_licor_43, ingrediente=self.licor_43, volumen=60)\n self.ir_herradura_blanco = models.IngredienteReceta.objects.create(receta=self.trago_herradura_blanco, ingrediente=self.herradura_blanco, volumen=60)\n self.ir_jw_black = models.IngredienteReceta.objects.create(receta=self.trago_jw_black, ingrediente=self.jw_black, volumen=60)\n self.ir_carajillo = models.IngredienteReceta.objects.create(receta=self.carajillo, ingrediente=self.licor_43, volumen=45)\n\n \n def test_output_ok(self):\n \"\"\" Testear que el módulo registra las ventas y consumos de forma correcta \"\"\"\n\n # Creamos un dataset de prueba para el test\n payload = {\n 'sucursal_id': [self.magno_brasserie.id, self.magno_brasserie.id, self.magno_brasserie.id, self.magno_brasserie.id],\n 'caja_id': [self.caja_1.id, self.caja_1.id, self.caja_1.id, self.caja_1.id],\n 'codigo_pos': ['00050', '00126', '00167', '00081', ],\n 'nombre': ['CARAJILLO', 'CT HERRADURA BLANCO', 'CW JOHNNIE WALKER ETIQUETA NEGR A', 'LICOR 43'],\n 'unidades': [3, 1, 2, 1],\n 'importe': [285, 112, 340, 170]\n }\n\n df_test = pd.DataFrame(payload)\n\n\n # output_esperado = {\n\n # \"ventas_consumos\": [\n # {\n # \"venta\": \"RECETA: CARAJILLO - SUCURSAL: MAGNO-BRASSERIE - FECHA: 2019-04-13 - UNIDADES: 3 - IMPORTE: 285 - CAJA: CAJA: 1 - BARRA: BARRA 1\",\n # \"consumos\": [\n # \"INGREDIENTE: LICOR 43 - RECETA: CARAJILLO - VENTA: RECETA: CARAJILLO - SUCURSAL: MAGNO-BRASSERIE - FECHA: 2019-04-13 - UNIDADES: 3 - IMPORTE: 285 - CAJA: CAJA: 1 - BARRA: BARRA 1 - FECHA: 2019-04-13 - VOLUMEN 135\"\n # ]\n # },\n # {\n # \"venta\": \"RECETA: HERRADURA BLANCO DERECHO - SUCURSAL: MAGNO-BRASSERIE - FECHA: 2019-04-13 - UNIDADES: 1 - IMPORTE: 112 - CAJA: CAJA: 1 - BARRA: BARRA 1\",\n # \"consumos\": [\n # \"INGREDIENTE: HERRADURA BLANCO - RECETA: HERRADURA BLANCO DERECHO - VENTA: RECETA: HERRADURA BLANCO DERECHO - SUCURSAL: MAGNO-BRASSERIE - FECHA: 2019-04-13 - UNIDADES: 1 - IMPORTE: 112 - CAJA: CAJA: 1 - BARRA: BARRA 1 - FECHA: 2019-04-13 - VOLUMEN 60\"\n # ]\n # },\n # {\n # \"venta\": \"RECETA: JW BLACK DERECHO - SUCURSAL: MAGNO-BRASSERIE - FECHA: 2019-04-13 - UNIDADES: 2 - IMPORTE: 340 - CAJA: CAJA: 1 - BARRA: BARRA 1\",\n # \"consumos\": [\n # \"INGREDIENTE: JOHNNIE WALKER BLACK - RECETA: JW BLACK DERECHO - VENTA: RECETA: JW BLACK DERECHO - SUCURSAL: MAGNO-BRASSERIE - FECHA: 2019-04-13 - UNIDADES: 2 - IMPORTE: 340 - CAJA: CAJA: 1 - BARRA: BARRA 1 - FECHA: 2019-04-13 - VOLUMEN 120\"\n # ]\n # },\n # {\n # \"venta\": \"RECETA: LICOR 43 DERECHO - SUCURSAL: MAGNO-BRASSERIE - FECHA: 2019-04-13 - UNIDADES: 1 - IMPORTE: 170 - CAJA: CAJA: 1 - BARRA: BARRA 1\",\n # \"consumos\": [\n # \"INGREDIENTE: LICOR 43 - RECETA: LICOR 43 DERECHO - VENTA: RECETA: LICOR 43 DERECHO - SUCURSAL: MAGNO-BRASSERIE - FECHA: 2019-04-13 - UNIDADES: 1 - IMPORTE: 170 - CAJA: CAJA: 1 - BARRA: BARRA 1 - FECHA: 2019-04-13 - VOLUMEN 60\"\n # ]\n # }\n # ],\n # \"productos_no_registrados\": []\n # }\n\n # Ejecutamos el módulo 'ventas_consumos' con el dataframe de prueba y guardamos el resultado\n resultado = ventas_consumos.registrar(df_test, self.magno_brasserie)\n #print(resultado)\n \n # Convertimos el resultado del módulo en un JSON\n #json_resultado = json.dumps(resultado)\n #print(json_resultado)\n\n # Convertimos el output esperado en un JSON\n #json_output_esperado = json.dumps(output_esperado)\n\n # Tomamos las ventas registradas por el móculo\n ventas_registradas = models.Venta.objects.all()\n #print(ventas_registradas)\n\n # Tomamos los consumos registrados por el módulo\n consumos_registrados = models.ConsumoRecetaVendida.objects.all()\n #print(consumos_registrados)\n\n # Cotejamos que el módulo registró las 4 ventas esperadas\n self.assertEqual(ventas_registradas.count(), 4)\n\n # Cotejamos que el módulo registró los 4 consumos esperados\n self.assertEqual(consumos_registrados.count(), 4)\n \n # Cotejamos que el JSON retornado por el módulo sea igual al JSON esperado\n #self.assertEqual(json_resultado, json_output_esperado)\n\n\n def test_producto_sin_registro(self):\n \"\"\" Testear que se los productos sin registro se manejan de forma adecuada \"\"\"\n\n # Creamos un dataset de prueba para el test\n payload = {\n 'sucursal_id': [self.magno_brasserie.id, self.magno_brasserie.id],\n 'caja_id': [self.caja_1.id, self.caja_1.id],\n 'codigo_pos': ['00050', '00457'],\n 'nombre': ['CARAJILLO', 'APEROL SPRITZ'],\n 'unidades': [3, 1],\n 'importe': [285, 125]\n }\n\n df_test = pd.DataFrame(payload)\n\n # Ejecutamos el módulo 'ventas_consumos' con el dataframe de prueba y guardamos el resultado\n resultado = ventas_consumos.registrar(df_test, self.magno_brasserie)\n\n # Tomamos las ventas registradas por el módulo\n ventas_registradas = models.Venta.objects.all()\n\n # Cotejamos que el módulo registró 1 sola venta\n self.assertEqual(ventas_registradas.count(), 1)\n\n # Cotejamos que el resultado del módulo contiene 1 producto sin registro\n productos_sin_registro = len(resultado['productos_no_registrados'])\n #print(productos_sin_registro)\n self.assertEqual(productos_sin_registro, 1)\n\n\n\n\n\n\n","sub_path":"app/ventas/tests/test_ventasconsumos.py","file_name":"test_ventasconsumos.py","file_ext":"py","file_size_in_byte":8384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"39919952","text":"#!/usr/bin/env/python\n\n'''\nQuakeledger\n-----------------\n\nCommand line program to query data from a catalog.\n'''\n\nimport argparse\nimport os\n\nfrom eventdataprovider import Database\nfrom eventdeaggregation import DeaggregationAnalyzer, DeaggregationMatcher\nfrom eventwriter import QuakeMLWriter\n\n\nclass Main():\n '''\n Main class to execute\n '''\n def __init__(self, args):\n folder = os.path.dirname(__file__)\n\n # db to use to query all the data\n self.database = Database.from_local_sql_db(folder, 'sqlite3.db')\n\n # command line arguments\n self.lonmin = args.lonmin\n self.lonmax = args.lonmax\n self.latmin = args.latmin\n self.latmax = args.latmax\n self.mmin = args.mmin\n self.mmax = args.mmax\n self.zmin = args.zmin\n self.zmax = args.zmax\n self.probability = args.p\n self.etype = args.etype\n self.tlon = args.tlon\n self.tlat = args.tlat\n\n # some possibility to extract only a specific number of events\n self.num_events = -1\n\n # in case there is some deaggregation necessary\n # precision\n self.precision_lon = 0\n self.precision_lat = 0\n self.precision_mag = 0\n # data for the deaggregation itself\n self.optional_deaggregation_data = None\n\n # result\n self.selected = None\n\n self.filename_output = 'test.xml'\n\n def _check_longitude(self):\n '''If there is a longitude > 180 than it should be converted'''\n if self.lonmin > 180:\n self.lonmin = Main._convert_360(self.lonmin)\n if self.lonmax > 180:\n self.lonmax = Main._convert_360(self.lonmax)\n\n @staticmethod\n def _convert_360(lon):\n '''\n convert a longitude specified with 180+\n '''\n return lon-360\n\n def _needs_deaggreation(self):\n return self.etype == 'deaggregation'\n\n def _prepare_deaggreation(self, data_provider):\n '''\n Extracts all the necessary data for the deaggregation\n and stores it in the instance variables\n '''\n site_provider = data_provider.create_provider_for_sites()\n site = site_provider.get_nearest(self.tlon, self.tlat)\n deagg_provider = data_provider.create_provider_for_mean_deagg()\n self.optional_deaggregation_data = deagg_provider.get_all_for_site_and_poe(\n site, self.probability)\n deagg_analyzer = DeaggregationAnalyzer(self.optional_deaggregation_data)\n p_lon, p_lat, p_mag = deagg_analyzer.get_precisions_lon_lat_mag()\n self.precision_lon, self.precision_lat, self.precision_mag = p_lon, p_lat, p_mag\n # the reason behind storing this data is,\n # that the deaggregation may change the location of the data\n # so we need the precision of the deaggregated values to\n # extend the bounding box to query the database\n #\n # it there is no need for deaggregation,\n # than the precisions are all zero\n # and they don't influence the database query\n\n def _deaggregate(self):\n '''\n Does the deaggregation.\n Returns a pandas dataframe with the result.\n Because of the deaggregation a bigger extend of data\n must be queried from the database\n (see the method for binning).\n So we need another spatial filtering\n (and filtering for the magnitude as well)\n after deaggregation.\n '''\n matcher = DeaggregationMatcher(\n self.optional_deaggregation_data,\n self.precision_lon,\n self.precision_lat,\n self.precision_mag)\n deaggregation_result = matcher.match_deaggregation(self.selected)\n # another filter\n # because the deaggregation has needed a bigger extend of data\n deaggregation_result.add_filter_spatial(\n self.lonmin, self.lonmax, self.latmin,\n self.latmax, self.zmin, self.zmax)\n deaggregation_result.add_filter_magnitude(self.mmin, self.mmax)\n deaggregation_result.add_ordering_magnitude_desc()\n\n return deaggregation_result.get_result()\n\n def _write_file(self):\n\n writer = QuakeMLWriter(self.filename_output)\n writer.write(self.selected)\n\n def _filter_num_events(self):\n '''\n If the setting for the number of events is set,\n then only query the first n\n '''\n\n if self.num_events > 0:\n self.selected = self.selected.iloc[0:self.num_events]\n\n def run(self):\n '''\n Method to:\n - connect with the database\n - query the database\n - do some deaggregation if necessary\n - write the output\n '''\n\n self._check_longitude()\n\n with self.database as data_provider:\n\n event_provider = data_provider.create_provider_for_events()\n event_provider.add_filter_type(self.etype, self.probability)\n\n if self._needs_deaggreation():\n self._prepare_deaggreation(data_provider)\n\n # if the deaggregation is necessary\n # then the fields for the precision\n # have meaningful values\n #\n # to prepare the deaggregation it is also\n # necessary to provide a bigger extend\n # to search for earth quakes, because\n # the may be binned inside of the area\n # of interest\n event_provider.add_filter_spatial(\n self.lonmin - self.precision_lon,\n self.lonmax + self.precision_lon,\n self.latmin - self.precision_lat,\n self.latmax + self.precision_lat,\n self.zmin,\n self.zmax)\n # same for the magnitude\n event_provider.add_filter_magnitude(\n self.mmin - self.precision_mag,\n self.mmax + self.precision_mag)\n\n # there should be the ordering\n # with the highest magnitde first\n event_provider.add_ordering_magnitude_desc()\n\n self.selected = event_provider.get_results()\n\n if self._needs_deaggreation():\n self.selected = self._deaggregate()\n\n # because of sorting by magnitde\n # there are only those events with the\n # hightest magnitude\n self._filter_num_events()\n\n self._write_file()\n\n @classmethod\n def create_with_arg_parser(cls):\n '''\n Creates an arg parser and uses that to create the Main class\n '''\n arg_parser = argparse.ArgumentParser(\n description='''Program to query a earth quake catalog'''\n )\n arg_parser.add_argument(\n 'lonmin',\n help='Minimal longitude to search for earth quakes',\n type=float,\n default=288.0)\n arg_parser.add_argument(\n 'lonmax',\n help='Maximal longitude to search for earth quakes',\n type=float,\n default=292.0)\n arg_parser.add_argument(\n 'latmin',\n help='Minimal latitude to search for earth quakes',\n type=float,\n default=-70.0)\n arg_parser.add_argument(\n 'latmax',\n help='Maximal latitude to search for earth quakes',\n type=float,\n default=-10.0)\n arg_parser.add_argument(\n 'mmin',\n help='Lowest magnitude to search for earth qaukes',\n type=float,\n default=6.6)\n arg_parser.add_argument(\n 'mmax',\n help='Hightes magnitude to search for earth quakes',\n type=float,\n default=8.5)\n arg_parser.add_argument(\n 'zmin',\n help='Mininal depth to search for earth quakes',\n type=float,\n default=5.0)\n arg_parser.add_argument(\n 'zmax',\n help='Maximal depth to search for earth quakes',\n type=float,\n default=140.0)\n arg_parser.add_argument(\n 'p',\n help='Probability for deaggregation',\n type=float,\n default=0.1)\n arg_parser.add_argument(\n 'etype',\n help='Type of the earth quake in the catalog (expert, stochastic, deaggregation)',\n type=str,\n default=\"deaggregation\")\n arg_parser.add_argument(\n 'tlon',\n help='Longitude to search for the nearest side on deaggregation',\n type=float,\n default=-71.5730623712764)\n arg_parser.add_argument(\n 'tlat',\n help='Latitude to search for the nearest side on deaggregation',\n type=float,\n default=-33.1299174879672)\n args = arg_parser.parse_args()\n\n return cls(args)\n\nif __name__ == '__main__':\n Main.create_with_arg_parser().run()\n","sub_path":"eventquery.py","file_name":"eventquery.py","file_ext":"py","file_size_in_byte":8892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"265971516","text":"import matplotlib.pyplot as plt\nimport taxiagent\nimport randomagent\n\n# Izvrsavamo oba algoritma\nrandom_agent_scores = randomagent.randomagent(verbose=True)\nq_agent_scores = taxiagent.taxiagent(verbose=True)\n\n# Crtamo nagrade\nplt.plot(random_agent_scores, \"ko\", markersize=0.3)\nplt.title(\"Random Agent\")\nplt.xlabel('Episodes')\nplt.ylabel('Score')\nplt.show()\n\nplt.plot(q_agent_scores, \"ko\", markersize=0.3)\nplt.title(\"Q-learning Agent\")\nplt.xlabel('Episodes')\nplt.ylabel('Score')\nplt.show()\n","sub_path":"2020.2021/13_ucenje_potkrepljivanjem/dodatno/02.table.q.taxi.v3/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"81386313","text":"import sys\nimport numpy as np\nimport math\n\n\nINF = sys.float_info.max\n\n\nclass State(object):\n heuristic = \"\"\n connectionType = \"\"\n startState = None\n goalState = None\n stepSizeX = 0\n stepSizeY = 0\n stepSizeTheta = 0\n tolValue = 0\n G = float(\"inf\")\n E = float(\"inf\")\n env = None\n handler = []\n robot = None\n nodesDict = dict()\n stateList = []\n edgeCost = 1\n hMatrix = [[5,5,5,5],[INF,4,INF,4],[INF,3,INF,3],[INF,2,INF,3],[INF,1,INF,3],[0,1,2,3]]\n\n def __init__(self, config, pConfig, goalConfig=None):\n self._config = config\n self._parent = pConfig\n if goalConfig==None:\n self._hValue = euclideanMetric(self._config, self.goalState._config)\n else:\n self._hValue = euclideanMetric(self._config, goalConfig)\n self._gValue = sys.float_info.max\n self._fValue = 0\n self._edgeCosts = 1\n self._rhsValue = sys.float_info.max\n\n @property\n def gValue(self):\n return self._gValue\n\n @gValue.setter\n def gValue(self, value):\n self._gValue = value\n\n\n @property\n def hValue(self):\n return self._hValue\n\n @hValue.setter\n def hValue(self, value):\n self._hValue = value\n\n @property\n def fValue(self):\n return self._fValue\n\n\n @fValue.setter\n def fValue(self, value):\n self._fValue = value\n\n @property\n def rhsValue(self):\n return self._rhsValue\n\n @rhsValue.setter\n def rhsValue(self, value):\n self._rhsValue = value\n\n @property\n def config(self):\n return self._config\n\n @config.setter\n def config(self, conf):\n self._config = conf\n\n @property\n def parent(self):\n return self._parent\n\n @parent.setter\n def parent(self, conf):\n self._parent = conf\n\n def getCosts(self):\n return self._edgeCosts\n\ndef getEightConnectedNeighbors(state, stepSizeX, stepSizeY, stepSizeTheta):\n temp = []\n nextCells = []\n\n for i in [-1, 0, 1]:\n for j in [-1, 0, 1]:\n for k in [-1, 0, 1]:\n if i == j == k == 0:\n continue\n if (state[2] + k * stepSizeTheta) >= math.pi:\n Z = state[2] - 2 * math.pi\n elif (state[2] + k * stepSizeTheta) <= -1 * math.pi:\n Z = state[2] + 2 * math.pi\n else:\n Z = state[2]\n temp = [state[0] + i * stepSizeX, state[1] + j * stepSizeY, Z + k * stepSizeTheta]\n nextCells.append(temp)\n return nextCells\n\ndef euclideanMetric(current, goal):\n temp = [current[i]-goal[i] for i in range(len(current))]\n temp = np.asarray(temp)\n heuristic = np.linalg.norm(temp,2)\n return heuristic\n\ndef manhattanMetric(current, goal):\n temp = [current[i] - goal[i] for i in range(len(current))]\n temp = np.asarray(temp)\n heuristic = np.linalg.norm(temp,1)\n return heuristic","sub_path":"utils/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"187475111","text":"import collections\r\nclass Solution(object):\r\n def hammingWeight(self, n):\r\n \"\"\"\r\n :type n: int\r\n :rtype: int\r\n \"\"\"\r\n oribin='{0:032b}'.format(n)\r\n oList=list(oribin)\r\n count=0\r\n for pos in range(len(oList)):\r\n if oList[pos]=='1':\r\n count+=1\r\n return count\r\n\r\n return bin(n).count(\"1\")","sub_path":"191numberOf1Bits.py","file_name":"191numberOf1Bits.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"523809012","text":"import matplotlib.pyplot as plt\nfrom scipy.signal import butter, lfilter\nfrom math import sqrt\nfrom numpy import array, mean, std\n\ndef Motion_Data_2_Dict(Path2MotionFile):\n notanumber=True\n label=''\n value=[]\n with open(Path2MotionFile) as file:\n while(notanumber): # read until find numbers, previous line - label\n line = file.readline()\n if((line=='\\n') or (line=='')):\n continue\n line=line.split(';')\n while((line[-1][-1] == '\\n') or ((line[-1] == ''))):\n newitem=''\n for i in range(len(line[-1])-1):\n newitem+=line[-1][i]\n del line[-1]\n if(len(newitem)):\n line.append(newitem)\n try:\n for i in range(len(line)):\n line[i] = float(line[i])\n value.append(line)\n notanumber=False\n except(ValueError):\n label=line\n for i in range(len(label)):\n newitem = ''\n for letter in label[i]:\n if letter==' ':\n continue\n newitem+=letter\n label[i]=newitem\n\n\n while(len(line)):\n line = file.readline()\n if((line=='\\n') or (line=='')):\n continue\n line=line.split(';')\n while ((line[-1][-1] == '\\n') or ((line[-1] == '')) or (line[-1]=='\\n')):\n newitem = ''\n for i in range(len(line[-1]) - 1):\n newitem += line[-1][i]\n del line[-1]\n if (len(newitem)):\n line.append(newitem)\n for i in range(len(line)):\n line[i]=float(line[i])\n value.append(line)\n\n cvalue=[]\n for i in range(len(value[0])):\n column=[]\n for k in range(len(value)):\n column.append(value[k][i])\n cvalue.append(column)\n\n if(len(label)==len(cvalue)):\n valuedict = {label[i]:cvalue[i] for i in range(len(label))}\n return valuedict\n else:\n print(\"Something goes wrong, check number of labels and number of data columns\")\n exit(33)\n\ndef butter_bandpass_filter(data, lowcut, highcut, fs, order=2):\n nyq = 0.5 * fs\n low = lowcut / nyq\n high = highcut / nyq\n\n b, a = butter(order, [low, high], btype='band')\n y = lfilter(b, a, data)\n return y\n\ndef get_patient_name(path):\n slash=0\n reverse_name=''\n for i in range(len(path)-1,-1,-1):\n if (path[i]=='/'):\n slash+=1\n continue\n if (slash == 1):\n reverse_name+=path[i]\n if (slash == 2):\n break\n name=''\n for i in range(len(reverse_name) - 1, -1, -1):\n name+=reverse_name[i]\n return name\n\ndef get_folder(path):\n slash = 0\n for i in range(len(path) - 1, -1, -1):\n if (path[i] == '/'):\n slash+=1\n\n path2folder=''\n for i in range(len(path)):\n if (path[i] == '/'):\n slash-=1\n if (slash==0):\n break\n path2folder+=path[i]\n\n return path2folder\n\n\n name = ''\n for i in range(len(reverse_name) - 1, -1, -1):\n name += reverse_name[i]\n return name\n\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfilename\nTk().withdraw()\npath2File = askopenfilename(initialdir=\"C:\\\\Users\\Dante\\Desktop\\Новая папка\",\n filetypes =((\"CSV File\", \"*.csv\"),(\"Text File\", \"*.txt\"), (\"All Files\",\"*.*\")),\n title = \"Choose a motion data file\"\n )\n\nmyDict=Motion_Data_2_Dict(path2File)\n\nfs = int(len(myDict['TIMESTAMP']) / (myDict['TIMESTAMP'][-1] - myDict['TIMESTAMP'][0]))\n\nx = myDict['GYROX']\ny = myDict['GYROY']\nz = myDict['GYROZ']\nrow = [x, y, z]\nrNames = ['Row gyro X data', 'Row gyro Y data', 'Row gyro Z data']\nX = butter_bandpass_filter(myDict['GYROX'], 0.3, 20, fs)\nY = butter_bandpass_filter(myDict['GYROY'], 0.3, 20, fs)\nZ = butter_bandpass_filter(myDict['GYROZ'], 0.3, 20, fs)\nfiltered = [X, Y, Z]\nfNames = ['Filtered gyro X data', 'Filtered gyro Y data', 'Filtered gyro Z data']\n\nstamps = [5, 8.2, 11.4, 14.6,19.6]\nfor i in range(len(stamps)):\n stamps[i] *= 60\n stamps[i] += myDict['TIMESTAMP'][0]\n\nif stamps[-1]>myDict['TIMESTAMP'][-1]:\n stamps[-1] = myDict['TIMESTAMP'][-2]\n\nstageTime = [0]\nk = 0\nfor i in range(len(myDict['TIMESTAMP'])):\n if (myDict['TIMESTAMP'][i] > stamps[k]):\n stageTime.append(i)\n k += 1\n if (k == len(stamps)):\n break\n\nacceModule = []\nfor i in range(len(X)):\n acceModule.append(sqrt(X[i] * X[i] + Y[i] * Y[i] + Z[i] * Z[i]))\n\ng = 0\nfor i in range(len(acceModule)):\n g += acceModule[i]\ng /= len(acceModule)\ng *= 7\n\nfor i in range(len(acceModule)):\n acceModule[i] /= g\n\nstages = []\nfor i in range(len(stamps)):\n stages.append(array(acceModule[stageTime[i]:stageTime[i + 1]]))\n\n\nstagesNames = ['Background', 'First TOVA test', 'Hyperventilation', 'Second TOVA test', 'Aftereffect']\nstagesDict = {stagesNames[i]: stages[i] for i in range(len(stages))}\n\nmeanValue = []\nstdValue = []\nfor key in stagesDict:\n meanValue.append(mean(stagesDict[key]))\n stdValue.append(std(stagesDict[key]))\n\nforCSV = [';Mean;STD\\n']\nfor i in range(len(stagesNames)):\n forCSV.append(stagesNames[i] + ';')\n\nfor i in range(len(meanValue)):\n forCSV[i + 1] += str(round(meanValue[i],3))\n forCSV[i + 1] += ';'\n forCSV[i + 1] += str(round(stdValue[i],3))\n forCSV[i + 1] += '\\n'\n\n\n\ncsvName=get_patient_name(path2File)\npath2Save=get_folder(path2File)\npath2Save+='/Analysed'\n\nfrom os import makedirs\nfrom os.path import exists\nif not exists(path2Save):\n makedirs(path2Save)\n\n\n\nwith open(path2Save+'/'+csvName+\" Gyroscope.csv\", 'w') as file:\n for line in forCSV:\n file.write(line)\n file.close()\n\nplt.figure(figsize=(24.0, 15.0))\nfor i in range(6):\n\n if (i < 3):\n plt.subplot(2, 3, i + 1)\n plt.plot(myDict['TIMESTAMP'], row[i])\n plt.title(rNames[i])\n plt.xlabel('Time(sec)')\n plt.ylabel('Value')\n else:\n plt.subplot(2, 3, i + 1)\n plt.plot(myDict['TIMESTAMP'], filtered[i - 3])\n plt.title(fNames[i - 3])\n plt.xlabel('Time(sec)')\n plt.ylabel('Value')\nplt.savefig(path2Save+'/'+csvName+ ' Gyro signals.png')\n\nplt.figure(figsize=(24.0, 15.0))\nplt.plot(myDict['TIMESTAMP'], acceModule)\nplt.title(\"Gyroscope's value module at different stages\")\nplt.axis([myDict['TIMESTAMP'][0] + 20, myDict['TIMESTAMP'][stageTime[-1]], 0, 4])\nfor i in range(1, len(stageTime), 1):\n plt.plot((myDict['TIMESTAMP'][stageTime[i]], myDict['TIMESTAMP'][stageTime[i]]), (0, 4), 'r--')\nplt.xlabel('Time(sec)')\nplt.ylabel('Value(g)')\nfor i in range(len(stagesNames)):\n plt.text(myDict['TIMESTAMP'][stageTime[i]] + 50, 3.5, stagesNames[i],\n bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})\nplt.savefig(path2Save+'/'+csvName+ \" Gyroscope's value module.png\")\n\n\n\n'''''''''''''''''\n# writing to ANOVA csv\n'''''''''''''''''\npath2ANOVA='C:\\ANOVA\\MD\\Gyro'\nif not exists(path2ANOVA):\n makedirs(path2ANOVA)\n\n\ntry: # Mean value\n with open(path2ANOVA+'\\Mean.csv','a') as file:\n line=''\n for i in range(len(meanValue)):\n line+=str(meanValue[i])+';'\n line=line[:len(line)-1]\n line+='\\n'\n file.write(line)\n file.close()\nexcept:\n with open(path2ANOVA+'\\Mean.csv','w') as file:\n line=''\n for i in range(len(meanValue)):\n line+=str(meanValue[i])+';'\n line=line[:len(line)-1]\n line+='\\n'\n file.write(line)\n file.close()\n\ntry: # STD value\n with open(path2ANOVA+'\\STD.csv','a') as file:\n line=''\n for i in range(len(stdValue)):\n line+=str(stdValue[i])+';'\n line=line[:len(line)-1]\n line+='\\n'\n file.write(line)\n file.close()\nexcept:\n with open(path2ANOVA+'\\STD.csv','w') as file:\n line=''\n for i in range(len(stdValue)):\n line+=str(stdValue[i])+';'\n line=line[:len(line)-1]\n line+='\\n'\n file.write(line)\n file.close()\n\nprint(csvName)\n","sub_path":"PycharmProjects/MBIC/MD_Analysis/Gyro.py","file_name":"Gyro.py","file_ext":"py","file_size_in_byte":8290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"371526342","text":"import datetime\n\nfrom django.db import models\n\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n starring = models.CharField(max_length=200)\n summary = models.CharField(max_length=2000)\n genre = models.CharField(max_length=20)\n average_score = models.DecimalField(max_digits=5, decimal_places=3, default = 0.000)\n release_date = models.DateField(null=True)\n pub_date = models.DateTimeField('date published')\n\n @classmethod\n def movie_filter(cls, genre, time_frame, sort, title):\n movies = cls.objects \n\n # filter\n if genre != None and genre != '':\n movies = movies.filter(genre=genre)\n \n if time_frame != None and time_frame != '':\n if time_frame == 'last90days':\n movies = movies.filter(release_date__lte=datetime.date.today(), release_date__gt=datetime.date.today()-datetime.timedelta(days=90))\n else:\n movies = movies.filter(release_date__year=time_frame)\n\n if title != None and title != '':\n movies = movies.filter(title__icontains=title)\n\n # sort\n if sort == None or sort == '':\n movies = movies.order_by('-release_date')\n elif sort == 'A_Z':\n movies = movies.order_by('title')\n elif sort == 'Z_A':\n movies = movies.order_by('-title')\n elif sort == 'Score':\n movies = movies.order_by('-average_score')\n\n return movies\n\n class Meta:\n db_table = \"movies\"\n\n\n\nclass MovieTest(models.Model):\n title = models.CharField(max_length=200)\n starring = models.CharField(max_length=200)\n summary = models.CharField(max_length=2000)\n genre = models.CharField(max_length=20)\n average_score = models.DecimalField(max_digits=5, decimal_places=3, default = 0.000)\n release_date = models.DateField(null=True)\n pub_date = models.DateTimeField('date published')\n\n class Meta:\n db_table = \"movie_test\"\n\n","sub_path":"mvcrt/movie/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"284964668","text":"'''\r\n\r\nWelcome to GDB Online.\r\nGDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,\r\nC#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.\r\nCode, Compile, Run and Debug online from anywhere in world.\r\n\r\n'''\r\nimport math\r\ndef cetak_gambar (n) :\r\n if(n/2 == 0):\r\n return 0;\r\n \r\n res = ''\r\n # res += \"X X X X X \\n\"\r\n s = round(math.floor(n/2))\r\n for x in range(n):\r\n for y in range(n):\r\n if(x > 0 and x != n - 1):\r\n if(y == s):\r\n res += \"X \"\r\n else:\r\n res += \"= \"\r\n else :\r\n res += \"X \"\r\n \r\n res += \"\\n\"\r\n # res += \"X X X X X \\n\"\r\n print(res)\r\n\r\ncetak_gambar(5)\r\n\r\ncetak_gambar(7)\r\n","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"361520199","text":"#coding=UTF-8 \nimport sys \nimport pymysql\n\nif __name__==\"__main__\": \n \n #建立与数据库的链接 \n conn = pymysql.Connect(\n host='127.0.0.1',\n port=3306,\n user='root',\n passwd='root',\n db='test',\n charset='utf8'\n )\n sql='''DROP TABLE IF EXISTS `bccount`;\n CREATE TABLE `bccount` (\n `acctid` int(11) unsigned NOT NULL AUTO_INCREMENT,\n `money` int(11) NOT NULL,\n PRIMARY KEY (`acctid`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8;'''\n sql3=\"INSERT INTO `bccount` VALUES ('11','50')\"\n sql4=\"INSERT INTO `bccount` VALUES ('12','100')\"\n sql5=\"select * from bccount\"\n sql6= \"DELETE FROM bccount WHERE acctid > '%s'\" %(10)\n sql7= \"UPDATE bccount SET money = 80 WHERE acctid <'%s'\" %(10)\n sql8=\"INSERT INTO `bccount` VALUES ('1','10')\"\n sql9=\"INSERT INTO `bccount` VALUES ('2','20')\"\n\n try:\n cursor=conn.cursor()\n cursor.execute(sql)\n cursor.execute(sql3)\n cursor.execute(sql4)\n\n #提交当前事务 \n conn.commit()\n\n cursor.execute(sql5)\n for rs in cursor.fetchall():\n print(rs)\n\n cursor.execute(sql6)\n cursor.execute(sql8)\n cursor.execute(sql9)\n \n #提交当前事务 \n conn.commit()\n\n cursor.execute(sql5)\n for rs in cursor.fetchall():\n print(rs)\n\n cursor.execute(sql7)\n\n #提交当前事务 \n conn.commit()\n\n cursor.execute(sql5)\n for rs in cursor.fetchall():\n print(rs)\n\n except Exception as e:\n print(\"出现问题:\"+str(e))\n finally:\n cursor.ciose()#一般应在conn.commit()之前关闭cursor\n conn.close()\n #关闭链接 ","sub_path":"python学习训练/0 早期/创建表.py","file_name":"创建表.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"298682816","text":"\"\"\"performs CURD operations\r\n\"\"\"\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom dataQueue import engine, User, config\r\nimport sqlalchemy.exc\r\nimport logging\r\nfrom logging import basicConfig\r\nfrom LOGCONFIG.dict_config import config\r\n\r\nlogging.config.dictConfig(config)\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n# creating session to intract with database\r\nSession = sessionmaker(bind=engine)\r\n\r\n\r\ndef display_data():\r\n session = Session()\r\n try:\r\n users = session.query(User).all()\r\n except NameError as e:\r\n logger.error(e)\r\n else:\r\n user_list = []\r\n for user in users:\r\n values = {\r\n \"id\": user.id,\r\n \"username\": user.username,\r\n \"comment\": user.comment\r\n }\r\n user_list.append(values)\r\n session.close()\r\n return user_list\r\n\r\n\r\ndef insert_data(uname, comment):\r\n session = Session()\r\n user = User()\r\n user.username = uname\r\n user.comment = comment\r\n try:\r\n session.add(user)\r\n session.commit()\r\n logger.info('Record Created Successfully')\r\n return 'Record Created Successfully'\r\n\r\n except sqlalchemy.exc.IntegrityError as e:\r\n logger.error(e)\r\n return(\"username already exists!\")\r\n session.close()\r\n\r\n\r\ndef update_data(uid, u_name, u_comment):\r\n session = Session()\r\n u_id = '{}'.format(uid)\r\n try:\r\n if u_name is None and u_comment is None:\r\n return 'Required minimum one optional argument [--username][--comment]'\r\n elif u_name is None:\r\n x = session.query(User).filter(User.id == u_id).first()\r\n x.comment = u_comment\r\n session.commit()\r\n logger.info('comment updated to : {} '.format(u_comment))\r\n return 'comment updated to : {} '.format(u_comment)\r\n elif u_comment is None:\r\n x = session.query(User).filter(User.id == u_id).first()\r\n x.username = u_name\r\n session.commit()\r\n session.close()\r\n logger.info('username updated to : {}'.format(u_name))\r\n return 'username updated to : {}'.format(u_name)\r\n else:\r\n x = session.query(User).filter(User.id == u_id).first()\r\n x.username = u_name\r\n x.comment = u_comment\r\n session.commit()\r\n session.close()\r\n logger.info('updated username => {} and comment => {}'.format(\r\n u_name, u_comment))\r\n return 'updated username => {} and comment => {}'.format(u_name, u_comment)\r\n except sqlalchemy.exc.IntegrityError as e:\r\n logger.error(e)\r\n return 'username must be unique'\r\n return 'Updated'\r\n\r\n\r\ndef delete_data(uid):\r\n session = Session()\r\n u_id = '{}'.format(uid)\r\n x = session.query(User).filter(User.id == u_id). \\\r\n delete(synchronize_session=False)\r\n session.commit()\r\n session.close()\r\n return 'Deleted data for ID : {} '.format(u_id)\r\n","sub_path":"queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"32306132","text":"import numpy as np\nfrom gpmap.utils import hamming_distance\n\nclass EvolverError(Exception):\n \"\"\"Exception class for evolver methods\"\"\"\n\ndef get_neighbors(genotype, mutations):\n \"\"\"List all neighbors that are a single a mutation away from genotype.\n\n Parameters\n ----------\n genotype: str\n reference genotype.\n mutations : dict\n sites (keys) mapped to an alphabet list in genotype space (values).\n\n Returns\n -------\n neighbors : list\n List of neighbor genotypes\n \"\"\"\n sites = list(genotype)\n neighbors = []\n for i, alphabet in mutations.items():\n if alphabet is not None:\n # Copy alphabet to avoid over-writing\n alphabet = alphabet[:]\n alphabet.remove(sites[i])\n # Replace letters\n for a in alphabet:\n g = sites[:]\n g[i] = a\n neighbors.append(\"\".join(g))\n return neighbors\n\ndef get_forward_neighbors(source, current, mutations):\n \"\"\"List all neighbors that are a single a mutation away from genotype and\n move away from the source.\n\n Parameters\n ----------\n source : str\n source genotype which determines the direction to be moving away.\n current: str\n reference genotype.\n mutations : dict\n sites (keys) mapped to an alphabet list in genotype space (values).\n\n Returns\n -------\n neighbors : list\n List of neighbor genotypes\n \"\"\"\n s_sites = list(source)\n sites = list(current)\n hd = hamming_distance(source, current)\n neighbors = []\n for i, alphabet in mutations.items():\n if alphabet is not None:\n # Copy alphabet to avoid over-writing\n alphabet = alphabet[:]\n alphabet.remove(sites[i])\n # Replace letters\n for a in alphabet:\n g = sites[:]\n g[i] = a\n if hamming_distance(source, g) > hd:\n neighbors.append(\"\".join(g))\n return neighbors\n\n\ndef monte_carlo(gpm, source, target, model, max_moves=1000, forward=False, return_bad=False, **kwargs):\n \"\"\"Use a Monte Carlo approach to sample a single trajectory between a source\n genotype and a target genotype in a genotype-phenotype map.\n\n The only edges accessible to a given genotype in this implementation are genotypes\n that differ by a single mutation. All other moves are ignored. The algorithm\n builds a list of neighbors on-the-fly for each step. There is no `self` probability\n considered when making a move, thus, this will NOT recapitulate stationary\n frequencies, uncover a fitness landscape, or find equilibrium states. For the sake of\n efficiency, it merely samples pathways from source to target. If you'd like\n a better sampling of the fitness landscape and its equilibrium states, try\n the monte_carlo_metropolis_criterion function.\n\n If the trajectory doesn't make it to the target, an EvolverError is raised.\n\n Parameters\n ----------\n gpm : GenotypePhenotypeMap object (or subclassed object)\n The genotype-phenotype map to sample.\n source : str\n The starting genotype for simulation.\n target : str\n The ending genotype for simulation.\n model : callable\n A callable evolutionary model function that calculates the probability\n of transitioning between two genotypes.\n max_moves : int (default=1000)\n The max number of moves to try, in case the simulation gets stuck.\n forward : bool (default True)\n Set to True to only consider forward moves. Slows down the get_neighbors\n call, but avoids longer paths.\n return_bad : bool (default False)\n if True, return any trajectories that were not finished.\n\n Keyword Arguments\n -----------------\n Keyword arguments get passed directly to the model.\n\n Returns\n -------\n visited : tuple\n A tuple of all genotypes visited along a trajectory.\n \"\"\"\n # acquire a mapping of genotype to phenotype\n mapping_p = gpm.map(\"genotypes\", \"phenotypes\")\n # Set up get_neighbors method\n args = []\n if forward is True:\n args.append(source)\n neighbors_method = get_forward_neighbors\n else:\n neighbors_method = get_neighbors\n # Begin Monte Carlo loop.\n visited = (source,)\n moves = 0\n while visited[-1] != target and moves <= max_moves:\n # Observe new genotype\n current = visited[-1]\n fitness0 = mapping_p[current]\n # Find neighbors and calculate the probability of transitioning (normalized)\n nb_args = args[:] + [current, gpm.mutations]\n neighbors = np.array(neighbors_method(*nb_args))\n fitnesses = np.nan_to_num([model(fitness0, mapping_p[n], **kwargs) for n in neighbors])\n norm = fitnesses.sum()\n # Check that some move is possible. If not, raise error.\n if norm == 0:\n if return_bad:\n return visited\n else:\n raise EvolverError (\"Monte Carlo simulation got stuck; neighbors are deleterious. \\n\"\n \"Current progress : \" + str(visited))\n # Calculate a cumulative distribution to Monte Carlo sample neighbors.\n cumulative_dist = np.array([sum(fitnesses[:i+1])/norm for i in range(len(fitnesses))])\n # Monte Carlo number to sample\n mc_number = np.random.rand()\n # Make move\n new = neighbors[cumulative_dist>=mc_number][0]\n visited += (new,)\n moves += 1\n # Check for convergence and return visited.\n if moves > max_moves:\n raise EvolverError(\"Monte Carlo exceeded max number of moves.\")\n return visited\n\ndef monte_carlo_metropolis_criterion(gpm, source, target, model, max_fails=1000, **kwargs):\n \"\"\"Use a Monte Carlo, Metropolis Criterion method to sample a single path\n through a genotype-phenotype map.\n\n The only edges accessible to a given genotype in this implementation are genotypes\n that differ by a single mutation. All other moves are ignored. The algorithm\n builds a list of neighbors on-the-fly for each step. This method chooses a sample\n at random from its neighbors and uses a Metropolis criterion to accept or\n reject the move. The output will include all moves in the simulation, including\n all 'self' moves. This is useful for sampling the fitness landscape's stationary\n frequencies.\n\n Parameters\n ----------\n gpm : GenotypePhenotypeMap object (or subclassed object)\n The genotype-phenotype map to sample.\n source : str\n The starting genotype for simulation.\n target : str\n The ending genotype for simulation.\n model : callable\n A callable evolutionary model function that calculates the probability\n of transitioning between two genotypes.\n max_fails : int (default=1000)\n The max number of failed moves, in case the simulation gets stuck.\n\n Keyword Arguments\n -----------------\n Keyword arguments get passed directly to the model.\n\n Returns\n -------\n visited : tuple\n A tuple of all genotypes visited along a trajectory.\n \"\"\"\n # acquire a mapping of genotype to phenotype\n mapping_p = gpm.map(\"genotypes\", \"phenotypes\")\n # Begin Monte Carlo loop.\n visited = (source,)\n fails = 0\n while visited[-1] != target and fails <= max_fails:\n # Observe new genotype\n current = visited[-1]\n fitness0 = mapping_p[current]\n # Find neighbors and calculate the probability of transitioning (normalized)\n neighbors = np.array(get_neighbors(current, gpm.mutations))\n # sample neighbors\n mc_choice = np.random.choice(neighbors)\n mc_fitness = model(fitness0, mapping_p[mc_choice], **kwargs)\n # Metropolis criterion\n mc_number = np.random.rand()\n if mc_number < mc_fitness:\n visited += (mc_choice,)\n else:\n visited += (current,)\n fails += 1\n # Check for convergence and return visited.\n if fails > max_fails:\n raise EvolverError(\"Monte Carlo exceeded max number of moves.\")\n return visited\n","sub_path":"gpmap/evolve/mc.py","file_name":"mc.py","file_ext":"py","file_size_in_byte":8128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"62954126","text":"import re\n\nline_count = 0\nlit = 0\n\n\nscreen = [[0 for i in range(50)] for i in range(6)]\n\n\ndef make_rect(column, row):\n\tfor x in range(row):\n\t\tfor y in range(column):\n\t\t\tscreen[x][y] = 1\n\treturn screen\n\n\ndef move_row(row, shift):\n\trow_to_shift = screen[row]\n\tstartrow = row_to_shift[-shift:]\n\tendrow = row_to_shift[0:-shift]\n\tfinalrow = startrow + endrow\n\tscreen[row] = finalrow\n\treturn screen\n\t\n\ndef move_column(column, shift):\n\tcollist = [x[column] for x in screen]\n\tstartcol = collist[-shift:]\n\tendcol = collist[0:-shift]\n\tfinalcol = startcol + endcol\n\tfor x in range(len(screen)):\n\t\tscreen[x][column] = finalcol[x]\n\treturn screen\n\nf = open('commands.txt')\nfor line in f:\n\tshift_pos = []\n\trect = []\n\ts = line.split()\n\tif s[0] == 'rect':\n\t\trect = re.findall(r'rect (\\d+)x(\\d+)', line)\n\t\trect_row = int(rect[0][1])\n\t\trect_col = int(rect[0][0])\n\t\tmake_rect(rect_col, rect_row)\n\telse:\n\t\tshift_pos = re.findall(r'\\w+\\s{1}([a-z]+)\\s(x|y)=(\\d+)\\s{1}by\\s{1}(\\d+)', line)\n\t\tif shift_pos[0][0] == 'row':\n\t\t\trow_shift = int(shift_pos[0][3])\n\t\t\trow_num = int(shift_pos[0][2])\n\t\t\tmove_row(row_num, row_shift)\n\t\telse:\n\t\t\tcol_shift = int(shift_pos[0][3])\n\t\t\tcol_num = int(shift_pos[0][2])\n\t\t\tmove_column(col_num, col_shift)\n\tline_count += 1\t\n\nf.close()\nfor x in range(len(screen)):\n\tfor y in range(len(screen[x])):\n\t\tlit = lit + screen[x][y]\n\nprint (lit)\n\nfor x in screen:\n\tprint (x)","sub_path":"Day8/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"61868448","text":"# Time Complexity : O(n)\n# Space Complexity : O(n)\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\nclass Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n count_map = collections.Counter(nums)\n count =0\n for key in count_map.keys():\n if k == 0 and count_map[key+k] >= 2: # if k is 0, then there must be 2 same elements in the list to be counted as pair\n count+=1\n elif k > 0 and key+k in count_map: # k cannot be negative\n count+=1\n return count","sub_path":"532._K-diff_Pairs_in_an_Array.py","file_name":"532._K-diff_Pairs_in_an_Array.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"439814910","text":"##\n## Imprima la suma de la columna 2 por cada letra \n## de la columna 4, ordnados alfabeticamente.\n##\n## a,114\n## b,40\n## c,91\n## d,65\n## e,79\n## f,110\n## g,35\n##\n# Crear el archivo como una lista\nDatos = open('data.csv', 'r').readlines()\n# Eliminar el ultimo caracter\nDatos= [row[0:-1] for row in Datos]\n# Utilizar el separador de tabulación\nDatos= [row.split('\\t') for row in Datos]\n#Crar arreglo de Alfabeto Primero correr esta instrucción\nArreglo = []\n\nr= 0\nfor t in Datos:\n\tArreglo.append([])\n\tfor y in t:\n\t\tq = y.split(',')\n\t\tif(len(q) == 1):\n\t\t\tArreglo[r].append(q[0])\n\t\telse:\n\t\t\tArreglo[r].append(q)\n\tr += 1\n\nVector = {}\n\nfor rt in Arreglo:\n\tfor cl in rt[3]:\n\t\tif cl in Vector:\n\t\t\tVector[cl] += int(rt[1])\n\t\telse:\n\t\t\tVector[cl] = int(rt[1])\n\n# Imprimir\nfor vb in sorted(Vector.keys()):\n print(vb + ',' + str(Vector[vb]))","sub_path":"q12.py","file_name":"q12.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"328603521","text":"import re\nfrom ConfigParser import *\n\ndef itemsToOptions(items):\n options = {}\n for item in items:\n options[item[0]] = item[1]\n return options\n \nclass SystemConfig:\n def __init__(self,file,myselfName):\n self.file = file\n self.servers = []\n self.services = {}\n self.myself = None\n self.myselfName = myselfName\n self.parse()\n \n \n def get_redis_config(self,name):\n system_config = self.system_config\n host = system_config.get(name,\"host\")\n port = system_config.getint(name,\"port\")\n db = system_config.getint(name,\"db\")\n password = system_config.get(name,'password') if system_config.has_option(name,'password') else None\n return host,port,db,password\n \n def get_database_config(self,db_name):\n system_config = self.system_config\n user = system_config.get(db_name,\"user\")\n password = system_config.get(db_name,\"password\")\n if system_config.has_option(db_name,\"db_host\"):\n host = system_config.get(db_name,\"db_host\")\n else:\n host = \"localhost\"\n if system_config.has_option(db_name,\"db_port\"): \n port = system_config.getint(db_name,\"db_port\")\n else:\n port = None\n database = system_config.get(db_name,\"database\")\n if system_config.has_option(db_name,\"pool_size\"): \n pool_size = system_config.getint(db_name,\"pool_size\") \n else:\n pool_size = 5\n\n return user,password,database,host,port,pool_size\n \n def parse(self):\n self.servers = []\n self.myself = None\n cp = ConfigParser()\n cp.read(self.file)\n self.system_config = cp\n self.options = itemsToOptions(cp.items(\"system\"))\n if self.myselfName == None:\n return\n srv_names = cp.get(\"system\",\"servers\").split(\" \")\n myselfName = self.myselfName\n for name in srv_names:\n srv_conf = ServerConfig(name, cp.get(name,\"ip\"), \n cp.getint(name,\"port\"), itemsToOptions(cp.items(name)))\n self.servers.append(srv_conf)\n self.parseServer(srv_conf, cp)\n if (name == myselfName):\n self.myself = srv_conf\n \n if (self.myself == None):\n raise \"Need set myself variable\"\n\n def parseServer(self, srv_conf, parser):\n services = parser.get(srv_conf.name, \"services\").split(\" \")\n for service in services:\n service = service.strip()\n if service == \"\":\n continue\n re_match = re.match(r\"(\\w+)\\((\\d+)\\)\",service)\n if re_match == None:\n id = parser.getint(service, \"id\")\n else:\n service = re_match.group(1)\n id = parser.getint(service, \"id\") + int(re_match.group(2))\n \n options = itemsToOptions(parser.items(service))\n service_config = ServiceConfig(srv_conf, id, service, options)\n srv_conf.addService(service_config)\n if self.services.get(service_config.service) == None:\n self.services[service_config.service] = [service_config]\n else:\n self.services[service_config.service].append(service_config)\n \n \n def __repr__(self):\n return self.myself.name + \"->\" + str(self.servers)\n\nclass ServerConfig:\n def __init__(self,name,ip,port,options):\n self.name = name\n self.ip = ip\n self.port = port\n self.services = {}\n self.options = options\n \n def addService(self,serviceConfig):\n self.services[serviceConfig.id] = serviceConfig\n \n def __repr__(self):\n return self.name + str(self.services)\n\n \nclass ServiceConfig:\n def __init__(self,host,id,name,options):\n self.host = host\n self.id = id\n self.name = name\n handler = options.get(\"handler\",None)\n if handler == None:\n n0 = name[0].upper()\n n1 = name[1:]\n handler = name + \".\" + name + \"service.\" + n0 + n1 + \"Service\"\n options[\"handler\"] = handler\n if options.get(\"service\",None) == None:\n self.service = handler[handler.rindex(\".\")+1:]\n else:\n self.service = options.get(\"service\")\n self.options = options\n \n def __repr__(self):\n return \"host=\" + self.host.name + \" name=\" + self.name + \" id=\" + str(self.id)\n\nif __name__ == \"__main__\":\n import os,sys\n os.chdir(sys.path[0])\n\n config = SystemConfig(\"system.ini\")\n \n","sub_path":"code/systemconfig.py","file_name":"systemconfig.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"149373448","text":"#************************************************************************************************************************************************\n#\n# Copyright 2017-2020 David Briant\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 atA2WQ\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#************************************************************************************************************************************************\n\n\n\"\"\"Pipeable is a decorator that extends a function with the >> and << opertors with the effect of adding pipeline like behaviour (e.g. similar to |> in F#)\n\nx >> f and fn >> x both answer fn(x)\nx << f calls fn(x) and answers x\nf << x calls fn(x) and answers fn\n\nor equivalently\nlhs >> rhs answers f(x)\nlhs << rhs calls f(x) and answers the lhs\n\nSee /tests/test_pipeable for a fuller description and code examples\n\"\"\"\n\nfrom __future__ import annotations\n\n\nfrom typing import Any, Union\nimport types, inspect, collections, sys\nfrom ._core import Missing\n\n\n# add options to speed up\n# quickBindOneArg\n# if unary and (), << or >>\n# immediately execute\n# else () only\n# then quickBindHandleOneEllipses (next call (), << or >> will execute)\n\n# quickBindLastArg\n# if unary\n# immediately execute\n# else\n# if len(args) == len(myArgs)\n# then execute immediately\n# else quickBindNoEllipses (next call will execute)\n\n# quickBindNoEllipses - throws error if ellipses? or reverts to quickBindHandleOneEllipses or doesn't check until final call throws an error\n\n# could also add state so PipeableFunction is prepped ready for the last arg\n\ndef Pipeable(*args, overrideLHS=False, pipeOnly=False, leftToRight=Missing, rightToLeft=Missing):\n # overrideLHS allows a higher order function PF2 to override the behaviour of another PipeableFunction PF1\n # for PF1 >> PF2 or PF1 << PF2, i.e. execution order changes from PF1(), PF2() to PF2(), PF1()\n\n leftToRight, rightToLeft = (True, False) if (leftToRight is Missing and rightToLeft is Missing) else (leftToRight, rightToLeft)\n leftToRight = not rightToLeft if leftToRight is Missing else leftToRight\n rightToLeft = not leftToRight if rightToLeft is Missing else rightToLeft\n\n def _DecorateWithPF(fnOrClass):\n coreBindings = {}\n optionalBindings = {}\n optionalBindingsReprs = []\n hasKwargs = False\n if isinstance(fnOrClass, type):\n parameters = dict(inspect.signature(fnOrClass.__init__).parameters)\n selfName = list(parameters.keys())[0]\n del parameters[selfName]\n else:\n parameters = inspect.signature(fnOrClass).parameters\n for name, parameter in parameters.items():\n if parameter.kind == inspect.Parameter.VAR_POSITIONAL:\n raise TypeError('Function must not include *%s' % name)\n elif parameter.kind == inspect.Parameter.VAR_KEYWORD:\n hasKwargs= True\n optionalBindingsReprs.append('**%s' % name)\n else:\n if parameter.default == inspect.Parameter.empty:\n coreBindings[name] = Missing\n else:\n optionalBindings[name] = Missing\n optionalBindingsReprs.append('%s=%s' % (name, parameter.default))\n doc = fnOrClass.__doc__ if hasattr(fnOrClass, '__doc__') else ''\n fnRepr = '%s(%s)' % (fnOrClass.__name__, ', '.join(list(coreBindings.keys()) + optionalBindingsReprs))\n answer = PipeableFunction(fnOrClass, coreBindings, len(coreBindings), optionalBindings, hasKwargs, overrideLHS, pipeOnly, leftToRight, rightToLeft, doc, fnRepr)\n return answer\n\n if len(args) == 1 and isinstance(args[0], (types.FunctionType, types.MethodType, type)):\n # of form @Pipeable so args[0] is the function or class being decorated\n return _DecorateWithPF(args[0])\n else:\n # of form as @Pipeable() or @Pipeable(overrideLHS=True) etc\n return _DecorateWithPF\n\n\nclass PipeableFunction(object):\n # PipeableFunction accumulates arguments via () ,<< or >>\n # when it has enough arguments it calls the wrapped function\n __slots__ = [\n '_fnOrClass', '_hasKwargs', '_overrideLHS', '_pipeOnly', '_leftToRight', '_rightToLeft',\n '_doc', '_coreBindings', '_optionalBindings', '_fnRepr', '_numAvailableCoreBindings'\n ]\n\n def __init__(self, fn, coreBindings, numAvailableCoreBindings, optionalBindings, hasKwargs, overrideLHS, pipeOnly, leftToRight, rightToLeft, doc, fnRepr):\n self._fnOrClass = fn\n self._coreBindings = coreBindings\n self._numAvailableCoreBindings = numAvailableCoreBindings\n self._optionalBindings = optionalBindings\n self._hasKwargs = hasKwargs\n self._overrideLHS = overrideLHS\n self._pipeOnly = pipeOnly\n self._leftToRight = leftToRight\n self._rightToLeft = rightToLeft\n self._doc = doc\n self._fnRepr = fnRepr\n\n def _copy(self) -> PipeableFunction:\n return PipeableFunction(\n self._fnOrClass,\n dict(self._coreBindings),\n self._numAvailableCoreBindings, \n dict(self._optionalBindings),\n self._hasKwargs,\n self._overrideLHS,\n self._pipeOnly,\n self._leftToRight,\n self._rightToLeft,\n self._doc,\n self._fnRepr\n )\n\n def __repr__(self) -> str:\n # for pretty display in pycharm debugger\n return 'Pipeable=>%s' % self._fnRepr\n\n def __call__(self, *args, **kwargs) -> Any:\n \"\"\"Appends args and kwargs to the list of arguments for the function and returns the result\"\"\"\n if self._pipeOnly:\n raise TypeError('Cannot add arguments to %s using ()' % self._fnOrClass.__name__)\n return self._bindAndCall(*args, **kwargs)\n\n def __rrshift__(self, lhs: Any) -> Any:\n # lhs >> self\n \"\"\"Appends LHS to the list of arguments for the function and returns the result\"\"\"\n if not self._leftToRight:\n raise TypeError('Cannot add arguments to %s with >>' % self._fnOrClass.__name__)\n if isinstance(lhs, _Arg):\n return self._bindAndCall(lhs.arg)\n elif isinstance(lhs, _Args):\n return self._bindAndCall(*lhs.args)\n elif isinstance(lhs, _Kwargs):\n return self._bindAndCall(**lhs.kwargs)\n else:\n return self._bindAndCall(lhs)\n\n def __rshift__(self, rhs: Any) -> Any:\n # self >> rhs\n \"\"\"Appends RHS to the list of arguments for the function and returns the result\"\"\"\n if isinstance(rhs, (PipeableFunction,)) and rhs._overrideLHS and rhs._leftToRight:\n return rhs.__rrshift__(self)\n else:\n if not self._leftToRight:\n raise TypeError('Cannot add arguments to %s with >>' % self._fnOrClass.__name__)\n if isinstance(rhs, _Arg):\n return self._bindAndCall(rhs.arg)\n elif isinstance(rhs, _Args):\n return self._bindAndCall(*rhs.args)\n elif isinstance(rhs, _Kwargs):\n return self._bindAndCall(**rhs.kwargs)\n else:\n return self._bindAndCall(rhs)\n\n def __rlshift__(self, lhs: Any) -> Any:\n # lhs << self\n \"\"\"Appends LHS to the list of arguments for the function and returns the LHS\"\"\"\n if not self._rightToLeft:\n raise TypeError('Cannot add arguments to %s with <<' % self._fnOrClass.__name__)\n if self._numAvailableCoreBindings != 1:\n raise TypeError(\n 'Can only call %s with << when there is only one available core binding. Currently there are %s' % (\n self._fnOrClass.__name__, self._numAvailableCoreBindings))\n self._bindAndCall(lhs)\n return lhs\n\n def __lshift__(self, rhs: Any) -> Any:\n # self << rhs\n \"\"\"Appends RHS to the list of arguments for the function and returns the LHS (i.e. self)\"\"\"\n if isinstance(rhs, (PipeableFunction,)) and rhs._overrideLHS and rhs._rightToLeft:\n return rhs.__rrshift__(self)\n else:\n if not self._rightToLeft:\n raise TypeError('Cannot add arguments to %s with <<' % self._fnOrClass.__name__)\n if self._numAvailableCoreBindings != 1:\n raise TypeError(\n 'Can only call %s with << when there is only one available core binding. Current there are %s' % (\n self._fnOrClass.__name__, self._numAvailableCoreBindings))\n self._bindAndCall(rhs)\n return self\n\n def _bindAndCall(self, *args, **kwargs):\n # _bindAndCall is slightly easier to step through in a debugger\n bindResult = self._bind(*args, **kwargs)\n if isinstance(bindResult, tuple):\n return self._fnOrClass(*bindResult[0], **bindResult[1])\n else:\n return bindResult\n\n\n def _bind(oldself, *args, **kwargs):\n self = oldself._copy()\n\n availableCoreBindings = {k: v for (k, v) in self._coreBindings.items() if (isinstance(v, _ELLIPSIS) or v is Missing)}\n availableOptionalBindings = {k: v for (k, v) in self._optionalBindings.items() if(isinstance(v, _ELLIPSIS) or v is Missing)}\n\n def filterAndSort(bindingItems):\n bindingItems = [(k,v) for (k,v) in bindingItems if isinstance(v, _ELLIPSIS)]\n bindingItems.sort(key=lambda x: x[1].id)\n return bindingItems\n coreBindingsWithEllipsis = filterAndSort(availableCoreBindings.items())\n optionalBindingsWithEllipsis = filterAndSort(availableOptionalBindings.items())\n\n # process each arg finding it a home\n addedArgEllipsis = False\n addedKwargEllipsis = False\n checkForEllipsis = True\n checkForMissing = True\n while args:\n arg = args[0]\n if arg is ...:\n arg = _ADDING_ELLIPSIS()\n addedArgEllipsis = True\n elif arg is na:\n arg = Missing\n if checkForEllipsis:\n # fill the _ELLIPSIS first\n checkForEllipsis = False\n if coreBindingsWithEllipsis:\n name, v = coreBindingsWithEllipsis[0]\n self._coreBindings[name] = arg\n del availableCoreBindings[name]\n del coreBindingsWithEllipsis[0]\n checkForEllipsis = True\n args = args[1:]\n arg = _PROCESSED\n if arg is not _PROCESSED:\n if optionalBindingsWithEllipsis:\n name, v = optionalBindingsWithEllipsis[0]\n self._optionalBindings[name] = arg\n del availableOptionalBindings[name]\n del optionalBindingsWithEllipsis[0]\n checkForEllipsis = True\n args = args[1:]\n arg = _PROCESSED\n if arg is _PROCESSED:\n continue\n if checkForMissing:\n # once the _ELLIPSIS have been exhausted fill the Missing\n checkForMissing = False\n for name, v in availableCoreBindings.items():\n if v is Missing:\n self._coreBindings[name] = arg\n del availableCoreBindings[name]\n checkForMissing = True\n args = args[1:]\n arg = _PROCESSED\n break\n if arg is not _PROCESSED:\n for name, v in availableOptionalBindings.items():\n if v is Missing:\n self._optionalBindings[name] = arg\n del availableOptionalBindings[name]\n checkForMissing = True\n args = args[1:]\n arg = _PROCESSED\n break\n if arg is _PROCESSED:\n continue\n if arg is not _PROCESSED:\n raise TypeError('%s>>Number of args passed in > number of unbound parameters' % self._fnRepr)\n\n # process each kwarg finding it a home\n for name, arg in kwargs.items():\n if arg is ...:\n arg = _ADDING_ELLIPSIS()\n addedKwargEllipsis = True\n if name in availableCoreBindings:\n coreValue = availableCoreBindings[name]\n if isinstance(coreValue, _ELLIPSIS) or coreValue is Missing:\n self._coreBindings[name] = arg\n del availableCoreBindings[name]\n continue\n if name in availableOptionalBindings:\n optionalValue = availableOptionalBindings[name]\n if isinstance(optionalValue, _ELLIPSIS) or optionalValue is Missing:\n self._optionalBindings[name] = arg\n del availableOptionalBindings[name]\n continue\n if self._hasKwargs:\n self._optionalBindings[name] = arg\n continue\n raise TypeError('%s>>No unbound parameter available for arg named \"%s\"' % (self._fnRepr, name))\n\n\n if addedArgEllipsis:\n if len(availableCoreBindings) > 0:\n raise TypeError('%s>>... - number of args passed in < number of unbound parameters' % self._fnRepr)\n\n if addedArgEllipsis or addedKwargEllipsis:\n for name, arg in self._coreBindings.items():\n if isinstance(arg, _ADDING_ELLIPSIS):\n self._coreBindings[name] = _ELLIPSIS(arg.id)\n for name, arg in self._optionalBindings.items():\n if isinstance(arg, _ADDING_ELLIPSIS):\n self._optionalBindings[name] = _ELLIPSIS(arg.id)\n\n self._numAvailableCoreBindings = len(availableCoreBindings) \n if not (addedArgEllipsis or addedKwargEllipsis) and self._numAvailableCoreBindings == 0:\n return (\n list(self._coreBindings.values()),\n {k:v for k,v in self._optionalBindings.items() if v is not Missing}\n )\n else:\n return self\n\n\n\nclass _Arg(object):\n def __init__(self, arg):\n self.arg = arg\n\nclass _Args(object):\n def __init__(self, args):\n self.args = args\n\nclass _Kwargs(object):\n def __init__(self, kwargs):\n self.kwargs = kwargs\n\n\ndef arg(arg) -> _Arg:\n return _Arg(arg)\n\n@Pipeable(overrideLHS=True)\ndef args(args) -> _Args:\n if not hasattr(args, '__iter__'):\n raise TypeError('The argument to args must be iterable')\n return _Args(args)\n\n@Pipeable(overrideLHS=True)\ndef kwargs(kwargs) -> _Kwargs:\n if not isinstance(kwargs, collections.abc.Mapping):\n raise TypeError('The argument to kwargs must be a mapping')\n return _Kwargs(kwargs)\n\n\n\nif not hasattr(sys, '_NA'):\n class _NA(object):\n # def __str__(self):\n # return 'na'\n def __repr__(self):\n # for pretty display in pycharm debugger\n return 'na'\n sys._NA = _NA()\nna = sys._NA\n\n\n_ellipsisSeed = 0\nclass _ADDING_ELLIPSIS(object):\n def __init__(self):\n global _ellipsisSeed\n _ellipsisSeed += 1\n self.id = _ellipsisSeed\n # def __str__(self):\n # return '_ADDING_ELLIPSIS'\n def __repr__(self):\n # for pretty display in pycharm debugger\n return '_ADDING_ELLIPSIS(%s)' % self.id\n\nclass _ELLIPSIS(object):\n def __init__(self, id):\n self.id = id\n def __repr__(self):\n # for pretty display in pycharm debugger\n return '_ELLIPSIS(%s)' % self.id\n\nif not hasattr(sys, '_PROCESSED'):\n class _PROCESSED(object):\n # def __str__(self):\n # return '_PROCESSED'\n def __repr__(self):\n # for pretty display in pycharm debugger\n return '_PROCESSED'\n sys._PROCESSED = _PROCESSED()\n_PROCESSED = sys._PROCESSED\n\n","sub_path":"coppertop/pipeable.py","file_name":"pipeable.py","file_ext":"py","file_size_in_byte":16543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"54858425","text":"import random\r\n\r\na = []\r\n\r\n# Gera um vetor com 20 elementos entre 0 e 999.\r\ndef gera_vetor(a):\r\n\r\n for _ in range(20):\r\n a.append(random.randrange(0, 999))\r\n\r\n\r\ndef selection_sort(a):\r\n\r\n # Percorre o vetor de 0 ao tamanho do vetor, define x como a posição atual.\r\n for i in range(len(a)):\r\n x = i\r\n\r\n # Percorre a \"metade desordenada\" do vetor, comparando o elemento da posição \r\n # atual com os demais e colocando em x a posição do valor menor encontrado.\r\n for j in range(i+1, len(a)):\r\n if a[x] > a[j]:\r\n x = j\r\n\r\n # Troca o elemento da posição atual (iteração) com o menor elemento da \"metade desordenada\".\r\n a[i], a[x] = a[x], a[i]\r\n\r\n print(f'Vetor ordenado: {a}')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n gera_vetor(a)\r\n\r\n print(f'Vetor original: {a}')\r\n\r\n selection_sort(a)\r\n","sub_path":"selection_sort.py","file_name":"selection_sort.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"166804198","text":"# import modules\nfrom tkinter import *\nimport sqlite3\nimport tkinter.messagebox\nimport os.path\nimport timeit\nimport sys\nimport random\nimport time\nimport datetime\nfrom Security_code import Security\n\n# connect to the databse.\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\ndb_path = os.path.join(BASE_DIR, 'database.db')\nconn = sqlite3.connect(db_path)\n#DB 경로수정\n\n# cursor to move around the databse\nc = conn.cursor()\n\n# empty list to later append the ids from the database\nids = []\n\nstart_time = 0.0\nbtn_counter = 0\ncrt_time = 0.0\nid_num = 0\n\n# tkinter window\nclass Application:\n def __init__(self, master):\n self.master = master\n\n root.title(\"hospital_management\")\n root.title('hospital_reservation_system')\n\n # creating the frames in the master\n self.left = Frame(master, width=800, height=720, bg='aliceblue')\n self.left.pack(side=LEFT)\n\n self.right = Frame(master, width=400, height=720, bg='lightsteelblue')\n self.right.pack(side=RIGHT)\n\n now = datetime.datetime.now()\n nowDatetime = now.strftime('%Y-%m-%d %H시%M분')\n\n # labels for the window\n self.heading = Label(self.left, text=\"군밤 병원 예약관리시스템\", font=('나눔스퀘어_ac 40'), fg='black', bg='aliceblue')\n self.heading.place(x=130, y=50)\n\n # labels for now_datetime\n self.nowdatetime = Text(self.left, font=('나눔스퀘어_ac 13'), bg = 'aliceblue', fg = 'gray', width = 19, height=1)\n self.nowdatetime.place(x = 610, y = 0)\n self.nowdatetime.insert(END, nowDatetime)\n self.nowdatetime.configure(state = 'disabled')\n \n # patients name\n self.name = Label(self.left, text=\"이 름\", font=('나눔스퀘어_ac 17 bold'), fg='black', bg='aliceblue')\n self.name.place(x=200, y=150)\n\n # age\n self.age = Label(self.left, text=\"나 이\", font=('나눔스퀘어_ac 17 bold'), fg='black', bg='aliceblue')\n self.age.place(x=200, y=190)\n\n # gender\n self.gender = Label(self.left, text=\"성 별\", font=('나눔스퀘어_ac 17 bold'), fg='black', bg='aliceblue')\n self.gender.place(x=200, y=230)\n\n # location\n self.location = Label(self.left, text=\"주 소\", font=('나눔스퀘어_ac 17 bold'), fg='black', bg='aliceblue')\n self.location.place(x=200, y=270)\n\n # appointment time\n self.time = Label(self.left, text=\"예약 시간\", font=('나눔스퀘어_ac 17 bold'), fg='black', bg='aliceblue')\n self.time.place(x=200, y=310)\n\n # phone\n self.phone = Label(self.left, text=\"전화 번호\", font=('나눔스퀘어_ac 17 bold'), fg='black', bg='aliceblue')\n self.phone.place(x=200, y=350)\n\n # 안내사항1\n self.info1 = Label(self.left, text = \"☞ 예약 완료 전 꼭 읽어보세요 ☜\", font = ('굴림 15 bold'), fg = 'black', bg = 'aliceblue')\n self.info1.place(x=250, y=560)\n\n # 안내사항2\n self.info = Label(self.left, text = \"예약 당일 반드시 원무팀 접수창구에서 예약확인 후 진료과로 가십시오.\\n예약 후 내원하신 경우에도 진료실 사정에 따라 진료시간이 늦어질 수 있습니다.\\n \",\n justify = 'left', font = ('굴림 13 '), fg = 'black', bg = 'aliceblue')\n self.info.place(x=120, y=600)\n\n # Entries for all labels============================================================\n self.name_ent = Entry(self.left, width=25)\n self.name_ent.place(x=350, y=155)\n\n self.age_ent = Entry(self.left, width=25)\n self.age_ent.place(x=350, y=195)\n \n self.gender_ent = Entry(self.left, width=25)\n self.gender_ent.place(x=350, y=235)\n\n self.location_ent = Entry(self.left, width=25)\n self.location_ent.place(x=350, y=275)\n\n self.time_ent = Entry(self.left, width=25)\n self.time_ent.place(x=350, y=315)\n\n self.phone_ent = Entry(self.left, width=25)\n self.phone_ent.place(x=350, y=355)\n\n # button to perform a command\n self.submit = Button(self.left, text=\"예약\", width=6, height=1, bg='lightsteelblue', fg='white', font=('나눔스퀘어_ac 13 bold'), command=self.add_appointment)\n self.submit.place(x=360, y=420)\n \n \n # displaying the logs in our right frame\n self.logs = Label(self.right, text=\"예약 현황\", font=('나눔스퀘어_ac 30 bold'), fg='white', bg='lightsteelblue')\n self.logs.place(x=125, y=60)\n\n self.box = Text(self.right, width=50, height=30)\n self.box.place(x=25, y=140)\n #self.box.configure(state='disabled')\n\n self.update = Button(self.right, text = '새로고침', width = 6, height = 1, bg = 'lightsteelblue', fg = 'black', font = ('나눔스퀘어_ac 13'), command = self.data_update)\n self.update.place(x = 170, y = 570)\n\n def data_update(self):\n global id_num\n self.box.delete('1.0', END)\n # sql2 = \"SELECT ID FROM appointments \"\n # self.result = c.execute(sql2)\n # for self.row in self.result:\n # self.id = self.row[0]\n # ids.append(self.id) \n # self.new = sorted(ids)\n # self.final_id = self.new[len(ids)-1]\n # self.box.insert(END, \"마지막 ID는 \" + str(self.final_id)+ \"입니다.\\n\\n\")\n datas = c.execute(\"SELECT DISTINCT name, scheduled_time FROM appointments\")\n #datas = c.execute(\"SELECT name FROM appointments\")\n for data in datas:\n info1 = list(data)\n self.box.insert(END, str(info1[0]) + '님 \\t' + str(info1[1]) + '\\n' )\n \n\n # funtion to call when the submit button is clicked\n def add_appointment(self):\n global btn_counter\n global start_time\n global crt_time\n global id_num\n \n if btn_counter == 0:\n start_time = timeit.default_timer() \n\n btn_counter += 1\n\n # sql2 = \"SELECT ID FROM appointments \"\n # self.result = c.execute(sql2)\n # for self.row in self.result:\n # self.id = self.row[0]\n # ids.append(self.id) \n # self.new = sorted(ids)\n # self.final_id = self.new[len(ids)-1]\n # id_num = int(str(self.final_id))\n #print(id_num)\n\n if btn_counter >= 5:\n user1='user1'\n crt_time = timeit.default_timer() - start_time\n btn_counter = 0\n start_time = 0.0\n print(crt_time)\n #self.box.insert(END, str(crt_time) + \"\\n\")\n if crt_time < 0.5:\n tkinter.messagebox.showinfo(\"오류\", \"비 정상적인 사용이 감지되었습니다.\") # 메세지박스 띄우기\n print(\"매크로 방지 실행.\")\n print('%.2f' %crt_time, \"초에 5회 입력\")\n security_new = Security(user1)\n security_new.run() \n crt_time = 0.0\n return\n else: \n crt_time = 0.0 \n \n \n # getting the user inputs\n self.val1 = self.name_ent.get()\n self.val2 = self.age_ent.get()\n self.val3 = self.gender_ent.get()\n self.val4 = self.location_ent.get()\n self.val5 = self.time_ent.get()\n self.val6 = self.phone_ent.get()\n\n # checking if the user input is empty\n if self.val1 == '' or self.val2 == '' or self.val3 == '' or self.val4 == '' or self.val5 == '':\n tkinter.messagebox.showinfo(\"부적절한 접근\", \"채우지 않은 칸이 있습니다.\")\n else:\n # now we add to the database\n sql = \"INSERT INTO 'appointments' (name, age, gender, location, scheduled_time, phone) VALUES(?, ?, ?, ?, ?, ?)\"\n c.execute(sql, (self.val1, self.val2, self.val3, self.val4, self.val5, self.val6))\n conn.commit()\n \n \n\n# creating the object\nroot = Tk()\nb = Application(root)\n\n# resolution of the window\nroot.geometry(\"1200x720+0+0\")\n\n# preventing the resize feature\nroot.resizable(False, False)\n\n\n\n# end the loop\nroot.mainloop()","sub_path":"appointment.py","file_name":"appointment.py","file_ext":"py","file_size_in_byte":8165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"241823666","text":"import random as rd\nimport re\nimport warnings\nfrom itertools import chain\n\nimport nltk\nimport numpy as np\nimport pandas as pd\nfrom datasketch import MinHash, MinHashLSH\nfrom similarity.levenshtein import Levenshtein\nfrom similarity.normalized_levenshtein import NormalizedLevenshtein\n\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\nREPLACE_BY_SPACE_RE = re.compile('[-._/(){}\\[\\]\\|@,;\\\\\\/]')\nBAD_SYMBOLS_NUMBERS = re.compile('[^\\d*(\\.\\d+)?]')\nBAD_SYMBOLS_RE = re.compile('[^0-9a-z A-Z]')\nSTOPWORDS = set(stopwords.words('english'))\n\n\ndef check_info(df, columns=[]):\n null = df.isnull().sum()\n if len(columns) == 0:\n columns = df.columns\n for c in columns:\n print(\"column: \", c)\n print(\"total not null values: \", len(df[df[c].notnull()]))\n print(\"total null values: \", null[c])\n print(\"total unique values: \", len(df[c].unique()))\n gr_title_count = df.groupby(c).count()\n print(\"Duplicated values: \", gr_title_count[gr_title_count['id'] > 1].shape[0])\n print(\"Duplicated instances: \",\n gr_title_count[gr_title_count['id'] > 1]['id'].sum() - gr_title_count[gr_title_count['id'] > 1].shape[0])\n print(\"===================\")\n\n\ndef data_preprocessing(dfs, params):\n \"\"\"\n Preprocess dataframes according to the parameters passed in the params dict. Default parameters are provided.\n :param dfs: list of data frames\n :param params: processing parameters\n :return: the concatenated dataset\n \"\"\"\n parameters = {\n 'missing_value': 'nan,ukn,none,unknown,', # values to be interpreted as nulls\n 'missing_value_strategy': '', # strategy to be used when handling null values\n 'round_number': -1, # number of rounding digits for float numbers\n 'round_columns': '', # columns to be rounded\n 'split_columns': '', # columns that contain lists to be split\n 'split_delimiter': ',', # delimiter used in the lists\n 'expand_columns': '', # columns that should be expanded in the graph generation phase\n 'tokenize_shared': True, # flag to use heuristic\n 'concatenate': '', # one of {'outer', 'inner', 'horizon'}\n 'auto_merge': False, # flag used to trigger automatic LSH merge of candidates\n 'mh_k_shingles': 3, # size of lsh shingles\n 'mh_threshold': .5, # minhash threshold\n 'mh_perm': 128, # minhash permutations\n 'distance': 'normalized_edit_distance', # string distance to be used\n 'distance_threshold': .20, # distance threshold to decide similar values\n 'merge_columns': '', # columns to study when performing the lsh merge\n 'remove_stop_word': False, # flag to use to remove stop words\n 'case_sensitive': False, # flag to use to specify if the content of the dataset is case sensitive\n }\n for _ in params.keys():\n if _ in parameters:\n parameters[_] = params[_]\n\n # Check if parameters are valid\n try:\n parameters['round_number'] = int(parameters['round_number'])\n except ValueError:\n parameters['round_number'] = -1\n warnings.warn('Round number must be an integer. Run without rounding number.')\n if parameters['round_number'] > -1 and parameters['round_columns'] == '':\n warnings.warn('No attributes chosen to round.')\n if parameters['auto_merge'] and parameters['merge_columns'] == '':\n parameters['auto_merge'] = False\n warnings.warn('No attributes chosen to merge.')\n\n if isinstance(dfs, pd.DataFrame):\n dfs = [dfs]\n parameters['concatenate'] = ''\n\n all_merge_columns = []\n\n df_words = {}\n\n # Iterate through all data frames.\n for i, df in enumerate(dfs):\n # Set all values to lowercase if words are not case sensitive.\n if not parameters['case_sensitive']:\n df.columns = [_.lower() for _ in df.columns]\n df.columns = [re.sub(r'\\s+', '_', str(x)) for x in df.columns]\n # df[c] = df[c].apply(lambda x: )\n #\n # normalize missing values\n if parameters['missing_value'] != '':\n missing_value = parameters['missing_value'].split(',')\n missing_value = [_.strip() for _ in missing_value]\n missing_value = \"|\".join(missing_value)\n pattern = re.compile('^\\s*(' + missing_value + ')\\s*$', re.IGNORECASE)\n df = df.replace(pattern, np.nan)\n\n # Extract the columns needed to perform different operations on\n num_columns = [_ for _ in parameters['round_columns'].split(',') if _ in df.columns]\n split_columns = [_ for _ in parameters['split_columns'].split(',') if _ in df.columns]\n if parameters['tokenize_shared']:\n expand_columns = df.columns\n else:\n expand_columns = [_ for _ in parameters['expand_columns'].split(',') if _ in df.columns]\n\n # normalize text: lower/trim/replace by space/remove bad chars/concatenate string\n for c in df.columns:\n\n # Apply string normalization only on string fields.\n if df[c].dtype == 'object':\n\n if c in num_columns:\n warnings.warn(\n 'Column {} is marked to be rounded, but it contains non-numeric characters.'.format(c))\n df[c] = df[c].apply(lambda x: re.sub(BAD_SYMBOLS_NUMBERS, '', str(x)))\n try:\n df[c] = df[c].replace('', np.nan).astype(float)\n except ValueError():\n print('Something went wrong. Wrong type found. Skipping column {}'.format(c))\n else:\n if not parameters['case_sensitive']:\n df[c] = df[c].str.lower()\n # If the column under observation is a list, it will be expanded\n if c in split_columns:\n df[c] = df[c].apply(_split_lists, delimiter=parameters['split_delimiter'])\n else:\n df[c] = df[c].apply(lambda x: re.sub(BAD_SYMBOLS_RE, '', str(x)))\n df[c] = df[c].apply(lambda x: re.sub(REPLACE_BY_SPACE_RE, ' ', str(x).strip().lower()))\n # If the column should be expanded,\n if c in expand_columns:\n df[c] = df[c].apply(lambda x: re.sub(r'\\s+', '_', str(x)))\n else:\n df[c] = df[c].apply(lambda x: re.sub(r'\\s+', '|', str(x)))\n if parameters['remove_stop_word']:\n df[c] = df[c].apply(_remove_stop_words, '_')\n\n for c in num_columns:\n df[c] = df[c].apply(lambda x: re.sub(r'[^\\d.]', '', str(x)))\n df[c] = df[c].apply(_round_number, ndigits=parameters['round_number'])\n\n # change the columns name in case of horizon concatenation\n if parameters['concatenate'] == 'horizon' and len(dfs) > 1:\n for idx, c in enumerate(parameters['merge_columns'].split(',')):\n if c in df.columns:\n all_merge_columns.append(str(i) + '_' + c)\n df.columns = str(i) + '_' + df.columns\n\n dfs[i] = df\n df_words[i] = get_unique_string_values(df, df.columns)\n\n # concatenate datasets\n if len(dfs) > 1:\n if parameters['concatenate'] == 'inner':\n concat_df = pd.concat(dfs, join=\"inner\")\n elif parameters['concatenate'] == 'horizon':\n concat_df = pd.concat(dfs, axis=0, ignore_index=True, sort=True)\n else:\n concat_df = pd.concat(dfs, sort=True)\n else:\n concat_df = dfs[0]\n\n def retokenize(line, words):\n if line in words:\n return line.replace('_', '|')\n else:\n return line\n\n if len(dfs) > 1:\n if parameters['tokenize_shared']:\n intersection = df_words[0].intersection(df_words[1])\n if len(dfs) > 2:\n for i, df in enumerate(dfs[2:]):\n intersection = intersection.intersection(df_words[i])\n for c in concat_df.columns:\n concat_df[c] = concat_df[c].apply(retokenize, words=intersection)\n\n concat_df.reset_index(inplace=True, drop=True)\n\n # merge\n if parameters['auto_merge']:\n if len(all_merge_columns) == 0:\n all_merge_columns = [_ for _ in parameters['merge_columns'].split(',') if _ in concat_df.columns]\n if len(all_merge_columns) > 0:\n # get unique values\n uniq_values = set(concat_df[all_merge_columns].astype(str).values.ravel())\n lsh = LSHMerge(uniq_values, parameters['mh_k_shingles'], parameters['mh_threshold'], parameters['mh_perm'])\n replacement = lsh.get_replacement(parameters['distance'], parameters['distance_threshold'])\n\n # rep_path = '../pipeline/replacements/'\n # with open(rep_path + parameters['output_file'] + '.txt', 'wb') as fp:\n # fp.write(pickle.dumps(replacement))\n\n concat_df = concat_df.replace(replacement)\n else:\n pass\n\n # empty value\n # concat_df = concat_df.fillna('')\n if parameters['missing_value_strategy'] == 'separated_null':\n for c in concat_df.columns:\n c_idx = concat_df.columns.get_loc(c)\n concat_df.loc[concat_df[c] == '', c] = c_idx + '_null_' + concat_df.loc[concat_df[c] == '', c].index.astype(\n str)\n elif parameters['missing_value_strategy'] == 'one_null':\n concat_df = concat_df.replace('', 'null')\n\n return concat_df\n\n\ndef _remove_stop_words(text, delimiter=\" \"):\n text = delimiter.join([word for word in text.split(delimiter) if word not in STOPWORDS])\n return text\n\n\ndef _split_lists(line, delimiter=','):\n split = []\n if line is np.nan:\n return ''\n for word in [_.strip() for _ in line.split(delimiter)]:\n x = re.sub(BAD_SYMBOLS_RE, '', str(word))\n x = re.sub(REPLACE_BY_SPACE_RE, ' ', str(x).strip().lower())\n x = re.sub(' ', '|', str(x).strip().lower())\n split.append(x)\n s = '_'.join(split)\n return s\n\n\ndef _split_sticked_words(text):\n try:\n f_text = float(text)\n return f_text\n except ValueError:\n s = \"\"\n i = 0\n while i < (len(text) - 1):\n if text[i].isdigit():\n if text[i - 1].isalpha() and text[i + 1].isdigit():\n s = s + \" \" + text[i]\n elif text[i - 1].isalpha() and text[i + 1].isalpha():\n s = s + text[i] + \" \"\n else:\n s += text[i]\n elif text[i].islower() and text[i + 1].isupper():\n s = s + text[i] + \" \"\n else:\n s += text[i]\n i += 1\n return s + text[-1]\n\n\ndef expand_columns_old(df, columns, drop=True):\n \"\"\"\n Expand a column into word-based columns\n :param df:\n :param column:\n :param drop:\n :return:\n \"\"\"\n if isinstance(columns, str):\n columns = [columns]\n for c in columns:\n old_columns = df.columns\n new_columns = []\n expanded_columns = df[c].str.split(\"_\", expand=True)\n for i in range(expanded_columns.shape[1]):\n df[c + \"_\" + str(i)] = expanded_columns[i]\n new_columns.append(c)\n if drop:\n df.drop(columns=[c], inplace=True)\n old_columns.remove(c)\n df.columns = old_columns + new_columns\n\n # if drop:\n # df.drop(columns=columns, inplace=True)\n return df\n\n\ndef _round_number(value, ndigits):\n try:\n return round(float(value), ndigits)\n except ValueError:\n return value\n\n\ndef get_unique_string_values(df, columns, level='token'):\n \"\"\"\n Get unique values in token level or word level\n :param df:\n :param columns:\n :param level:\n :return:\n \"\"\"\n values = df[columns].astype(str).values.ravel()\n if level == 'word':\n words = [v.split('_') for v in values]\n words = set(chain.from_iterable(words))\n else:\n words = set(values)\n w_f = []\n for w in words:\n try:\n if float(w):\n w_f.append(w)\n except ValueError:\n pass\n for w in w_f:\n words.remove(w)\n return words\n\n\ndef merge(df, replacement_dict, columns, level='token'):\n \"\"\"\n Merge values based on a dictionary of replacement in level token / word\n :param df:\n :param replacement_dict:\n :param columns:\n :param level:\n :return:\n \"\"\"\n if isinstance(columns, str):\n columns = [columns]\n if level == 'token':\n df = df.replace(replacement_dict)\n elif level == 'word':\n for f, r in replacement_dict.items():\n f_pattern = re.compile('(^|_)' + f + '($|_)', re.IGNORECASE)\n r_repl = lambda m: m.group(1) + r + m.group(2)\n for c in columns:\n df[c] = df[c].str.replace(f_pattern, r_repl)\n return df\n\n\ndef write_info_file(dfs, output, f=[]):\n \"\"\"\n Write the info file\n :param f: list of file paths\n :param dfs: list of dataframes in the same order as the concatenation in the dp phase\n :param output: output file name\n :return:\n \"\"\"\n # info_path = '../pipeline/info/'\n with open(output, 'w') as fp:\n if len(f) != len(dfs):\n f = list(range(len(dfs)))\n for idx, df in enumerate(dfs):\n fp.write('{},{}\\n'.format(f[idx], df.shape[0]))\n\n\nclass LSHMerge:\n def __init__(self, uniq_values, k_shingles=3, mh_threshold=.5, mh_num_perm=128, delimiter='_'):\n self.k_shingles = k_shingles\n self.mh_threshold = mh_threshold\n self.mh_num_perm = mh_num_perm\n self.uniq_values = uniq_values\n self.delimiter = delimiter\n self.lsh = MinHashLSH(threshold=self.mh_threshold, num_perm=self.mh_num_perm)\n self._generate_hashes()\n\n def _generate_hashes(self):\n for token in self.uniq_values:\n if isinstance(token, str):\n m = self._generate_hash(token)\n self.lsh.insert(token, m)\n\n def _generate_hash(self, value):\n if isinstance(self.k_shingles, int):\n shingles = set([value[max(0, i - self.k_shingles):i] for i in range(self.k_shingles, len(value) + 1)])\n elif self.k_shingles == 'word':\n shingles = set(value.split(self.delimiter))\n\n m = MinHash(num_perm=self.mh_num_perm)\n for shingle in shingles:\n m.update(shingle.encode('utf8'))\n return m\n\n def get_similarities(self, value):\n m = self._generate_hash(value)\n return self.lsh.query(m)\n\n def get_sample_blocks(self, n=5):\n count = 0\n n_tries = 20\n results = []\n tried = set()\n while len(results) < n and count < n_tries:\n samples = rd.sample(self.uniq_values, min(n, len(self.uniq_values)))\n for _ in samples:\n if len(results) >= n:\n break\n if _ not in tried:\n m = self._generate_hash(_)\n similarities = self.lsh.query(m)\n if len(similarities) > 1:\n results.append(similarities)\n tried.add(_)\n count += 1\n return results\n\n def get_replacement(self, distance='lsh', threshold=.8):\n if distance == 'edit_distance':\n distance = Levenshtein()\n elif distance == 'normalized_edit_distance':\n distance = NormalizedLevenshtein()\n\n # for each token, get its bin\n # for each bin, iterate each element and get the groups of satisfied tokens such as\n # [white] = [whit, whie, whit]\n # [whie] = [whine,white]\n\n replacement = {}\n s = self.uniq_values\n\n while len(s) > 0:\n token = rd.sample(s, 1)[0]\n s.remove(token)\n m = self._generate_hash(token)\n similarities = self.lsh.query(m)\n similarities = [_ for _ in similarities if _ not in replacement.values() and _ not in replacement.keys()]\n if len(similarities) > 1:\n scores = {}\n bin_replacement = {}\n if distance != 'lsh':\n for idx, item in enumerate(similarities):\n count = 0\n candidates = []\n for idx_compared in range(idx + 1, len(similarities)):\n candidate = similarities[idx_compared]\n if item != candidate and distance.distance(item, candidate) < threshold:\n if idx not in bin_replacement:\n bin_replacement[idx] = [idx_compared]\n else:\n bin_replacement[idx].append(idx_compared)\n if idx_compared not in bin_replacement:\n bin_replacement[idx_compared] = [idx]\n else:\n bin_replacement[idx_compared].append(idx)\n\n for idx_item, candidates in sorted(bin_replacement.items(), key=lambda x: -len(x[1])):\n item = similarities[idx_item]\n if item in replacement.keys():\n item = replacement[item]\n for idx_candidate in candidates:\n candidate = similarities[idx_candidate]\n if candidate != item and candidate not in replacement.keys():\n if item not in replacement.keys():\n replacement[candidate] = item\n elif replacement[item] != candidate:\n replacement[candidate] = replacement[item]\n else:\n for candidate in similarities:\n if candidate != token:\n replacement[candidate] = token\n\n return replacement\n\n\nif __name__ == '__main__':\n parameters = {\n 'output_file': '',\n 'concatenate': 'outer',\n 'missing_value': 'nan,ukn,none,unknown,-',\n 'missing_value_strategy': '',\n 'round_number': 1,\n 'round_columns': '',\n 'auto_merge': False,\n 'expand_columns': '',\n 'tokenize_shared': False\n }\n f1 = '../pipeline/experiments/programming_challenge/www.shopbot.com.au.csv'\n df1 = pd.read_csv(f1, encoding='ISO-8859-1')\n for c in df1.columns:\n if df1[c].dtype == 'object':\n df1[c] = df1[c].str.replace('_', ' ')\n\n f2 = '../pipeline/datasets/programming_challenge/www.pricedekho.com.csv'\n df2 = pd.read_csv(f2, encoding='ISO-8859-1')\n\n for c in df2.columns:\n if df2[c].dtype == 'object':\n df2[c] = df2[c].str.replace('_', ' ')\n\n # print(\"Datasets exploration:\", f1)\n # check_info(df1, ['title', 'manufacturer', 'description'])\n # print(\"Datasets exploration:\", f2)\n # check_info(df2, ['title', 'manufacturer', 'description'])\n\n df_c = data_preprocessing([df1, df2], parameters)\n write_info_file([df1, df2], 'cameras_testing', [f1, f2])\n\n # Merge title in word level\n # words = get_unique_string_values(df_c, 'title', 'word')\n #\n # lsh = LSHMerge(words, 2, .5, 128)\n # replacement = lsh.get_replacement('normalized_edit_distance', .35)\n #\n # df_c = merge(df_c, replacement, ['title'], 'word')\n\n # Manually handle the merge for each column using different params\n # print(\"Start merging title\")\n # uniq_values = set(df_c[['title']].values.ravel())\n #\n # start_time = datetime.datetime.now()\n # lsh = LSHMerge(uniq_values, 2, .3, 128)\n # replacement = lsh.get_replacement('normalized_edit_distance', .7)\n # end_time = datetime.datetime.now()\n #\n # print('Generate replacement list: ', end_time - start_time)\n # print('Length of replacement list: ', len(replacement))\n #\n # df_c = df_c.replace(replacement)\n\n # print(\"Start merging manufacturer\")\n # uniq_values = set(df_c[['manufacturer']].values.ravel())\n #\n # start_time = datetime.datetime.now()\n # lsh = LSHMerge(uniq_values, 3, .5, 128)\n # replacement = lsh.get_replacement('normalized_edit_distance', .2)\n # end_time = datetime.datetime.now()\n #\n # print('Generate replacement list: ', end_time - start_time)\n # print('Length of replacement list: ', len(replacement))\n #\n # print(\"Concatenated dataset exploration:\")\n # check_info(df_c, ['title', 'manufacturer', 'description'])\n\n # Export the file\n df_c.to_csv('../pipeline/datasets/' + parameters['output_file'] + '.csv', index=False)\n","sub_path":"algorithms/embdi/EmbDI/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":20754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"515557154","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image as PILImage\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nfrom torch.nn import BCELoss\nfrom torch.utils import data\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\nfrom torch.utils.tensorboard import SummaryWriter\n\n# Commented out IPython magic to ensure Python compatibility.\n# %matplotlib inline\ndevice = torch.device('cpu')\nif torch.cuda.is_available():\n device = torch.device('cuda')\n\n\n# ================================================== Dataset ============================================ #\nclass Cars(data.Dataset):\n def __init__(self, **kwargs):\n self.img_data = kwargs['img_data']\n self.img_size = kwargs['img_size']\n self.imgs = os.listdir(self.img_data)\n\n def transform_img(self, img, img_size):\n h_, w_ = img_size[0], img_size[1]\n im_size = tuple([h_, w_])\n t_ = transforms.Compose([\n transforms.ToPILImage(),\n transforms.Resize(im_size),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.457, 0.407],\n std=[1, 1, 1])\n ])\n img = t_(img)\n return img\n\n def load_img(self, idx):\n im = np.array(PILImage.open(os.path.join(self.img_data, self.imgs[idx])))\n im = self.transform_img(im, self.img_size)\n return im\n\n def __len__(self):\n return len(self.imgs)\n\n def __getitem__(self, idx):\n X = self.load_img(idx)\n return idx, X\n\n# ================================================= Generator =========================================== #\nclass Generator(nn.Module):\n def __init__(self, **kwargs):\n super(Generator, self).__init__()\n self.latentVect = kwargs['latentVect']\n self.FeaGen = kwargs['FeaGen']\n self.nc = kwargs['nc']\n self.main = nn.Sequential(\n # input is Z, going into a convolution\n nn.ConvTranspose2d(in_channels=self.latentVect, out_channels=self.FeaGen * 15, kernel_size=2,\n stride=1, padding=0,\n bias=False),\n nn.BatchNorm2d(self.FeaGen * 15),\n nn.ReLU(True),\n # state size. (FeaGen*15) x 2 x 2\n nn.ConvTranspose2d(self.FeaGen * 15, self.FeaGen * 12, 3, 1, 1, bias=False),\n nn.BatchNorm2d(self.FeaGen * 12),\n nn.ReLU(True),\n # state size. (FeaGen*12) x 2 x 2\n nn.ConvTranspose2d(self.FeaGen * 12, self.FeaGen * 8, kernel_size= 4,stride= 2,padding= 1, bias=False),\n nn.BatchNorm2d(self.FeaGen * 8),\n nn.ReLU(True),\n # state size. (FeaGen*8) x 4 x 4\n nn.ConvTranspose2d(self.FeaGen * 8, self.FeaGen * 4, kernel_size=4,stride= 2, padding= 1, bias=False),\n nn.BatchNorm2d(self.FeaGen * 4),\n nn.ReLU(True),\n # state size. (FeaGen*4) x 8 x 8\n nn.ConvTranspose2d(self.FeaGen * 4, self.FeaGen*2, kernel_size=4, stride= 2,padding= 1, bias=False),\n nn.BatchNorm2d(self.FeaGen*2),\n nn.ReLU(True),\n # state size. (FeaGen*2) x 16 x 16\n nn.ConvTranspose2d(self.FeaGen*2, self.FeaGen, kernel_size=4,stride= 2,padding= 1, bias=False),\n nn.BatchNorm2d(self.FeaGen),\n nn.ReLU(True),\n # state size. (nc) x 32 x 32\n nn.ConvTranspose2d(self.FeaGen, self.nc, kernel_size=4,stride=2,padding=1, bias = False),\n nn.Tanh(),\n )\n\n def forward(self, input):\n return self.main(input)\n\n# ============================================== Discriminator ========================================== #\n# Discriminator takes an 'image': object dimensionality batch_size x 3 x H x W\nclass Discriminator(nn.Module):\n def __init__(self, **kwargs):\n super(Discriminator, self).__init__()\n self.FeaDis = kwargs['FeaDis']\n self.nc = kwargs['nc']\n self.main = nn.Sequential(\n # input is (nc) x 64 x 64\n nn.Conv2d(in_channels=self.nc, out_channels=self.FeaDis, kernel_size=4, stride=2, padding=1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (FeaDis) x 32 x 32\n nn.Conv2d(self.FeaDis, self.FeaDis * 2, kernel_size=4,stride= 2,padding= 1, bias=False),\n nn.BatchNorm2d(self.FeaDis * 2),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (FeaDis*2) x 16 x 16\n nn.Conv2d(self.FeaDis * 2, self.FeaDis * 4, kernel_size=4,stride= 2,padding= 1, bias=False),\n nn.BatchNorm2d(self.FeaDis * 4),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (FeaDis*4) x 8 x 8\n nn.Conv2d(self.FeaDis * 4, self.FeaDis * 8, kernel_size=4,stride= 2,padding= 1, bias=False),\n nn.BatchNorm2d(self.FeaDis * 8),\n nn.LeakyReLU(0.2, inplace=True),\n #\n nn.Conv2d(self.FeaDis * 8, self.FeaDis * 12, kernel_size=4,stride= 2,padding= 1, bias=False),\n nn.BatchNorm2d(self.FeaDis * 12),\n nn.LeakyReLU(0.2, inplace=True),\n #\n # state size. (FeaDis*8) x 4 x 4\n nn.Conv2d(self.FeaDis * 12, out_channels= 1, kernel_size= 4, stride= 2, padding= 1, bias=False),\n nn.Sigmoid()\n )\n self.classifier = nn.Sequential(\n nn.Linear(768 * 11 * 11, 1),\n # nn.Sigmoid()\n )\n\n def forward(self, input):\n features = self.main(input)\n # features = features.view(-1, features.size()[1]*features.size()[2]*features.size()[3])\n # out=self.classifier(features)\n return features\n\n\n# ========================================= Training Parameters ======================================== #\nbatch_size = 256\nbatch_size_str = str(batch_size)\nimage_size = [64, 64]\nassert len(image_size) == 2\nwd = os.getcwd()\n# number of channels\nnc = 3\n# latent space (z) size: G input\nlatentVect = 100\n# Features discriminator\nFeaDis = 64\n# Features generator\nFeaGen = 64\n# epochs\nnum_epochs = 3501\n# learning rate\nlrate = 1e-4\n# optimizer parameters\noptimizer_pars = {'lr': lrate, 'weight_decay': 1e-3}\n# strings for saving\nw_decay_str = '001'\nlrate_str = '0001'\n# ============================================= Dataset path ========================================= #\n#path_img = os.path.join(wd, \"cars3_green\")\n# this is just for now, use path above for server training\npath_img = \"/Users/willemvandemierop/Google Drive/DL Classification (705)/v_03_with_carimages/cars3_green\"\nfor filename in sorted(os.listdir(path_img)):\n if filename == '.DS_Store':\n os.remove(path_img + \"/\" + filename)\n# ====================================== dataset and dataloader ====================================== #\ndataset_pars = {'img_size': image_size, 'img_data': path_img}\nobs = Cars(**dataset_pars)\ndataloader_pars = {'batch_size': batch_size, 'shuffle': True}\ndataloader = data.DataLoader(obs, **dataloader_pars)\n# get the right device\n# optimizers\n\n\ndirname = 'model_Bigger_DCGAN_batch' + str(batch_size) + \"_wd\" + w_decay_str + \"_lr\" + lrate_str\nif not os.path.exists(os.path.join(wd, dirname)): os.mkdir(os.path.join(wd, dirname))\n\n# instantiate models and put them on CUDA\ng_pars = {'latentVect': latentVect, 'FeaGen': FeaGen, 'nc': nc}\nd_pars = {'FeaDis': FeaDis, 'nc': nc}\n\n# models\nstart_epochs = 0\ng = Generator(**g_pars)\nd = Discriminator(**d_pars)\ng = g.to(device)\nd = d.to(device)\n\n# =========================================== Print parameters of models ===================================== #\n\nprint(g)\ntotal_g = 0\nfor _n, _par in g.state_dict().items():\n total_g += _par.numel()\n\nprint(\"parameters generator\", total_g)\nprint(d)\ntotal_d = 0\nfor _n, _par in d.state_dict().items():\n total_d += _par.numel()\nprint(\"parameters discriminator\", total_d)\n\n# =============================================== Optimizers ========================================= #\n# create labels\nreal_label = 1\ngenerated_label = 0\n\noptimizerD = optim.Adam(d.parameters(), **optimizer_pars)\noptimizerG = optim.Adam(g.parameters(), **optimizer_pars)\n\n# =========================================== Pretrained Loading ===================================== #\n# main train loop\nepochs = 0\nfolder_name = os.path.join(wd, dirname)\nif os.path.exists(os.path.join(folder_name, 'checkpoint.pth')):\n print(\"loading pretrained optimizers\")\n checkpoint = torch.load(os.path.join(dirname, 'checkpoint.pth'))\n optimizerD.load_state_dict(checkpoint['optimizer_state_dict_D'])\n optimizerG.load_state_dict(checkpoint['optimizer_state_dict_G'])\n epochs = checkpoint['epoch'] + 1\n try:\n weights_g = torch.load(os.path.join(folder_name, \"gen_gr_ResN_batch_\" + batch_size_str + \"_wd\"\n + w_decay_str + \"_lr\" + lrate_str + \"_e\" + str(epochs -1) + \".pth\"))\n g.load_state_dict(weights_g)\n print(\"Loaded intermediate weights for generator\")\n except:\n raise FileNotFoundError(\"could not load intermediate weights Generator\")\n\n try:\n weights_d = torch.load(os.path.join(folder_name, \"dis_gr_ResN_batch_\" + batch_size_str + \"_wd\"\n + w_decay_str + \"_lr\" + lrate_str + \"_e\" + str(epochs -1) + \".pth\"))\n d.load_state_dict(weights_d)\n print(\"Loaded intermediate weights for Discriminator\")\n except:\n raise FileNotFoundError(\"could not load intermediate weights Discriminator\")\n\n\n# ================================================= Training ================================================== #\n\nimage_folder_name = \"Generated_images_gr_DCGAN_Bigger\"\nif not os.path.exists(wd + '/' + image_folder_name):\n os.mkdir(wd + '/' + image_folder_name)\n# loss function\n# loss = BCEWithLogitsLoss()\ntb = SummaryWriter(comment=\"DC_GAN_Bigger_batch\" + batch_size_str + \"_wd\" + w_decay_str + \"_lr\" + lrate_str)\nloss = BCELoss()\nloss = loss.to(device)\nfor e in range(epochs, num_epochs):\n for id, data in dataloader:\n # print(id)\n # first, train the discriminator\n d.zero_grad()\n g.zero_grad()\n data = data.to(device)\n batch_size = data.size()[0]\n # labels: all 1s\n labels_t = torch.ones(batch_size).unsqueeze_(0)\n labels_t = labels_t.to(device)\n # get the prediction of the D model\n # D(x)\n predict_d = d(data).view(1, -1)\n # loss from real data\n loss_t = loss(predict_d, labels_t)\n loss_t.backward()\n # generator input and output\n z = torch.randn(batch_size, latentVect, 1, 1, device=device)\n h = g(z)\n # all labels are 0s\n labels_g = torch.zeros(batch_size).unsqueeze_(0)\n labels_g = labels_g.to(device)\n # D(1-G(z))\n predict_g = d(h.detach()).view(1, -1)\n # loss from generated data\n loss_g = loss(predict_g, labels_g)\n loss_g.backward()\n total_loss = loss_t + loss_g\n # update discriminator weights\n optimizerD.step()\n # D(G(z))\n g.zero_grad()\n labels_g_real = torch.ones(batch_size).unsqueeze_(0)\n labels_g_real = labels_g_real.to(device)\n #\n o = d(h).view(1, -1)\n loss_g_real = loss(o, labels_g_real)\n # update generator weights\n loss_g_real.backward()\n optimizerG.step()\n\n tb.add_scalar('Discriminator Loss w.r.t. Real Data (D(x))', loss_t, e)\n tb.add_scalar('Discriminator Loss w.r.t. Generated Data (D(1-G(z)))', loss_g, e)\n tb.add_scalar('Total Loss', total_loss, e)\n\n if e % 100 == 0:\n torch.save({'epoch': e, 'optimizer_state_dict_D': optimizerD.state_dict(),\n \"optimizer_state_dict_G\": optimizerG.state_dict()}, os.path.join(folder_name, 'checkpoint.pth'))\n torch.save(g.state_dict(), os.path.join(folder_name, \"gen_gr_Big_DC_batch_\" + batch_size_str + \"_wd\" + w_decay_str + \"_lr\" + lrate_str + \"_e\" + str(e) + \".pth\"))\n torch.save(d.state_dict(), os.path.join(folder_name, \"dis_gr_Big_DC_batch_\" + batch_size_str + \"_wd\" + w_decay_str + \"_lr\" + lrate_str + \"_e\" + str(e) + \".pth\"))\n print(\"saved intermediate weights\")\n weights = torch.load(os.path.join(folder_name, \"gen_gr_Big_DC_batch_\" + batch_size_str + \"_wd\" + w_decay_str + \"_lr\" + lrate_str + \"_e\" + str(e) + \".pth\"))\n args = {'latentVect': 100, 'FeaGen': 128, 'nc': 3}\n model = Generator(**g_pars)\n model.load_state_dict(weights)\n for i in range(5):\n if not os.path.exists(wd + \"/\"+ image_folder_name + \"/\" + \"hallucinated_\" + str(e)):\n os.mkdir(wd + \"/\"+ image_folder_name + \"/\" + \"hallucinated_\" + str(e))\n z = torch.randn(1, 100, 1, 1)\n out = model(z)\n t_ = transforms.Normalize(mean=[-0.485, -0.450, -0.407], std=[1, 1, 1])\n out = out.detach().clone().squeeze_(0)\n out = t_(out).numpy().transpose(1, 2, 0)\n plt.imshow(out)\n filename = wd + \"/\"+ image_folder_name + \"/\" + \"hallucinated_\" + str(e) + \"/generated_\" + str(i) + \".png\"\n plt.savefig(filename)\n\ntb.close()\ntorch.save({'epoch': e, 'optimizer_state_dict_D': optimizerD.state_dict(),\n \"optimizer_state_dict_G\": optimizerG.state_dict()}, os.path.join(folder_name,'checkpoint.pth'))\ntorch.save(g.state_dict(), os.path.join(folder_name, \"gen_gr_Big_DC_batch_\" + batch_size_str + \"_wd\" + w_decay_str + \"_lr\" + lrate_str + \"_e\" + str(e) + \".pth\"))\ntorch.save(d.state_dict(), os.path.join(folder_name, \"dis_gr_Big_DC_batch_\" + batch_size_str + \"_wd\" + w_decay_str + \"_lr\" + lrate_str + \"_e\" + str(e) + \".pth\"))\nprint(\"finished training\")","sub_path":"DCGAN/DCGAN_bigger.py","file_name":"DCGAN_bigger.py","file_ext":"py","file_size_in_byte":13737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"27383968","text":"\"\"\"\n41. Maximum Subarray\nhttps://www.lintcode.com/problem/maximum-subarray/description?_from=ladder&&fromId=37\n\ndp[i] maximum sum of continuous array inlcuding point X[i]\n\nanalysis, dp has the choice of either including previous sum or not, either way, it must including X[i] by definition.\ndp[i] = dp[i - 1] + X[i] if dp[i - 1] > 0, else, it will only make it smaller, so dp[i]\n时间复杂度O(N)\nintilization\ndp[0] = nums[0]\nanswer: max(dp)\n\"\"\"\nclass Solution:\n \"\"\"\n @param nums: A list of integers\n @return: A integer indicate the sum of max subarray\n \"\"\"\n def maxSubArray(self, nums):\n # write your code here\n if not nums:\n return 0\n dp = [0] * len(nums)\n dp[0] = nums[0]\n for i in range(1, len(nums)):\n if dp[i - 1] > 0:\n dp[i] = dp[i - 1] + nums[i]\n else:\n dp[i] = nums[i]\n \n return max(dp)","sub_path":"lintcode/41.py","file_name":"41.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"314533653","text":"import os\nimport errno\n\ndef file_picker():\n\tfile_path = raw_input(\"Please enter the file to check: \")\n\tfile_path = str(file_path)\n\tprint(\"Attempting to open file: \"+file_path)\n\ttry:\n\t\tfile = open(file_path,\"r\") #open file for 'r' READing\n\texcept IOError as e:\n\t\tif e.errno == errno.ENOENT:\n\t\t\treturn \"unusable input\"\n\t\traise\n\telse: \n\t\treturn file\n\ndef check_profanity(file):\n\tdata = {}\n\tprofane = 1\n\tlist_profanity = ['shit','fuck','ass']\n\tfor LineNumber, Line in enumerate(iter(file.readline, b'')):\n\t\tfor WordNumber, Word in enumerate(Line.split()):\n\t\t\tWord = Word.strip(\".,;:\")\n\t\t\tfor swear in list_profanity:\n\t\t\t\tif Word.lower() == swear:\n\t\t\t\t\tprint(\"LINE: \"+str(LineNumber)+\n\t\t\t\t\t\t\" WORD: \"+str(WordNumber)+\n\t\t\t\t\t\t\" <\"+Word+\n\t\t\t\t\t\t\"> is most profane!!\")\n\t\t\t\t\tprofane = 0\n\tif(profane):\n\t\tprint(\"Good Job! You responded without swearing!\")\n\ndef main():\n\tfile=file_picker()\n\tcheck_profanity(file)\n\nmain()","sub_path":"fsnd/2017/2017/check_profanity/check_profanity.py","file_name":"check_profanity.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"486002011","text":"from flask import Flask, jsonify, request, Response\nfrom app.producer import publish\nimport prometheus_client\nfrom prometheus_client.core import CollectorRegistry\nfrom prometheus_client import Summary, Counter, Histogram, Gauge\nimport pika\nimport time\n\n\n\n\ndef create_app():\n app = Flask(__name__)\n\n INF = float(\"inf\")\n\n graphs = {}\n graphs['c'] = Counter('python_request_operations_total', 'The total number of processed requests')\n graphs['h'] = Histogram('python_request_duration_seconds', 'Histogram for the duration in seconds.', buckets=(1, 2, 5, 6, 10, INF))\n\n\n @app.route('/')\n def add_command():\n print(\"Request json is {}\".format(request.get_json()))\n start = time.time()\n command = request.get_json()[\"data\"]\n publish(command, \"jobmanager\")\n end = time.time()\n graphs['h'].observe(end - start)\n return jsonify(\"command <<{}>> published\".format(command))\n\n @app.route(\"/metrics\")\n def requests_count():\n res = []\n for k,v in graphs.items():\n res.append(prometheus_client.generate_latest(v))\n return Response(res, mimetype=\"text/plain\")\n\n return app\n\n\n\nif __name__ == '__main__':\n app = create_app()\n app.run(port=8000)","sub_path":"backend/dataAccess/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"93359388","text":"\"\"\"\nMRvisor加载数据的函数\n\"\"\"\nimport os\nimport sys\nimport subprocess\nimport configparser\nfrom MR.Kernel import Universal, Error, ColoredOutput\n\n\"\"\"\nconfig_dict格式:{名称:{命令,是否自动重启},{},{}...}\nprocess_dict格式:{名称:{启动时间,subprocess对象,重启次数},{},{}...}\n\"\"\"\n\n\ndef load():\n \"\"\"\n 加载数据\n \"\"\"\n try:\n config_dict = load_config_dict()\n except Error.NoProperConfigFileFound:\n ColoredOutput.to_red(\"No proper config file found, going down\")\n sys.exit(0)\n else:\n process_dict = to_process_dict(config_dict)\n return config_dict, process_dict\n\n\ndef check_config() -> list:\n \"\"\"\n 检查所有的配置文件,返回所有合法的配置文件列表\n \"\"\"\n parser = configparser.ConfigParser()\n possible_config = []\n\n # 过滤所有后缀名不是conf的文件\n for file in os.listdir(\"Config\"):\n if Universal.get_file_suffix(file) == \"conf\":\n possible_config.append(file)\n\n # 检查配置文件的内容\n for file in possible_config:\n try:\n parser.read(\"Config/%s\" % file)\n except:\n # 读取配置文件出错,是非法的配置文件\n possible_config.remove(file)\n ColoredOutput.to_red(\"Unable to load %s\" % file)\n else:\n # 检查sections,只应有MRvisor一个section\n if not parser.sections() == [\"MRvisor\"]:\n possible_config.remove(file)\n ColoredOutput.to_red(\"Unable to load %s\" % file)\n else:\n # 检查option,只应有nickname, script, autorestart三项\n if not parser.options(\"MRvisor\") == ['nickname', 'script', 'autorestart']:\n possible_config.remove(file)\n ColoredOutput.to_red(\"Unable to load %s\" % file)\n return possible_config\n\n\ndef load_config_dict() -> dict:\n \"\"\"\n 加载配置文件,返回配置字典\n \"\"\"\n config_list = check_config()\n config_dict = {}\n parser = configparser.ConfigParser()\n\n if not config_list:\n # 得到的是空列表,抛出异常\n raise Error.NoProperConfigFileFound\n else:\n for file in config_list:\n parser.read(\"Config/%s\" % file)\n config_dict[parser.get(\"MRvisor\", \"NickName\")] = {\n \"Script\": parser.get(\"MRvisor\", \"Script\"),\n \"AutoRestart\": parser.get(\"MRvisor\", \"AutoRestart\")\n }\n return config_dict\n\n\ndef to_process_dict(config_dict: dict) -> dict:\n \"\"\"\n 将配置字典转换为子程序字典\n \"\"\"\n process_dict = {}\n for config_name, config_detail in config_dict.items():\n script = config_detail[\"Script\"]\n p = subprocess.Popen(\n script, shell=True,\n stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, preexec_fn = os.setsid)\n process_dict[config_name] = {\n \"StartTime\": Universal.get_time(),\n \"ProcessObject\": p,\n \"RestartTimes\": 0\n }\n return process_dict\n","sub_path":"MR/Kernel/Load.py","file_name":"Load.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"626246698","text":"from zad1testy import runtests\n\ndef intuse( I, x, y ):\n n = len( I )\n \n nums = [] #tablica wszystkich cyfr wystepujacych w przedzialach\n for i in range( n ):\n nums.append( I[i][0] )\n nums.append( I[i][1] )\n\n nums.sort()\n uniquenums = [nums[0]]\n\n for i in range( 1, len(nums) ):\n if nums[i] == nums[i - 1]:\n continue\n uniquenums.append(nums[i])\n\n m = len( nums )\n DPY = [False for _ in range(m + 1)] #True if current num can be connected with Y\n DPX = [False for _ in range(m + 1)] #True if current num can be connected with X \n \n DPY[y] = True\n DPX[x] = True\n\n intervals_sorted_reversed = sorted(I, reverse = True)\n\n for interval in intervals_sorted_reversed:\n if DPY[interval[1]] == True:\n DPY[interval[0]] = True\n\n intervals_sorted = sorted(I, key = lambda x: x[1])\n\n for interval in intervals_sorted:\n if DPX[interval[0]] == True:\n DPX[interval[1]] = True\n \n result = []\n for i in range( len(I) ):\n if DPX[I[i][0]] and DPY[I[i][1]]:\n result.append(i)\n return result\n\nruntests( intuse )\n","sub_path":"colloquiumsAndExams/exam2/zad1v2.py","file_name":"zad1v2.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"206103536","text":"from django.core.management.base import BaseCommand\nfrom django.db import transaction\nfrom core.models import Biography, User\n\n\nclass Command(BaseCommand):\n help = 'create users'\n\n def success(self, message):\n return self.stdout.write(\n self.style.SUCCESS(message)\n )\n\n def warning(self, warning):\n return self.stdout.write(\n self.style.WARNING(warning)\n )\n\n def error(self, error):\n return self.stdout.write(\n self.style.ERROR(error)\n )\n\n def handle(self, *args, **options):\n self.warning(\n 'if something goes wrong after fixtres installations,\\\n please use: python manage.py flush'\n )\n\n with transaction.atomic():\n \"\"\"create user admin\"\"\"\n admin = User.objects.create_superuser(\n email='admin@cotizate.com',\n password='admin2019'\n )\n Biography.objects.create(\n terms_cond=True,\n email_2='admin@cotizate.com',\n is_complete=True,\n is_representative=True,\n user=admin\n )\n self.success('admin user created.')\n\n \"\"\"create users creators and contributors\"\"\"\n\n user_creator_1 = User.objects.create_user(\n name='jhon',\n last_name='Doe',\n cellphone='123654',\n dni='654987',\n address='here brasil',\n type_user=1,\n email='jhondoe@yopmail.com',\n password='me123',\n is_active=True\n )\n Biography.objects.create(\n terms_cond=True,\n email_2='admin@cotizate.com',\n is_complete=True,\n is_representative=True,\n user=user_creator_1\n )\n user_creator_2 = User.objects.create_user(\n name='mery',\n last_name='Doe',\n cellphone='123654',\n dni='654987',\n address='here brasil',\n type_user=1,\n email='merydoe@yopmail.com',\n password='me123',\n is_active=True\n )\n Biography.objects.create(\n terms_cond=True,\n email_2='admin@cotizate.com',\n is_complete=True,\n is_representative=True,\n user=user_creator_2\n )\n self.success('users creators created')\n\n \"\"\"user contributors\"\"\"\n user_contributor_1 = User.objects.create_user(\n name='mario',\n last_name='Lucas',\n cellphone='123654',\n dni='654987',\n address='here other way',\n type_user=2,\n email='maricolucas@yopmail.com',\n password='me123',\n is_active=True\n )\n Biography.objects.create(\n terms_cond=True,\n email_2='mariolucas@cotizate.com',\n is_complete=True,\n is_representative=True,\n user=user_contributor_1\n )\n user_contributor_2 = User.objects.create_user(\n name='marina',\n last_name='Lucas',\n cellphone='123654',\n dni='654987',\n address='here beyond away',\n type_user=2,\n email='marinalucas@yopmail.com',\n password='me123',\n is_active=True\n )\n Biography.objects.create(\n terms_cond=True,\n email_2='marinalucas@cotizate.com',\n is_complete=True,\n is_representative=True,\n user=user_contributor_2\n )\n self.success('user contributors created.')\n","sub_path":"apiuser/core/management/commands/dbuser.py","file_name":"dbuser.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"100073509","text":"import numpy\n\nfrom neuralnetworks.activationfunctions.activationfunction import ActivationFunction\n\n\nclass NeuralLayer(object):\n def __init__(self, weights: numpy.ndarray, activation_function: ActivationFunction, use_bias: bool,\n last_layer=None):\n \"\"\"\n Args:\n weights: The weights from last layer to this layer, each vector in weights represent the incoming weights\n for a certain neuron in this layer\n activation_function: The activation function of this layer\n use_bias: Whether to add bias neuron to this layer or not\n last_layer: The layer before this layer (If has none)\n \"\"\"\n self._use_bias = use_bias\n\n self._number_of_neurons_without_bias = weights.shape[0]\n\n if self._use_bias:\n self._number_of_neurons = self._number_of_neurons_without_bias + 1\n else:\n self._number_of_neurons = self._number_of_neurons_without_bias\n\n self._activation_function = activation_function\n self.last_layer = last_layer\n self._values = numpy.zeros(self._number_of_neurons)\n\n if self._use_bias:\n self._values_without_bias = self._values[:-1]\n self._values[-1] = 1\n else:\n self._values_without_bias = self._values\n\n self.weights = weights\n\n def forward_values(self):\n \"\"\"\n Forward the value from the layer before to this layer\n \"\"\"\n if self.last_layer is not None:\n summed_input = numpy.dot(self.weights, self.last_layer.values)\n self.activation_function.calculate(summed_input, self._values_without_bias[:])\n\n @property\n def values(self) -> numpy.ndarray:\n \"\"\"\n Returns:\n The values fired from this layer\n \"\"\"\n return self._values\n\n @property\n def values_without_bias(self) -> numpy.ndarray:\n \"\"\"\n Returns:\n The values fired from this layer not including the value from the bias neuron\n \"\"\"\n return self._values_without_bias\n\n @property\n def use_bias(self) -> bool:\n \"\"\"\n Returns:\n Whether this layer has bias neuron\n \"\"\"\n return self._use_bias\n\n @property\n def activation_function(self) -> ActivationFunction:\n \"\"\"\n Returns:\n The activation function of this layer\n \"\"\"\n return self._activation_function\n\n @classmethod\n def generate_random(cls, number_of_neurons: int, activation_function: ActivationFunction, use_bias: bool,\n last_layer=None):\n \"\"\"\n Args:\n number_of_neurons: The number of neuron in this layer (not including bias)\n activation_function: The activation function of this layer\n use_bias: Whether this layer has bias neuron\n last_layer: The layer before this layer\n\n Returns:\n NeuralLayer: A layer with random weights\n \"\"\"\n if last_layer is not None:\n upper_bound = numpy.sqrt(6 / (number_of_neurons + len(last_layer.values)))\n\n lower_bound = -1 * upper_bound\n weights = numpy.random.uniform(low=lower_bound, high=upper_bound,\n size=(number_of_neurons, len(last_layer.values)))\n else:\n weights = numpy.array([[]]*number_of_neurons)\n\n return NeuralLayer(weights, activation_function, use_bias, last_layer)\n","sub_path":"neuralnetworks/neurallayer.py","file_name":"neurallayer.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"568335249","text":"\"\"\"\n출력 예\nWhat is the input string? Homer\nHomer has 5 characters.\n\n제약 조건\n- 출력 결과에는 입력 받은 문자열이 그대로 나타나도록 할 것\n- 출력을 위해 하나의 출력문을 사용할 것\n- 문자열의 길이를 구하기 위해 프로그래밍 언어에서 제공하는 내장 함수를 사용할 것\n\"\"\"\ninputString = input('What is the input string? ')\nresult = '{inputString} has {length} characters.'.format(inputString=inputString, length=len(inputString))\nprint(result)\n","sub_path":"exercises-for-programmers/exercise2/python/count_word.py","file_name":"count_word.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"191452927","text":"'''\nAutor: Marcos Felipe da Silva\nDescricao: Testes na rota /grava_acesso para recuperar\n\n'''\n\nimport unittest, json\nfrom requests import Session\n\nID = ''\n\nclass TestVendedorXLentes(unittest.TestCase):\n def __init__(self, *args, **kargs):\n super(TestVendedorXLentes, self).__init__(*args, **kargs)\n self._c = Session()\n self._host = 'http://localhost:8585'\n self._url = '/grava_acesso'\n self._chave = '4XhUhmpdVOb1N4OH9i4ZC5kfZVP2'\n \n def setUp(self):\n self._c.get(self._host+'/validar_autenticacao/'+self._chave)\n \n def tearDown(self):\n self._c.get(self._host+'/logout')\n \n def test_a_post_dados_ausente(self):\n ''' TESTA ENVIO CAMPO DADOS AUSENTE '''\n dados = {'outros': json.dumps({\n 'pagina': '/vendas_por_loja'\n })}\n resp = self._c.post(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_b_post_dados_nao_json(self):\n ''' TESTA O ENVIO DO CAMPO DADOS MAS NAO JSON '''\n dados = {'dados': {\n 'pagina': '/vendas_por_loja'\n }}\n resp = self._c.post(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_c_post_dados_sem_atr_pagina(self):\n ''' TESTA O ENVIO DO CAMPO DADOS SEM O ATRIBUTO pagina '''\n dados = {'dados': json.dumps({\n 'ip': '10.5.0.41'\n })}\n resp = self._c.post(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_d_post_dados_envio_correto(self):\n ''' TESTA O ENVIO CORRETO DE UMA GRAVACAO DE ACESSO '''\n # Objeto sem o campo data_hora\n dados = {'dados': json.dumps({\n 'ip': '10.5.0.41',\n 'pagina': '/vendas_por_loja' \n })}\n resp = self._c.post(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('sucesso', resp.keys())\n \n def test_e_post_dados_sem_autenticacao(self):\n ''' TESTA A TENTATIVA DE ENVIO COM UM USUÁRIO NAO AUTENTICADO '''\n self._c.get(self._host+'/logout')\n # Objeto sem o campo data_hora\n dados = {'dados': json.dumps({\n 'ip': '10.5.0.41',\n 'pagina': '/vendas_por_loja' \n })}\n resp = self._c.post(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n\n\nif __name__ == '__main__': unittest.main()","sub_path":"__testes__/rest_estatisticas/test_grava_acesso.py","file_name":"test_grava_acesso.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"96262258","text":"\r\nimport data_creator\r\nimport pandas as pd\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.feature_selection import chi2\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfTransformer\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn.model_selection import cross_val_score\r\nimport seaborn as sns\r\nfrom sklearn.metrics import confusion_matrix, classification_report\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\n\r\nstock_data=data_creator.reading_label(range(4,71)) \r\n\r\n\r\ntfidf = TfidfVectorizer(sublinear_tf=True, min_df=2, encoding='utf-8', ngram_range=(1, 2), stop_words='english')\r\nfeatures = tfidf.fit_transform(stock_data['reading_title']).toarray()\r\nlabels = stock_data['label']\r\n#features.shape\r\nX_train, X_test, y_train, y_test = train_test_split(stock_data['reading_title'], stock_data['label'], random_state =0)\r\ncount_vect = CountVectorizer()\r\nX_train_counts = count_vect.fit_transform(X_train)\r\ntfidf_transformer = TfidfTransformer()\r\nX_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)\r\nclf = MultinomialNB().fit(X_train_tfidf, y_train)\r\n\r\n\r\nmodels = [\r\n RandomForestClassifier(n_estimators=200, max_depth=10, random_state=0),\r\n LinearSVC(),\r\n MultinomialNB(),\r\n LogisticRegression(random_state=0),\r\n]\r\nCV = 5\r\ncv_df = pd.DataFrame(index=range(CV * len(models)))\r\nentries = []\r\nfor model in models:\r\n model_name = model.__class__.__name__\r\n accuracies = cross_val_score(model, features, labels, scoring='accuracy', cv=CV)\r\n for fold_idx, accuracy in enumerate(accuracies):\r\n entries.append((model_name, fold_idx, accuracy))\r\n cv_df = pd.DataFrame(entries, columns=['model_name', 'fold_idx', 'accuracy'])\r\n\r\n# sns.boxplot(x='model_name', y='accuracy', data=cv_df)\r\n# sns.stripplot(x='model_name', y='accuracy', data=cv_df, \r\n# size=8, jitter=True, edgecolor=\"gray\", linewidth=2)\r\n# #plt.show()\r\nprint(cv_df.groupby('model_name').accuracy.mean())\r\n\r\n\r\nmodel = LinearSVC()\r\nX_train, X_test, y_train, y_test, indices_train, indices_test = train_test_split(features, labels, stock_data.index, test_size=0.2, random_state=0)\r\nmodel.fit(X_train, y_train)\r\ny_pred = model.predict(X_test)\r\n\r\nconf_mat = confusion_matrix(y_test, y_pred)\r\n\r\nprint(conf_mat)\r\nprint(classification_report(y_test, y_pred))\r\n\r\nfig, ax = plt.subplots(figsize=(10,10))\r\nsns.heatmap(conf_mat, annot=True, fmt='d', xticklabels=['DOWN','Neitral','UP'], yticklabels=['DOWN','Neitral','UP'])\r\nplt.ylabel('Actual')\r\nplt.xlabel('Predicted')\r\n#plt.show()\r\n\r\n\r\n\r\n\r\ndef get_features(df):\r\n N = 2\r\n for label in sorted(dict(df[['label']]).items()):\r\n features_chi2 = chi2(features, labels == label)\r\n indices = np.argsort(features_chi2[0])\r\n feature_names = np.array(tfidf.get_feature_names())[indices]\r\n unigrams = [v for v in feature_names if len(v.split(' ')) == 1]\r\n bigrams = [v for v in feature_names if len(v.split(' ')) == 2]\r\n print(\"# '{}':\".format(label))\r\n print(\" . Most correlated unigrams:\\n. {}\".format('\\n. '.join(unigrams[-N:])))\r\n print(\" . Most correlated bigrams:\\n. {}\".format('\\n. '.join(bigrams[-N:])))","sub_path":"model_2.py","file_name":"model_2.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"265657094","text":"from datetime import datetime\nfrom typing import (Any, Optional, Callable, Mapping, Sequence, Tuple,\n Iterable, TypeVar, List, cast)\nfrom numbers import Number\n\nimport rads.config.ast as ast\nimport rads.config.parsers as p\nfrom .tree import Cycles, Repeat, ReferencePass, SubCycles, Unit, Range\nfrom ..xml.base import Element\n\nT = TypeVar('T')\n\n\ndef nop(value: T) -> T:\n return value\n\n\ndef source_from_element(element: Element):\n return ast.Source(line=element.opening_line, file=element.file)\n\n\ndef error_at(element: Element) -> Callable[[str], p.GlobalParseFailure]:\n def error(message: str) -> p.GlobalParseFailure:\n return p.GlobalParseFailure(\n element.file, element.opening_line, message)\n\n return error\n\n\ndef parse_condition(attr: Mapping[str, str]) -> ast.Condition:\n # currently the only condition RADS uses is based on the satellite\n try:\n sat = attr['sat'].strip()\n return ast.SatelliteCondition(\n satellites=set(sat.strip('!').split()), invert=sat.startswith('!'))\n except KeyError:\n return ast.TrueCondition()\n\n\ndef parse_action(element: Element) -> ast.ActionType:\n action = element.attributes.get('action', 'replace')\n if action == 'replace':\n return ast.replace\n if action == 'noreplace':\n return ast.keep\n if action == 'append':\n return ast.append\n raise error_at(element)('Invalid action=\"{:s}\".'.format(action))\n\n\ndef list_of(parser: Callable[[str], T]) -> Callable[[str], List[T]]:\n def _parser(string: str) -> List[T]:\n return [parser(s) for s in string.split()]\n\n return _parser\n\n\ndef alias() -> p.Parser:\n def process(element: Element) -> ast.Alias:\n try:\n alias = element.attributes['name']\n except KeyError:\n raise error_at(element)(\"'name' attribute missing from \")\n variables = element.text.split() if element.text else []\n if not variables:\n raise error_at(element)(' cannot be empty')\n condition = parse_condition(element.attributes)\n action = parse_action(element)\n source = source_from_element(element)\n return ast.Alias(alias, variables, condition, action, source=source)\n\n return p.tag('alias') ^ process\n\n\ndef ignore(tag: Optional[str] = None) -> p.Parser:\n def process(element: Element) -> ast.NullStatement:\n return ast.NullStatement(source=source_from_element(element))\n\n if tag:\n return p.tag(tag) ^ process\n return p.any() ^ process\n\n\ndef value(parser: Callable[[str], Any] = nop, tag: Optional[str] = None,\n var: Optional[str] = None) -> p.Parser:\n def process(element: Element) -> ast.Assignment:\n var_ = var if var else element.tag\n condition = parse_condition(element.attributes)\n action = parse_action(element)\n text = element.text if element.text else ''\n source = source_from_element(element)\n try:\n return ast.Assignment(\n name=var_,\n value=parser(text),\n condition=condition,\n action=action,\n source=source)\n except (ValueError, TypeError) as err:\n raise error_at(element)(str(err))\n\n if tag:\n return p.tag(tag) ^ process\n return p.any() ^ process\n\n\ndef if_statement(internal: p.Parser) -> p.Parser:\n def process(statements: Tuple[Element, ast.Statement]) -> ast.Statement:\n if_element, false_statement = statements\n condition = parse_condition(if_element.attributes)\n true_statement = internal(if_element.down())[0]\n source = source_from_element(if_element)\n return ast.If(condition=condition,\n true_statement=true_statement,\n false_statement=false_statement,\n source=source)\n\n return p.tag('if') + p.opt(\n elseif_statement(internal) | else_statement(internal)) ^ process\n\n\ndef elseif_statement(internal: p.Parser) -> p.Parser:\n def process(statements: Iterable[Any]) -> ast.Statement:\n elseif_element, false_statement = statements\n condition = parse_condition(elseif_element.attributes)\n true_statement = internal(elseif_element.down())[0]\n source = source_from_element(elseif_element)\n return ast.If(condition, true_statement, false_statement,\n source=source)\n\n return p.Apply(p.tag('elseif') + p.opt(\n p.lazy(lambda: elseif_statement(internal)) | else_statement(\n internal)), process)\n\n\ndef else_statement(internal: p.Parser) -> p.Parser:\n def process(element: Element) -> Any:\n return internal(element.down())[0]\n\n return p.tag('else') ^ process\n\n\ndef satellites() -> p.Parser:\n def process(element: Element) -> ast.Satellites:\n source = source_from_element(element)\n if not element.text:\n return ast.Satellites(source=source)\n satellites_ = []\n for num, line in enumerate(element.text.strip().splitlines()):\n line = line.strip()\n if line:\n id_source = ast.Source(\n line=element.opening_line + num + 1,\n file=element.file)\n try:\n id_, id3, *names = line.split()\n except ValueError:\n raise p.GlobalParseFailure(\n id_source.file, id_source.line,\n f\"missing 3 character ID for satellite '{id_}'\")\n satellites_.append(\n ast.SatelliteID(id_, id3, set(names), source=id_source))\n return ast.Satellites(*satellites_, source=source)\n\n return p.tag('satellites') ^ process\n\n\ndef cycles(cycles_string: str) -> Cycles:\n try:\n return Cycles(*(int(s) for s in cycles_string.split()))\n except TypeError:\n num_values = len(cycles_string.split())\n if num_values == 0:\n raise TypeError(\"missing 'first' cycle\")\n if num_values == 1:\n raise TypeError(\"missing 'last' cycle\")\n raise TypeError(\n \"too many cycles given, expected only 'first' and 'last'\")\n\n\ndef repeat(repeat_string: str) -> Repeat:\n parts = repeat_string.split()\n if len(parts) > 3:\n raise TypeError(\n \"too many values given, expected only 'days', \"\n \"'passes', and 'unknown'\")\n try:\n return Repeat(*(f(s) for f, s in zip((float, int), parts)))\n except TypeError:\n if parts:\n raise TypeError(\"missing length of repeat cycle in 'passes'\")\n raise TypeError(\"missing length of repeat cycle in 'days'\")\n\n\ndef time(time_string: str) -> datetime:\n try:\n return datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S')\n except ValueError:\n try:\n return datetime.strptime(time_string, '%Y-%m-%dT%H:%M')\n except ValueError:\n try:\n return datetime.strptime(time_string, '%Y-%m-%dT%H')\n except ValueError:\n try:\n return datetime.strptime(time_string, '%Y-%m-%dT')\n except ValueError:\n try:\n return datetime.strptime(time_string, '%Y-%m-%d')\n except ValueError:\n # required to avoid 'unconverted data' message from\n # strptime\n raise ValueError(\n \"time data '{:s}' does not match format \"\n \"'%Y-%m-%dT%H:%M:%S'\".format(time_string))\n\n\ndef ref_pass(ref_pass_string: str) -> ReferencePass:\n parts = ref_pass_string.split()\n if len(parts) > 5:\n raise TypeError(\"too many values given, expected only 'time', \"\n \"'longitude', 'cycle number', 'pass number', and \"\n \"optionally 'absolute orbit number'\")\n try:\n funcs: Sequence[Callable[[str], Any]] = (time, float, int, int, int)\n return ReferencePass(*(f(s) for f, s in zip(funcs, parts)))\n except TypeError:\n if not parts:\n raise TypeError(\"missing 'time' of reference pass\")\n if len(parts) == 1:\n raise TypeError(\"missing 'longitude' of reference pass\")\n if len(parts) == 2:\n raise TypeError(\"missing 'cycle number' of reference pass\")\n # len(parts) == 3\n raise TypeError(\"missing 'pass number' of reference pass\")\n # absolute orbit number is defaulted in ReferencePass\n\n\ndef unit(unit_string) -> Unit:\n try:\n return Unit(unit_string)\n except ValueError:\n # TODO: Need better handling for dB and yymmddhhmmss units.\n return unit_string.strip()\n\n\ndef range_of(parser: Callable[[str], Number]) -> Callable[[str], Range]:\n def _parser(string: str) -> Range:\n min, max = [parser(s) for s in string.split()]\n return Range(min, max)\n return _parser\n\n\ndef subcycles() -> p.Parser:\n def process(element: Element) -> ast.Statement:\n start: Optional[int]\n condition = parse_condition(element.attributes)\n action = parse_action(element)\n try:\n start = int(element.attributes['start'])\n except KeyError:\n start = None\n except ValueError as err:\n raise error_at(element)(str(err))\n text = element.text if element.text else ''\n lengths = [int(s) for s in text.split()]\n source = source_from_element(element)\n return ast.Assignment(\n name='subcycles',\n value=SubCycles(lengths, start=start),\n condition=condition,\n action=action,\n source=source)\n\n return p.tag('subcycles') ^ process\n\n\ndef block(\n parser: p.Parser,\n error_msg: str = 'Invalid configuration block or value.') -> p.Parser:\n def process(statements: Sequence[ast.Statement]) -> ast.Statement:\n # flatten if only a single statement\n if len(statements) == 1:\n return statements[0]\n return ast.CompoundStatement(*statements)\n\n def recursive_parser() -> p.Parser:\n return block(parser, error_msg)\n\n block_parser = p.star(\n parser | if_statement(p.lazy(recursive_parser)) | value())\n return (p.start() + (block_parser ^ process) + p.end()\n << error_msg) ^ (lambda x: x[1])\n\n\ndef named_block_processor(tag: str, parser: p.Parser, node: ast.NamedBlock) \\\n -> Callable[[Element], ast.NamedBlock]:\n def process(element: Element) -> ast.NamedBlock:\n try:\n name = element.attributes['name']\n except KeyError:\n raise error_at(element)(f\"<{tag}> is missing 'name' attribute.\")\n try:\n statement = cast(\n ast.Statement, parser(element.down())[0])\n except StopIteration:\n statement = ast.NullStatement()\n condition = parse_condition(element.attributes)\n source = source_from_element(element)\n return node(name, statement, condition, source=source)\n\n return process\n\ndef phase() -> p.Parser:\n phase_block = block(\n value(str, 'mission') |\n value(cycles, 'cycles') |\n value(repeat, 'repeat') |\n value(ref_pass, 'ref_pass', var='reference_pass') |\n value(time, 'start_time') |\n value(time, 'end_time') |\n subcycles()\n )\n process = named_block_processor('phase', phase_block, ast.Phase)\n return p.tag('phase') ^ process\n\n\ndef variable() -> p.Parser:\n variable_block = block(\n value(str, 'long_name', var='name') |\n value(str, 'standard_name') |\n value(str, 'source') |\n value(str, 'comment') |\n value(unit, 'units') |\n value(list_of(str), 'flag_values') |\n value(list_of(str), 'flag_masks') |\n value(range_of(float), 'limits') |\n value(range_of(float), 'plot_range') |\n # used by rads for database generation, has no effect on end users\n ignore('parameters') |\n ignore('data') | # TODO: Complex field.\n value(list_of(str), 'quality_flag') |\n # not currently used\n value(int, 'dimensions') |\n ignore('format') |\n ignore('compress') |\n ignore('default')\n )\n process = named_block_processor('var', variable_block, ast.Variable)\n return p.tag('var') ^ process\n\n\ndef parse(root: Element) -> ast.Statement:\n root_block = block(\n # ignore the global attributes\n ignore('global_attributes') |\n\n # satellite id/names table\n satellites() |\n\n # top level satellite parameters\n value(str, 'satellite', var='name') |\n ignore('satid') |\n value(float, 'dt1hz') |\n value(float, 'inclination') |\n value(list_of(float), 'frequency') |\n ignore('xover_params') |\n\n # satellite phase\n phase() |\n\n # variable aliases\n alias() |\n\n # variables\n variable()\n )\n return cast(ast.Statement, root_block(root.down())[0])\n\n\ndef preparse(root: Element) -> ast.Statement:\n def process(elements: Sequence[Element]) -> Element:\n return elements[-1]\n\n parser = p.until(p.tag('satellites')) + satellites() ^ process\n return cast(ast.Statement, parser(root.down())[0])\n","sub_path":"rads/config/grammar.py","file_name":"grammar.py","file_ext":"py","file_size_in_byte":13276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"204901218","text":"from sklearn.cluster import KMeans, DBSCAN\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.tree import ExtraTreeRegressor\nfrom datrics_json import csr\nimport numpy as np\nimport scipy as sp\nfrom datrics_json import classification as clf\nfrom datrics_json import regression as reg\nfrom dask_ml.preprocessing import OneHotEncoder, LabelEncoder, MinMaxScaler\nimport pandas as pd\nimport dask.dataframe as dd\n\n\ndef serialize_kmeans_clustering(model):\n serialized_model = {\n 'meta': 'kmeans_clustering',\n 'cluster_centers_': model.cluster_centers_.tolist(),\n 'labels_': model.labels_.tolist(),\n 'inertia_': model.inertia_,\n 'n_features_in_': model.n_features_in_,\n 'n_iter_': model.n_iter_,\n '_n_threads': model._n_threads,\n '_tol': model._tol,\n\n 'params': model.get_params()\n }\n\n return serialized_model\n\n\ndef deserialize_kmeans_clustering(model_dict):\n model = KMeans(model_dict['params'])\n\n model.cluster_centers_ = np.array(model_dict['cluster_centers_'])\n model.labels_ = np.array(model_dict['labels_'])\n model.inertia_ = model_dict['inertia_']\n model.n_features_in_ = model_dict['n_features_in_']\n model.n_iter_ = model_dict['n_iter_']\n model._n_threads = model_dict['_n_threads']\n model._tol = model_dict['_tol']\n\n return model\n\n\ndef serialize_dbscan_clustering(model):\n serialized_model = {\n 'meta': 'dbscan_clustering',\n 'components_': model.components_.tolist(),\n 'core_sample_indices_': model.core_sample_indices_.tolist(),\n 'labels_': model.labels_.tolist(),\n 'n_features_in_': model.n_features_in_,\n '_estimator_type': model._estimator_type,\n\n 'params': model.get_params()\n }\n\n return serialized_model\n\n\ndef deserialize_dbscan_clustering(model_dict):\n model = DBSCAN(**model_dict['params'])\n #model.eps = model_dict['params']['eps']\n\n model.components_ = np.array(model_dict['components_'])\n model.labels_ = np.array(model_dict['labels_'])\n model.core_sample_indices_ = model_dict['core_sample_indices_']\n model.n_features_in_ = model_dict['n_features_in_']\n model._estimator_type = model_dict['_estimator_type']\n\n return model\n\n\ndef serialize_iforest(model):\n params = model.get_params()\n n_features_ = model.n_features_\n n_features_in_ = model.n_features_in_\n max_samples_ = model.max_samples_\n _max_features = model._max_features\n max_features = model.max_features\n estimators_features_ = model.estimators_features_\n _seeds = model._seeds\n _n_samples = model._n_samples\n\n base_estimator_ = model.base_estimator_.get_params()\n base_estimator_.pop('splitter')\n\n offset_ = model.offset_\n oob_score = model.oob_score\n\n estimators_ = []\n for est in model.estimators_:\n\n tree_, dtypes = clf.serialize_tree(est.tree_)\n\n tree_dtypes = []\n for i in range(0, len(dtypes)):\n tree_dtypes.append(dtypes[i].str)\n\n et_params = est.get_params()\n et_params.pop('splitter')\n\n serialized_tree = {\n \"params\": et_params,\n \"splitter\": est.splitter,\n \"max_features_'\": est.max_features_,\n \"n_features_\": est.n_features_,\n \"n_features_in_\": est.n_features_in_,\n \"n_outputs_\": est.n_outputs_,\n \"tree_\": tree_}\n\n serialized_tree['tree_']['nodes_dtype'] = tree_dtypes\n\n estimators_.append(serialized_tree)\n\n estimators_features_ = list(map(lambda x: x.tolist(), estimators_features_))\n\n serialized_model = {\n \"meta\": \"iforest_anomaly\",\n \"params\": params,\n \"base_estimator_\": base_estimator_,\n \"estimators_features_\": estimators_features_,\n \"_seeds\": _seeds.tolist(),\n \"n_features_\": n_features_,\n \"n_features_in_\": n_features_in_,\n \"max_samples_\": max_samples_,\n \"max_features\": max_features,\n \"_max_features\": _max_features,\n \"_n_samples\": _n_samples,\n \"offset_\": offset_,\n \"oob_score\": oob_score,\n \"estimators_\": estimators_}\n\n return serialized_model\n\ndef deserialize_iforest(model_dict):\n model = IsolationForest(**model_dict['params'])\n\n for param in list(model_dict.keys())[4:-1]:\n setattr(model, param, model_dict[param])\n\n model.base_estimator_ = ExtraTreeRegressor(**model_dict['base_estimator_'])\n\n estimators_features_ = list(map(lambda x: np.array(x), model_dict['estimators_features_']))\n model.estimators_features_ = estimators_features_\n\n _seeds = np.array(model_dict['_seeds'])\n model._seeds = _seeds\n\n new_estimators = []\n for est_dict in model_dict['estimators_']:\n est = ExtraTreeRegressor(**est_dict['params'])\n for param in list(est_dict.keys())[1:-1]:\n setattr(est, param, est_dict[param])\n est.tree_ = reg.deserialize_tree(est_dict['tree_'],\n est_dict['n_features_'],\n est.n_classes_[0],\n est_dict['n_outputs_'])\n new_estimators.append(est)\n model.estimators_ = new_estimators\n\n return model\n\n\ndef serialize_label_encoder(model):\n result = model.transform(dd.from_pandas(pd.Series(model.classes_), npartitions=1))\n dict = {\"values\": model.classes_.tolist(), \"labels\": result.compute().tolist()}\n\n serialized_model = {\n \"meta\": \"label_encoder\",\n \"dictionary\": dict,\n \"params\": model.get_params(),\n \"classes_\": model.classes_.tolist()}\n\n return serialized_model\n\n\ndef deserialize_label_encoder(model_dict):\n model = LabelEncoder(**model_dict['params'])\n model.classes_ = np.array(model_dict['classes_'])\n\n return model\n\ndef serialize_onehot_encoder(model):\n categories_ = list(map(lambda x: x.tolist(), model.categories_))\n\n result = model.transform(dd.from_pandas(pd.DataFrame({'data': model.categories_[0]}), npartitions=1))\n dict = result.compute().to_dict()\n\n serialized_model = {\n \"meta\": \"onehot_encoder\",\n \"dictionary\": dict,\n \"params\": model.get_params(),\n \"categories_\": categories_}\n\n serialized_model['params'].pop('dtype')\n\n return serialized_model\n\n\ndef deserialize_onehot_encoder(model_dict):\n model = OneHotEncoder(**model_dict['params'])\n categories_ = list(map(lambda x: np.array(x), model_dict['categories_']))\n dtypes_ = list(map(lambda x: pd.CategoricalDtype(categories=x), model_dict['categories_']))\n\n model.categories_ = categories_\n model.dtypes_ = dtypes_\n\n return model\n\ndef serialize_min_max_scaler(model):\n\n serialized_model = {\n \"meta\": \"min_max_scaler\",\n \"data_max_index\": list(model.data_max_.index),\n \"data_max_values\": list(model.data_max_.values),\n \"data_min_index\": list(model.data_min_.index),\n \"data_min_values\": list(model.data_min_.values),\n \"data_range_index\": list(model.data_range_.index),\n \"data_range_values\": list(model.data_range_.values),\n \"min_index\": list(model.min_.index),\n \"min_values\": list(model.min_.values),\n \"n_features_in_\": model.n_features_in_,\n \"scale_index\": list(model.scale_.index),\n \"scale_values\": list(model.scale_.values),\n \"params\": model.get_params()}\n\n return serialized_model\n\n\ndef deserialize_min_max_scaler(model_dict):\n model = MinMaxScaler(**model_dict[\"params\"])\n\n model.data_max_ = pd.Series(data=model_dict[\"data_max_values\"], index=model_dict[\"data_max_index\"])\n model.data_min_ = pd.Series(data=model_dict[\"data_min_values\"], index=model_dict[\"data_min_index\"])\n model.data_range_ = pd.Series(data=model_dict[\"data_range_values\"], index=model_dict[\"data_range_index\"])\n model.min_ = pd.Series(data=model_dict[\"min_values\"], index=model_dict[\"min_index\"])\n model.scale_ = pd.Series(data=model_dict[\"scale_values\"], index=model_dict[\"scale_index\"])\n\n model.n_features_in_ = model_dict[\"n_features_in_\"]\n\n return model","sub_path":"datrics_json/unsupervized.py","file_name":"unsupervized.py","file_ext":"py","file_size_in_byte":8019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"513572278","text":"import vaex.misc.progressbar\nimport pytest\n\ndef test_progress_bar():\n pb = vaex.misc.progressbar.ProgressBar(0, 100)\n pb.update(0)\n pb.update(50)\n assert \"50.00%\" in repr(pb)\n pb.finish()\n assert \"elapsed time\" in repr(pb)\n\ndef test_progress_bar_widget():\n pb = vaex.misc.progressbar.ProgressBarWidget(0, 100)\n pb.update(0)\n pb.update(50)\n assert \"50.00%\" in repr(pb)\n assert pb.bar.value == 50\n pb.finish()\n assert \"elapsed time\" in repr(pb)\n\n@pytest.mark.parametrize(\"progress\", ['vaex', 'widget'])\ndef test_progress(progress):\n df = vaex.from_arrays(x=vaex.vrange(0, 10000))\n df.sum('x', progress=progress)","sub_path":"tests/progress_test.py","file_name":"progress_test.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"360304619","text":"# 각 자리가 숫자(0부터9)로만 이루어진 문자열 S가 주어졌을 때, 왼쪽부터 오른쪽으로 하나씩 모든 숫자를 확인하며 숫자 사이에 'X'혹은 '+'연산자를 넣어 결과적으로 만들어질 수 있는 가장 큰 수를 구하는 프로그램을 작성하라.\n\nS = input(\"문자열: \")\nresult=0\nfor i in range(len(S)):\n if S[i] == 0 or S[i] == 1 or result==0:\n result+=int(S[i])\n else:\n result*=int(S[i])\nprint(result)","sub_path":"개념 공부/Greedy Algorithms/곱하기 혹은 더하기.py","file_name":"곱하기 혹은 더하기.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"299172934","text":"\nfrom flask import Flask, request, render_template, url_for, flash, redirect, session\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, RadioField, ValidationError\nfrom wtforms.validators import Required\nimport requests\nimport json\n\nimport os\nimport datetime\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager, login_required, login_user, logout_user, current_user, UserMixin\nfrom requests_oauthlib import OAuth2Session # If you haven't, need to pip install requests_oauthlib\nfrom requests.exceptions import HTTPError\nfrom flask_migrate import Migrate, MigrateCommand\nfrom flask_script import Manager, Shell\nfrom stuff import clientid, clientsecret\n\nos.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # So you can use http, not just https\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n\n\"\"\"App Configuration\"\"\"\n## See this tutorial for how to get your application credentials and set up what you need: http://bitwiser.in/2015/09/09/add-google-login-in-flask.html\n#everything in the class below can be copied/pasted, except for client ID & secret\nclass Auth:\n \"\"\"Google Project Credentials\"\"\"\n CLIENT_ID = clientid\n CLIENT_SECRET = clientsecret\n REDIRECT_URI = 'http://localhost:5000/gCallback' # Our (programmer's) decision\n # URIs determined by Google, below\n AUTH_URI = 'https://accounts.google.com/o/oauth2/auth'\n TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'\n USER_INFO = 'https://www.googleapis.com/userinfo/v2/me'\n SCOPE = ['profile', 'email'] # Could edit for more available scopes -- if reasonable, and possible without $$\n\n\nclass Config:\n \"\"\"Base config\"\"\"\n APP_NAME = \"Test Google Login\"\n SECRET_KEY = os.environ.get(\"SECRET_KEY\") or \"something secret\"\n\n#development environment, local to your machine\nclass DevConfig(Config):\n \"\"\"Dev config\"\"\"\n DEBUG = True\n USE_RELOADER = True\n SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \"postgresql://localhost/recipeapp\" # TODO: Need to create this database or edit URL for your computer\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n SQLALCHEMY_COMMIT_ON_TEARDOWN = True\n\n#when you actually deploy it for users to use\nclass ProdConfig(Config):\n \"\"\"Production config\"\"\"\n DEBUG = False\n USE_RELOADER = True\n SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \"postgresql://localhost/recipeapp\" # If you were to run a different database in production, you would put that URI here. For now, have just given a different database name, which we aren't really using.\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n SQLALCHEMY_COMMIT_ON_TEARDOWN = True\n\n# To set up different configurations for development of an application\nconfig = {\n \"dev\": DevConfig,\n \"prod\": ProdConfig,\n \"default\": DevConfig\n}\n\n\"\"\"APP creation and configuration\"\"\"\napp = Flask(__name__)\napp.config.from_object(config['dev']) # Here's where we specify which configuration is being used for THIS Flask application instance, stored in variable app, as usual!\napp.config['SECRET_KEY'] = 'hardtoguessstring'\napp.config['HEROKU_ON'] = os.environ.get('HEROKU')\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = os.environ.get('DATABASE_URL') or \"postgresql://localhost/recipeapp\"\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n\ndb = SQLAlchemy(app)\nmanager = Manager(app)\n#below commented out since we're not using migrations right now, can add later\n# migrate = Migrate(app, db)\n# manager.add_command('db', MigrateCommand)\n\n#CAN JUST COPY/PASTE BELOW\nlogin_manager = LoginManager(app)\nlogin_manager.login_view = \"login\"\nlogin_manager.session_protection = \"strong\" # New - because using sessions with oauth instead of our own auth verification\n\n\n#MODELS\n\n# Association table -\n\n#TODO figure this out?? below, an example\n#to_read = db.Table('to_read',db.Column('book_id',db.Integer, db.ForeignKey('books.id')),db.Column('user_id',db.Integer, db.ForeignKey('users.id'))) # Many to many, books to users\n# Of course, access current user's books with query\n\n\nclass Recipe(db.Model):\n # don't need regular old constructor, can create Recipe objects using DB variables\n # def __init__(self, name, picURL, url):\n # self.name = name\n # self.picURL = picURL\n # self.url = url\n __tablename__ = \"recipes\"\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n name = db.Column(db.String(200), unique=True,nullable=False)\n url = db.Column(db.String(400))\n picURL = db.Column(db.String(400))\n\n\n\nclass User(db.Model, UserMixin):\n __tablename__ = \"users\"\n id = db.Column(db.Integer, primary_key = True)\n email = db.Column(db.String(100), unique=True, nullable=False)\n name = db.Column(db.String(100), nullable=True)\n avatar = db.Column(db.String(200))\n tokens = db.Column(db.Text)\n created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow())\n#TODO: modify below to establish relationship with recipes\n #books = db.relationship('Book',secondary=to_read,backref=db.backref('books',lazy='dynamic'),lazy='dynamic')\n\n\n## IMPORTANT FUNCTION / MANAGEMENT\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n\n\"\"\" OAuth Session creation \"\"\"\ndef get_google_auth(state=None, token=None):\n if token:\n return OAuth2Session(Auth.CLIENT_ID, token=token)\n if state:\n return OAuth2Session(\n Auth.CLIENT_ID,\n state=state,\n redirect_uri=Auth.REDIRECT_URI)\n oauth = OAuth2Session(\n Auth.CLIENT_ID,\n redirect_uri=Auth.REDIRECT_URI,\n scope=Auth.SCOPE)\n return oauth\n\n\n#FORM CLASSES\n\nclass IngredForm(FlaskForm):\n ingredient = StringField('Search for a recipe: ', validators = [Required()])\n submit = SubmitField('Submit')\n\n#TODO - delete these & replace with HTML forms? these are so small and pointless\nclass AddForm(FlaskForm):\n submit = SubmitField('Add to my recipe box')\n\nclass SeeRecipesForm(FlaskForm):\n submit = SubmitField('See my recipe box')\n\n#HELPER FUNCTIONS\n#TODO: THis section!\n\n# def get_or_create_author(name, hometown):\n# pass # TODO: save and return new author object if one of the same name does not already exist; if so, return that one\n#\n# def get_or_create_book(book_title, author, hometown):\n# pass # TODO: if not a book by this title that already exists (let's go simple for now and identify books solely by their title), save author and associate its id with the new book instance, use current_user to append the created book to the current user, and return the book object, all committed to DB\n#\n\n\n#ROUTES AND VIEW FUNTIONS\n\n#error handling routes\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n return render_template('500.html'), 500\n\n\n#MAIN ROUTES\n\n@app.route('/')\n@login_required\ndef askForIngred():\n firstForm = IngredForm()\n\n return render_template('ingredIntake.html', form = firstForm)\n\n\n@app.route('/login')\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('askForIngred'))\n google = get_google_auth()\n auth_url, state = google.authorization_url(\n Auth.AUTH_URI, access_type='offline')\n session['oauth_state'] = state\n return render_template('login.html', auth_url=auth_url)\n\n@app.route('/gCallback')\ndef callback():\n if current_user is not None and current_user.is_authenticated:\n return redirect(url_for('askForIngred'))\n if 'error' in request.args: # Good Q: 'what are request.args here, why do they matter?'\n if request.args.get('error') == 'access_denied':\n return 'You denied access.'\n return 'Error encountered.'\n # print(request.args, \"ARGS\")\n if 'code' not in request.args and 'state' not in request.args:\n return redirect(url_for('login'))\n else:\n google = get_google_auth(state=session['oauth_state'])\n try:\n token = google.fetch_token(\n Auth.TOKEN_URI,\n client_secret=Auth.CLIENT_SECRET,\n authorization_response=request.url)\n except HTTPError:\n return 'HTTPError occurred.'\n google = get_google_auth(token=token)\n resp = google.get(Auth.USER_INFO)\n if resp.status_code == 200:\n # print(\"SUCCESS 200\") # For debugging/understanding\n user_data = resp.json()\n email = user_data['email']\n user = User.query.filter_by(email=email).first()\n if user is None:\n # print(\"No user...\")\n user = User()\n user.email = email\n user.name = user_data['name']\n # print(token)\n user.tokens = json.dumps(token)\n user.avatar = user_data['picture']\n db.session.add(user)\n db.session.commit()\n login_user(user)\n return redirect(url_for('askForIngred'))\n return 'Could not fetch your information.'\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('askForIngred'))\n\n\nrecipe_objects = []\nsearchTerm = \"\"\n\n@app.route('/recipes', methods = ['GET','POST'])\ndef getRecipes():\n form = IngredForm(request.form)\n print(form)\n\n print(\"FORM DATA\",form.ingredient.data)\n\n if form.ingredient.data:\n global searchTerm\n searchTerm = form.ingredient.data\n\n if form.ingredient.data:\n recipe_objects.clear()\n edamam_result = requests.get('http://api.edamam.com/search', params={\n 'q': form.ingredient.data,\n 'app_id': 'fa50cd3a',\n 'app_key': '45847a72028b77699b111aff32fab050'\n })\n\n print(\"RESPONSE\",edamam_result.text)\n\n edamam_obj = json.loads(edamam_result.text)\n\n # print(edamam_obj, indent = 4)\n\n for recipe in edamam_obj[\"hits\"]:\n tempRecipe = Recipe(\n name = recipe[\"recipe\"][\"label\"],\n picURL = recipe[\"recipe\"][\"image\"],\n url = recipe[\"recipe\"][\"url\"])\n\n recipe_objects.append(tempRecipe)\n\n form1 = AddForm()\n recForm = SeeRecipesForm()\n\n return render_template('searchResults.html',\n recipes = recipe_objects,\n search = searchTerm,\n form = form1,\n form2 = recForm)\n\n\n@app.route('/save/', methods = ['GET', 'POST'])\ndef saveRecipe(recipeName):\n if request.method == 'POST':\n name = recipeName\n\n #I have name, but to get other info I need (url, picurl), I'm looping\n #through the list of recipe objects to find a name match\n\n for recipe in recipe_objects:\n if recipe.name == name:\n url = recipe.url\n picURL = recipe.picURL\n\n\n recipe_obj = Recipe(name = name,\n url = url,\n picURL = picURL,\n user_id = current_user.id\n )\n db.session.add(recipe_obj)\n db.session.commit()\n\n flash(\"You added \" + name + \" to your recipe box!\")\n\n return redirect(url_for('getRecipes'))\n\n@app.route('/seeMyRecipes')\ndef getUsersRecipes():\n userRecipes = Recipe.query.filter_by(user_id = current_user.id).all()\n\n return render_template('myRecipes.html',\n recipes = userRecipes,\n name = current_user.name)\n\n@app.route('/remove/')\ndef removeRecipe(recipeName):\n recipeToDelete = Recipe.query.filter_by(name = recipeName, user_id = current_user.id).first()\n #this ^ returns a Recipe object\n db.session.delete(recipeToDelete)\n db.session.commit()\n return redirect(url_for('getUsersRecipes'))\n\n\nif __name__ == \"__main__\":\n db.create_all()\n manager.run()\n\n\n# if __name__ == '__main__':\n# app.run(use_reloader=True,debug=True)\n","sub_path":"main_app.py","file_name":"main_app.py","file_ext":"py","file_size_in_byte":11800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"105673884","text":"import pytest\nfrom shopping_basket import TriggerVolumeException, DiscountUnitsException \nfrom shopping_basket import DuplicateOfferException, OfferDoesNotExistException\n\n@pytest.mark.parametrize('offer_name,product_name,trigger_volume,\\\n discount_units,exception', [\n ('Offer3', 'Biscuits', 0, 0.75, TriggerVolumeException(\n 'The offer trigger volume cannot be zero')),\n ('Offer3', 'Biscuits', 3, 0, DiscountUnitsException(\n 'The offer discount units cannot be zero')),\n ('Offer2', 'Biscuits', 3, 2, DuplicateOfferException(\n 'Offer2 already exists in the offer list')),\n ('Offer3', 'Biscuits', 3, 2, None)\n])\ndef test_add_new_offer(base_offers_list, offer_name, product_name, \n trigger_volume, discount_units, exception):\n\n \"\"\" Tests the addition of a new offer \"\"\"\n\n assert base_offers_list.offer_count == 2\n\n try:\n base_offers_list.add_new_offer(offer_name, product_name, trigger_volume,\n discount_units)\n except (TriggerVolumeException, DiscountUnitsException, \n DuplicateOfferException) as inst:\n # Ensure correct exception type and message\n assert isinstance(inst, type(exception))\n assert inst.args == exception.args\n else:\n # No exception so test that offer has been added\n assert base_offers_list.offers_list[offer_name.strip()] == {\n 'product_name': product_name.strip(),\n 'trigger_volume': trigger_volume,\n 'discount_units': round(discount_units, 2)\n }\n assert base_offers_list.offer_count == 3\n\n@pytest.mark.parametrize('offer_name,exception', [\n ('Offer10', OfferDoesNotExistException(\n 'Offer10 does not exist in offer list')),\n ('Offer1', None)\n])\ndef test_remove_offer(base_offers_list, offer_name, exception):\n\n \"\"\" Tests the removal of an existing offer \"\"\"\n\n assert base_offers_list.offer_count == 2\n\n try:\n base_offers_list.remove_existing_offer(offer_name)\n except OfferDoesNotExistException as inst:\n # Ensure correct exception type and message\n assert isinstance(inst, type(exception))\n assert inst.args == exception.args\n else:\n # No exception so test that offer has been removed\n assert offer_name.strip() not in base_offers_list.offers_list.keys()\n assert base_offers_list.offer_count == 1","sub_path":"shopping_basket/shopping_basket_tests/test_offers.py","file_name":"test_offers.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"542062164","text":"# SYSTEM IMPORTS\nfrom tensorflow.keras.datasets import mnist\nfrom typing import Set\nfrom tqdm import tqdm\nimport argparse\nimport numpy as np\nimport os\nimport sys\nimport torch as pt\n\n_cd_: str = os.path.abspath(os.path.dirname(__file__))\nfor _dir_ in [_cd_, os.path.join(_cd_, \"..\")]:\n if _dir_ not in sys.path:\n sys.path.append(_dir_)\ndel _cd_\n\n\n# PYTHON PROJECT IMPORTS\nfrom mcas_gmra import CoverTree\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"data_dir\", type=str,\n help=\"directory to where covertree will serialize itself to\")\n parser.add_argument(\"--validate\", action=\"store_true\",\n help=\"if enabled, perform an expensive tree validate operation\")\n args = parser.parse_args()\n\n if not os.path.exists(args.data_dir):\n os.makedirs(args.data_dir)\n\n print(\"loading data\")\n # This part would be replaced with loading a custom dataset.\n # NOTE: the entire dataset does *not* have to fit into DRAM.\n # we can use a memory-mapped version of the dataset\n # (or some custom data loader) which will feed\n # one example at a time to the covertree.\n # P.S.: when data is fed into the covertree it MUST be a torch tensor!!!\n (X_train, _), (X_test, _) = mnist.load_data()\n X: np.ndarray = np.vstack([X_train, X_test])\n X = X.reshape(X.shape[0], -1).astype(np.float32)\n\n # this is a throwaway tensor...just used to feed into the covertree\n X_pt = pt.from_numpy(X)\n print(\"done\")\n\n # NOTE: build covertree w/ max scale = ceil(log_2(max(||x_i, x_j||_2^2)))\n # this is to ensure that every point in the dataset can be added to the tree\n # and is reachable from the root. For MNIST, I know beforehand that\n # this value is 13.\n # If you DON'T know this value for your dataset, you can compute it but be WARNED\n # it will take either LOTS of ram OR LOTS of time.\n cover_tree = CoverTree(max_scale=13)\n\n # make a nice progress bar. the CoverTree type will accept\n # a bunch of examples at once, however it doesn't have a progress bar.\n # I know its a little slower to use a pure python loop but I'm willing\n # to make the tradeoff so I can see the ETA.\n # NOTE: you can replace this entire process with the following line:\n # cover_tree.insert(X)\n for pt_idx in tqdm(list(range(X_pt.shape[0])),\n desc=\"building covertree\"):\n cover_tree.insert_pt(pt_idx, X_pt)\n\n if(args.validate):\n print(\"validating covertree...this may take a while\")\n assert(cover_tree.validate(X_pt))\n\n filename = \"mnist_covertree.json\"\n filepath = os.path.join(args.data_dir, filename)\n\n print(\"serializing covertree to [%s]\" % filepath)\n cover_tree.save(filepath)\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"pymm-gmra/experiments/mnist/covertree_build.py","file_name":"covertree_build.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"272951581","text":"# -*- coding: utf-8 -*-\n# Copyright (c) Hebes Intelligence Private Company\n\n# This source code is licensed under the Apache License, Version 2.0 found in the\n# LICENSE file in the root directory of this source tree.\n\nimport logging\n\nimport numpy as np\nimport pandas as pd\n\nfrom eensight.models._composite import AggregatePredictor\nfrom eensight.models._conformal import AggregatedCp\n\nfrom .sampling import generate_samples\n\nlogger = logging.getLogger(\"savings\")\n\n\ndef apply_compare(\n data: pd.DataFrame,\n mean_model: AggregatePredictor,\n conformal_model: AggregatedCp,\n of_apply_compare: dict,\n):\n \"\"\"Estimate cumulative energy savings.\n\n Args:\n data (pandas.DataFrame): The input data\n mean_model (AggregatePredictor): The baseline consumption model.\n conformal_model (AggregatedCp): The conformal prediction model for\n uncertainty estimation.\n of_apply_compare (dict): The parameters of the estimation step (typically\n read from `conf/base/parameters/compare.yaml`).\n\n Raises:\n ValueError: [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n to_drop = data.filter(like=\"_outlier\", axis=1).columns.to_list()\n if len(to_drop) > 0:\n data = data.drop(to_drop, axis=1)\n\n if \"consumption\" not in data:\n raise ValueError(\"Consumption missing from input data\")\n y_true = data.pop(\"consumption\")\n\n significance = np.linspace(0, 1, of_apply_compare.get(\"steps\", 20))[1:-1]\n\n pred_mean = mean_model.predict(data)\n pred_conf = conformal_model.predict(data, significance)\n samples = generate_samples(\n of_apply_compare.get(\"n_samples\", 200),\n prediction=pred_mean[\"consumption\"],\n quantiles=pred_conf,\n )\n\n savings = samples.sub(y_true, axis=0)\n keep_n_last = of_apply_compare.get(\"keep_n_last\")\n if keep_n_last is None:\n fract_savings = savings.apply(np.cumsum, axis=0).div(\n pred_mean[\"consumption\"].cumsum(), axis=0\n )\n elif keep_n_last == 1:\n fract_savings = pd.DataFrame.from_dict(\n {\n savings.index[-1]: savings.sum(axis=0)\n .div(pred_mean[\"consumption\"].sum(), axis=0)\n .to_dict()\n },\n orient=\"index\",\n )\n else:\n fract_savings = (\n savings.apply(np.cumsum, axis=0)\n .div(pred_mean[\"consumption\"].cumsum(), axis=0)\n .iloc[-keep_n_last:]\n )\n\n logger.info(f\"Mean of fractional savings (%) {100 * fract_savings.iloc[-1].mean()}\")\n logger.info(\n f\"Standard deviation of fractional savings (%) {100 * fract_savings.iloc[-1].std()}\"\n )\n return fract_savings\n","sub_path":"src/eensight/pipelines/compare/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"557697461","text":"from . import client\nfrom google.appengine.api.users import User as AppengineUser\nfrom ferris.core import template\nimport logging\n\n# Register User Formatter\n\n#template.formatters[AppengineUser] = lambda x: x.domain_info['name']['fullName'] if x.domain_info and x.domain_info.get('name') else unicode(x)\n\n\n# Monkey Patch App Engine users\n\ndef _get_info(self):\n if not hasattr(self, '_domain_info'):\n setattr(self, '_domain_info', None)\n if self._domain_info is None:\n try:\n self._domain_info = client.get_user_info_cached(self.email())\n except Exception as e:\n logging.error(\"Error occured while fetching user for %s info: %s\" % (self.email(), e))\n self._domain_info = False\n return self._domain_info\n\nsetattr(AppengineUser, 'domain_info', property(_get_info))\n\n\n# Monkey patch json\n\ndef _to_json(self):\n output = {'__class__': 'User'}\n methods = ['nickname', 'email', 'user_id']\n for method in methods:\n output[method] = getattr(self, method)()\n\n info = self.domain_info\n if info:\n try:\n name = info.get('name', None)\n output['name'] = name.get('fullName') if name else None\n output['org_unit'] = info.get('orgUnitPath', None)\n output['groups'] = [\n {'name': x['name'], 'email': x['email']} for x in info.get('groups', None)\n ]\n except:\n output['name'] = None\n output['org_unit'] = None\n output['groups'] = None\n\n return output\n\nsetattr(AppengineUser, '__json__', _to_json)\n\n\n# Monkey Patch protopigeon\n\nfrom protorpc import messages\nfrom protopigeon import converters\n\n\nclass GroupMessage(messages.Message):\n name = messages.StringField(1)\n email = messages.StringField(2)\n\nclass ExtendedUserMessage(messages.Message):\n email = messages.StringField(1)\n user_id = messages.StringField(2)\n nickname = messages.StringField(3)\n name = messages.StringField(4)\n org_unit = messages.StringField(5)\n groups = messages.MessageField(GroupMessage, 6, repeated=True)\n\n\nclass ExtendedUserConverter(converters.UserConverter):\n @staticmethod\n def to_message(Mode, property, field, value):\n info = value.domain_info\n return ExtendedUserMessage(\n email=value.email(),\n user_id=value.user_id(),\n nickname=value.nickname(),\n name=info['name']['fullName'] if info else None,\n org_unit=info['orgUnitPath'] if info else None,\n groups=[\n GroupMessage(email=x['email'], name=x['name']) for x in info['groups']\n ] if info else [])\n\n @staticmethod\n def to_model(Message, property, field, value):\n from google.appengine.api import users\n if isinstance(value, basestring):\n return users.User(email=value)\n elif isinstance(value, ExtendedUserMessage) and value.email:\n return users.User(email=value.email)\n\n @staticmethod\n def to_field(Model, property, count):\n return messages.MessageField(ExtendedUserMessage, count, repeated=property._repeated)\n\n\nconverters.converters['UserProperty'] = ExtendedUserConverter\n","sub_path":"plugins/google_directory/monkey.py","file_name":"monkey.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"623977739","text":"# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# --------------------------------------------------------\n\n\"\"\"Factory method for easily getting imdbs by name.\"\"\"\n\n__sets = {}\n\n# import datasets.pascal_voc\nimport datasets.imagenet_vid\nimport numpy as np\n\n\"\"\"def _selective_search_IJCV_top_k(split, year, top_k):\n imdb = datasets.pascal_voc(split, year)\n imdb.roidb_handler = imdb.selective_search_IJCV_roidb\n imdb.config['top_k'] = top_k\n return imdb\n\"\"\"\n\nyear = '2015'\n\n# Set up voc__ using selective search \"fast\" mode\nfor split in ['train', 'test']: #, 'val', 'trainval', 'test']:\n name = 'vid_{}'.format(split)\n __sets[name] = (lambda split=split, year=year:\n datasets.imagenet_vid(split, year))\n\n\ndef get_imdb(name):\n \"\"\"Get an imdb (image database) by name.\"\"\"\n if not __sets.has_key(name):\n raise KeyError('Unknown dataset: {}'.format(name))\n return __sets[name]()\n\ndef list_imdbs():\n \"\"\"List all registered imdbs.\"\"\"\n return __sets.keys()\n","sub_path":"lib/datasets/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"228438104","text":"from tkinter import scrolledtext\r\nfrom urllib.request import urlopen\r\nimport matplotlib.pyplot as plt\r\nfrom tkinter import *\r\nimport tkinter as tk\r\nfrom tkinter import messagebox\r\nfrom PIL import *\r\nfrom PIL import ImageTk,Image\r\nfrom datetime import date, datetime, timedelta\r\n\r\n'''Se hace el webscrapper de una pagina de protocolos de salud para tiendas de \r\ncomestibles en epoca de Covid19 y se guarda en una lista de una longitud de 45 \r\ncaracteres utilizando el codigo de formato del taller 6'''\r\nurl = \"https://blog.qupos.com/recomendaciones-para-minisuper-supermercados-covid-19\"\r\npage = urlopen(url)\r\n\r\nhtml_bytes = page.read()\r\nhtml = html_bytes.decode(\"utf-8\")\r\nindice_final = 0\r\nRecomendaciones_para_supermercados_Covid19 = []\r\ncontador = 1\r\nfor i in range(13):\r\n lineamientos = html.find('

')\r\n indice_inicial = lineamientos + len('

')\r\n indice_final = html.find(\"

\")\r\n\r\n title = html[indice_inicial:indice_final]\r\n\r\n if i != 4:\r\n añadir = (str(contador) + \".\" + title)\r\n Recomendaciones_para_supermercados_Covid19.append(añadir)\r\n contador = contador + 1\r\n\r\n nueva_html = len(html[:indice_final + 11])\r\n html = html[nueva_html:]\r\ncontador = 1\r\ncovid = ''\r\nfor texto in Recomendaciones_para_supermercados_Covid19:\r\n lista = texto.split(' ')\r\n numero_caracteres = 45\r\n a = 0\r\n linea = ''\r\n for b in lista:\r\n calcular_len = len(b)\r\n a = a + calcular_len\r\n if a <= numero_caracteres:\r\n if a == numero_caracteres:\r\n linea = linea + b\r\n else:\r\n linea = linea + b + ' '\r\n a = a + 1\r\n else:\r\n lon_espacio = len(linea)\r\n if lon_espacio == numero_caracteres:\r\n covid = covid + '\\n' + linea\r\n a = 0\r\n linea = ''\r\n linea = linea + b + ' '\r\n calcular_len = len(b)\r\n a = a + calcular_len + 1\r\n else:\r\n mult = numero_caracteres - lon_espacio\r\n linea = linea + (' ' * mult)\r\n covid = covid + '\\n' + linea\r\n a = 0\r\n linea = ''\r\n linea = linea + b + ' '\r\n calcular_len = len(b)\r\n a = a + calcular_len + 1\r\n contador = contador + 1\r\n\r\n lon_espacio = len(linea)\r\n if lon_espacio == numero_caracteres:\r\n covid = covid + '\\n' + linea\r\n a = 0\r\n linea = ''\r\n linea = linea + b + ' '\r\n calcular_len = len(b)\r\n a = a + calcular_len + 1\r\n else:\r\n mult = numero_caracteres - lon_espacio\r\n linea = linea + (' ' * mult)\r\n covid = covid + '\\n' + linea\r\n a = 0\r\n linea = ''\r\n linea = linea + b + ' '\r\n calcular_len = len(b)\r\n a = a + calcular_len + 1\r\n\r\n'''Se define el menu general que tiene botones para agregar inventario, ver inventario,\r\n quitar inventario, ver ganancias y ver protocolos de Covid 19'''\r\ndef menu_general():\r\n menu_general = Tk()\r\n\r\n menu_general.title(\"Menu\")\r\n menu_general.geometry(\"400x400\")\r\n menu_general.configure(bg=\"papaya whip\")\r\n menu_general.iconbitmap('C:/Unal.ico')\r\n\r\n label = Label(menu_general, text=\"Menu\", font=(\"Arial Bold\", 20), bg='papaya whip')\r\n label.grid(row=0, column=1)\r\n\r\n agregar_inventario = Button(menu_general, text=\"Agregar productos\", command=agregar_productos_inventario, bg='misty rose')\r\n agregar_inventario.grid(row=3, column=1)\r\n\r\n espacio = Label(menu_general, text=' ', bg=\"papaya whip\")\r\n espacio.grid(row=2, column=0)\r\n\r\n verinventario = Button(menu_general, text=\"Ver inventario\", command=ver_inventario,bg='misty rose')\r\n verinventario.grid(row=5, column=1)\r\n espacio = Label(menu_general, text=' ', bg=\"papaya whip\")\r\n espacio.grid(row=4, column=0)\r\n\r\n quitar_inventario = Button(menu_general, text=\"Quitar productos\", command=eliminar_inventario,bg='misty rose')\r\n quitar_inventario.grid(row=7, column=1)\r\n espacio = Label(menu_general, text=' ', bg=\"papaya whip\")\r\n espacio.grid(row=6, column=0)\r\n\r\n ver_ganancia = Button(menu_general, text=\"Ver ganancias\", command=ver_ganancias,bg='misty rose')\r\n ver_ganancia.grid(row=10, column=1)\r\n espacio = Label(menu_general, text=' ', bg=\"papaya whip\")\r\n espacio.grid(row=9, column=0)\r\n\r\n covid = Button(menu_general, text=\"Covid19\", command=recomendaciones,bg='misty rose')\r\n covid.grid(row=14, column=1)\r\n espacio = Label(menu_general, text=' ', bg=\"papaya whip\")\r\n espacio.grid(row=13, column=3)\r\n\r\n salir = Button(menu_general, text=\"Salir\", command=menu_general.quit, anchor=E,bg='misty rose')\r\n salir.grid(row=16, column=3, sticky=W + E, rowspan=1, columnspan=1)\r\n espacio = Label(menu_general, text=' ', bg=\"papaya whip\")\r\n espacio.grid(row=15, column=0)\r\n\r\n menu_general.mainloop()\r\n\r\n'''La funcion recomendaciones tiene los protocolos de seguridad para el Covid19, utiliza scrollbar para ver todas las recomendaciones'''\r\ndef recomendaciones():\r\n recomen_covid19 = Tk()\r\n recomen_covid19.title(\"Recomendaciones Covid 19\")\r\n recomen_covid19.geometry(\"400x400\")\r\n recomen_covid19.configure(bg=\"lemon chiffon\")\r\n\r\n espacio = Label(recomen_covid19, text=' ', bg=\"lemon chiffon\")\r\n espacio.grid(row=0, column=0)\r\n\r\n recomendac = tk.Label(recomen_covid19, text=\"Recomendaciones para supermercados\" + '\\n' + \"en contexto de COVID-19\",font=(\"Arial Bold\", 12), bg='lemon chiffon')\r\n recomendac.grid(row=0, column=0)\r\n\r\n boton_menu = Button(recomen_covid19, text=\"Menu principal\", command=menu_general,bg='khaki')\r\n boton_menu.grid(row=4, column=0)\r\n\r\n barra = scrolledtext.ScrolledText(recomen_covid19,width=45,height=20,bg=\"lemon chiffon\")\r\n barra.grid(row=2,column=0)\r\n\r\n barra.insert(INSERT,covid)\r\n\r\n'''La funcion agregar productos inventario tiene \r\nlas entradas para el nombre del producto, el precio, la fecha de vencimiento y \r\ncantidad de unidades, todo esto con labels para indicar que se debe ingresar'''\r\ndef agregar_productos_inventario():\r\n agregar_inventario = Tk()\r\n agregar_inventario.title(\"Agregar Inventario\")\r\n agregar_inventario.geometry(\"400x400\")\r\n agregar_inventario.configure(bg=\"thistle3\")\r\n\r\n espacio = Label(agregar_inventario, text=' ', bg=\"thistle3\")\r\n espacio.grid(row=2, column=0)\r\n\r\n agregar_inventario_label = tk.Label(agregar_inventario, text=\"Agregar inventario\", font=(\"Arial Bold\", 20),bg='thistle3')\r\n agregar_inventario_label.grid(row=0, column=1)\r\n\r\n agregar_nombre_label = tk.Label(agregar_inventario, text=\"Nombre del producto:\", font=(\"Arial Bold\", 10),bg='thistle3')\r\n agregar_nombre_label.grid(row=1, column=1)\r\n\r\n agregar_nombre_entry = tk.Entry(agregar_inventario, width=30)\r\n agregar_nombre_entry.grid(column=1, row=2)\r\n\r\n agregar_precio_label = tk.Label(agregar_inventario, text=\"Precio del producto:\", font=(\"Arial Bold\", 10),bg='thistle3')\r\n agregar_precio_label.grid(row=3, column=1)\r\n\r\n agregar_precio_entry = tk.Entry(agregar_inventario, width=30)\r\n agregar_precio_entry.grid(column=1, row=4)\r\n\r\n agregar_vencimiento_label = tk.Label(agregar_inventario, text=\"Fecha de vencimiento del producto:\",font=(\"Arial Bold\", 10), bg='thistle3')\r\n agregar_vencimiento_label.grid(row=5, column=1)\r\n\r\n agregar_vencimiento_entry = tk.Entry(agregar_inventario, width=30)\r\n agregar_vencimiento_entry.grid(column=1, row=6)\r\n\r\n agregar_cantidad_label = tk.Label(agregar_inventario, text=\"Cantidad de unidades del producto:\",font=(\"Arial Bold\", 10), bg='thistle3')\r\n agregar_cantidad_label.grid(row=7, column=1)\r\n\r\n agregar_cantidad_entry = tk.Entry(agregar_inventario, width=30)\r\n agregar_cantidad_entry.grid(column=1, row=8)\r\n\r\n boton_guardar = Button(agregar_inventario, text=\"Guardar\",command=lambda: llamar_datos(agregar_nombre_entry.get(), agregar_precio_entry.get(),agregar_vencimiento_entry.get(), agregar_cantidad_entry.get()),bg='plum2')\r\n boton_guardar.grid(row=9, column=1)\r\n\r\n boton_nuevo_producto = Button(agregar_inventario, text=\"Agregar nuevo producto\",command=agregar_productos_inventario,bg='plum2')\r\n boton_nuevo_producto.grid(row=10, column=1)\r\n\r\n boton_menu = Button(agregar_inventario, text=\"Menu principal\", command=menu_general,bg='plum2')\r\n boton_menu.grid(row=11, column=1)\r\n\r\n'''La funcion llamar datos toma las entradas ingresadas en la funcion anterior y las guarda en la \r\nbase de datos del inventario, en esta funcion tambien se validan los datos ingresados a traves de \r\nmessageboxes en caso de error por parte del usuario'''\r\ndef llamar_datos(nombre, precio, fecha, cantidad):\r\n archivo = open('Base de datos productos.txt', 'r')\r\n matriz_inventario = []\r\n contador = 0\r\n for linea in archivo.readlines():\r\n linea = linea.split(',')\r\n matriz_inventario.append(linea)\r\n archivo.close()\r\n\r\n lista_nombres = []\r\n for linea in matriz_inventario:\r\n lista_nombres.append(linea[0])\r\n\r\n if nombre not in lista_nombres:\r\n contenido = nombre.rstrip() + \",\"\r\n contador = contador + 1\r\n if nombre in lista_nombres:\r\n messagebox.showinfo('Error', 'El producto ingresado ya existe en el inventario')\r\n if type(precio) == str:\r\n try:\r\n precio_validado = int(precio)\r\n contenido = contenido + precio.rstrip() + \",\"\r\n contador = contador + 1\r\n except ValueError:\r\n messagebox.showinfo('Error', 'El precio debe ser un numero entero')\r\n if fecha[2] == '/' and fecha[5] == '/' and int(fecha[:2]) < 32 and int(fecha[3:5]) < 13 and int(fecha[6:10]) > 2019:\r\n dia_vencimento_con_formato = datetime.strptime(fecha, '%d/%m/%Y')\r\n dia_actual = datetime.today()\r\n dia_vencimiento_referecia = dia_actual + timedelta(days=5)\r\n imprimir = 0\r\n if dia_vencimento_con_formato <= dia_vencimiento_referecia:\r\n imprimir = 1\r\n contenido = contenido + fecha.rstrip() + \",\"\r\n contador = contador + 1\r\n else:\r\n messagebox.showinfo('Error', 'La fecha ingresada no cumple con del formato dd/mm/aa')\r\n if type(cantidad) == str:\r\n try:\r\n cantidad_validado = int(cantidad)\r\n contenido = contenido + cantidad.rstrip() + \"\\n\"\r\n contador = contador + 1\r\n except ValueError:\r\n messagebox.showinfo('Error', 'La cantidad de unidades debe ser un numero entero')\r\n\r\n if contador == 4:\r\n archivo = open('Base de datos productos.txt', 'a')\r\n archivo.write(contenido)\r\n archivo.close()\r\n if imprimir == 1:\r\n messagebox.showinfo('Atención',\"El producto ingresado va a vencer pronto (En 5 dias o menos)\")\r\n messagebox.showinfo('Guardado', 'El producto ha sido agregado al inventario')\r\n\r\n'''La funcion de ver inventario toma todos los datos guardados en la base de datos del inventario \r\ny los muestra organizadamente en una tabla'''\r\ndef ver_inventario():\r\n class Table:\r\n\r\n def __init__(self, root):\r\n\r\n for i in range(total_rows):\r\n for j in range(total_columns):\r\n if j == 1:\r\n self.e = Entry(root, width=12, fg='black', bg='azure',\r\n font=('Arial', 10, 'bold'))\r\n self.e.grid(row=i + 1, column=j)\r\n self.e.insert(END, lst[i][j])\r\n elif j == 2:\r\n self.e = Entry(root, width=12, fg='black', bg='azure',\r\n font=('Arial', 10, 'bold'))\r\n self.e.grid(row=i + 1, column=j)\r\n self.e.insert(END, lst[i][j])\r\n elif j == 3:\r\n self.e = Entry(root, width=10, fg='black', bg='azure',\r\n font=('Arial', 10, 'bold'))\r\n self.e.grid(row=i + 1, column=j)\r\n self.e.insert(END, lst[i][j])\r\n else:\r\n self.e = Entry(root, width=15, fg='black', bg='azure',\r\n font=('Arial', 10, 'bold'))\r\n\r\n self.e.grid(row=i + 1, column=j)\r\n self.e.insert(END, lst[i][j])\r\n archivo = open('Base de datos productos.txt', 'r')\r\n matriz_inventario = []\r\n for linea in archivo.readlines():\r\n linea = linea.split(',')\r\n matriz_inventario.append(linea)\r\n archivo.close()\r\n lst = matriz_inventario\r\n total_rows = len(matriz_inventario)\r\n total_columns = len(matriz_inventario[1])\r\n\r\n root = Tk()\r\n t = Table(root)\r\n root.title(\"Inventario\")\r\n root.geometry(\"400x400\")\r\n root.configure(bg=\"azure\")\r\n root.iconbitmap('C:/Unal.ico')\r\n\r\n label = Label(root, text=\"Ver\" + \"\\n\" + \"Inventario\", font=(\"Arial Bold\", 15), bg='azure')\r\n label.grid(row=0, column=0)\r\n\r\n espacio = Label(root, text=' ', bg=\"azure\")\r\n espacio.grid(row=50, column=2)\r\n\r\n boton_menu = Button(root, text=\"Menu principal\", command=menu_general)\r\n boton_menu.grid(row=51, column=2)\r\n\r\n root.mainloop()\r\n\r\n'''La funcion de eliminar inventario tiene los las opciones de eliminar unidades y eliminar producto'''\r\ndef eliminar_inventario():\r\n quitar_inventario = Tk()\r\n quitar_inventario.title(\"Quitar productos del inventario\")\r\n quitar_inventario.geometry(\"400x400\")\r\n quitar_inventario.configure(bg=\"DarkSeaGreen1\")\r\n\r\n quitar_inventario_label = tk.Label(quitar_inventario, text=\" Menú quitar inventario\", font=(\"Arial Bold\", 18),bg='DarkSeaGreen1')\r\n quitar_inventario_label.grid(row=0, column=1)\r\n\r\n espacio = Label(quitar_inventario, text=' ', bg=\"DarkSeaGreen1\")\r\n espacio.grid(row=2, column=0)\r\n\r\n boton_eliminar_unidades = Button(quitar_inventario, text='Eliminar Unidades', bg='DarkSeaGreen3',command=quitar_producto_unidades)\r\n boton_eliminar_unidades.grid(row=4, column=1)\r\n\r\n espacio = Label(quitar_inventario, text=' ', bg=\"DarkSeaGreen1\")\r\n espacio.grid(row=5, column=1)\r\n\r\n boton_eliminar_producto = Button(quitar_inventario, text='Eliminar Producto', bg='DarkSeaGreen3',command=eliminar_producto)\r\n boton_eliminar_producto.grid(row=6, column=1)\r\n\r\n espacio = Label(quitar_inventario, text=' ', bg=\"DarkSeaGreen1\")\r\n espacio.grid(row=9, column=0)\r\n\r\n espacio = Label(quitar_inventario, text=' ', bg=\"DarkSeaGreen1\")\r\n espacio.grid(row=10, column=0)\r\n\r\n boton_menu = Button(quitar_inventario, text=\"Menu principal\", command=menu_general, bg='DarkSeaGreen3')\r\n boton_menu.grid(row=11, column=1)\r\n\r\n'''La funcion de eliminar producto tiene la entrada para que el usuario ingrese el nombre del producto y asi poder eliminarlo'''\r\ndef eliminar_producto():\r\n quitar_productos = Tk()\r\n quitar_productos.title(\"Quitar productos del inventario\")\r\n quitar_productos.geometry(\"400x400\")\r\n quitar_productos.configure(bg=\"PaleGreen1\")\r\n\r\n titulo_quitar_inventario_label = tk.Label(quitar_productos, text=\"Quitar del inventario\",font=(\"Arial Bold\", 18), bg='PaleGreen1')\r\n titulo_quitar_inventario_label.grid(row=0, column=1)\r\n\r\n nombre_producto_label = tk.Label(quitar_productos, text=\"Nombre del producto:\", font=(\"Arial Bold\", 10),bg='PaleGreen1')\r\n nombre_producto_label.grid(row=1, column=1)\r\n\r\n espacio = Label(quitar_productos, text=' ', bg=\"PaleGreen1\")\r\n espacio.grid(row=2, column=0)\r\n\r\n nombre_producto_entry = tk.Entry(quitar_productos, width=30)\r\n nombre_producto_entry.grid(column=1, row=3)\r\n\r\n espacio = Label(quitar_productos, text=' ', bg=\"PaleGreen1\")\r\n espacio.grid(row=4, column=0)\r\n\r\n boton_guardar = Button(quitar_productos, text=\"Guardar cambios\",command=lambda: eliminar_producto_archivo(nombre_producto_entry.get()),bg='PaleGreen3')\r\n boton_guardar.grid(row=5, column=1)\r\n\r\n boton_menu_eliminar = Button(quitar_productos, text=\"Menu quitar inventario\", command=eliminar_inventario,bg='PaleGreen3')\r\n boton_menu_eliminar.grid(row=6, column=1)\r\n\r\n boton_menu_principal = Button(quitar_productos, text=\"Menu principal\", command=menu_general, bg='PaleGreen3')\r\n boton_menu_principal.grid(row=7, column=1)\r\n\r\n'''La funcion eliminar producto de archivo toma el nombre ingresado en la funcion anterior \r\ny lo elimina de la base de datos, tiene validacion en caso de que el nombre no este en el inventario'''\r\ndef eliminar_producto_archivo(nombre):\r\n archivo = open('Base de datos productos.txt' , 'r')\r\n matriz_inventario = []\r\n for linea in archivo.readlines():\r\n linea = linea.split(',')\r\n matriz_inventario.append(linea)\r\n archivo.close()\r\n\r\n lista_nombres = []\r\n for linea in matriz_inventario:\r\n lista_nombres.append(linea[0])\r\n\r\n if nombre in lista_nombres:\r\n for linea in range(len(matriz_inventario)):\r\n if matriz_inventario[linea][0] == nombre:\r\n matriz_inventario.remove(matriz_inventario[linea])\r\n archivo = open('Base de datos productos.txt', 'w')\r\n for linea in matriz_inventario:\r\n archivo.write(','.join(linea))\r\n archivo.close()\r\n messagebox.showinfo('Guardado', 'Guardado con éxito')\r\n break\r\n else:\r\n messagebox.showinfo('Error', 'El producto ingresado no esta en el inventario')\r\n\r\n'''La funcion de quitar unidades de producto tiene las entradas para ingresar el nombre del producto y la cantidad de unidades a eliminar'''\r\ndef quitar_producto_unidades():\r\n quitar_unidades_inventario = Tk()\r\n quitar_unidades_inventario.title(\"Quitar unidades del inventario\")\r\n quitar_unidades_inventario.geometry(\"400x400\")\r\n quitar_unidades_inventario.configure(bg=\"SeaGreen1\")\r\n\r\n titulo_quitar_inventario_label = tk.Label(quitar_unidades_inventario, text=\"Quitar del inventario\",font=(\"Arial Bold\", 18), bg='SeaGreen1')\r\n titulo_quitar_inventario_label.grid(row=0, column=1)\r\n\r\n nombre_producto_label = tk.Label(quitar_unidades_inventario, text=\"Nombre del producto:\", font=(\"Arial Bold\", 10),bg='SeaGreen1')\r\n nombre_producto_label.grid(row=1, column=1)\r\n\r\n espacio = Label(quitar_unidades_inventario, text=' ', bg=\"SeaGreen1\")\r\n espacio.grid(row=2, column=0)\r\n\r\n nombre_producto_entry = tk.Entry(quitar_unidades_inventario, width=30)\r\n nombre_producto_entry.grid(column=1, row=2)\r\n\r\n espacio = Label(quitar_unidades_inventario, text=' ', bg=\"SeaGreen1\")\r\n espacio.grid(row=3, column=0)\r\n\r\n cantidad_eliminar_label = tk.Label(quitar_unidades_inventario, text=\"Cantidad de unidades a eliminar:\",font=(\"Arial Bold\", 10), bg='SeaGreen1')\r\n cantidad_eliminar_label.grid(row=4, column=1)\r\n\r\n eliminar_cantidad_entry = tk.Entry(quitar_unidades_inventario, width=30)\r\n eliminar_cantidad_entry.grid(column=1, row=5)\r\n\r\n espacio = Label(quitar_unidades_inventario, text=' ', bg=\"SeaGreen1\")\r\n espacio.grid(row=6, column=0)\r\n\r\n boton_guardar = Button(quitar_unidades_inventario, text=\"Guardar cambios\",command=lambda: eliminar_unidades_producto(nombre_producto_entry.get(),eliminar_cantidad_entry.get()),bg='SeaGreen3')\r\n boton_guardar.grid(row=7, column=1)\r\n\r\n boton_menu_eliminar = Button(quitar_unidades_inventario, text=\"Menu quitar inventario\", command=eliminar_inventario,bg='SeaGreen3')\r\n boton_menu_eliminar.grid(row=8, column=1)\r\n\r\n boton_menu_principal = Button(quitar_unidades_inventario, text=\"Menu principal\", command=menu_general,bg='SeaGreen3')\r\n boton_menu_principal.grid(row=9, column=1)\r\n\r\n'''La funcion eliminar unidades del producto toma las entradas del el nombre y la cantidad de unidades a eliminar obtenidas en la funcion anterior,\r\n estos datos se ponen en una lista y se eliminan de la base de datos, tiene validación de datos en caso de que el \r\n nombre del producto no este en el inventario o la cantidad de unidades a eliminar sea mayor a la existente en el inventario'''\r\ndef eliminar_unidades_producto(nombre, unidades):\r\n archivo = open('Base de datos productos.txt', 'r')\r\n matriz_inventario = []\r\n for linea in archivo.readlines():\r\n linea = linea.split(',')\r\n matriz_inventario.append(linea)\r\n archivo.close()\r\n\r\n lista_nombres = []\r\n lista_unidades = []\r\n lista_precios = []\r\n for linea in matriz_inventario:\r\n lista_nombres.append(linea[0])\r\n lista_unidades.append(linea[-1])\r\n lista_precios.append(linea[1])\r\n\r\n if nombre in lista_nombres:\r\n try:\r\n unidades = int(unidades)\r\n for linea in range(len(matriz_inventario)):\r\n if nombre == lista_nombres[linea]:\r\n if unidades < int(lista_unidades[linea]):\r\n matriz_inventario[linea][-1] = str(int(matriz_inventario[linea][-1]) - unidades) + '\\n'\r\n archivo = open('Base de datos productos.txt', 'w')\r\n for line in matriz_inventario:\r\n archivo.write(','.join(line))\r\n archivo.close()\r\n matriz_ventas = []\r\n ventas = open('Productos_vendidos.txt', \"r\")\r\n for linea1 in ventas.readlines():\r\n linea1 = linea1.split(',')\r\n matriz_ventas.append(linea1)\r\n ventas.close()\r\n lista_nombres_ventas = []\r\n lista_ganacias_ventas = []\r\n for a in matriz_ventas:\r\n lista_nombres_ventas.append(a[0])\r\n lista_ganacias_ventas.append(a[1])\r\n if nombre in lista_nombres_ventas:\r\n for indice in range(len(matriz_ventas)):\r\n if nombre == lista_nombres_ventas[indice]:\r\n añadir = int(lista_precios[linea]) * int(unidades)\r\n suma = añadir + int(lista_ganacias_ventas[indice])\r\n matriz_ventas[indice][1] = str(suma)+'\\n'\r\n ventas = open('Productos_vendidos.txt', 'w')\r\n for new_line in matriz_ventas:\r\n ventas.write(','.join(new_line))\r\n ventas.close()\r\n else:\r\n ventas = open('Productos_vendidos.txt', 'a')\r\n ventas.writelines(nombre + \",\" + str(int(lista_precios[linea])*int(unidades)) + \"\\n\")\r\n ventas.close()\r\n archivo.close()\r\n messagebox.showinfo('Guardado', 'Guardado con éxito')\r\n else:\r\n messagebox.showinfo('Error', 'Ingrese numero de unidades menor al existente')\r\n except ValueError:\r\n messagebox.showinfo('Error', 'Cantidad debe ser numero entero')\r\n else:\r\n messagebox.showinfo('Error', 'El producto ingresado no esta en el inventario')\r\n\r\n'''La funcion de ver ganancias mustra una grafica de las ganancias obtenidas por los productos vendidos'''\r\ndef ver_ganancias():\r\n ventas = open('Productos_vendidos.txt', \"r\")\r\n matriz_ganancias = []\r\n producto_x = []\r\n ganancias_y = []\r\n for linea in ventas.readlines():\r\n linea =linea.split(',')\r\n matriz_ganancias.append(linea)\r\n for i in matriz_ganancias:\r\n producto_x.append(i[0])\r\n numero_sin_0 = (int(i[1]) / 10000)\r\n ganancias_y.append(numero_sin_0)\r\n plt.plot(producto_x, ganancias_y)\r\n plt.title('Ganancias obtenidas por producto')\r\n plt.ylabel('Ganancias obtenidas/10000')\r\n plt.xlabel('Productos vendidos')\r\n\r\n plt.legend()\r\n plt.grid()\r\n plt.show()\r\n\r\n'''La funcion de login tiene el logo del inventario y las entradas para el usuario y la contraseña'''\r\ndef login():\r\n ventana = tk.Tk()\r\n ventana.title(\"Login\")\r\n ventana.geometry('400x400')\r\n ventana.configure(background='pale turquoise')\r\n\r\n espacio = tk.Label(ventana, text=' ', bg=\"pale turquoise\")\r\n espacio.grid(row=0, column=0)\r\n\r\n logo = ImageTk.PhotoImage(Image.open(r'C:\\logo_recortado2.png').resize((130, 120)))\r\n label = Label(image=logo, bg='pale turquoise')\r\n label.grid(row=2, column=1)\r\n\r\n espacio = tk.Label(ventana, text=' ', bg=\"pale turquoise\")\r\n espacio.grid(row=3, column=0)\r\n label = tk.Label(ventana, text='Login', font=('Arial bold', 25), bg='pale turquoise')\r\n label.grid(row=3,column=1)\r\n\r\n espacio = tk.Label(ventana, text=' ', bg=\"pale turquoise\")\r\n espacio.grid(row=1, column=0)\r\n\r\n label1 = tk.Label(ventana, text='Usuario',font=('Arial bold', 18), bg='pale turquoise')\r\n label1.grid(row=7,column=0)\r\n usuario_entry = tk.Entry(ventana, width=30)\r\n usuario_entry.grid(column = 1, row=7)\r\n\r\n label2 = tk.Label(ventana, text='Contraseña',font=('Arial bold', 18), bg='pale turquoise')\r\n label2.grid(row=9,column=0)\r\n contraseña_entry = tk.Entry(ventana, width=30)\r\n contraseña_entry.grid(column = 1, row=9)\r\n\r\n espacio = tk.Label(ventana, text=' ', bg=\"pale turquoise\")\r\n espacio.grid(row=15, column=0)\r\n espacio = tk.Label(ventana, text=' ', bg=\"pale turquoise\")\r\n espacio.grid(row=11, column=0)\r\n espacio = tk.Label(ventana, text=' ', bg=\"pale turquoise\")\r\n espacio.grid(row=12, column=0)\r\n nuevo_usuario = Button(ventana, text=\"Registrar nuevo usuario\", command=lambda:res_nuevo_usurario(ventana),bg = 'medium turquoise')\r\n nuevo_usuario.grid(row=13, column=1)\r\n\r\n ingresar = Button(ventana, text=\"Ingresar\", command=lambda: comprobar_usu_con(usuario_entry.get(),contraseña_entry.get()), bg='medium turquoise')\r\n ingresar.grid(row=10, column=1)\r\n\r\n ventana.mainloop()\r\n\r\n'''La funcion de comprobar usuario toma las entradas de la funcion anterior y las valida en caso de que el usuario no coincida con la contraseña'''\r\ndef comprobar_usu_con(usu,contr):\r\n archivo = open('Base de datos usurios.txt', 'r')\r\n datos = []\r\n\r\n for linea in archivo.readlines():\r\n datos.append(linea)\r\n\r\n datos_nuevos = []\r\n for a in datos:\r\n a = a[:-1]\r\n datos_nuevos.append(a.split(':'))\r\n\r\n\r\n diccionario = {}\r\n for b in datos_nuevos:\r\n diccionario[b[0]] = b[1]\r\n\r\n for llave in diccionario.keys():\r\n diccionario[llave] = diccionario[llave].split(\",\")\r\n\r\n datos_login = {}\r\n for llave in diccionario.keys():\r\n datos_login[llave] = diccionario[llave][1]\r\n\r\n\r\n archivo.close()\r\n\r\n if usu in datos_login.keys():\r\n if datos_login[usu] == contr:\r\n menu_general()\r\n else:\r\n messagebox.showinfo('Error', 'Contraseña Incorrecta')\r\n else:\r\n messagebox.showinfo('Error', 'Usuario inexistente')\r\n\r\n'''La funcion de registro nuevo usuario tiene las entradas para el nombre, el usuario, la \r\ncontraseña (y la confirmacion de contraseña) y si es dueño o empleado'''\r\ndef res_nuevo_usurario(n_usuario):\r\n\r\n ventana1 = Toplevel(n_usuario)\r\n ventana1.title(\"Registrar Nuevo Usuario\")\r\n ventana1.geometry('400x400')\r\n ventana1.configure(background='SteelBlue2')\r\n espacio = tk.Label(ventana1, text=' ', bg=\"SteelBlue2\")\r\n espacio.grid(row=0, column=0)\r\n label = tk.Label(ventana1, text='Registrar\\nNuevo\\nUsuario', font=('Arial bold', 18), bg='SteelBlue2')\r\n label.grid(row=0, column=1, columnspan=1)\r\n\r\n label1 = tk.Label(ventana1, text='Nombre', font=('Arial bold', 15), bg='SteelBlue2')\r\n label1.grid(row=3, column=0)\r\n nombre_entry = tk.Entry(ventana1, width=30)\r\n nombre_entry.grid(column=1, row=3)\r\n espacio = tk.Label(ventana1, text=' ', bg=\"SteelBlue2\")\r\n espacio.grid(row=1, column=1,columnspan=2)\r\n\r\n label1 = tk.Label(ventana1, text='Usuario', font=('Arial bold', 15), bg='SteelBlue2')\r\n label1.grid(row=4, column=0)\r\n usuario_entry = tk.Entry(ventana1, width=30)\r\n usuario_entry.grid(row=4,column=1)\r\n\r\n label1 = tk.Label(ventana1, text='Contraseña', font=('Arial bold', 15), bg='SteelBlue2')\r\n label1.grid(row=5, column=0)\r\n nueva_contraseña_entry = tk.Entry(ventana1, width=30)\r\n nueva_contraseña_entry.grid(row=5, column=1)\r\n\r\n label1 = tk.Label(ventana1, text=' Confirmar Contraseña', font=('Arial bold', 12), bg='SteelBlue2')\r\n label1.grid(row=6, column=0)\r\n contraseña_comfir_entry = tk.Entry(ventana1, width=30)\r\n contraseña_comfir_entry.grid(row=6, column=1)\r\n\r\n selected = tk.IntVar()\r\n\r\n opcion_1 = Radiobutton(ventana1, text='Dueño', value=1, variable=selected, bg='SteelBlue2')\r\n opcion_1.grid(column=1, row=7)\r\n opcion_2 = Radiobutton(ventana1, text='Empleado', value=2, variable=selected, bg='SteelBlue2')\r\n opcion_2.grid(column=1, row=8)\r\n\r\n nuevo_usuario = Button(ventana1, text=\"Guardar nuevo usuario\", command=lambda:guardar_nuevo_usuario(nombre_entry.get(), usuario_entry.get(), nueva_contraseña_entry.get(), contraseña_comfir_entry.get(), selected.get()), bg='SteelBlue3')\r\n\r\n nuevo_usuario.grid(row=9, column=1)\r\n\r\n '''La funcion guardar nuevo usuario toma las entradas de la funcion anterior y las valida en caso de que \r\n el nombre tenga un numero, el usuario tenga espacios o ya exista en la base de datos, la contraseña y la \r\n confirmacion de contraseña no coincidan; despues de comprobar todos los datos los guarda en la base de datos de login'''\r\n def guardar_nuevo_usuario(nombre, nuevo_usuario, nuevo_contraseña, confirm_nueva_contraseña, cargo):\r\n archivo = open('Base de datos usurios.txt', 'r')\r\n\r\n datos = []\r\n\r\n for linea in archivo.readlines():\r\n datos.append(linea)\r\n\r\n datos_nuevos = []\r\n for a in datos[:-1]:\r\n a = a[:-1]\r\n datos_nuevos.append(a.split(':'))\r\n\r\n base_registar_usuario = {}\r\n for b in datos_nuevos:\r\n base_registar_usuario[b[0]] = b[1]\r\n\r\n archivo.close()\r\n contador = 0\r\n if '1' in nombre or '2' in nombre or '3' in nombre or '4' in nombre or '5' in nombre or '6' in nombre or '7' in nombre or '8' in nombre or '9' in nombre or '0' in nombre:\r\n messagebox.showinfo('Error', 'Nombre Inválido')\r\n contador = 1\r\n if ' ' in nuevo_usuario:\r\n messagebox.showinfo('Error', 'Usuario no puede contener espacios')\r\n contador = 1\r\n if nuevo_contraseña != confirm_nueva_contraseña:\r\n messagebox.showinfo('Error', 'Confirmación de contraseña incorrecta')\r\n contador = 1\r\n if nuevo_usuario in base_registar_usuario.keys():\r\n messagebox.showinfo('Error', 'Usuario ingresado ya existe')\r\n contador = 1\r\n if contador == 0:\r\n archivo = open('Base de datos usurios.txt', 'a')\r\n salto_linea = '\\n'\r\n archivo.write(salto_linea)\r\n guardar_usuario = (\"{}:({},{},{})\".format(nuevo_usuario, nombre, nuevo_contraseña, cargo))\r\n archivo.write(guardar_usuario)\r\n archivo.close()\r\n messagebox.showinfo('Guardado', 'Su usuario ha sido registrado con éxito')\r\n\r\ndef main():\r\n login()\r\n\r\nmain()","sub_path":"Código fuente/Codigo Fuente.py","file_name":"Codigo Fuente.py","file_ext":"py","file_size_in_byte":31802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"9757485","text":"import socket\nimport threading\nfrom AES_lib import AESCipher\nimport random\n\nclass Client:\n def __init__(self):\n self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.host = socket.gethostbyname(socket.gethostname())\n self.port = 5068\n self.addr = (self.host, self.port)\n self.header = 1024\n self.name = \"bot\"+str(random.randint(1,99999))\n self.format = \"utf-8\"\n self.disconnect = 'exit'\n\n self.key = b'\\00' * 16\n # self.iv = b'\\01' * 16\n self.aes=AESCipher(self.key)\n\n def start_client(self):\n self.client.connect(self.addr)\n self.client.send(self.name.encode(self.format))\n\n recv_msg_thread=threading.Thread(target=self.recv_msg)\n recv_msg_thread.start()\n\n send_msg_thread=threading.Thread(target=self.send_msg)\n send_msg_thread.start()\n\n def stop_client(self):\n self.client.send(self.aes.encrypt_cbc(self.disconnect))\n self.client.close()\n exit(0)\n\n def recv_msg(self):\n while True:\n try:\n msg = self.client.recv(self.header)\n msg = self.aes.decrypt(msg).decode(self.format)\n except:\n print(\"Disconnected from server\")\n break\n\n def send_msg(self):\n while True:\n try:\n msg = input('Message:')\n if msg == self.disconnect:\n break\n msg = self.aes.encrypt(msg.encode(self.format))\n self.client.send(msg)\n except:\n print(\"Disconnected from server\")\n break\n\ns=Client()\ns.start_client()\n\n\n","sub_path":"from Library/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"164290553","text":"import importlib\nimport sys\nimport numpy as np\nimportlib.reload(sys)\n\nfrom sklearn.grid_search import GridSearchCV \nfrom sklearn.preprocessing import Imputer\nfrom sklearn import preprocessing\nimport glob\nimport numpy as np\nfrom sklearn import datasets, linear_model\nfrom sklearn.linear_model import LinearRegression\n\ntext_filename=glob.glob('/home/rxx/quant/FctResults/DataByDate_pre/*')\ntext_filename.sort()\n\n\nx_train = []\ny_train = []\n\nfor filename in text_filename:\n\tif filename[-12:-4]>'20151020' and filename[-12:-4]<'20161020':\n\t\tff=open('/home/rxx/quant/stock/data1/ALL/'+filename[-12:-8]+'/'+filename[-8:-6]+'/alpha.'+filename[-12:-4],'r')\n\t\tline1=ff.readline()\n\t\twhile line1:\n\t\t\ttoken1=line1.strip().split('|')\n\t\t\ty_train.append(token1[3])\n\t\t\t#print(y_train)\n\t\t\tprint(token1[0])\n\n\n\t\t\tf=open(filename,'r')\n\t\t\tprint(filename)\n\t\t\tline=f.readline()\n\t\t\twhile line:\n\t\t\t\ttoken=line.strip().split(' ')\n\t\t\t\tprint(token[0])\n\t\t\t\tprint(token1[0])\n\t\t\t\tif token[0]==token1[0]:\n\t\t\t\t\t\n\t\t\t\t\ttemp = []\n\t\t\t\t\tfor i in range(1,36):\n\t\t\t\t\t\ttemp.append(token[i])\n\t\t\t\t\tx_train.append(temp)\n\t\t\t\t\t#print(x_train)\n\t\t\t\tline=f.readline()\n\n\t\t\tline1=ff.readline()\n\n\t\t\n\n\n\t\tclf=LinearRegression(n_jobs=-1,normalize=True)\n\t\tclf.fit(x_train,y_train)\n\t\tprint(filename[-12:-4])\n\t\tprint(clf.intercept_)\n\n\n\n\n\n\n","sub_path":"数据处理/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"497077413","text":"#\n# This file is part of The Principles of Modern Game AI.\n# Copyright (c) 2015, AiGameDev.com KG.\n#\n\nimport nltk.chat\nimport vispy # Main application support.\n\nimport speech\nimport window # Terminal input and display.\n\nAGENT_RESPONSES = [\n (r'you are (worrying|scary|disturbing)', # Pattern 1.\n ['Yes, I am %1.', # Response 1a.\n 'Oh, sooo %1.']),\n\n (r'are you ([\\w\\s]+)\\??', # Pattern 2.\n [\"Why would you think I am %1?\", # Response 2a.\n \"Would you like me to be %1?\"]),\n\n (r'', # Pattern 3. (default)\n [\"is everything OK?\", # Response 3a.\n \"Can you still communicate?\"])\n]\n\nSHIP = \"\"\"\n ********\n * *\n ***********+****************\n *** * * * * *---\n ** * * * * * *-----\n* ** + * * * *------\n ** + **** **** +**** *----- \n *** + *---\n ***********++***************\n * *\n ********\n\"\"\".splitlines()\n\n\nclass HAL9000(object):\n def __init__(self, terminal):\n \"\"\"Constructor for the agent, stores references to systems and initializes internal memory.\n \"\"\"\n self.terminal = terminal\n self.location = (4, 14)\n self.chatbot = nltk.chat.Chat(AGENT_RESPONSES, nltk.chat.util.reflections)\n\n def on_input(self, evt):\n \"\"\"Called when user types anything in the terminal, connected via event.\n \"\"\"\n if evt.text == \"map\":\n self.print_map()\n\n else:\n response = self.chatbot.respond(evt.text)\n self.say(response)\n\n def on_command(self, evt):\n \"\"\"Called when user types a command starting with `/` also done via events.\n \"\"\"\n if evt.text == 'quit':\n vispy.app.quit()\n\n elif evt.text.startswith('move'):\n move_evt = evt.text[5:]\n if move_evt.startswith('left'):\n self.try_move((self.location[0], self.location[1] - 1))\n elif move_evt.startswith('right'):\n self.try_move((self.location[0], self.location[1] + 1))\n elif move_evt.startswith('up'):\n self.try_move((self.location[0] - 1, self.location[1]))\n elif move_evt.startswith('down'):\n self.try_move((self.location[0] + 1, self.location[1]))\n\n else:\n self.terminal.log('Command `{}` unknown.'.format(evt.text),\n align='left', color='#ff3000')\n self.say(\"I'm afraid you can't do that.\")\n\n def print_map(self):\n for idx, line in enumerate(SHIP):\n location_y = self.location[0]\n location_x = self.location[1]\n if location_y == idx:\n line = line[:location_x] + \"M\" + line[location_x + 1:]\n self.terminal.log(line, face=\"Courier\")\n\n def try_move(self, location):\n if SHIP[location[0]][location[1]] == ' ':\n self.location = location\n self.print_map()\n self.say('One step at the time.')\n elif SHIP[location[0]][location[1]] == '+':\n self.location = location\n self.print_map()\n self.say('Don\\'t stand in the doorway for too long!')\n elif SHIP[location[0]][location[1]] == '*':\n self.say('Stop banging your head against the wall. It\\'s gonna be ok!')\n else:\n self.print_map()\n self.say('Something is really wrong with your location `{}`!'.format(location))\n\n def say(self, message):\n self.terminal.log('\\u2014 ' + message, align='right', color='#00805A')\n self.terminal.speak(message)\n\n def update(self, _):\n \"\"\"Main update called once per second via the timer.\n \"\"\"\n pass\n\n\nclass TerminalWithVoice(window.TerminalWindow, speech.SpeechMixin):\n def __init__(self, *args, **kwargs):\n super(TerminalWithVoice, self).__init__(*args, **kwargs)\n speech.SpeechMixin.__init__(self, 'Victoria', 2000, *args, **kwargs)\n\n def on_message(self, source, message):\n self.log(message, align='left')\n self.events.user_input(window.TextEvent(message))\n\n def debug(self, log):\n print(log)\n\n\nclass Application(object):\n def __init__(self):\n # Create and open the window for user interaction.\n self.window = TerminalWithVoice()\n\n # Print some default lines in the terminal as hints.\n self.window.log('Operator started the chat.', align='left', color='#808080')\n self.window.log('HAL9000 joined.', align='right', color='#808080')\n\n # Construct and initialize the agent for this simulation.\n self.agent = HAL9000(self.window)\n\n # Connect the terminal's existing events.\n self.window.events.user_input.connect(self.agent.on_input)\n self.window.events.user_command.connect(self.agent.on_command)\n\n def run(self):\n timer = vispy.app.Timer(interval=1.0)\n timer.connect(self.agent.update)\n timer.start()\n\n vispy.app.run()\n\n\nif __name__ == \"__main__\":\n vispy.set_log_level('WARNING')\n vispy.use(app='glfw')\n\n app = Application()\n app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"193056944","text":"import numpy as np\n\n#zad 1\na = np.arange(2,82,2)\n\n#zad 2\na = np.array([x**0.5 for x in range(1,101)])\nb = a.astype('int64')\n\n#zad 3\n\ndef inicjalizuj(n):\n return np.array([[x+n*y for x in range(1,n+1)] for y in range(n)])\n\n#zad 4\n\ndef potegi(podstawa, n):\n return np.logspace(1.0, n, num=n, base = podstawa, dtype=int)\n\n#zad 5\n\ndef wektor(n):\n a = np.arange(n, 0, -1)\n macierz = np.diag([x for x in a])\n return macierz\n\n#zad 6\n\nslowo1 = 'kuter'\nslowo2 = 'kajak'\ndlugosc = len(slowo1)\n\nmacierz2 = np.diag([x for x in slowo1])\nfor x in range(dlugosc):\n macierz2[x, 0] = slowo2[x]\n macierz2[0, x] = slowo2[dlugosc-1-x]\n\nprint(macierz2)\n\n#zad 7 \n\ndef dwojki(n):\n macierz3 = np.zeros((n,n))\n for x in range(n):\n for y in range(n):\n if x+y < n:\n macierz3[x, x+y] = 2*(y+1)\n macierz3[x+y, x] = 2*(y+1)\n if x-y >= n:\n macierz3[x-y, x] = 2*(y+1)\n macierz3[x, x-y] = 2*(y+1)\n\n return macierz3\n\n#zad 8\n\nmat = np.arange(36)\nprint(len(mat))\n# teraz zmienimy kształt tablicy jednowymiarowej na macierz 5x5\nmat = mat.reshape((6,6))\n\ndef ciecie(tablica, kierunek):\n if kierunek == 'poziom':\n if len(tablica[:,0]) > 1:\n tablica = tablica[0:(len(tablica[:,0])+1)//2]\n return tablica\n else:\n print(\"tablica zbyt niska\")\n Exception\n if kierunek == 'pion':\n if len(tablica[0,:]) > 1:\n tablica = tablica[:,0:(len(tablica[0,:])+1)//2]\n return tablica\n else:\n print(\"tablica zbyt wąska\")\n Exception\n \nmat = ciecie(mat, 'poziom')\nprint(mat)\nmat = ciecie(mat, 'pion')\n\nprint(mat)\n\n#zad 9\nmat = np.arange(25)\nmat[0] = 0\nmat[1] = 1\nfor x in range(2,25):\n mat[x] = mat[x-1]+mat[x-2]\n\nmat = mat.reshape((5,5))\nprint(mat)\n\n \n\n\n\n","sub_path":"cwiczenie6.py","file_name":"cwiczenie6.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"632885914","text":"import numpy as np\n\n### Python Standard Libaray ###\nimport sys, os\nimport random\nimport collections\nimport pickle\nimport itertools\n\n'''\n### Settings for nlg worksation ###\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth=True\nconfig.intra_op_parallelism_threads=1\nconfig.inter_op_parallelism_threads=2\n#config.gpu_options.per_process_gpu_memory_fraction=0.333\ntf.set_random_seed(7)\nset_session(tf.Session(config=config))\n'''\n\n### import Keras modules ###\nfrom keras.models import Model, Sequential, load_model\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import *\nfrom keras.regularizers import *\nfrom keras.initializers import *\nimport keras.backend as K\n\nfrom keras.utils import np_utils\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\n\n# import other utils ###\nfrom sklearn.model_selection import train_test_split\n\nif __name__ == '__main__':\n\n ### For reproducibilty ###\n np.random.seed(7)\n random.seed(7)\n\n TRAIN = False\n r = 39 # random seed\n d = 256 # latent dim\n\n if TRAIN:\n \n train_data_path = 'train.csv'\n with open(train_data_path, 'r') as f:\n f.readline()\n users = []\n movies = []\n ratings = []\n for line in f:\n line = line.strip('\\n').split(',')\n users.append(int(line[1]))\n movies.append(int(line[2]))\n ratings.append(int(line[3]))\n\n num_users=max(users)\n num_movies=max(movies)\n\n users = np.array(users)\n movies = np.array(movies)\n ratings = np.array(ratings, dtype=np.float32)\n num_data = len(ratings)\n\n # validation split\n users_train, users_val, movies_train, movies_val, ratings_train, ratings_val = train_test_split(users,\n movies, ratings, test_size=0.1, random_state=r)\n\n # build model\n user_input = Input(shape=(1,), dtype='int64')\n movie_input = Input(shape=(1,), dtype='int64')\n user_embedding = Embedding(input_dim=6041, output_dim=d, embeddings_initializer=Orthogonal())(user_input)\n user_embedding = Flatten()(user_embedding)\n movie_embedding = Embedding(input_dim=3953, output_dim=d, embeddings_initializer=Orthogonal())(movie_input)\n movie_embedding = Flatten()(movie_embedding)\n \n user_bias = Embedding(input_dim=6041, output_dim=1, embeddings_initializer=Orthogonal())(user_input)\n user_bias = Flatten()(user_bias)\n movie_bias = Embedding(input_dim=3953, output_dim=1, embeddings_initializer=Orthogonal())(movie_input)\n movie_bias = Flatten()(movie_bias)\n \n predicted_preference = dot(inputs=[user_embedding, movie_embedding], axes=1)\n predicted_preference = add(inputs=[predicted_preference, user_bias, movie_bias])\n \n model = Model(inputs=[user_input, movie_input], outputs=predicted_preference)\n model.compile(loss='mse', optimizer='rmsprop')\n\n checkpointer = ModelCheckpoint(filepath='MF.h5',\n monitor='val_loss',save_best_only=True,\n verbose=1)\n \n model.fit([users_train, movies_train], ratings_train,\n batch_size=256, epochs=35,\n validation_data=([users_val, movies_val], ratings_val),\n callbacks=[checkpointer],\n verbose=1)\n\n\n else:\n \n model = load_model('MF.h5')\n test_data_path = sys.argv[1]\n with open(test_data_path, 'r') as f:\n f.readline()\n test_user = []\n test_movie = []\n for line in f:\n line = line.strip('\\n').split(',')\n test_user.append(int(line[1]))\n test_movie.append(int(line[2]))\n \n test_user = np.array(test_user)\n test_movie = np.array(test_movie)\n \n result = np.squeeze(model.predict([test_user, test_movie], verbose=1))\n\n #with open('/home/mhfu/ML2017FALL/hw5/result_%d_%d.csv' % (d,r),'w') as f:\n with open(sys.argv[2], 'w') as f:\n f.write('TestDataID,Rating\\n')\n for i, r in enumerate(result):\n f.write('%d,%.4f\\n' %(i+1, r))\n\n","sub_path":"hw5/mf.py","file_name":"mf.py","file_ext":"py","file_size_in_byte":4376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"465961670","text":"# _*_ coding:utf-8 _*_\nimport pika\nimport time\nmq_conn = pika.BlockingConnection(pika.ConnectionParameters('172.16.10.10', 5672))\n\nmq_channel = mq_conn.channel()\n\nmq_channel.queue_declare(queue='hello')\n\n# mq_channel.basic_publish(\n# exchange='',\n# routing_key='hello',\n# body='Hello World!'\n# )\n\nfor i in range(1,100):\n mq_channel.basic_publish(\n exchange='',\n routing_key='hello',\n body='Hello World!'\n )\n print(\"[%s] Sent 'Hello World!'\" % i)\n time.sleep(0.5)\n\n\nmq_channel.close()\n","sub_path":"learning/stage5/rabbitmq/rabbitmq基本使用_producer.py","file_name":"rabbitmq基本使用_producer.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"599028736","text":"#1.打印功能提示\nprint(\"=\"*50)\nprint(\" 名片管理系统 v0.01\")\nprint(\"1.添加一个新的名片\")\nprint(\"2.删除一个名片\")\nprint(\"3.修改一个名片\")\nprint(\"4.查询一个名片\")\nprint(\"5.显示所有的名片\")\nprint(\"6.退出系统\")\nprint(\"=\"*50)\n\n#用来存储名片\ncard_infors=[]\nwhile True:\n #2.获取用户的输入\n num=int(input(\"请输入操作序号:\"))\n #3.根据用户的数据执行相应的功能\n if num==1:\n new_name=input(\"请输入新的名字:\")\n new_qq = input(\"请输入新的QQ:\")\n new_weixin = input(\"请输入新的微信:\")\n new_addr = input(\"请输入新的地址:\")\n\n #定义一个新的字典\n new_infor = {}\n new_infor[\"name\"]=new_name\n new_infor[\"qq\"] = new_qq\n new_infor[\"weixin\"] = new_weixin\n new_infor[\"addr\"] = new_addr\n card_infors.append(new_infor)#将一个字典添加到列表中\n\n print(card_infors)\n\n elif num==2:\n pass\n elif num==3:\n pass\n elif num==4:\n find_name=input(\"请输入要查找的姓名:\")\n find_flag=0#默认没有找到\n for temp in card_infors:\n if find_name==temp[\"name\"]:\n print(\"%s\\t%s\\t%s\\t%s\"%(temp['name'],temp['qq'],temp['weixin'],temp['addr']))\n find_flag=1#表示找到了\n break\n #判断是否找到了\n if find_flag==0:\n print(\"没有查到此人\")\n elif num==5:\n print(\"姓名\\tQQ\\t微信\\t地址\")\n for temp in card_infors:\n print(\"%s\\t%s\\t%s\\t%s\"%(temp['name'],temp['qq'],temp['weixin'],temp['addr']))\n elif num==6:\n break\n else:\n print(\"输入有误,请重新输入\")\n print(\"\")","sub_path":"day07/IDManage_Second.py","file_name":"IDManage_Second.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"116434686","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 30 21:13:35 2017\n\n@author: luke\n\nTODO:\n \n THIS IS NOT RIGHT YET!\n\"\"\"\nfrom __future__ import print_function\n\n\n#from design_tree import HullDesignNode as hullclp\nfrom simple_hull_rules import HullDesignNode as hullclp\n#from design_tree import DesignTree\n#import inspect\nimport pydot\nimport networkx as nx\n\n\n\ndef pydot_graph_of_rules(rlist):\n \n ## map \n ## function.name : function\n methods = {}\n for parameter in rlist:\n for arc in parameter.arcs:\n if arc.__name__ in methods.keys():\n pass\n else:\n methods[arc.__name__]=arc\n #\n #\n #\n ## graph \n ## initialize\n graph = pydot.Dot(graph_type='graph',\n overlap='scale',\n splines='true')\n #\n #\n #\n ## map \n ## graphed_function.name : pydot.Node(shape = 'box', style = 'filled)\n mrules = {}\n for method in methods:\n rule = pydot.Node(method, \n shape='box',\n style='filled')\n mrules[method] = rule\n graph.add_node(rule)\n #\n #\n #\n ## GRAPH \n ## node(variable.name) : pydot.Node(default)\n for parameter in rlist:\n pnode = pydot.Node(parameter.name)\n graph.add_node(pnode)\n \n for method in parameter.arcs:\n graph.add_edge(pydot.Edge(pnode, mrules[method.__name__]))\n return graph\n \n \n \ndef plot_some_rules(graph,name):\n #\n #\n #\n subfolder = name.split('.')[0]\n #\n #----------------------------------------------- Plotting\n #\n graph.write_pdf(\"graphs/\"+subfolder+\"/_circlegraph_\"+name,\n prog='circo')\n graph.write_pdf(\"graphs/\"+subfolder+\"/_neato_\"+name,\n prog='neato')\n return\n \n \n \n \ndef graph_andplot_rules(rlist,name):\n graph = pydot_graph_of_rules(rlist)\n plot_some_rules(graph,name)\n return \n \n \ndef plot_netx_of_pydot_graph(pydot_graph):\n \"\"\"\n input: pydot graph object\n \n retult: Plot a networkx graph made from a pydot graph\n \"\"\"\n netx_primary = nx.nx_pydot.from_pydot(pydot_graph)\n nx.draw(netx_primary)\n return\n \n\n\nif __name__ == '__main__':\n \n hdp = hullclp()\n #\n #\n #\n graph_andplot_rules(hdp.Primary, name='primary.pdf')\n graph_andplot_rules(hdp.Coefficients, name='coefficients.pdf')\n graph_andplot_rules(hdp.alists, name='all.pdf')\n #\n #\n #\n dotgraph = pydot_graph_of_rules(hdp.alists)\n plot_netx_of_pydot_graph(pydot_graph=dotgraph)","sub_path":"relational_lsplines/graph_constructor.py","file_name":"graph_constructor.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"102354095","text":"import cv2\nimport glob\nimport imageio\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport subprocess\nimport torch\nimport torchvision.transforms as transforms\n\nfrom torchvision.utils import save_image\nfrom torchvision import datasets\n\n\ndef configure_dataloader(dset, batch_size, img_size, shuffle=True):\n # Configure data loader\n if dset == 'mnist':\n os.makedirs(\"../../data/mnist\", exist_ok=True)\n dataloader = torch.utils.data.DataLoader(\n datasets.MNIST(\n \"../../data/mnist\",\n train=True,\n download=True,\n transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]),\n ),\n batch_size=batch_size,\n shuffle=shuffle,\n )\n else:\n data_transforms = transforms.Compose([\n transforms.Resize((img_size, img_size)),\n # transforms.RandomResizedCrop(128),\n # transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n ])\n dataset = datasets.ImageFolder(root=dset, transform=data_transforms)\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle)\n return dataloader\n\n\ndef setup_dirs(opt):\n\n model_name = opt.model_name\n\n # Output path where we store experiment log and weights\n model_dir = os.path.join(\"../models\", model_name)\n fig_dir = os.path.join(\"../figures\", model_name)\n\n print(\"Creating\", model_dir, \"and\", fig_dir)\n os.makedirs(model_dir, exist_ok=True)\n os.makedirs(fig_dir, exist_ok=True)\n\n # Copy main.py, train.py and model.py\n py_files = glob.glob(\"*.py\")\n for py_file in py_files:\n subprocess.call(['cp', py_file, model_dir])\n\n # Write all config params\n print(\"Writing config params in\", os.path.join(model_dir, 'config.txt'))\n with open(os.path.join(model_dir, 'config.txt'), 'w') as f:\n for i in opt.__dict__:\n f.write(str(i) + ' ' + str(opt.__dict__[i]) + '\\n')\n\n print(\"Writing config params in\", os.path.join(fig_dir, 'config.txt'))\n with open(os.path.join(fig_dir, 'config.txt'), 'w') as f:\n for i in opt.__dict__:\n f.write(str(i) + ' ' + str(opt.__dict__[i]) + '\\n')\n\n return model_dir, fig_dir\n\n\ndef plot_images(fake_imgs, fig_dir, model_name, batch, suffix='train', MAX_FRAMES_PER_GIF=100):\n\n print(\"Saving images...\")\n save_image(fake_imgs.data[:16], os.path.join(fig_dir, \"current_batch.png\"), nrow=4, normalize=True)\n\n # Make gif\n gif_frames = []\n\n # Read old gif frames\n try:\n gif_frames_reader = imageio.get_reader(os.path.join(fig_dir, model_name + \"_%s.gif\" % suffix))\n for frame in gif_frames_reader:\n gif_frames.append(frame[:, :, :3])\n except:\n pass\n\n # Append new frame\n fake_im = np.transpose(fake_imgs.data[0], (1, 2, 0))\n fake_im_min = fake_im.min(); fake_im_max = fake_im.max()\n fake_im = (fake_im - fake_im_min)/(fake_im_max - fake_im_min) * 255\n im = cv2.putText(np.concatenate((np.zeros((32, fake_im.shape[1], fake_im.shape[2])), fake_im), axis=0),\n '%s iter' % str(batch+1), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1, cv2.LINE_AA).astype('uint8')\n gif_frames.append(im)\n\n # If frames exceeds, save as different file\n if len(gif_frames) > MAX_FRAMES_PER_GIF:\n print(\"Splitting the GIF...\")\n gif_frames_00 = gif_frames[:MAX_FRAMES_PER_GIF]\n num_of_gifs_already_saved = len(glob.glob(os.path.join(fig_dir, model_name + \"_%s_*.gif\" % suffix)))\n print(\"Saving\", os.path.join(fig_dir, model_name + \"_%s_%03d.gif\" % (suffix, num_of_gifs_already_saved)))\n imageio.mimsave(os.path.join(fig_dir, model_name + \"_%s_%03d.gif\" % (suffix, num_of_gifs_already_saved)), gif_frames_00)\n gif_frames = gif_frames[MAX_FRAMES_PER_GIF:]\n\n # Save gif\n print(\"Saving\", os.path.join(fig_dir, model_name + \"_%s.gif\" % suffix))\n imageio.mimsave(os.path.join(fig_dir, model_name + \"_%s.gif\" % suffix), gif_frames)\n\n\ndef plot_losses(d_losses, g_losses, freq,\n fig_dir, model_name, init_epoch=0):\n print(\"Plotting losses...\")\n epochs = np.arange(0, len(d_losses)*freq, freq) + init_epoch\n fig = plt.figure()\n plt.subplot(211)\n plt.plot(epochs, d_losses)\n plt.xlabel(\"Iterations\")\n plt.title('Discriminator Loss')\n plt.subplot(212)\n plt.plot(epochs, g_losses)\n plt.xlabel(\"Iterations\")\n plt.title('Generator Loss')\n # plt.legend()\n # plt.title(\"Losses\")\n plt.savefig(os.path.join(fig_dir, model_name + \"_losses.png\"), bbox_inches='tight')\n plt.clf()\n plt.close()\n\n\ndef save_models(models_dict, model_dir, iter_num, keep_last_n_weights):\n print(\"Saving models...\")\n model_names = models_dict.keys()\n purge_weights(keep_last_n_weights, model_dir, model_names)\n for model_name in model_names:\n torch.save(models_dict[model_name].state_dict(), os.path.join(model_dir, model_name + \"_iter_{0:06d}\".format(iter_num) + \".pth\"))\n\n\ndef purge_weights(keep_last_n_weights, model_dir, model_names):\n for name in model_names:\n weight_files = sorted(glob.glob(os.path.join(model_dir, name + \"*\")))\n for weight_file in weight_files[:-keep_last_n_weights]:\n os.remove(os.path.realpath(weight_file))\n","sub_path":"implementations/wgan_gp/src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"393598371","text":"from __future__ import absolute_import\n\nimport six\n\nfrom sentry import tagstore\nfrom sentry.api.base import DocSection, EnvironmentMixin\nfrom sentry.api.bases import GroupEndpoint\nfrom sentry.api.serializers import serialize\nfrom sentry.api.paginator import DateTimePaginator\nfrom sentry.models import Environment, Event, Group\nfrom sentry.search.utils import parse_query\nfrom sentry.utils.apidocs import scenario, attach_scenarios\nfrom rest_framework.response import Response\nfrom sentry.search.utils import InvalidQuery\n\n\n@scenario('ListAvailableSamples')\ndef list_available_samples_scenario(runner):\n group = Group.objects.filter(project=runner.default_project).first()\n runner.request(method='GET', path='/issues/%s/events/' % group.id)\n\n\nclass GroupEventsEndpoint(GroupEndpoint, EnvironmentMixin):\n doc_section = DocSection.EVENTS\n\n @attach_scenarios([list_available_samples_scenario])\n def get(self, request, group):\n \"\"\"\n List an Issue's Events\n ``````````````````````\n\n This endpoint lists an issue's events.\n\n :pparam string issue_id: the ID of the issue to retrieve.\n :auth: required\n \"\"\"\n\n events = Event.objects.filter(\n group_id=group.id,\n )\n\n query = request.GET.get('query')\n if query:\n try:\n query_kwargs = parse_query(group.project, query, request.user)\n except InvalidQuery as exc:\n return Response({'detail': six.text_type(exc)}, status=400)\n\n if query_kwargs['query']:\n events = events.filter(\n message__icontains=query_kwargs['query'],\n )\n\n if query_kwargs['tags']:\n try:\n environment_id = self._get_environment_id_from_request(\n request, group.project.organization_id)\n except Environment.DoesNotExist:\n event_ids = []\n else:\n event_ids = tagstore.get_group_event_ids(\n group.project_id, group.id, environment_id, query_kwargs['tags'])\n\n if event_ids:\n events = events.filter(\n id__in=event_ids,\n )\n else:\n events = events.none()\n\n return self.paginate(\n request=request,\n queryset=events,\n order_by='-datetime',\n on_results=lambda x: serialize(x, request.user),\n paginator_cls=DateTimePaginator,\n )\n","sub_path":"src/sentry/api/endpoints/group_events.py","file_name":"group_events.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"429226792","text":"# You will have to figure out what parameters to include\n# 🚨 All functions must use recursion 🚨\n\n# Write a recursive function called `reverse` that accepts a ss and returns a reversed ss.\n\ndef reverse_string(string):\n # print(string[1:])\n if len(string) == 0:\n return string\n else:\n print(string[0], string[1:])\n return reverse_string(string[1:]) + string[0]\n\nprint(reverse_string(\"Python\"))\n\n# def reverse_string(string, result=\"\"):\n# string1 = list(string)\n# last_char = string1.pop()\n# result = result + last_char\n# if len(string1) == 0:\n# return result\n# return reverse_string(\"\".join(string1), result)\n\n# print(reverse_string(\"Python\"))\n\n# print(reverse(\"\")) \n# => \"\"\n# print(reverse(\"a\")) \n# => \"a\"\n# print(reverse(\"ab\")) \n# => \"ba\"\n# print(reverse(\"computer\")) \n# => \"retupmoc\"\n# print(reverse(reverse(\"computer\"))) \n# => \"computer\"","sub_path":"reverse.py","file_name":"reverse.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"189907649","text":"#!/usr/bin/env python3\n\"\"\"\nCreated on 2018/11/29\nFunction:\n transfer yuv image to jpg\n transfer nv21 image to jpg\n\n@author: yangshifu\n@mail: yangshifu@sensetime.com\n\n\"\"\"\n\nimport numpy as np\nimport cv2, os, sys\nimport argparse\nimport imutils\n\ndef cvt_yuv_nv21_to_rgb(args, yuv_file):\n # yuv_file = 't.yuv'\n # print 'yuv_file = ',yuv_file\n stream = open(yuv_file, 'rb')\n # Seek to the fourth frame in the file\n # stream.seek(4 * width * height * 1.5)\n # Calculate the actual image size in the stream (accounting for rounding\n # of the resolution)\n fwidth = (args.width + 31) // 32 * 32\n fheight = (args.height + 15) // 16 * 16\n # Load the Y (luminance) data from the stream\n\n Y = np.fromfile(stream, dtype=np.uint8, count=fwidth*fheight).\\\n reshape((fheight, fwidth))\n # Load the UV (chrominance) data from the stream, and double its size\n UV = np.fromfile(stream, dtype=np.uint8, count= 2 * (fwidth//2)*(fheight//2)).\\\n reshape((fheight//2, fwidth//2,2)).\\\n repeat(2, axis=0).repeat(2, axis=1)\n\n U = UV[:,:,0] \n V = UV[:,:,1]\n\n # Stack the YUV channels together, crop the actual resolution, convert to\n # floating point for later calculations, and apply the standard biases\n YUV = np.dstack((Y, U, V))[:args.height, :args.width, :].astype(np.float)\n YUV[:, :, 0] = YUV[:, :, 0] - 16 # Offset Y by 16\n YUV[:, :, 1:] = YUV[:, :, 1:] - 128 # Offset UV by 128\n # YUV conversion matrix from ITU-R BT.601 version (SDTV)\n # Note the swapped R and B planes!\n # Y U V\n M = np.array([[1.164, 2.017, 0.000], # B\n [1.164, -0.392, -0.813], # G\n [1.164, 0.000, 1.596]]) # R\n # Take the dot product with the matrix to produce BGR output, clamp the\n # results to byte range and convert to bytes\n BGR = YUV.dot(M.T).clip(0, 255).astype(np.uint8)\n RGB = cv2.cvtColor(BGR, cv2.COLOR_BGR2RGB)\n IMG = imutils.rotate_bound(RGB, args.rotate)\n return IMG\n\n\ndef process(args, yuv_list):\n count = 0\n succ = 0\n fail = 0\n for file in yuv_list:\n count += 1\n # image_path = args.files_path + file.strip()\n image_path = os.path.dirname(file) + os.sep + os.path.basename(file).strip()\n try:\n img = cvt_yuv_nv21_to_rgb(args, image_path)\n saved_image_path = image_path.rstrip('.yuv') + '.jpg'\n cv2.imwrite(saved_image_path, img)\n print(\"[%d/%d] Success: %s\" % (count, len(yuv_list), image_path), end='\\r')\n succ += 1\n except:\n print(\"[%d/%d] Fail: %s\" % (count, len(yuv_list), image_path))\n fail += 1\n\n print()\n print(\"Success %d times\" % succ)\n print(\"Fail %d times\" % fail)\n\n\ndef getYuvFileList(filesPath, file_type='yuv'):\n all_filesList = []\n yuv_filesList = []\n for (dirpath, dirnames, filenames) in os.walk(filesPath):\n for f in filenames:\n file_path = os.path.join(dirpath, f)\n all_filesList.append(file_path)\n # all_filesList.extend(filenames)\n for file in all_filesList:\n if file.endswith(file_type):\n yuv_filesList.append(file)\n \n return yuv_filesList\n\n\nif __name__ == '__main__':\n default_description = 'transfrom yuv image to jpg'\n parser = argparse.ArgumentParser(prog=\"nv12_to_jpg.py\", description=default_description)\n parser.add_argument('-p', '--files_path', type=str, required=False, default='./', help='default ./')\n parser.add_argument('-t', '--height', type=int, required=False, default=480, help='default 480')\n parser.add_argument('-w', '--width', type=int, required=False, default=640, help='default 640')\n parser.add_argument('-a', '--rotate', type=int, required=False, default=0, help='default 0')\n parser.add_argument('-y', '--is_yuv', action=\"store_false\", required=False, default=True, help='default yuv. else nv21')\n args = parser.parse_args()\n\n print()\n print('----------START----------')\n print()\n if args.is_yuv:\n yuv_filesList = getYuvFileList(args.files_path)\n else:\n yuv_filesList = getYuvFileList(args.files_path, 'nv21')\n\n if len(yuv_filesList) is not 0:\n process(args, yuv_filesList)\n else:\n print('no yuv file')\n\n print()\n print('----------END----------')\n\n","sub_path":"image/yuv2jpg.py","file_name":"yuv2jpg.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"106559249","text":"import queue\nimport threading\nimport time\nimport traceback\nimport sys\nfrom collections import deque\n\nfrom . import uarm_async\n\nCMD_IDX_MIN = 1\nCMD_IDX_MAX = 10000\n\nSLOT_COUNT = 2\n\nclass UArmQueue:\n\n def __init__(self, lock=None):\n if lock == None:\n lock = threading.RLock()\n \n self.lock = lock\n self.uaa = uarm_async.UArmAsync()\n self.cmd_queue = queue.Queue()\n self.next_cmd_idx = CMD_IDX_MIN\n self.loop_thread = None\n\n def connect(self,port=None):\n self.uaa.connect(port)\n self.loop_thread = threading.Thread(target=self._loop)\n self.loop_thread.start()\n\n def close(self):\n self.cmd_queue.put({'type':'close'})\n if self.loop_thread != None:\n self.loop_thread.join()\n self.uaa.close()\n\n def wait_ready(self):\n return self.uaa.wait_ready()\n\n def set_on_msg(self,on_msg):\n self.uaa.on_msg = on_msg\n\n def _get_next_cmd_idx(self):\n cmd_idx = self.next_cmd_idx\n self.next_cmd_idx += 1\n if self.next_cmd_idx > CMD_IDX_MAX:\n self.next_cmd_idx = CMD_IDX_MIN\n return cmd_idx\n\n def send_cmd(self,cmd):\n cmd_idx = self._get_next_cmd_idx()\n cmd_unit = {\n 'type': 'cmd',\n 'idx': cmd_idx,\n 'cmd': cmd,\n 'future': None,\n 'uaa_future': None\n }\n future = _Future(self, cmd_unit)\n cmd_unit['future'] = future\n self.cmd_queue.put(cmd_unit)\n return future\n\n def _loop(self):\n try:\n busy_queue = []\n next_cmd_time = 0 # uarm easy die if cmd go too fast\n while(True):\n unit = self.cmd_queue.get(block=True)\n if unit['type'] == 'close':\n return\n if unit['type'] == 'cmd':\n while len(busy_queue) >= 2:\n #wait_unit = busy_queue.popleft()\n #wait_unit['future'].wait()\n\n pop_idx = None\n for i in range(len(busy_queue)):\n wait_unit = busy_queue[i]\n if not wait_unit['future'].is_busy():\n pop_idx = i+1\n if pop_idx is None:\n time.sleep(0.05)\n else:\n if pop_idx>1:\n print('RCKTQSNETX cmd skip detected')\n busy_queue = busy_queue[pop_idx:]\n busy_queue.append(unit)\n now_time = time.time()\n #printf('URTSGFSDLS now_time:{:.3f}, next_cmd_time:{:.3f}'.format(now_time,next_cmd_time),file=sys.stderr)\n if now_time < next_cmd_time:\n time.sleep(next_cmd_time-now_time)\n now_time = next_cmd_time\n with unit['future'].cond:\n unit['uaa_future'] = self.uaa.send_cmd(unit['cmd'])\n unit['future'].cond.notify_all()\n next_cmd_time = now_time + 0.1\n except:\n traceback.print_exc()\n\n def wait_ready(self):\n self.uaa.wait_ready()\n \nclass _Future:\n \n def __init__(self,uq,unit):\n self.uq = uq\n self.unit = unit\n self.cond = threading.Condition()\n \n def wait(self):\n with self.cond:\n self.cond.wait_for(lambda: self.unit['uaa_future'] != None)\n return self.unit['uaa_future'].wait()\n \n def is_busy(self):\n if self.unit['uaa_future'] == None:\n return True\n return self.unit['uaa_future'].is_busy()\n","sub_path":"python3/clover/uarmswiftpro/uarm_queue.py","file_name":"uarm_queue.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"114846169","text":"\"\"\"Models representing Bodega legacy items.\"\"\"\nfrom __future__ import unicode_literals\nfrom datetime import datetime, timedelta\nfrom uuid import uuid4\n\nfrom bodega_core.models import BaseModel, Item\nfrom django.contrib.contenttypes.fields import GenericRelation\nfrom django.db import models\nfrom pytz import utc\n\n\nclass JenkinsTask(BaseModel):\n \"\"\"A Jenkins build designated as an infrastructure task.\n\n Although this isn't an item, it lives here because it's only used for\n legacy items.\n\n A UUID should uniquely identify a build for future retrieval from Jenkins.\n \"\"\"\n\n def __str_additional_info_nvps__(self):\n \"\"\"Get additional name-value pairs for the string representation.\"\"\"\n return [\n ('uuid', self.uuid)\n ]\n\n uuid = models.UUIDField(\n primary_key=False,\n default=uuid4,\n editable=True,\n help_text='The UUID tag used to identify builds from the Jenkins API.')\n cached_job_url = models.URLField(\n null=True,\n help_text='The cached URL of a Jenkins job, used for display only.')\n cached_buildnum = models.PositiveIntegerField(\n null=True,\n help_text='The cached buildnum of a Jenkins build.')\n holding_items = GenericRelation('bodega_core.Item',\n content_type_field='held_by_content_type',\n object_id_field='held_by_object_id')\n # This is not enforced; it is up to the user to update this field as well\n time_uuid_updated = models.DateTimeField(\n auto_now_add=True,\n help_text='The last time the UUID of this task was updated.')\n\n @property\n def cached_build(self):\n \"\"\"Return cached information for a build.\n\n If both the job URL and buildnum are available, return a full URL.\n Else, return whatever we have in a sensible fashion.\n \"\"\"\n if not self.cached_job_url:\n return self.cached_buildnum\n elif not self.cached_buildnum:\n return self.cached_job_url\n else:\n return str(self.cached_job_url) + str(self.cached_buildnum) + '/'\n\n @property\n def time_since_uuid_update(self):\n td = datetime.now(utc) - self.time_uuid_updated\n return str(td - timedelta(microseconds=td.microseconds))\n\n\nclass ReleaseQualBaton(Item):\n \"\"\"A way for release qualification pipelines to cooperatively throttle.\"\"\"\n\n @property\n def name(self):\n return 'release_qual_baton_%s' % self.sid\n\n\nclass RktestYml(Item):\n \"\"\"An item which is an rktest.yml file representing an entire pod.\n\n This is a legacy resource type for us to slowly migrate our workflows\n towards Bodega by minimizing the workflow change while moving the\n management work out of Jenkins / lockable resources into Bodega.\n \"\"\"\n\n def __str_additional_info_nvps__(self):\n \"\"\"Get additional name-value pairs for the string representation.\"\"\"\n return [\n ('filename', self.filename)\n ]\n\n @property\n def name(self):\n return self.filename\n\n PLATFORM_AWS = 'AWSPOD'\n PLATFORM_AZURE = 'AZUREPOD'\n PLATFORM_CISCO = 'CISCO'\n PLATFORM_DELL = 'DELL'\n PLATFORM_DYNAPOD = 'DYNAPOD'\n PLATFORM_DYNAPOD_ROBO = 'DYNAPOD_ROBO'\n PLATFORM_DYNAPOD_ROBO_AHV = 'DYNAPOD_ROBO_AHV'\n PLATFORM_DYNAPOD_ROBO_HYPERV = 'DYNAPOD_ROBO_HYPERV'\n PLATFORM_HPE = 'HPE'\n PLATFORM_LENOVO = 'LENOVO'\n PLATFORM_PROD_BRIK = 'PROD_BRIK'\n PLATFORM_STATIC = 'STATIC'\n PLATFORM_STATIC_ROBO = 'STATIC_ROBO'\n\n PLATFORM_CHOICES = (\n (PLATFORM_AWS, PLATFORM_AWS),\n (PLATFORM_AZURE, PLATFORM_AZURE),\n (PLATFORM_CISCO, PLATFORM_CISCO),\n (PLATFORM_DELL, PLATFORM_DELL),\n (PLATFORM_DYNAPOD, PLATFORM_DYNAPOD),\n (PLATFORM_DYNAPOD_ROBO, PLATFORM_DYNAPOD_ROBO),\n (PLATFORM_DYNAPOD_ROBO_AHV, PLATFORM_DYNAPOD_ROBO_AHV),\n (PLATFORM_DYNAPOD_ROBO_HYPERV, PLATFORM_DYNAPOD_ROBO_HYPERV),\n (PLATFORM_HPE, PLATFORM_HPE),\n (PLATFORM_LENOVO, PLATFORM_LENOVO),\n (PLATFORM_PROD_BRIK, PLATFORM_PROD_BRIK),\n (PLATFORM_STATIC, PLATFORM_STATIC),\n (PLATFORM_STATIC_ROBO, PLATFORM_STATIC_ROBO),\n )\n\n # The filename of the rktest.yml item.\n filename = models.CharField(\n max_length=80,\n blank=False,\n help_text='Filename of the rktest.yml item',\n unique=True)\n\n description = models.TextField(\n blank=True,\n default=\"\",\n null=False,\n help_text='Description of this RktestYml item.')\n\n location = models.ForeignKey(\n 'bodega_core.Location', on_delete=models.CASCADE,\n help_text='The location of this RktestYml.')\n\n network = models.ForeignKey(\n 'bodega_core.Network', on_delete=models.CASCADE,\n help_text='The network of this RktestYml.')\n\n platform = models.CharField(\n max_length=24,\n blank=False,\n choices=PLATFORM_CHOICES,\n help_text='Platform, one of %s' %\n repr([choice[0] for choice in PLATFORM_CHOICES]))\n\n acropolis = models.BooleanField(\n default=False,\n help_text='Has Acropolis host and VMs')\n\n benchmarking = models.BooleanField(\n default=False,\n help_text='Usable for benchmarking')\n\n encrypted = models.BooleanField(\n default=False,\n help_text='Is encrypted')\n\n esx_6_0 = models.BooleanField(\n default=False,\n help_text='Has ESX 6.0 host for general purpose usage')\n\n fc_aix_agent = models.BooleanField(\n default=False,\n help_text='Has AIX host which has access to Pure FC LUN')\n\n fc_linux_agent = models.BooleanField(\n default=False,\n help_text='Has Linux host which has access to Pure FC LUN')\n\n hyperv_2016 = models.BooleanField(\n default=False,\n help_text='Has HyperV 2016 host and VMs')\n\n linux_agent = models.BooleanField(\n default=False,\n help_text='Has Centos 6 and Ubuntu 14')\n\n linux_agent_all_versions = models.BooleanField(\n default=False,\n help_text='Has Centos 5,6,7 and Ubuntu 12,14,16')\n\n manufacturable = models.BooleanField(\n default=False,\n help_text='Is manufacturable')\n\n model_r6xx = models.BooleanField(\n default=False,\n help_text='Is R6xx series')\n\n mssql = models.BooleanField(\n default=False,\n help_text='Has MSSQL')\n\n robofm = models.BooleanField(\n default=False,\n help_text='Has fileset and mssql components')\n\n robossd = models.BooleanField(\n default=False,\n help_text='Has an ssd for the OS')\n\n stronger = models.BooleanField(\n default=False,\n help_text='Has double the compute power (4 vCPUs for DYNAPOD)')\n\n tpm = models.BooleanField(\n default=False,\n help_text='Has TPM')\n\n vcenter_5_1 = models.BooleanField(\n default=False,\n help_text='Has VCenter 5.1')\n\n vcenter_5_5 = models.BooleanField(\n default=False,\n help_text='Has VCenter 5.5')\n\n vcenter_6_0 = models.BooleanField(\n default=False,\n help_text='Has VCenter 6.0')\n\n vcenter_6_5 = models.BooleanField(\n default=False,\n help_text='Has VCenter 6.5')\n\n vcloud_8_1 = models.BooleanField(\n default=False,\n help_text='Has vCloud Director 8.1')\n\n vcloud_8_2 = models.BooleanField(\n default=False,\n help_text='Has vCloud Director 8.2')\n\n vcloud_9_0 = models.BooleanField(\n default=False,\n help_text='Has vCloud Director 9.0')\n\n windows_app_test_only = models.BooleanField(\n default=False,\n help_text='Has resources for testing windows applications')\n","sub_path":"lab/bodega/bodega_legacy_items/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"520161512","text":"#! /usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n# @Time : 2018/12/5 1:19\r\n# @Author : 码农凯凯\r\n# @File : multiconn-server.py\r\n# @belief : stay foolish,stay hungry\r\n# -*- coding: cp936 -*-\r\nimport sys\r\nif(sys.version[:1] == \"3\"):\r\n import _thread as thread\r\nimport time\r\n# import thread\r\nimport socket\r\n\r\n\r\n# def timer(no, interval):\r\n# cnt = 0\r\n# while cnt < 10:\r\n# print('Thread:(%d) Time:%s/n' % (no, time.ctime()))\r\n# time.sleep(interval)\r\n# cnt += 1\r\n# thread.exit_thread()\r\n#\r\n#\r\n# def test(): # Use thread.start_new_thread() to create 2 new threads\r\n# thread.start_new_thread(timer, (1, 1))\r\n# thread.start_new_thread(timer, (2, 2))\r\n\r\n\r\ndef child_connection(index, sock, connection):\r\n try:\r\n print(\"begin connecion \", index)\r\n print(\"begin connecion %d\" % index)\r\n connection.settimeout(50)\r\n # 获得一个连接,然后开始循环处理这个连接发送的信息\r\n while True:\r\n buf = connection.recv(1024)\r\n print(\"Get value %s from connection %d: \" % (buf, index))\r\n if buf == '1':\r\n print(\"send welcome\")\r\n\r\n connection.send('welcome to server!'.encode())\r\n elif buf != '0':\r\n connection.send('please go out!'.encode())\r\n print(\"send refuse\")\r\n\r\n else:\r\n print(\"close\")\r\n\r\n break # 退出连接监听循环\r\n except socket.timeout: # 如果建立连接后,该连接在设定的时间内无数据发来,则time out\r\n print('time out')\r\n\r\n print(\"closing connection %d\" % index) # 当一个连接监听循环退出后,连接可以关掉\r\n connection.close()\r\n # 关闭连接,最后别忘了退出线程\r\n thread.exit_thread()\r\n\r\n\r\n'''\r\n建立一个python server,监听指定端口,\r\n如果该端口被远程连接访问,则获取远程连接,然后接收数据,\r\n并且做出相应反馈。\r\n'''\r\nif __name__ == \"__main__\":\r\n\r\n print(\"Server is starting\")\r\n\r\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n sock.bind(('127.0.0.1', 8998)) # 配置soket,绑定IP地址和端口号\r\n sock.listen(5) # 设置最大允许连接数,各连接和server的通信遵循FIFO原则\r\n print( \"Server is listenting port 8001, with max connection 5\")\r\n\r\n index = 0\r\n while True: # 循环轮询socket状态,等待访问\r\n\r\n connection, address = sock.accept()\r\n index += 1\r\n # 当获取一个新连接时,启动一个新线程来处理这个连接\r\n thread.start_new_thread(child_connection, (index, sock, connection))\r\n if index > 10:\r\n break\r\n sock.close()\r\n\r\n","sub_path":"handout/multiconn-server.py","file_name":"multiconn-server.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"241109696","text":"import sys\nimport os\nimport time\nimport threading\nimport random\nimport json\nimport logging\nfrom pathlib import Path\nimport argparse\nfrom dapr.clients import DaprClient\nfrom dapr.clients.grpc._state import StateItem, StateOptions, Consistency, Concurrency\nfrom PIL import Image\nimport io\nfrom typing import List\n\nlogging.basicConfig(level=logging.INFO)\nparser = argparse.ArgumentParser()\nparser.add_argument('--c', dest='concurrency', type=int, default=1)\nparser.add_argument('--s', dest='save_image', action='store_true')\nargs = parser.parse_args()\nconcurrency = args.concurrency\nsave_image = args.save_image\n\nrandom.seed(time.time())\n\npubsub_name = 'object-detect-pubsub'\ntopic_name = 'object-detect'\n\nimg_store = os.getenv('IMAGE_STORE', 'image-store-test')\npost_store = os.getenv('POST_STORE', 'post-store-test')\n\n# save states\nimages = [\n 'panda2.jpg', \n 'panda.jpeg', \n 'shiba2.jpg', \n 'shiba.jpg',\n ]\nif save_image:\n with DaprClient() as d:\n for img in images:\n with open('images/' + img, 'rb') as f:\n img_data = f.read()\n pil_img = Image.open(io.BytesIO(img_data))\n print(pil_img)\n # logging.info(img)\n logging.info('%s, len=%d, size=%d' %(img, len(img_data), sys.getsizeof(img_data)))\n d.save_state(\n store_name=img_store, \n key=img, \n value=img_data,\n # options=StateOptions(consistency=Consistency.strong),\n )\n print('%s saved' %img)\n\ndef make_post_id(user: str, ts: int):\n return \"%s*%d\" %(user, ts)\n\ndef meta_key(post_id: str):\n return post_id + \"-me\"\n\n# time.sleep(5)\ndef object_detect(post_id: str, images: List[str]):\n with DaprClient() as d:\n ts = int(time.time() * 1000)\n req_data = {\n 'post_id': post_id,\n 'pubsub_name': pubsub_name,\n 'topic_name': topic_name,\n 'images': images,\n 'send_unix_ms': ts,\n 'client_unix_ms': ts,\n }\n resp = d.publish_event(\n pubsub_name=pubsub_name,\n topic_name=topic_name,\n data=json.dumps(req_data),\n data_content_type='application/json',\n )\n print(resp)\n\nthreads = []\nposts = []\nfor i in range(0, concurrency):\n n = random.randint(1, len(images))\n l = list(images)\n random.shuffle(l)\n pid = make_post_id('snow', i * 1000 + 500000)\n posts.append(pid)\n t = threading.Thread(\n target=object_detect, \n kwargs={\n 'post_id': pid,\n 'images': l[:n],\n }\n )\n threads.append(t)\n t.start()\n\nfor t in threads:\n t.join()\n\nprint('--------- post ids ---------')\nprint(posts)\n\ntime.sleep(0.5)\nprint('--------- check post meta from post store --------')\nwith DaprClient() as d:\n for p in posts:\n print('-------------')\n print(p)\n state = d.get_state(\n store_name=post_store, \n key=meta_key(p), \n )\n print(json.loads(state.data))\n","sub_path":"daprApps_v1/socialNetwork/object-detect/test/test_objdet.py","file_name":"test_objdet.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"277173849","text":"\"\"\"Example script for setting up and solving an electric grid optimal operation problem.\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\n\nimport mesmo\n\n\ndef main():\n # Settings.\n scenario_name = \"singapore_6node\"\n results_path = mesmo.utils.get_results_path(__file__, scenario_name)\n\n # Recreate / overwrite database, to incorporate changes in the CSV files.\n mesmo.data_interface.recreate_database()\n\n # Obtain data.\n price_data = mesmo.data_interface.PriceData(scenario_name)\n\n # Obtain models.\n electric_grid_model = mesmo.electric_grid_models.ElectricGridModel(scenario_name)\n power_flow_solution = mesmo.electric_grid_models.PowerFlowSolutionFixedPoint(electric_grid_model)\n linear_electric_grid_model_set = mesmo.electric_grid_models.LinearElectricGridModelSet(\n electric_grid_model, power_flow_solution\n )\n der_model_set = mesmo.der_models.DERModelSet(scenario_name)\n\n # Instantiate optimization problem.\n optimization_problem = mesmo.solutions.OptimizationProblem()\n\n # Define electric grid problem.\n node_voltage_magnitude_vector_minimum = 0.5 * np.abs(electric_grid_model.node_voltage_vector_reference)\n node_voltage_magnitude_vector_maximum = 1.5 * np.abs(electric_grid_model.node_voltage_vector_reference)\n branch_power_magnitude_vector_maximum = 10.0 * electric_grid_model.branch_power_vector_magnitude_reference\n linear_electric_grid_model_set.define_optimization_problem(\n optimization_problem,\n price_data,\n node_voltage_magnitude_vector_minimum=node_voltage_magnitude_vector_minimum,\n node_voltage_magnitude_vector_maximum=node_voltage_magnitude_vector_maximum,\n branch_power_magnitude_vector_maximum=branch_power_magnitude_vector_maximum,\n )\n\n # Define DER problem.\n der_model_set.define_optimization_problem(optimization_problem, price_data)\n\n # Solve optimization problem.\n optimization_problem.solve()\n\n # Obtain results.\n results = mesmo.problems.Results()\n results.update(linear_electric_grid_model_set.get_optimization_results(optimization_problem))\n results.update(der_model_set.get_optimization_results(optimization_problem))\n\n # Print results.\n print(results)\n\n # Store results to CSV.\n results.save(results_path)\n\n # Obtain DLMPs.\n dlmps = linear_electric_grid_model_set.get_optimization_dlmps(optimization_problem, price_data)\n\n # Print DLMPs.\n print(dlmps)\n\n # Store DLMPs to CSV.\n dlmps.save(results_path)\n\n # Print results path.\n mesmo.utils.launch(results_path)\n print(f\"Results are stored in: {results_path}\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/run_electric_grid_optimal_operation.py","file_name":"run_electric_grid_optimal_operation.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"461006818","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#--author--:lingyc\n#--date--:2017-06-09\nimport maya.cmds as cmds\ndef check_renderLayer():\n '''\n {'load':'maya_Check','defaultOption':1,'CNname':'¼ì²é¶àÓàäÖȾ²ã'}\n '''\n allRenderLayer= set(cmds.ls(typ= 'renderLayer'))\n normalRendeLayer= {'defaultRenderLayer'}\n otherRenderLayer= list(allRenderLayer.difference(normalRendeLayer))\n return otherRenderLayer","sub_path":"last_at_HQ/weimeng/checkNodes/fantaTexClass/rendering/check_renderLayer.py","file_name":"check_renderLayer.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"148203298","text":"import sys\n### \\\\// === ++++ === \\\\// ###\n# ~~~ Tens Game Solver ~~~ #\n### //\\\\ === ++++ === //\\\\ ###\n\n### === +++ GAME Setup +++ === ###\n# python3 ten_upwards.py [start] [end] [moves]\nstart = 10\nend = 0\nmoves = [1,2]\nif len(sys.argv) == 4:\n\tstart = int(sys.argv[1])\n\tend = int(sys.argv[2])\n\tmoves = list(sys.argv[3].split(\",\"))\n\tfor i in range(len(moves)):\n\t\tmoves[i] = int(moves[i])\n### === +++ GAME Setup +++ === ###\n\nWIN = \"win\"\nLOSE = \"lose\"\nTIE = \"draw\"\nUNKNOWN = \"unknown\"\n\ndef generate_moves(position):\n\t\"\"\"returns the list of moves that a position can take\"\"\"\n\t\"return a list of moves\"\n\tpossible_moves = []\n\tif position == end:\n\t\treturn possible_moves\n\tfor move in moves:\n\t\tif position-move >= end and position-move <= start and move <= start-end:\n\t\t\tpossible_moves.append(move)\n\treturn possible_moves\n\ndef generate_reverse_moves(position):\n\t\"\"\"returns the list of moves that can get to a given position\"\"\"\n\tpossible_moves = []\n\tfor move in moves:\n\t\tif position+move <= start and position+move >= end and move <= start-end:\n\t\t\tpossible_moves.append(move)\n\treturn possible_moves\n\ndef reverse_move(position, move):\n\t\"\"\"returns the position after a move has been reversed\"\"\"\n\treturn position + move\n\n#Data Structure: dictionary {position : [num of pointers, primitive, children type]}\npointer = {end:[end, LOSE, []]}\npointer.update({position: [len(generate_moves(position)), UNKNOWN, []] for position in range(end+1, start+1)})\n\n#general retrograde solver\n\ndef parents(position):\n\t\"\"\"returns the parents of a given position\"\"\"\n\treturn [reverse_move(position, move) for move in generate_reverse_moves(position)]\n\ndef solve_reverse():\n\t\"\"\"solves game iteritively\"\"\"\n\tfor position in list(sorted(pointer.keys())):\n\t\tfor parent in parents(position):\n\t\t\tpointer[parent][0] -= 1\n\t\t\tif parent == 0:\n\t\t\t\tpointer[parent][0] += 1\n\t\t\telif parent == position:\n\t\t\t\tpointer[position][1] = TIE\n\t\t\t\tpointer[position][2].append(TIE)\n\t\t\telif pointer[position][1] == LOSE:\n\t\t\t\tpointer[parent][2].append(LOSE)\n\t\t\telif pointer[position][1] == WIN:\n\t\t\t\tpointer[parent][2].append(WIN)\n\t\t\telif pointer[position][1] == UNKNOWN:\n\t\t\t\tpointer[parent][2].append(UNKNOWN)\n\t\t\telse:\n\t\t\t\tpointer[parent][2].append(TIE)\n\t\t\tif pointer[parent][0] == 0:\n\t\t\t\tif LOSE in pointer[parent][2]:\n\t\t\t\t\tpointer[parent][1] = WIN\n\t\t\t\telif ((TIE not in pointer[parent][2])\n\t\t\t\t\tand (UNKNOWN not in pointer[parent][2])):\n\t\t\t\t\tpointer[parent][1] = LOSE\n\t\t\t\telse: #(UNKNOWN not in pointer[parent][2]):\n\t\t\t\t\tpointer[parent][1] = TIE\n\t\t\t\t#else:\n\t\t\t\t#\tpointer[parent][1] = UNKNOWN\n\nsolve_reverse()\nprint(\"playing from \" + str(start) + \" to \" + str(end) + \", subtracting \" + str(moves))\nfor position in range(start, end-1, -1):\n\tif pointer[position][1] == UNKNOWN:\n\t\tprint(str(position) + \" has value \" + TIE)\n\telse:\n\t\tprint(str(position) + \" has value \" + pointer[position][1])\n","sub_path":"ten_upwards.py","file_name":"ten_upwards.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"507614386","text":"from org.franken.spider import SpiderNetWork\nfrom org.franken.spider import SpiderNovel\nfrom org.franken.spider import SpiderTimit\n\nimport math\nimport numpy as np\n\n# SpiderNetWork.get_data_github()\n\n# SpiderNovel.exe_spider()\n\n# SpiderNovel.send_sms_laixinma_wages()\n\n# SpiderTimit.exe_spider()\n\n\ndef test_nerual_network():\n l = 0.15\n w = 0.6\n b = 0.9\n x = 1.0\n y = 0\n for i in range(100):\n z = w * x + b\n sigmoid = 1 / (1 + math.exp(-z))\n print(\"w:\" + str(w) + \", b:\" + str(b) + \", output:\" + str(sigmoid))\n w = w - (l * sigmoid * (1 - sigmoid))\n b = b - (l * sigmoid * (1 - sigmoid))\n\n\n# test_nerual_network()\n\n\ndef freq_to_mel(hz):\n temp = 1 + hz / 700\n res = 2595 * math.log(temp, 10)\n print(str(res))\n return res\n\n\ndef mel_to_freq(mel):\n temp = mel / 2595\n res = (math.pow(10, temp) - 1) * 700\n print(str(res))\n return res\n\nmels = [93.3 * i for i in range(0, 23)]\n\nfreqs = [mel_to_freq(i) for i in mels]\n\nffts = np.fft.fft(freqs)\nffts = np.absolute(ffts)\nfreq_to_mel(4000)\nfreq_to_mel(8000)\n\nx = 3.3\nz = -math.log(math.exp(-2.5) + math.exp(-3.5), x)\nprint(str(z))\n\ny = -math.log(math.exp(-1.5), x)\nprint(str(y))\n\n\n","sub_path":"org/franken/spider/ExecSpider.py","file_name":"ExecSpider.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"99235462","text":"from datetime import datetime\nfrom collections import defaultdict\nimport pandas as pd\n\nclass card:\n manager_pwd = 7777\n '''\n Contains base card class attribute and methods\n \n Attributes:\n -----------\n acct_title : str\n the name of the account holder\n acct_no : int\n account number associated with the card\n card_no : int\n card number\n card_pin : int\n card pin number\n bal_curr : int/float\n current balance of the account\n trans_hist: dictionary with datetime(keys): transaction details(values)\n time/transaction history of account\n \n Methods:\n --------\n makePayment\n Withdraws money from the card and prints new account balance. \n \n checkCode - INTERNAL FUNCTION\n Checks if the input pin is correct\n\n changePIN\n Sets a new PIN for the card, requires old PIN.\n\n checkBalance\n Prints card holder, card account number and current balance\n \n checkTransactions\n Prints summary information of past transactions.\n '''\n\n def __init__(self, acct_no, acct_title, card_no, pin_entered, amount = 0):\n '''\n Parameters\n ----------\n acct_title : str\n the name of the account holder\n acct_no : int\n account number associated with the card\n card_no : int\n card number\n pin_entered : int\n card pin number\n amount : int/float (optional)\n initial deposit into the account\n \n Raises\n ------\n NotImplementedError\n When account number/title, card number/pin are not provided.\n '''\n if (acct_no is None) | (acct_title is None) | (card_no is None) | (pin_entered is None):\n raise NotImplementedError(\"Please provide correct details to create a bank card\")\n \n self.acct_title = acct_title\n self.acct_no = acct_no\n self.card_no = card_no\n self.__card_pin = pin_entered\n self.bal_curr = amount\n # Initialize balance records\n self.trans_hist = defaultdict(dict)\n self.trans_hist[datetime.now().strftime(\"%Y/%m/%d, %H:%M:%S\")]= [amount, 'Initialized Account']\n \n \n def makePayment(self, pin_entered, amount, srvc_point=\"Unknown\"):\n # Payment will be specific to the card type.\n # Sub-classes credit and debit implement this function\n pass\n\n\n\n def checkCode(self, pin_entered):\n '''\n INTERNAL FUNCTION\n Checks if the input pin is correct\n\n Parameters:\n ----------\n pin_entered : int. Must be four digits\n returns : True or False\n '''\n return self.__card_pin == pin_entered\n\n\n def changePIN(self, oldPIN, newPIN):\n '''\n Sets a new PIN for the card, requires old PIN.\n\n Parameters:\n ----------\n oldPIN : int. Must be four digits\n newPIN : int. Must be four digits\n returns : Status, True or False\n '''\n # Customer Authentication\n if (oldPIN is None) | (not self.checkCode(oldPIN)):\n print(\"Invalid pin code, please try again!\")\n else:\n self.__card_pin = newPIN\n print(\"Card pin code successfully changed!\")\n\n\n def checkBalance(self, pin_entered):\n '''\n Prints card holder, card account number and current balance\n\n Parameters:\n ----------\n pin_entered : int. Must be four digits\n returns : int, returns current account balance\n '''\n\n # Customer Authentication\n if (pin_entered is None) | (not self.checkCode(pin_entered)):\n print(\"Invalid pin code, please try again!\")\n else:\n print(\"Account Holder: {}\".format(self.acct_title))\n print(\"Card Number: {}\".format(self.card_no))\n print(\"Current Balance: ${:.2f}\".format(self.bal_curr))\n\n\n def checkTransactions(self, pin_entered):\n '''\n Prints summary information for the card balance.\n Parameters:\n ----------\n pin_entered : int. Must be four digits\n returns : none\n '''\n\n # Customer Authentication\n if (pin_entered is None) | (not self.checkCode(pin_entered)):\n print(\"Invalid pin code, please try again!\")\n else:\n print(\"Account Holder: {}\".format(self.acct_title))\n print(\"Current Balance: ${:.2f}\".format(self.bal_curr))\n print(\"Your balance history for the past transcations:\\n\")\n \n df = pd.DataFrame(self.trans_hist, index=['Amount', 'Card Service Point']).T\n print(df)\n print(\"Current Available Balance: ${}\".format(self.bal_curr))","sub_path":"build/lib/Bank/cards/card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":4876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"46106568","text":"import networkx as nx \nG = nx.DiGraph()\nG.add_node('A',type='input')\nG.add_node('B',type='input')\nG.add_node('C',type='input')\nG.add_node('D',type='input')\nG.add_node('E',type='input')\nG.add_node('F',type='input')\n\nG.add_node('fanout1',type='fanout')\nG.add_node('fanout2',type='fanout')\nG.add_node('fanout3',type='fanout')\nG.add_node('fanout4',type='fanout')\nG.add_node('fanout5',type='fanout')\nG.add_node('fanout6',type='fanout')\nG.add_node('fanout7',type='fanout')\n\n\nG.add_node('G1',type='gate',gatetype='nand')\nG.add_node('G2',type='gate',gatetype='nand')\nG.add_node('G3',type='gate',gatetype='nand')\nG.add_node('G5',type='gate',gatetype='nand')\nG.add_node('G7',type='gate',gatetype='nand')\nG.add_node('G8',type='gate',gatetype='nand')\nG.add_node('G9',type='gate',gatetype='nand')\nG.add_node('G10',type='gate',gatetype='nand')\n\nG.add_node('G11',type='gate',gatetype='not')\nG.add_node('G12',type='gate',gatetype='not')\nG.add_node('G13',type='gate',gatetype='not')\n\n\n\nG.add_node('output1',type='output')\n\n\nG.add_edges_from([('A', 'fanout1'),('fanout1', 'G1'),('fanout1','G2'),('B','fanout2'),('fanout2','G1'),('fanout2','G3'),('C','fanout3'),('fanout3','G1'),\n('fanout3','G8'),('G1','fanout4'),('fanout4','G5'),('fanout4','G7'),('fanout4','G9'),('D','fanout5'),('fanout5','G11'),('fanout5','G5'),('G11','G2'),\n('E','fanout6'),('fanout6','G12'),('fanout6','G7'),('G12','G3'),('F','fanout7'),('fanout7','G13'),('fanout7','G9'),('G13','G8'),('G2','G10'),('G10','output1')\n,('G5','G10'),('G3','G10'),('G7','G10'),('G8','G10'),('G9','G10')], value_non_fault='x',value_faulty='x', fault='')\n\nG.add_edge('fanout1','G1', value_non_fault='x',value_faulty='x',fault='sa1')\n\n\n#Dummy node for bfs\nG.add_node('PI',type='check')\nG.add_edge('PI','A', value_non_fault='x',value_faulty='x',fault='')\nG.add_edge('PI','B', value_non_fault='x',value_faulty='x',fault='')\nG.add_edge('PI','C', value_non_fault='x',value_faulty='x',fault='')\nG.add_edge('PI','D', value_non_fault='x',value_faulty='x',fault='')\nG.add_edge('PI','E', value_non_fault='x',value_faulty='x',fault='')\nG.add_edge('PI','F', value_non_fault='x',value_faulty='x',fault='')\n\n\n\nbfs=nx.single_source_shortest_path_length(G,'PI')\n#print bfs\n\n\n\n\n","sub_path":"Graph_Abramovici.py","file_name":"Graph_Abramovici.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"241661692","text":"# !/urs/bin/env python\n\n#This custom python script takes input as a fastq file and makes an output with a table of k-mer (column 1) and count (column 2) \n\n\n##Change input and output file path here##\npathinput='.fastq'\npathoutput='.kmerscore.txt'\n###########################################\n\n##Function1:This function reads in a fastq file and scores kmers in a dictionary\ndef ReadFASTQ(fastq,k):\n kmerscore = {}\n chars='ATGCNatgcn'\n i=0\n n=0\n for line in fastq:\n line=line.rstrip()\n i+=1\n if line[0] in chars and i%4 !=0: ##some have > sign so switch chars to > AND i check to make sure phred score line is not read.\n for j in range(len(line)-(k-1)):\n kmer=line[j:j+k]\n n+=1\n if 'N' in kmer:\n continue\n if 'n' in kmer:\n continue\n if kmer in kmerscore:\n kmerscore[kmer] = kmerscore[kmer] + 1\n elif kmer not in kmerscore:\n kmerscore[kmer]=1\n print('kmer score from fastq file done')\n return kmerscore\n\n\nk=15\n#k=31\n\n###read in fastq file\nfastq=open(pathinput,'r')\nkmerscore=ReadFASTQ(fastq,k)\nfileoutput=open(pathoutput,'w')\nfor kmer,score in kmerscore.items():\n fileoutput.write(kmer)\n fileoutput.write('\\t')\n fileoutput.write(str(score))\n fileoutput.write('\\n')\nfileoutput.close()\nprint('kmer tab separated file made')","sub_path":"kmer_composition.py","file_name":"kmer_composition.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"164059408","text":"\n\nfrom xai.brain.wordbase.adjectives._gourmet import _GOURMET\n\n#calss header\nclass _GOURMETS(_GOURMET, ):\n\tdef __init__(self,): \n\t\t_GOURMET.__init__(self)\n\t\tself.name = \"GOURMETS\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"gourmet\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_gourmets.py","file_name":"_gourmets.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"166904982","text":"import argparse\nimport numpy as np\nimport pylab as plt\n\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\n\nfrom kernel_conv.utils_kernels import extract_tensor_patches\nfrom kernel_conv.conv import KernelConvUnfold2d\nfrom kernel_conv.conv import KernelConvConv2d\n\n# from kernel_conv.conv import kernel_wrapper\nfrom kernel_conv.kernels import MaskedDCTKernel\n# from tqdm import tqdm\n\nfrom kernel_conv.my_dct_pytorch import compute_dct_pytorch\n\ntorch.autograd.set_detect_anomaly(True)\n\nclass SharpnessModelConv(nn.Module):\n def __init__(self, num_classes):\n super().__init__()\n self.num_classes = num_classes\n self.kernel_size = 50\n self.kernel_fn = MaskedDCTKernel(in_features=self.kernel_size, cuda=False)\n\n # self.pad_layer = torch.nn.modules.ReflectionPad2d([0, self.kernel_size // 2, 0, self.kernel_size // 2])\n self.dct_conv = nn.Sequential(\n KernelConvConv2d(in_channels=1, out_channels=1, kernel_size=self.kernel_size, kernel_fn=self.kernel_fn,\n stride=4, padding=25, dilation=1, groups=1, bias=False, padding_mode='reflect')\n )\n\n self.fc = nn.Sequential(\n nn.Linear(1, num_classes)\n )\n\n def forward(self, x):\n # x = self.pad_layer(x)\n x = self.dct_conv(x).abs()\n # print(x)\n # x = torch.mean(x, dim=3)\n # x, _ = torch.max(x, dim=2)\n # x = self.fc(x)\n return x #[self.kernel_size // 2:, self.kernel_size // 2:]\n\n\nclass SharpnessModelUnfold(nn.Module):\n def __init__(self, num_classes):\n super().__init__()\n self.num_classes = num_classes\n self.kernel_size = 50\n self.kernel_fn = MaskedDCTKernel(in_features=self.kernel_size, cuda=False)\n self.dct_conv = nn.Sequential(\n KernelConvUnfold2d(in_channels=1, out_channels=1, kernel_size=self.kernel_size, kernel_fn=self.kernel_fn,\n stride=4, padding=25, dilation=1, groups=1, bias=False, padding_mode='reflect')\n )\n\n self.fc = nn.Sequential(\n nn.Linear(1, num_classes)\n )\n\n def forward(self, x):\n # x = self.pad_layer(x)\n x = self.dct_conv(x).abs()\n # print(x)\n # x = torch.mean(x, dim=3)\n # x, _ = torch.max(x, dim=2)\n # x = self.fc(x)\n return x #[self.kernel_size // 2:, self.kernel_size // 2:]\n\n\ndef main():\n # # Parsing command line args\n # parser = argparse.ArgumentParser(description='CIFAR10 example')\n # parser.add_argument('--kernel', type=str, default=None,\n # help='Kernel type to use: [gaussian, polynomial, sigmoid, DCT] (default: None)')\n #\n # parser.add_argument('--epoch', type=int, default=2, help='Number of epochs (default: 2)')\n # parser.add_argument('--batch_size', type=int, default=4, help='Batch suze (default: 4)')\n # parser.add_argument('--gpu', type=bool, default=True, help='Use GPU? (default: True)')\n #\n # args = parser.parse_args()\n #\n # device = 'cpu'\n # if args.gpu:\n # device = 'cuda'\n #\n # # Initiating network\n # resnet50 = torchvision.models.resnet50()\n # resnet50._modules['fc'] = torch.nn.Linear(2048, 10, True)\n # net = resnet50\n #\n # if args.kernel == 'gaussian':\n # kernel_wrapper(net, GaussianKernel())\n # elif args.kernel == 'polynomial':\n # kernel_wrapper(net, PolynomialKernel())\n # elif args.kernel == 'sigmoid':\n # kernel_wrapper(net, SigmoidKernel())\n # elif args.kernel == \"DCT\":\n # kernel_wrapper(net, SigmoidKernel())\n # elif args.kernel is not None:\n # raise Exception('Invalid kernel')\n\n net = SharpnessModelUnfold(num_classes=3)\n net2 = SharpnessModelConv(num_classes=3)\n\n # net.to(device)\n\n # Loading datasets\n transform = transforms.Compose([\n transforms.Grayscale(),\n transforms.ToTensor()\n # transforms.Normalize((0.49, 0.48, 0.45), (0.25, 0.24, 0.26))\n ])\n\n # trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\n # trainloader = torch.utils.data.DataLoader(trainset, batch_size=1, shuffle=True, num_workers=2)\n testset = torchvision.datasets.FakeData(transform=transform)\n # testset = torchvision.datasets.(root='./data', train=False, download=True, transform=transform)\n # testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)\n testloader = torch.utils.data.DataLoader(testset, batch_size=1, shuffle=False, num_workers=2)\n\n img = plt.imread(\"./resourses/image_blur3.jpg\")[:200, :200, 0:1]\n torch_images = torch.Tensor(img).transpose(0, 2).transpose(1, 2).unsqueeze(0)\n with torch.no_grad():\n net.eval()\n # print(net)\n # for (images, labels) in testloader:\n # images = images.to(device)\n # labels = labels.to(device)\n outputs = net(torch_images)\n outputs2 = net2(torch_images)\n\n # dct_map_2 = compute_dct_pytorch(img[:, :, 0].astype(np.float))\n # dct_map_2[0][0, 0] = dct_map[0].max()\n # print(np.abs(dct_map).mean())\n # print(np.abs(dct_map_2[0]).mean())\n # print(np.abs(dct_map_conv).mean())\n\n dct_map = outputs.data.numpy()[0, 0]\n dct_map_conv = outputs2.data.numpy()[0, 0]\n\n assert outputs.shape == outputs2.shape\n assert np.abs(dct_map_conv).mean() == np.abs(dct_map).mean()\n assert np.abs(dct_map_conv).max() == np.abs(dct_map).max()\n\n # print(np.abs(dct_map).max())\n # print(np.abs(dct_map_2[0]).max())\n # print(np.abs(dct_map_conv).max())\n\n\n # print(np.abs(dct_map).min())\n # print(np.abs(dct_map_2[0]).min())\n # print(np.abs(dct_map_conv).min())\n\n\n # image = torch_images.data.numpy()[0, 0]\n\n # print(image.shape)\n # print(dct_map.shape)\n # print(dct_map_2[0].shape)\n # print(dct_map_conv.shape)\n\n # plt.show()\n # print(torch_images.shape)\n # patches = extract_tensor_patches(torch_images, window_size=50, stride=4)\n # patches_unfold = F.unfold(torch_images, kernel_size=50, stride=4)\n # print(patches.shape)\n # print(patches_unfold.shape)\n\n # print(patches[0])\n # print(patches_unfold[0])\n\n # kconv = KernelConv2d(in_channels=1, out_channels=1, kernel_size=50, kernel_fn=self.kernel_fn,\n # stride=4, padding=0, dilation=1, groups=1, bias=False, padding_mode='reflection')\n # patches_old = kconv(torch_images, window_size=50, stride=4)\n # plt.imsave(\"dct_map_2.png\", dct_map_2[0])\n # plt.imsave(\"dct_map.png\", dct_map)\n # plt.imsave(\"dct_map_conv.png\", dct_map_conv)\n #\n # plt.imsave(\"image.png\", image)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"test_dct.py","file_name":"test_dct.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"495640193","text":"\"\"\"\nRead and write tables to astropy tables.\n\n[This is missing a lot of metadata -- figure out how to cope]\n\"\"\"\n\nfrom astropy import table\nimport random\nimport os\nfrom os import getcwd, path\nfrom sys import path as systempath\ncwd = getcwd()\nsystempath.append(path.join(cwd, '../'))\n\nfrom phot_db import feed_to_table_many\n\ndef load_astropy_table(conn, db_table_name, table):\n \"\"\"ingests the astropy table table into db_table_name via conn.\n \"\"\"\n feed_to_table_many(\n conn,\n db_table_name,\n table.colnames,\n [tuple(r) for r in table])\n\n\ndef query_to_astropy_table(conn, query, args=()):\n \"\"\"tries to come up with a reasonable astropy table for a database\n query result.\n \"\"\"\n cursor = conn.cursor()\n cursor.execute(query, args)\n keys = [cd[0] for cd in cursor.description]\n tuples = list(cursor)\n \n def getColumn(index):\n return [t[index] for t in tuples]\n \n data = [\n table.Column(name=k,\n data=getColumn(i))\n for i,k in enumerate(keys)]\n return table.Table(data=data)\n","sub_path":"trials/db/astropy_interface.py","file_name":"astropy_interface.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"609254451","text":"# Write a Python program that calculates the factorial of a given number n.\n# The value of n should be entered by the user.\n# The program must print the result and use a loop to calculate it.\n\nnumber = int(input(\"Enter a number to calculate the factorial: \"))\n\nfactorial = 1\n\nfor i in range(2, number+1):\n factorial *= i\n\nprint(f\"The factorial value of !{number} is\", factorial)\n","sub_path":"Exercise 120. Calculate Factorial.py","file_name":"Exercise 120. Calculate Factorial.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"266683406","text":"from BaseClass import *\n\n\nclass SymmetricDDA(Line):\n def __init__(self,x1, y1, x2, y2,name):\n super(SymmetricDDA, self).__init__(x1, y1, x2, y2 ,name)\n\n def build_N(self):\n # 生成一个合理N 用来分隔线段 通过移位操作就可以实现\n self.dx = self.x2-self.x1\n self.dy = self.y2-self.y1\n max_increment = max(self.dx,self.dy)\n n = 0\n while 1:\n max_increment = max_increment >> 1\n n += 1\n if max_increment < 1:\n break\n self.N = 2**n\n\n def display(self):\n self.build_N()\n x_increment = self.dx/self.N\n y_increment = self.dy/self.N\n glBegin(GL_POINTS)\n glVertex2d(int(self.x1), int(self.y1))\n x,y = self.x1, self.y1\n for i in range(self.N):\n x, y = x + x_increment, y + y_increment\n glVertex2d(int(x), int(y))\n glEnd()\n glFlush()\n\nif __name__ == '__main__':\n line = SymmetricDDA(0,0, 280, 480, 'SymmetricDDA.py')\n line.run()","sub_path":"PY/SymmetricDDA.py","file_name":"SymmetricDDA.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"94034189","text":"import numpy as np\nimport pandas as pd\nimport sys\nimport os\nfrom tkinter import filedialog, Tk, Frame, Label, Button, Text, messagebox, filedialog\nimport tkinter as tk\nfrom datetime import datetime\nfrom tkinter import *\n\nfrom classification import Classifier\n\nPATH_FOR_DATA = \"C:/Users/Palina_Yuzvenka/Work/еязис/sentiment_analysis/movies-sentiment-anallysis/data/\"\n# \"D:/LABS/DataScience/Новая папка/Information-retrival-master/inform_retriv/data/documents/raw\"\n\nclass GUI:\n\n current_result = []\n classifier = Classifier()\n\n def __init__(self, window):\n \n window.wm_title(\"Database Interface\")\n self.root = window\n self.current_row=0\n\n self.save_button = Button (window, text=\"help\")\n self.save_button.configure(command=self.check)\n self.save_button.grid(row=self.current_row,column=0,columnspan=2)\n self.current_row += 1\n\n self.save_button = Button (window, text=\"classify document\", command=self.load_file)\n self.save_button.grid(row=self.current_row,column=0,columnspan=2)\n self.current_row += 1\n\n self.query_text = StringVar()\n self.metric_entry = Entry(window, textvariable=self.query_text)\n self.metric_entry.grid(row=self.current_row,column=0, columnspan=2)\n self.current_row += 1 \n\n self.save_button = Button (window, text=\"classify query\", command=self.classificate_query)\n self.save_button.grid(row=self.current_row-1,column=1,columnspan=3)\n self.current_row += 1\n\n ''' founded doc and metrix '''\n #Line to separate panels\n canvas = Canvas(master=window, width=500, height=40)\n canvas.create_line(0, 20, 500, 20, fill=\"black\")\n canvas.grid(row=self.current_row,column=0,columnspan=2)\n self.current_row += 1\n\n self.text = Text(width=60, height=40, cursor=\"hand2\")\n self.text.grid(columnspan=2)\n self.text.config(state='normal')\n \n def load_file(self):\n file_name = filedialog.askopenfilename()\n f = open(file_name)\n data = f.read()\n f.close()\n self.classificate_doc(data)\n\n\n def check(self):\n messagebox.showinfo(title=\"help\", message=\"If you wand to delete document - please, enter it's title.\\nIf you want to insert new document - choose file from the computer.\\nIf you wanr to find smth - enter relevant query.\\nNeed metrix? Just press button 'show metrix'\")\n\n def classificate_query(self):\n query = self.metric_entry.get()\n lstm_result = GUI.classifier.lstm(query)\n svm_result = GUI.classifier.svm(query)\n self.text.insert(tk.INSERT, '\\n\\n Results')\n self.text.insert(tk.INSERT, '\\n\\nquery: ' + query)\n self.text.insert(tk.INSERT, '\\nLSTM: ' + str(lstm_result))\n self.text.insert(tk.INSERT, '\\n\\nSVM: ' + str(svm_result))\n\n\n def classificate_doc(self, text):\n lstm_result = GUI.classifier.lstm(text)\n svm_result = GUI.classifier.svm(text)\n self.text.insert(tk.INSERT, '\\n\\n Results')\n self.text.insert(tk.INSERT, '\\n\\nLSTM: ' + str(lstm_result))\n self.text.insert(tk.INSERT, '\\n\\nSVM: ' + str(svm_result))\n\ndef main(args):\n window= Tk()\n start= GUI(window)\n window.mainloop()\n\nif __name__ == '__main__':\n args = sys.argv[1:]\n main(args)\n\n","sub_path":"python/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"369683609","text":"# -*- coding: utf-8 -*-\n\n'''\n A modeling spec for t850\n\n This spec follows basic settings and discussions in\n\n Data-driven medium-range weather prediction with a Resnet pretrained on climate simulations: A new model for WeatherBench\n by Stephan Rasp, Nils Thuerey\n https://arxiv.org/pdf/2008.08626.pdf\n\n'''\n\nimport torch as th\nimport torch.nn as nn\nfrom wxbtool.nn.model import Base2d\nfrom wxbtool.nn.setting import Setting\nfrom wxbtool.data.variables import vars3d, code2var, split_name\nfrom wxbtool.norms.meanstd import normalizors, denorm_t850\n\n\nmse = nn.MSELoss()\n\n\nclass SettingRasp(Setting):\n def __init__(self):\n super().__init__()\n self.resolution = '5.625deg' # The spatial resolution of the model\n\n # Which vertical levels to choose\n self.levels = ['50', '250', '500', '600', '700', '850', '925']\n # How many vertical levels to choose\n self.height = len(self.levels)\n\n # The name of variables to choose, for both input features and output\n self.vars = ['geopotential', 'temperature', 'specific_humidity', 'u_component_of_wind', 'v_component_of_wind',\n '2m_temperature', 'total_precipitation', 'toa_incident_solar_radiation']\n\n # The code of variables in input features\n self.vars_in = ['z50', 'z250', 'z500', 'z600', 'z700', 'z850', 'z925',\n 't50', 't250', 't500', 't600', 't700', 't850', 't925',\n 'q50', 'q250', 'q500', 'q600', 'q700', 'q850', 'q925',\n 'u50', 'u250', 'u500', 'u600', 'u700', 'u850', 'u925',\n 'v50', 'v250', 'v500', 'v600', 'v700', 'v850', 'v925',\n 't2m', 'tp', 'tisr']\n\n # The code of variables in output\n self.vars_out = ['t850']\n\n # temporal scopes for train\n self.years_train = [\n 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989,\n 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,\n 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,\n 2010, 2011, 2012, 2013, 2014,\n ]\n # temporal scopes for evaluation\n self.years_eval = [2015, 2016]\n # temporal scopes for test\n self.years_test = [2017, 2018]\n\n\nclass Setting3d(SettingRasp):\n def __init__(self):\n super().__init__()\n self.step = 8 # How many hours of a hourly step which all features in organized temporally\n self.input_span = 3 # How many hourly steps for an input\n self.pred_span = 1 # How many hourly steps for a prediction\n self.pred_shift = 72 # How many hours between the end of the input span and the beginning of prediction span\n\n\nclass Setting5d(SettingRasp):\n def __init__(self):\n super().__init__()\n self.step = 8 # How many hours of a hourly step which all features in organized temporally\n self.input_span = 3 # How many hourly steps for an input\n self.pred_span = 1 # How many hourly steps for a prediction\n self.pred_shift = 120 # How many hours between the end of the input span and the beginning of prediction span\n\n\nclass Spec(Base2d):\n def __init__(self, setting):\n super().__init__(setting)\n\n # following Rasp's schema from the above paper\n self.name = 't850_rasp'\n\n def get_inputs(self, **kwargs):\n vdic, vlst = {}, []\n for nm in self.setting.vars_in:\n c, l = split_name(nm)\n v = code2var[c]\n if v in vars3d:\n d = kwargs[v].view(-1, self.setting.input_span, self.setting.height, 32, 64)[:, :, self.setting.levels.index(l)]\n else:\n d = kwargs[v].view(-1, self.setting.input_span, 32, 64)\n d = normalizors[nm](d)\n d = self.augment_data(d)\n vdic[nm] = d\n vlst.append(d)\n\n return vdic, th.cat(vlst, dim=1)\n\n def get_targets(self, **kwargs):\n t850 = kwargs['temperature'].view(-1, 1, self.setting.height, 32, 64)[:, :, self.setting.levels.index('850')]\n t850 = self.augment_data(t850)\n return {'t850': t850}, t850\n\n def get_results(self, **kwargs):\n t850 = denorm_t850(kwargs['t850'])\n return {'t850': t850}, t850\n\n def forward(self, **kwargs):\n raise NotImplementedError('Spec is abstract and can not be initialized')\n\n def lossfun(self, inputs, result, target):\n _, rst = self.get_results(**result)\n _, tgt = self.get_targets(**target)\n rst = self.weight * rst.view(-1, 1, 32, 64)\n tgt = self.weight * tgt.view(-1, 1, 32, 64)\n\n losst = mse(rst[:, 0], tgt[:, 0])\n\n return losst\n","sub_path":"wxbtool/specs/res5_625/t850rasp.py","file_name":"t850rasp.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"435847452","text":"from enum import Enum, unique\n\n@unique\nclass Direction(Enum):\n HORIZONTAL = 1\n VERTICAL = 2\n DIAGONAL_ASCENDING = 3\n DIAGONAL_DESCENDING = 4\n\n@unique\nclass Player(Enum):\n MAX = 1\n MIN = 2\n\n@unique\nclass GameType(Enum):\n PvP = 1 # Player versus Player\n PvE = 2 # Player versus Environment (the IA)\n\n@unique\nclass StoneType(Enum):\n BLANK = 0\n BLACK = 1\n WHITE = 2\n\n@unique\nclass GameState(Enum):\n WIN = 0\n DRAW = 1\n RUNNING = 2","sub_path":"Definitions.py","file_name":"Definitions.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"109389592","text":"\"\"\"\nSome phone usage rate may be described as follows:\n\nfirst minute of a call costs min1 cents,\neach minute from the 2nd up to 10th (inclusive) costs min2_10 cents\neach minute after 10th costs min11 cents.\nYou have s cents on your account before the call. What is the duration of the longest call (in minutes rounded down to the nearest integer) you can have?\n\nExample\n\nFor min1 = 3, min2_10 = 1, min11 = 2, and s = 20, the output should be\nphoneCall(min1, min2_10, min11, s) = 14.\n\"\"\"\ndef phoneCall(min1, min2_10, min11, s):\n duration = 0\n if s0:\n s=s-min2_10\n if s>=0:\n duration+= 1\n return duration\n s=s-(min2_10*9)\n duration+=9\n while s>0:\n s=s-min11 \n if s>=0:\n duration+=1\n return duration \n\n","sub_path":"core/8_phoneCall.py","file_name":"8_phoneCall.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"648847115","text":"import re\nimport argparse\nimport itertools\nimport subprocess\n\nfrom pyadsb.algebra import Polynomial\n\n\ndef parse(adsb_message, log_file):\n '''Parse an ADS-B message adsb_message. The message is expected to come from\n rtl_adsb, a tool from rtl-sdr (http://bit.ly/1TgvTBx). '''\n\n # Check if the message matches what is expected from rtl_adsb. It should\n # be an asterisk followed by 28 hexadecial digits, a semicolon, and a\n # newline character.\n adsb_match = re.match(r'\\*([0-9a-f]{28});\\n', adsb_message)\n\n # If the message has the expected format, go ahead and parse it.\n if adsb_match:\n\n # ADSB-B messages are really 112-bit binary strings.\n adsb_hex = adsb_match.groups()[0].upper()\n adsb_bin = '{:112b}'.format(int(adsb_hex, 16))\n\n # Skip message if it fails parity check.\n if not parity(adsb_bin):\n return None\n\n # This dictionary will eventually contain decoded\n # parts of adsb_message.\n parsed_message = {}\n parsed_message['HEX'] = adsb_hex\n\n # The unique identifyer of the plane (or more precisely,\n # the transponder).\n parsed_message['ICAO24'] = adsb_hex[2:8]\n\n # DF = Downlink Format\n # TC = Type Code\n parsed_message['DF'] = int(adsb_bin[0:5], 2)\n parsed_message['TC'] = int(adsb_bin[32:37], 2)\n\n # DF of an ADS-B message is 17. If this is not the case\n # for adsb_message, there is no point in trying to decode it.\n if parsed_message['DF'] != 17:\n return None\n\n data_frame = adsb_bin[40:88]\n\n # The message contains Aircraft Identification\n if parsed_message['TC'] in [1, 2, 3, 4]:\n\n character_encoding = '-ABCDEFGHIJKLMNOPQRSTUVWXYZ---------------------0123456789------'\n\n # The data frame comprises 48 bits which are split into eight\n # chunks of size six. The integer representation of a chunk\n # is the index of the encoded letter in the character encoding.\n #\n # Example:\n #\n # ---------------------------------------------------------\n # |001001|000010|001011|111001|010100|010000|100000|100000|\n # | 9| 2| 11| 57| 20| 16| 32| 32|\n # | I| B| K| 9| T| P| -| -|\n # ---------------------------------------------------------\n #\n # Aircraft Identification = IBK9TP\n #\n # More information about the encoding may be found in Table 3-9 in\n # Annex 10 to the Convention on International Civil Aviation,\n # Aeronautical Telecommunications, Volume IV, Surveillance and\n # Collision Avoidance Systems (http://bit.ly/1R04HDR).\n\n parsed_message['DATA'] \\\n = ''.join([character_encoding[int(data_frame[i:i+6], 2)]\n for i in range(0, 48, 6)]).replace('-', '')\n\n return parsed_message\n\n # The message does not have the expected format. Skip it and\n # report an error in the log file.\n log_file.write('Skipping invalid input: {}'.format(adsb_message))\n\n\ndef parity(bin_message):\n ''' Performs parity check of binary ADS-B messages. For mathematical\n details, please refer to J.L. Gertz: Fundamentals of Mode S Parity\n Coding, Project Report ATC-117, Lincoln Laboratory, MIT, 2 April 1984\n (http://bit.ly/1Qcht5e).\n '''\n\n # Generator polynomial used for cyclic encoding of ADS-B messages.\n g = Polynomial([1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n\n # The ADS-B message represented as a polynomial.\n m = Polynomial([int(digit) for digit in bin_message][::-1])\n\n # Perform long division of m by g. If the remainder is non-zero,\n # the message fails the parity check.\n q, r = divmod(m, g)\n if r != Polynomial([0]):\n return False\n return True\n","sub_path":"pyadsb/adsb.py","file_name":"adsb.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"380198443","text":"import sqlite3\n\nconn = sqlite3.connect('example.db')\n\n# Never do this -- insecure!\nsymbol = 'RHAT'\nconn.execute(\"SELECT * FROM stocks WHERE symbol='%s'\" % symbol)\n\n# Do this instead\nsymbol = ['RHAT']\nconn.execute('SELECT * FROM stocks WHERE symbol=?', symbol)\nconn.fetchone()\n\n# Larger example that inserts many records at a time\npurchases = [\n ('2006-03-28', 'BUY', 'IBM', 1000, 45.00),\n ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),\n ('2006-04-06', 'SELL', 'IBM', 500, 53.00),\n]\n\nconn.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)","sub_path":"database/src/db-execute-many.py","file_name":"db-execute-many.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"55757230","text":"def maxSubArray(nums):\n # write your code here\n sum_l = nums[0]\n sum = nums[0]\n for i in range(1,len(nums)):\n sum_l = max(sum_l + nums[i], nums[i])\n print(sum_l)\n\n if (sum_l > sum):\n sum = sum_l\n return sum\n\nprint(maxSubArray([-2,2,-3,4,-1,2,1,-5,3]))\n\n","sub_path":"lintcode41.py","file_name":"lintcode41.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"89140513","text":"##File name: /Users/laptopuser/Documents/courses/cs127/class_exercises/f22/lecture10_class_exercises/maximum3.py\n##name: CSci127 teaching staff\n\nnums = [1, 4, 10, 6, 5, 42, 9, 8, 12]\n\nsize = len(nums)\nif size == 0:\n print(\"The list is empty and does not have a maximum\")\n exit(0) #cannot use return since this is not an function\n\nmaxNum = nums[0]\nfor i in range(1, size):\n if nums[i] > maxNum:\n maxNum = nums[i] \n\nprint(maxNum)\n","sub_path":"files/maximum3.py","file_name":"maximum3.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"563912310","text":"import sys\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\n\ndef main():\n resultFile = open(sys.argv[1],\"r\")\n county = []\n norm = open(\"norm_countyData.arff\",\"r\")\n for line in norm:\n if(line[0] not in [\"@\",\"\\n\"]):\n county.append(line.split(\",\")[-1][:-1])\n norm.close()\n\n index = 0\n clusterDict = {} #Key: cluster; #Value: county\n priorityDict = {} #Key: cluster; #Value: list of sums of each feature value\n for line in resultFile:\n if(line[0] not in [\"@\",\"\\n\",\"{\"]):\n attValues = list(map(float,line.split(\",\")[:4]))\n cluster = line.split(\",\")[-1][:-1]\n if(cluster not in clusterDict.keys()):\n clusterDict[cluster] = []\n if(cluster not in priorityDict.keys()):\n priorityDict[cluster] = [[0]*4,0]\n clusterDict[cluster].append(county[index])\n for i in range(0,4):\n priorityDict[cluster][0][i] += attValues[i]\n priorityDict[cluster][1] += 1\n index += 1\n resultFile.close()\n\n #Obtain magnitudes of cluster centers\n for k in priorityDict.keys():\n priorityDict[k][0] = [i / priorityDict[k][1] for i in priorityDict[k][0]]\n priorityDict[k] = (sum(i**2 for i in priorityDict[k][0]))**.5\n\n #Set cluster bar colors by priority\n cBins = []\n colors = [[1,0,0]]\n acc = 0\n pSort, keySort = zip(*sorted(zip(priorityDict.values(), priorityDict.keys()),reverse = True))\n for k in keySort:\n cBins.append(len(clusterDict[k])*[int(k[-1:])])\n if(len(keySort) < 5):\n colors.append([1,0.2*(acc+1),0.2*(acc+1)])\n acc += 1 \n\n #Make histogram\n colors = colors[:-1]\n plt.title(sys.argv[1][:-5])\n plt.hist(cBins,color = colors,label = keySort)\n plt.legend(bbox_to_anchor=(1.04,1), loc='upper left', ncol=1)\n fig = plt.gcf()\n plt.text(len(keySort)*1.05,10,\"Note: Darker red\\nindicates higher\\npriority. Clusters\\nare arranged\\nfrom highest to\\nlowest priority.\")\n fig.subplots_adjust(right=0.7)\n plt.show()\n\nmain()\n","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"208480704","text":"# This file is used to do optimisation based on different metrics.\n# We want to get three different hand poses through simulation.\n# See: https://www.rheumtutor.com/rheumtutoring/approach-to-hand-x-rays/\n# Author: Tianci Wen\n\nimport numpy as np\nimport random\nimport math\nimport matplotlib.pyplot as plt\nfrom time import time\nimport pandas as pd\nimport csv\nfrom scipy import optimize\nimport sys, argparse\nimport gvxrPython3 as gvxr\nfrom rotation import poserior_anterior\nimport App\nimport cv2\n\nfrom skimage.measure import compare_ssim as SSIM\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\n\ndef setXRayParameters(SOD, SDD):\n # Compute the source position in 3-D from the SOD\n gvxr.setSourcePosition(SOD, 0.0, 0.0, \"cm\");\n gvxr.setDetectorPosition(SOD - SDD, 0.0, 0.0, \"cm\");\n gvxr.usePointSource();\n\ndef objective_function(params):\n\n SOD = params[0];\n SDD = params[1];\n angle = len(params)-2;\n angle_list = np.zeros(angle);\n\n for i in range(angle):\n\n angle_list[i] = params[i+2];\n\n setXRayParameters(SOD*SDD, SDD);\n\n pred_image = poserior_anterior(angle_list);\n\n rmse = root_mean_squared_error(ground_truth_image, pred_image);\n\n return rmse\n\ndef relative_error(y_true, y_pred):\n s = 0;\n pix1 = 1024;\n pix2 = 1536;\n\n for i in range(pix1):\n for j in range(pix2):\n s += abs((y_true[i,j] - y_pred[i,j])/y_true[i,j]);\n s = s/(pix1*pix2);\n\n return s\n\ndef zero_mean_normalised_cross_correlation(y_true, y_pred):\n '''\n ZNCC = (1/n)*(1/(std(target_image)*std(est_image)))* SUM_n_by_n{(target_image-\n mean(target_image))*(est_image-mean(est_image))}\n '''\n z = 0;\n pix1 = 1024;\n pix2 = 1536;\n mean1 = np.mean(y_true);\n mean2 = np.mean(y_pred);\n std1 = np.std(y_true);\n std2 = np.std(y_pred);\n\n for i in range(pix1):\n for j in range(pix2):\n z += (y_true[i,j]-mean1)*(y_pred[i,j]-mean2);\n z = z/(pix1*pix2*std1*std2);\n\n return z\n\ndef root_mean_squared_error(y_true, y_pred):\n\n return math.sqrt(mean_squared_error(y_true, y_pred));\n\ndef structural_similarity(y_pred, y_true):\n\n return SSIM(y_pred, y_true);\n\ndef random_search():\n\n error_low = 1\n\n start = time();\n print(\"Optimising... using Random Search!\");\n\n random.seed();\n\n for j in range(1000):\n\n if j>99 and j%100 == 0:\n print(\"Iterations: %d \" % j);\n params = [];\n SOD = random.uniform(0., 1.);\n SDD = random.randint(0, 1000);\n params.append(SOD);\n params.append(SDD);\n\n for i in range(40):\n angles = random.randint(-180, 180);\n params.append(angles);\n\n error = objective_function(params);\n\n if error_low > error:\n\n print(\"Better parameters found, updating...\");\n error_low = error;\n result_params = params;\n print(\"Metrics: %.4f\" % error_low);\n print(\"Parameters: \", result_params);\n\n end = time();\n\n print(\"Time: %d\" % (end-start));\n\n result_angle_list = [];\n for a in range(len(result_params)-2):\n\n result_angle = result_params[a+2];\n result_angle_list.append(result_angle);\n\n pred_image = poserior_anterior(result_angle_list);\n\n return pred_image\n\nground_truth_SOD=100;\nground_truth_SDD=140;\nground_truth_angles = [-90, 20, -10, 0, 5, 0, 5, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,]\n\n# Create an OpenGL context\nprint(\"Create an OpenGL context\")\ngvxr.createWindow();\ngvxr.setWindowSize(512, 512);\n\n# Set up the beam\nprint(\"Set up the beam\")\ngvxr.usePointSource();\n#gvxr.useParallelBeam();\ngvxr.setMonoChromatic(0.08, \"MeV\", 1000);\n\n# Set up the detector\nprint(\"Set up the detector\");\ngvxr.setDetectorUpVector(0, 0, -1);\ngvxr.setDetectorNumberOfPixels(1024, 1536);\ngvxr.setDetectorPixelSize(0.5, 0.5, \"mm\");\n\nsetXRayParameters(ground_truth_SOD, ground_truth_SDD);\n\n# Load the data\nprint(\"Load the data\");\n\ngvxr.loadSceneGraph(\"/home/ti/Documents/gvxr-python3-gui/hand.dae\", \"m\");\ngvxr.moveToCentre('root');\ngvxr.disableArtefactFiltering();\n\n# Compute groud truth x-ray image\nground_truth_image = poserior_anterior(ground_truth_angles);\nplt.imsave(\"ground-truth.png\", ground_truth_image);\n# Compute optimisation\nimage = random_search();\nplt.imsave(\"prediction.png\", image);\n\nplt.subplot(1, 2, 1);\nplt.imshow(ground_truth_image);\n\nplt.subplot(1, 2, 2);\nplt.imshow(image);\nplt.show();\n\n# gvxr.displayScene();\n\n# app = App.App(0.08);\n","sub_path":"optimisation.py","file_name":"optimisation.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"46848988","text":"#Question 1 \n\nnumberlist = [0,7,15,8,9,56,2,3,13]\n\ndef count_odd(numlist):\n count = 0\n for i in numlist:\n if i%2 == 1:\n count +=1\n return count\nprint(count_odd(numberlist))\n\n#Question 2\n\ndef sum_even(numlist):\n sum = 0\n for i in numlist:\n if i%2 == 0:\n sum+=i\n return sum\n \nprint(sum_even(numberlist))\n\n#Question 3\n\nnegativenumberlist = [1,-3,9,-2,-9,6]\n\ndef sum_neg(numlist):\n sum = 0\n for i in numlist:\n if i < 0:\n sum +=i\n return sum\nprint(sum_neg(negativenumberlist))\n\n#Question 4\n\nwordlist = [\"cat\", \"apple\", \"laptop\", \"magic\"]\n\ndef fivewords(list):\n words = 0\n for i in list:\n if 5 == len(i):\n words += 1\n return words\nprint(fivewords(wordlist))\n\n#Question 5\n\nnumberlist = [7,15,8,2,3,13]\n\ndef evenfirst(numlist):\n sum=0\n for i in numlist:\n if i % 2 == 0:\n break\n else:\n sum +=i\n return sum\n\nprint(evenfirst(numberlist))\n\n\n#Question 6\n\nsamwords = [\"name1\",\"name2\", \"name3\", \"sam\"]\ndef samfxn(name):\n count =0\n for i in name:\n if i == \"sam\":\n count += 1\n break\n count +=1\n return count\n \nprint(samfxn(samwords))\n \n#Question 7\nn = 25\napprox = n/2\nwhile True:\n better = (approx + n/approx)/2.0\n print(better)\n if abs(better - approx) < 0.0000001:\n break\n approx = better #approx changes every time, not always n/2\n print(better)\n\n\n\n#Question 10\n \ndef is_prime(n): \n for i in range(2,n): #prime is only divisible by 1 and itself\n if n % i == 0:\n return False\n return True\n \n\n#Question 11\n\nimport turtle\nwn = turtle.Screen()\nstef = turtle.Turtle()\n\nsteps = [(160, 20), (-43, 10), (270, 8), (-43, 12)]\n\nfor (angle, moves) in steps:\n stef.right(angle)\n stef.forward(moves)\n \n#Question 12\n\nimport turtle\nwn = turtle.Screen()\nstef = turtle.Turtle()\nstef.pensize(10)\nhouse = [(270,50), (30, 50), (120,50), (120,50), (225,70.1), (225,50), (225,70.1), (225,50) ]\n\nfor (angle,moves) in house:\n stef.right(angle)\n stef.forward(moves)","sub_path":"Chapter7.1.py","file_name":"Chapter7.1.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"94655214","text":"from rhs_function import RHSFunction\nfrom scipy import optimize\nimport scipy.sparse as sparse\nfrom scipy import optimize\nfrom step_method import StepMethod\nimport numpy as np\nclass GaussLegendre(StepMethod):\n\n \"\"\"\n This Class implements Gauss Legendre RK method for solving ODE\n \"\"\"\n\n\n def __init__ (self,N,y0,domain,func):\n StepMethod.__init__(self, N, y0, domain, func)\n self.a11=0.25\n self.a12=0.25-np.sqrt(3)/6\n self.a21=0.25+np.sqrt(3)/6\n self.a22=0.25\n self.b1=0.5\n self.b2=0.5\n self.c1=0.5-np.sqrt(3)/6\n self.c2=0.5+np.sqrt(3)/6\n\n def step(self,f,u, t, h ,tol = 10**(-12), maxiter = 10):\n t_old= t\n # Copy u\n y_old=np.copy(u)\n # Guess k1 and k2\n k1 = f.eval(y_old,t_old)\n k2 = f.eval(y_old,t_old)\n N1=len(k1)\n def myF(k1,k2):\n val1 =np.vstack((k1, k2))\n val2 = h*(self.a11*k1+self.a12*k2)\n val3 = h*(self.a21*k1+self.a22*k2)\n f1=f.eval(y_old + val2, t_old+self.c1*h)\n f2=f.eval(y_old + val3, t_old+self.c2*h)\n val4 = np.vstack((f1, f2))\n return val4.flatten()-val1.flatten()\n\n def myJacF(k1,k2):\n val2 = h*(self.a11*k1 + self.a12*k2)\n val3 = h*(self.a21*k1 + self.a22*k2)\n \n A = f.jacobian(y_old+val2, t_old+self.c1*h)*self.a11*h\n B = A/self.a11*self.a12\n C = f.jacobian(y_old+val3, t_old+self.c2*h)*self.a21*h\n D = C/self.a21*self.a22\n if N1==1:\n E = sparse.hstack((A.T, B.T))\n F = sparse.hstack((C.T, D.T))\n G = sparse.hstack((E.T, F.T))\n else:\n E = np.vstack((A.T, B.T))\n F = np.vstack((C.T,D.T))\n G = np.vstack((E.T,F.T))\n return G-np.eye(2*N1)\n \n err = 1\n itercount = 0\n while err > tol and itercount < maxiter:\n Jac = myJacF(k1,k2)\n Fval = myF(k1,k2)\n if N1==1:\n Jac=sparse.csr_matrix(Jac)\n kappa=-sparse.linalg.spsolve(Jac,Fval)\n else:\n kappa=-np.linalg.solve(Jac,Fval)\n k1=kappa[0:N1]+k1\n k2=kappa[N1:2*N1+1]+k2\n err=np.max(np.abs(myF(k1,k2)))\n itercount += 1\n\n result= y_old+h/2.0*(k1+k2)\n \n return result\n\n\n\n\n","sub_path":"pyodesolver/method_Gauss_Legendre_2.py","file_name":"method_Gauss_Legendre_2.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"234796743","text":"import numpy as np\r\nimport os\r\nimport argparse\r\nimport tensorflow as tf\r\nimport re\r\nfrom shutil import move\r\n\r\ndef separate_classes_into_folders(labels):\r\n \"\"\" \"\"\"\r\n imglist = create_image_lists(args.path_to_pictures)\r\n unique_lbls = np.unique(labels)\r\n # Create The Folders Corrosponding To Labels\r\n for lbl in unique_lbls:\r\n path = args.path_to_save_images+\"/\"+str(int(lbl))\r\n print(\"Creating Label folder: \")\r\n print(path)\r\n \r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n \r\n #Copy Images Into Class Separated Folders\r\n \r\n for idx in np.transpose(np.where(labels==lbl)):\r\n head, tail = os.path.split(imglist[int(idx)])\r\n move(imglist[int(idx)], path+\"/\"+tail)\r\n\r\n\r\ndef create_image_lists(image_dir):\r\n \"\"\" Builds a list of images from the file system.\r\n \"\"\"\r\n # The root directory comes first, so skip it.\r\n is_root_dir = True\r\n extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']\r\n file_list = []\r\n dir_name = os.path.basename(image_dir)\r\n tf.logging.info(\"Looking for images in '\" + dir_name + \"'\")\r\n for extension in extensions:\r\n file_glob = os.path.join(image_dir, dir_name, '*.' + extension)\r\n file_list.extend(tf.gfile.Glob(file_glob))\r\n if not file_list:\r\n tf.logging.warning('No files found')\r\n return\r\n \r\n arg_sort = np.argsort([int(re.search(\"(\\d*\\.?\\d)\",val).group(0)) for val in file_list])\r\n imglist = [file_list[idx] for idx in arg_sort]\r\n return imglist\r\n\r\nif __name__ == '__main__':\r\n import sys\r\n from Tools.DataReader import load_labels\r\n\r\n parser = argparse.ArgumentParser(prog='Separate images into folders sorted by classes',\r\n description='''Program separates images into folders sorted by the classes of the image.\r\n The folders are created at the location specified or if unspecified at the script location''')\r\n parser.add_argument('path_to_pictures', \r\n help='Input path to images to be separated into classes')\r\n \r\n parser.add_argument('path_to_labels', \r\n help='Input path and name of file containing the labels of the images')\r\n \r\n parser.add_argument('-path_to_save_images', \r\n help='Input path to folder where the images should be saved',\r\n default=os.path.dirname(os.path.abspath(__file__)))\r\n\r\n # Parse Arguments\r\n args = parser.parse_args()\r\n\r\n # Path is a data file\r\n if os.path.exists(args.path_to_pictures):\r\n if os.path.exists(args.path_to_labels):\r\n # Read labels from file\r\n labels = load_labels(args.path_to_labels)\r\n \r\n else:\r\n print(\"Error: file '\" + args.path_to_labels + \"' not found\")\r\n exit(1)\r\n\r\n else:\r\n print(\"Error: file '\" + args.path_to_pictures + \"' not found\")\r\n exit(1)\r\n \r\n separate_classes_into_folders(labels)\r\n ","sub_path":"CVML/Project/Source code/Tools/separate_classes_into_folders.py","file_name":"separate_classes_into_folders.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"625658479","text":"from token import Token\nfrom token_handlers import *\nfrom token_constants import *\nimport json\n\nclass LexicalAnalyzer:\n \"\"\"\n used by the Syntactic Analyzer to return the next token each time.\n returns -1 if there are no tokens in the list.\n (either src file is empty or all items were popped)\n \"\"\"\n\n counter = 0\n\n def __init__(self):\n self._lexemes = [] # lexem objects, each contains: type, val & line num\n self._comment_errors = []\n self._unexpected_char_errors = []\n\n def getToken(self):\n \"\"\"\n if lexemes list is empty, it returns None\n else it returns the lexe\n \"\"\"\n if (len(self._lexemes) == 0):\n return None\n elif (len(self._lexemes) >= 1) and self.counter < len(self._lexemes):\n prev_counter = self.counter\n self.counter += 1\n return self._lexemes[prev_counter]\n\n def tokenizeIt(self, src_file_path):\n \"\"\"\n reads char stream from file and fills the tokens list.\n \"\"\"\n try:\n f = open(src_file_path, 'r')\n except IOError as e:\n print(\"I/O error({0}): {1}\".format(e.errno, e.strerror))\n raise\n\n line_number = 1\n last_char_read = None\n while True:\n #reads 1 byte/char and decides the path for the token\n if last_char_read is None:\n char = f.read(1)\n else:\n char = last_char_read\n\n if not char: # no more chars to read\n break\n\n elif char in SINGLE_CHAR_OPS: # as in: < > + - * / =\n tuple_returned = handle_operator(f, char)\n last_char_read = tuple_returned[0]\n if tuple_returned[1] is not None:\n self._lexemes.append(Token(tuple_returned[1],\n tuple_returned[2],\n line_number))\n\n elif char in SINGLE_CHAR_PUNCTUATION: # as in: , ; . ( ) { } [ ]\n self._lexemes.append(Token(RESERVED, char, line_number))\n last_char_read = None\n\n elif char.isdigit(): # as in: 0..9\n tuple_returned = handle_number(f, char)\n last_char_read = tuple_returned[0]\n self._lexemes.append(Token(tuple_returned[1],\n tuple_returned[2],\n line_number))\n if len(tuple_returned) == 4:\n self._lexemes.append(Token(RESERVED,\n DOT,\n line_number))\n\n elif char.isalpha(): # as in: a..z | A..Z\n tuple_returned = handle_alpha(f, char)\n last_char_read = tuple_returned[0]\n self._lexemes.append(Token(tuple_returned[1],\n tuple_returned[2],\n line_number))\n\n #check new lines to update the line_number count\n elif char == '\\n': # '\\n' is used to seperate lines in *nix\n # too bad for Win for now\n line_number += 1\n last_char_read = None\n\n #elif char == '\\r': # '\\r\\n' is used to seperate lines in Win\n #last_char_read = f.read(1)\n #if last_char_read == '\\n':\n # line_number += 1\n\n elif char.isspace():\n last_char_read = None # ignore whitespace\n else: # invalid char\n self._lexemes.append(Token(UNKNOWN, char, line_number))\n last_char_read = None\n \n def stripComments(self):\n \"\"\"\n removes multi-line comments between '/*' and '*/'\n lexi assumes '*/' with no starting '/*' means token '*' followed by '/'\n \"\"\"\n lexemes_kept = []\n insideComment = False\n last_comment_index = -1\n\n for index, lexeme in enumerate(self._lexemes):\n\n if lexeme._value == START_COMMENT and not insideComment:\n insideComment = True\n elif lexeme._value == START_COMMENT and insideComment:\n pass\n elif lexeme._value == END_COMMENT and not insideComment:\n self._comment_errors.append(\n \"ERROR: no matching '/*' found for '*/' in line: \" +\n str(lexeme._line_number)\n )\n lexemes_kept.append(lexeme)\n elif lexeme._value == END_COMMENT and insideComment:\n insideComment = False\n elif not insideComment: # and != '/*' and != '*/'\n lexemes_kept.append(lexeme)\n\n if insideComment:\n self._comment_errors.append(\n \"ERROR: no matching '*/' found for '/*' in line: \" +\n str(self._lexemes[last_comment_index]._line_number)\n )\n # add all lexemes that are after the unclosed '/*'\n lexemes_kept = lexemes_kept + self._lexemes[last_comment_index:]\n\n self._lexemes = lexemes_kept\n\n def reset(self):\n self._unexpected_char_errors = []\n self._comment_errors = []\n self._lexemes = []\n\n def checkUnexpectedCharErrors(self):\n self._unexpected_char_errors = \\\n [x for x in self._lexemes if x._type == UNKNOWN]\n\n def printTokens(self):\n for lexeme in self._lexemes:\n print(lexeme._type + \" \" + lexeme._value \n + \" on line:\" + str(lexeme._line_number))\n\n def printErrors(self):\n for error in self._comment_errors:\n print(error)\n\n for error in self._unexpected_char_errors:\n print(\n \"ERROR: Unexpected token: \"\n + error._value\n + \" on line \"\n + str(error._line_number)\n )\n\n return len(self._comment_errors) == 0 and len(self._unexpected_char_errors) == 0\n\n def logAll(self, file_name):\n f = open('/root/compiler/src/lexical_analyzer/test_files/' + file_name + '_tokens.txt',\"w+\")\n for lexeme in self._lexemes:\n if lexeme._type == IDENTIFIER:\n f.write(\"IDENTIFIER \" + lexeme._value \n + \" on line:\" + str(lexeme._line_number) + \"\\n\")\n elif lexeme._type == INTEGER:\n f.write(\"INTEGER \" + lexeme._value \n + \" on line:\" + str(lexeme._line_number) + \"\\n\")\n elif lexeme._type == FLOAT:\n f.write(\"FLOAT \" + lexeme._value \n + \" on line:\" + str(lexeme._line_number) + \"\\n\")\n elif lexeme._type == RESERVED:\n f.write(\"RESERVED \" + lexeme._value \n + \" on line:\" + str(lexeme._line_number) + \"\\n\")\n elif lexeme._type == UNKNOWN:\n f.write(\"UNEXPECTED \" + lexeme._value \n + \" on line:\" + str(lexeme._line_number) + \"\\n\")\n f.close()\n\n f = open('/root/compiler/src/lexical_analyzer/test_files/' + file_name + '_comment_errors.txt',\"w+\")\n for error in self._comment_errors:\n f.write(error + \"\\n\")\n f.close()\n\n f = open('/root/compiler/src/lexical_analyzer/test_files/' + file_name + '_unexpected_char_errors.txt',\"w+\")\n for error in self._unexpected_char_errors:\n f.write(\n \"ERROR: Unexpected token: \"\n + error._value\n + \" on line \"\n + str(error._line_number)+ \"\\n\"\n )\n f.close()\n\nif __name__ == \"__main__\":\n lexi = LexicalAnalyzer()\n\t\n files_to_test = []\n with open('/root/compiler/src/lexical_analyzer/test_files/testing_files_list.json') as json_data:\n data = json.load(json_data)\n\n files_to_test = data[\"test\"]\n for file in files_to_test:\n lexi.tokenizeIt('/root/compiler/src/lexical_analyzer/test_files/' + file + '.txt')\n lexi.stripComments()\n lexi.printTokens()\n lexi.checkUnexpectedCharErrors()\n lexi.printErrors()\n lexi.logAll(file)\n lexi.reset()\n","sub_path":"src/lexical_analyzer/lexi.py","file_name":"lexi.py","file_ext":"py","file_size_in_byte":8214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"58275806","text":"from django.views.generic.base import TemplateView\nfrom django.views.generic import ListView\nfrom communities.models import Community\nfrom posts.models import Post, PostComment\nfrom common.check.community import check_can_get_lists\nfrom common.template.post import get_permission_community_post_2\nfrom django.http import Http404\n\n\nclass PostCommunityCommentList(ListView):\n template_name, paginate_by = None, 15\n\n def get(self,request,*args,**kwargs):\n from common.templates import get_template_user_comments\n\n self.post, self.community = Post.objects.get(uuid=self.kwargs[\"uuid\"]), Community.objects.get(pk=self.kwargs[\"pk\"])\n if not request.is_ajax() or not self.post.comments_enabled:\n raise Http404\n self.template_name = get_template_user_comments(self.post, \"posts/c_post_comment/\", \"comments.html\", request.user, request.META['HTTP_USER_AGENT'])\n return super(PostCommunityCommentList,self).get(request,*args,**kwargs)\n\n def get_context_data(self, **kwargs):\n context = super(PostCommunityCommentList, self).get_context_data(**kwargs)\n context['parent'] = self.post\n context['community'] = self.community\n return context\n\n def get_queryset(self):\n comments = self.post.get_comments()\n return comments\n\n\nclass PostCommunityDetail(TemplateView):\n template_name = None\n\n def get(self,request,*args,**kwargs):\n self.template_name = get_permission_community_post_2(Community.objects.get(uuid=self.kwargs[\"uuid\"]), \"posts/post_community/\", \"detail.html\", request.user, request.META['HTTP_USER_AGENT'])\n return super(PostCommunityDetail,self).get(request,*args,**kwargs)\n\n def get_context_data(self,**kwargs):\n context = super(PostCommunityDetail,self).get_context_data(**kwargs)\n context[\"object\"] = self.object\n return context\n","sub_path":"posts/view/community.py","file_name":"community.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"438828583","text":"import pytz\nfrom datetime import datetime\nfrom os import path\nimport psycopg2\n\nfrom park_api import env\n\ndef get_most_lots_from_known_data(city, lot_name):\n \"\"\"\n Get the total value from the highest known value in the last saved JSON.\n This is useful for cities that don't publish total number of spaces for a parking lot.\n\n Caveats:\n - Returns 0 if not found.\n - If a lot name exists twice only the last value is returned.\n\n :param city:\n :param lot_name:\n :return:\n \"\"\"\n with psycopg2.connect(**env.DATABASE) as conn:\n cursor = conn.cursor()\n cursor.execute(\"SELECT data FROM parkapi WHERE city=%s;\", (city,))\n all_data = cursor.fetchall()\n\n most_lots = 0\n for json_data in all_data:\n lots = json_data[0][\"lots\"]\n for lot in lots:\n if lot[\"name\"] == lot_name:\n if int(lot[\"free\"]) > most_lots:\n most_lots = int(lot[\"free\"])\n return most_lots\n\n\ndef utc_now():\n \"\"\"\n Returns the current UTC time in ISO format.\n\n :return:\n \"\"\"\n return datetime.utcnow().replace(microsecond=0).isoformat()\n\n\ndef convert_date(date_string, date_format, timezone=\"Europe/Berlin\"):\n \"\"\"\n Convert a date into a ISO formatted UTC date string. Timezone defaults to Europe/Berlin.\n\n :param date_string:\n :param date_format:\n :param timezone:\n :return:\n \"\"\"\n last_updated = datetime.strptime(date_string, date_format)\n local_timezone = pytz.timezone(timezone)\n last_updated = local_timezone.localize(last_updated, is_dst=None)\n last_updated = last_updated.astimezone(pytz.utc).replace(tzinfo=None)\n\n return last_updated.replace(microsecond=0).isoformat()\n\n\ndef remove_special_chars(string):\n \"\"\"\n Remove any umlauts, spaces and punctuation from a string.\n\n :param string:\n :return:\n \"\"\"\n replacements = {\n \"ä\": \"ae\",\n \"ö\": \"oe\",\n \"ü\": \"ue\",\n \"ß\": \"ss\",\n \"-\": \"\",\n \" \": \"\",\n \".\": \"\",\n \",\": \"\",\n \"'\": \"\",\n \"\\\"\": \"\",\n \"/\": \"\",\n \"\\\\\": \"\"\n }\n for repl in replacements.keys():\n string = string.replace(repl, replacements[repl])\n return string\n\n\ndef generate_id(city_file_path, lot_name):\n \"\"\"\n Generate an ID for a parking lot by concatenating city name and lot name.\n\n :param city_file_path: __file__ for the city file\n :param lot_name: Name of the parking lot\n :return: ID\n \"\"\"\n return remove_special_chars((path.basename(city_file_path)[:-3] + lot_name).lower())\n","sub_path":"park_api/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"498636510","text":"import random\nimport colorsys\n\n\ndef random_color(alpha=1):\n hue = random.uniform(0, 1)\n saturation = random.uniform(0.75, 1)\n brightness = 1\n red, green, blue = colorsys.hsv_to_rgb(hue, saturation, brightness)\n return (red, green, blue, alpha)","sub_path":"generative_query_network/gqn/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"439668560","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Dec 13 23:22:51 2018\r\n\r\n@author: masahiro\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport os\r\nfrom numba.decorators import jit\r\n\r\n@jit\r\ndef main():\r\n df=pd.read_csv(\"output1\"+\"-100percent.csv\",header=None)\r\n df.to_csv('output_sum.csv',header=False,index=False)\r\n df_sum=pd.read_csv('output_sum.csv',header=None)\r\n\r\n cnt=1\r\n for n in range(2,200):\r\n if os.path.exists(\"output\"+str(n)+\"-100percent.csv\")==True:\r\n df = pd.read_csv(\"output\"+str(n)+\"-100percent.csv\",header=None)\r\n df_sum[str(n)]=df[0]\r\n df_sum.to_csv('output_sum.csv',header=False,index=False)\r\n cnt+=1\r\n print(str(cnt)+\",\"+str(n))\r\n else:\r\n print(str(cnt)+\",\"+str(n))\r\n \r\nmain()","sub_path":"csv結合.py","file_name":"csv結合.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"382672467","text":"# -*- coding: utf-8 -*-\nfrom django.views.generic import CreateView, TemplateView, ListView, DetailView\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.template import RequestContext\nfrom django.db.models import F\nfrom django.db.models import Count\nfrom .models import Customer, Seller, Brand, Product, Sale, SaleDetail\n\n\nclass Index(TemplateView):\n template_name = 'index.html'\n\n\nclass About(TemplateView):\n template_name = 'about.html'\n\n\nclass CustomerList(ListView):\n template_name = 'customer_list.html'\n model = Customer\n context_object = 'customer_list'\n paginate_by = 8\n\n def get_context_data(self, **kwargs):\n context = super(CustomerList, self).get_context_data(**kwargs)\n context['count'] = self.get_queryset().count()\n return context\n\n def get_queryset(self):\n cObj = Customer.objects.all()\n var_get_search = self.request.GET.get('search_box')\n # buscar por nome\n if var_get_search is not None:\n cObj = cObj.filter(firstname__icontains=var_get_search)\n return cObj\n\n\nclass SellerList(ListView):\n template_name = 'seller_list.html'\n model = Seller\n context_object = 'seller_list'\n paginate_by = 8\n\n def get_context_data(self, **kwargs):\n context = super(SellerList, self).get_context_data(**kwargs)\n context['count'] = self.get_queryset().count()\n return context\n\n def get_queryset(self):\n s = Seller.objects.all()\n var_get_search = self.request.GET.get('search_box')\n # buscar por nome\n if var_get_search is not None:\n s = s.filter(firstname__icontains=var_get_search)\n return s\n\n\nclass BrandList(ListView):\n template_name = 'brand_list.html'\n model = Brand\n context_object = 'brand_list'\n paginate_by = 10\n\n def get_context_data(self, **kwargs):\n context = super(BrandList, self).get_context_data(**kwargs)\n context['count'] = self.get_queryset().count()\n return context\n\n\nclass ProductList(ListView):\n template_name = 'product_list.html'\n model = Product\n context_object = 'product_list'\n paginate_by = 100\n\n def get_context_data(self, **kwargs):\n\n context = super(ProductList, self).get_context_data(**kwargs)\n context['count'] = self.get_queryset().count()\n return context\n\n def get_queryset(self):\n cObj = Product.objects.all()\n var_get_search = self.request.GET.get('search_box')\n # buscar por produto\n if var_get_search is not None:\n cObj = cObj.filter(product__icontains=var_get_search)\n # filtra produtos em baixo estoque\n if self.request.GET.get('filter_link', False):\n cObj = cObj.filter(stock__lt=F('stock_min'))\n\n return cObj\n\n\nclass SaleCreate(CreateView):\n template_name = 'sale_form.html'\n model = Sale\n success_url = reverse_lazy('sale_list')\n\n\nclass SaleList(ListView):\n template_name = 'sale_list.html'\n model = Sale\n context_object = 'sale_list'\n paginate_by = 20\n\n def get_context_data(self, **kwargs):\n context = super(SaleList, self).get_context_data(**kwargs)\n context['count'] = self.get_queryset().count()\n return context\n\n def get_queryset(self):\n qs = super(SaleList, self).get_queryset()\n # clica no cliente e retorna as vendas dele\n if 'customer' in self.request.GET:\n qs = qs.filter(customer=self.request.GET['customer'])\n # clica no vendedor e retorna as vendas dele\n if 'seller' in self.request.GET:\n qs = qs.filter(seller=self.request.GET['seller'])\n # filtra vendas com zero item\n if 'filter_sale_zero' in self.request.GET:\n qs = Sale.objects.annotate(\n itens=Count('sales_det')).filter(itens=0)\n # filtra vendas com um item\n if 'filter_sale_one' in self.request.GET:\n qs = Sale.objects.annotate(\n itens=Count('sales_det')).filter(itens=1)\n return qs\n\n\nclass SaleDetailView(TemplateView):\n template_name = 'sale_detail.html'\n model = Sale\n\n def get_context_data(self, **kwargs):\n Objvenda = Sale.objects.get(pk=self.kwargs['pk'])\n ItensVenda = SaleDetail.objects.all().filter(sale=Objvenda)\n context = super(SaleDetailView, self).get_context_data(**kwargs)\n context['count'] = ItensVenda.count()\n context['Sale'] = Objvenda\n context['Itens'] = ItensVenda\n return context\n","sub_path":"vendas_project/vendas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"347513329","text":" \n\n\"\"\"\nPlease note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nmatrix1 = tf.constant([[3, 3]])\nmatrix2 = tf.constant([[2],\n [2]])\nproduct = tf.matmul(matrix1, matrix2) # matrix multiply np.dot(m1, m2)\n\n# method 1\nsess = tf.Session()\nresult = sess.run(product)\nprint(result)\nsess.close()\n\n# method 2\nwith tf.Session() as sess:\n result2 = sess.run(product)\n print(result2)\n\n\n##x_data=np.linspace(-1,1,5)\n##print(x_data)\n\n#gdc ceshi\nX = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\nprint(X)\nprint(X.shape)\n\ninputs=np.array([[1],[2]])[:, np.newaxis]\n#Weights=np.transpose(np.array([1,2,3,4],[5,6,7,8]))#[:, np.newaxis]\nWeights=np.array([[1,2,3,4],[5,6,7,8]])\nWeights=np.transpose(Weights)\nprint(Weights)\nWeights=Weights[:, np.newaxis]\n#\nprint(inputs)\nprint(Weights)\n","sub_path":"tensorflow6_session.py","file_name":"tensorflow6_session.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"27558448","text":"#Daniel Bandler\n#5/17/18\n#anagram.py prints out all anagrams of word in dictionary\n\nfile = open(\"engmix.txt\")\n\nword1 = input(\"what is the word you want to anagramize? \")\n\nword1List = []\nword2List = []\n\nfor char in word1:\n word1List.append(char)\nword1List.sort()\n\nfor line in file:\n line = line.strip()\n for let in line:\n word2List.append(let)\n word2List.sort()\n if word2List == word1List:\n print(line)\n word2List = []\n","sub_path":"anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"585122635","text":"import sys\nimport random\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\n# https://networkx.github.io/documentation/stable/reference/drawing.html\n# https://networkx.github.io/documentation/stable/reference/functions.html\n# https://matplotlib.org/examples/color/named_colors.html\n# H = nx.Graph(G) # convert G to undirected graph\n# PyGraphviz\n# https://github.com/CristiFati/Prebuilt-Binaries/tree/master/Windows/PyGraphviz\n# Graphviz 64 bit windows\n# https://github.com/mahkoCosmo/GraphViz_x64/\n\ndef trayectoria_aumento(G):\n\t\n\ttempG=G.to_directed()\n\ttempG=nx.create_empty_copy(tempG)\n\n\n\n\tleftNodes, rigthNodes = nx.bipartite.sets(G)\n\tmaximalMatch=nx.maximal_matching(G)\n\n\ttempG.add_nodes_from(\n\t\t[\n\t\t\t[\"start\", {\"color\":\"orange\"}], \n\t\t\t[\"end\", {\"color\":\"orange\"}]\n\t\t]\n\t)\n\n\t# set new post\n\n\ttop = nx.bipartite.sets(G)[0]# Top is leftpart\n\tpos=nx.bipartite_layout(G, top)\n\tpos[\"start\"]=np.array([-1.5, 0.5])\n\tpos[\"end\"]=np.array([1.5, 0.5])\n\n\n\tfor nodeFromI, nodeToI in maximalMatch:\n\t\ttempG.add_edges_from(\n\t\t\t[\n\t\t\t\t[nodeFromI, nodeToI, {\"color\":\"red\"}]\n\t\t\t]\n\t\t)\n\n\t\tif(nodeFromI in leftNodes):\n\t\t\ttempG.add_edges_from(\n\t\t\t\t[\n\t\t\t\t\t[\"start\", nodeFromI, {\"color\":\"silver\"}]\n\t\t\t\t]\n\t\t\t)\n\t\tif(nodeToI in leftNodes):\n\t\t\ttempG.add_edges_from(\n\t\t\t\t[\n\t\t\t\t\t[\"start\", nodeToI, {\"color\":\"silver\"}]\n\t\t\t\t]\n\t\t\t)\n\t\tif(nodeFromI in rigthNodes):\n\t\t\ttempG.add_edges_from(\n\t\t\t\t[\n\t\t\t\t\t[nodeFromI, \"end\", {\"color\":\"silver\"}]\n\t\t\t\t]\n\t\t\t)\n\t\tif(nodeToI in rigthNodes):\n\t\t\ttempG.add_edges_from(\n\t\t\t\t[\n\t\t\t\t\t[nodeToI, \"end\", {\"color\":\"silver\"}]\n\t\t\t\t]\n\t\t\t)\n\tfor edgeI in G.edges():###\n\t\tif(not edgeI in tempG.edges() and not edgeI[::-1] in tempG.edges()):\n\t\t\ttempG.add_edges_from(\n\t\t\t[\n\t\t\t\t[nodeFromI, nodeToI, {\"color\":\"black\"}]\n\t\t\t]\n\t\t)\n\treturn tempG, pos\n\n\t\t\n\n\nif __name__ == \"__main__\":\n\tG = nx.Graph()\n\tX=[1,3,6,8,10,12,14,15,17,18]\n\tY=[2,4,5,7,9,11,13,16,19]\n\tG.add_nodes_from(X, bipartite=0)\n\tG.add_nodes_from(Y, bipartite=1)\n\tgraphEdgesList=[\n\t\t[1, 2], \n\t\t[1, 5],\n\t\t[2, 6],\n\t\t[5, 6],\n\t\t[5, 10],\n\t\t[6, 11],\n\t\t[10, 11],\n\t\t[11, 12],\n\t\t[11, 15],\n\t\t[12, 16],\n\t\t[12, 7],\n\t\t[12, 13],\n\t\t[15, 16],\n\t\t[16, 18],\n\t\t[7, 3],\n\t\t[3, 4],\n\t\t[4, 8],\n\t\t[8, 9],\n\t\t[8, 13],\n\t\t[9, 14],\n\t\t[13, 14],\n\t\t[13, 17],\n\t\t[17, 19],\n\t\t[18, 19],\n\n\t]\n\tG.add_edges_from(graphEdgesList)\n\t\n\t#G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123)\n\t\n\t#G = nx.complete_graph(5)\n\n\n\n\tcolors=[\"silver\", \"red\", \"forestgreen\", \"oliva\", \"gold\", \"teal\"]\n\t\n\tfor edgeI in G.edges:\n\t\tG.edges[edgeI][\"weight\"]=random.randint(1, 99)\n\n\t\n\t# pos=nx.nx_agraph.pygraphviz_layout(G, prog='dot')\n\t# print(nx.is_tree(G))\n\t# print(nx.to_prufer_sequence(G))\n\n\tnx.set_node_attributes(G, \"silver\", 'color')\n\tnx.set_edge_attributes(G, \"black\", \"color\")\n\tG, pos=trayectoria_aumento(G)\n\t\n\n\t\n\n\t\n\t\n\n\t\n\n\tedge_labels = nx.get_edge_attributes(G,'weight')\n\tnode_colors=nx.get_node_attributes(G,'color')\n\tedge_colors=nx.get_edge_attributes(G,'color')\n\n\t\n\tnx.draw(G, pos, edge_color=edge_colors.values(), node_color=node_colors.values(),with_labels=True, font_weight='bold')\n\n\t#pos[0]=pos[0]+0.2\n\t#nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, with_labels=True, font_weight='bold')\n\tplt.show()","sub_path":"classes/clase 05-07-2019/trayectoria aumento.py","file_name":"trayectoria aumento.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"209692782","text":"# Copyright 2018 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\nfrom datetime import datetime\nimport json\nimport re\nimport uuid\nfrom google.appengine.api import taskqueue\nfrom simpleeval import simple_eval\nfrom simpleeval import InvalidExpression\nfrom sqlalchemy import Column\nfrom sqlalchemy import Integer\nfrom sqlalchemy import String\nfrom sqlalchemy import DateTime\nfrom sqlalchemy import Text\nfrom sqlalchemy import Boolean\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.orm import load_only\nfrom core.database import BaseModel\nfrom core import inline\nfrom core.mailers import NotificationMailer\n\n\ndef _parse_num(s):\n try:\n return int(s)\n except ValueError:\n try:\n return float(s)\n # TODO(dulacp) should raise a ValueError exception, not silence it\n except ValueError:\n return 0\n\n\nclass Pipeline(BaseModel):\n __tablename__ = 'pipelines'\n id = Column(Integer, primary_key=True, autoincrement=True)\n name = Column(String(255))\n emails_for_notifications = Column(String(255))\n status = Column(String(50), nullable=False, default='idle')\n status_changed_at = Column(DateTime)\n jobs = relationship('Job', backref='pipeline',\n lazy='dynamic')\n run_on_schedule = Column(Boolean, nullable=False, default=False)\n schedules = relationship('Schedule', lazy='dynamic')\n params = relationship('Param', lazy='dynamic', order_by='asc(Param.name)')\n\n def __init__(self, name=None):\n self.name = name\n\n @property\n def state(self):\n return self.status\n\n @property\n def has_jobs(self):\n return self.jobs.count() > 0\n\n @property\n def recipients(self):\n if self.emails_for_notifications:\n return self.emails_for_notifications.split()\n return []\n\n def assign_attributes(self, attributes):\n for key, value in attributes.iteritems():\n if key in ['schedules', 'jobs', 'params']:\n continue\n if key == 'run_on_schedule':\n self.__setattr__(key, value == 'True')\n continue\n self.__setattr__(key, value)\n\n def save_relations(self, relations):\n for key, value in relations.iteritems():\n if key == 'schedules':\n self.assign_schedules(value)\n elif key == 'params':\n self.assign_params(value)\n\n def assign_params(self, parameters):\n Param.update_list(parameters, self)\n\n def assign_schedules(self, arg_schedules):\n # Remove if records not in list ids for update\n arg_schedule_ids = []\n for arg_schedule in arg_schedules:\n if arg_schedule.get('id') is not None:\n # Updating\n schedule = Schedule.find(arg_schedule.get('id'))\n schedule.update(cron=arg_schedule['cron'])\n arg_schedule_ids.append(arg_schedule['id'])\n else:\n # Creating\n schedule = Schedule.create(pipeline_id=self.id,\n cron=arg_schedule['cron'])\n arg_schedule_ids.append(schedule.id)\n # Removing\n ids_for_removing = []\n for schedule in self.schedules:\n if schedule.id not in arg_schedule_ids:\n ids_for_removing.append(schedule.id)\n Schedule.destroy(*ids_for_removing)\n\n def start(self):\n if self.status not in ['idle', 'finished', 'failed', 'succeeded']:\n return False\n jobs = self.jobs.all()\n if len(jobs) < 1:\n return False\n for job in jobs:\n if job.status not in ['idle', 'succeeded', 'failed']:\n return False\n for job in jobs:\n if not job.get_ready():\n return False\n for job in jobs:\n job.start()\n self.update(status='running', status_changed_at=datetime.now())\n return True\n\n def stop(self):\n if self.status != 'running':\n return False\n for job in self.jobs:\n job.stop()\n for job in self.jobs:\n if job.status not in ['succeeded', 'failed']:\n self.update(status='stopping', status_changed_at=datetime.now())\n return True\n self._finish()\n return True\n\n def start_single_job(self, job):\n if self.status not in ['idle', 'finished', 'failed', 'succeeded']:\n return False\n job.run()\n self.update(status='running', status_changed_at=datetime.now())\n return True\n\n def job_finished(self):\n for job in self.jobs:\n if job.status not in ['succeeded', 'failed', 'idle']:\n return False\n self._finish()\n return True\n\n def _finish(self):\n jobs = Job.query.outerjoin((StartCondition,\n Job.id == StartCondition.preceding_job_id))\n jobs = jobs.filter(Job.pipeline_id == self.id)\n jobs = jobs.filter(StartCondition.preceding_job_id == None)\n jobs = jobs.options(load_only('status')).all()\n status = 'succeeded'\n for job in jobs:\n if job.status == 'failed':\n status = 'failed'\n break\n self.update(status=status, status_changed_at=datetime.now())\n NotificationMailer().finished_pipeline(self)\n\n def import_data(self, data):\n self.assign_params(data['params'])\n self.assign_schedules(data['schedules'])\n job_mapping = {}\n jobs = []\n if data['jobs']:\n for job_data in data['jobs']:\n job = Job()\n job.pipeline_id = self.id\n job.assign_attributes(job_data)\n job.save()\n job.save_relations(job_data)\n jobs.append(job)\n job_mapping[job_data['id']] = job.id\n for job in jobs:\n job_id = job_mapping.keys()[job_mapping.values().index(job.id)]\n job_data = next((j for j in data['jobs'] if j['id'] == job_id), None)\n job.assign_hash_start_conditions(job_data['hash_start_conditions'],\n job_mapping)\n\n def is_blocked(self):\n return (self.run_on_schedule or self.status in ['running', 'stopping'])\n\n def destroy(self):\n sc_ids = [sc.id for sc in self.schedules]\n if sc_ids:\n Schedule.destroy(*sc_ids)\n\n for job in self.jobs:\n job.destroy()\n\n param_ids = [p.id for p in self.params.all()]\n if param_ids:\n Param.destroy(*param_ids)\n self.delete()\n\n\nclass Job(BaseModel):\n __tablename__ = 'jobs'\n id = Column(Integer, primary_key=True, autoincrement=True)\n name = Column(String(255))\n status = Column(String(50), nullable=False, default='idle')\n status_changed_at = Column(DateTime)\n worker_class = Column(String(255))\n pipeline_id = Column(Integer, ForeignKey('pipelines.id'))\n params = relationship('Param', backref='job', lazy='dynamic')\n start_conditions = relationship(\n 'StartCondition',\n primaryjoin='Job.id==StartCondition.job_id')\n dependent_jobs = relationship(\n 'Job',\n secondary='start_conditions',\n primaryjoin='Job.id==StartCondition.preceding_job_id',\n secondaryjoin='StartCondition.job_id==Job.id')\n enqueued_workers_count = Column(Integer, default=0)\n succeeded_workers_count = Column(Integer, default=0)\n failed_workers_count = Column(Integer, default=0)\n\n def __init__(self, name=None, worker_class=None, pipeline_id=None):\n self.name = name\n self.worker_class = worker_class\n self.pipeline_id = pipeline_id\n\n def destroy(self):\n sc_ids = [sc.id for sc in self.start_conditions]\n if sc_ids:\n StartCondition.destroy(*sc_ids)\n\n dependent_job_sc_ids = [\n sc.id for sc in StartCondition.where(preceding_job_id=self.id).all()]\n if dependent_job_sc_ids:\n StartCondition.destroy(*dependent_job_sc_ids)\n\n param_ids = [p.id for p in self.params.all()]\n if param_ids:\n Param.destroy(*param_ids)\n self.delete()\n\n def get_ready(self):\n if self.status not in ['idle', 'succeeded', 'failed']:\n return False\n try:\n for param in self.params:\n _ = param.val # NOQA\n except (InvalidExpression, TypeError) as e:\n from core.logging import logger\n logger.log_struct({\n 'labels': {\n 'pipeline_id': self.pipeline_id,\n 'job_id': self.id,\n 'worker_class': self.worker_class,\n },\n 'log_level': 'ERROR',\n 'message': 'Bad job param \"%s\": %s' % (param.label, e),\n })\n return False\n self.update(status='waiting', status_changed_at=datetime.now())\n return True\n\n def start(self):\n \"\"\"\n TODO(dulacp): refactor this method, too complex branching logic\n \"\"\"\n if self.status != 'waiting':\n return False\n for start_condition in self.start_conditions:\n if start_condition.condition == 'success':\n if start_condition.preceding_job.status != 'succeeded':\n if start_condition.preceding_job.status == 'failed':\n self.update(status='failed', status_changed_at=datetime.now())\n self._start_dependent_jobs()\n return False\n elif start_condition.condition == 'fail':\n if start_condition.preceding_job.status != 'failed':\n if start_condition.preceding_job.status == 'succeeded':\n self.update(status='failed', status_changed_at=datetime.now())\n self._start_dependent_jobs()\n return False\n elif start_condition.condition == 'whatever':\n if start_condition.preceding_job.status not in ['succeeded', 'failed']:\n return False\n self.run()\n return True\n\n def run(self):\n self.enqueued_workers_count = 0\n self.succeeded_workers_count = 0\n self.failed_workers_count = 0\n self.status = 'running'\n self.status_changed_at = datetime.now()\n worker_params = dict([(p.name, p.val) for p in self.params])\n self.enqueue(self.worker_class, worker_params)\n\n def stop(self):\n if self.status == 'waiting':\n self.update(status='failed', status_changed_at=datetime.now())\n return True\n elif self.status == 'running':\n self.update(status='stopping', status_changed_at=datetime.now())\n return True\n return False\n\n def enqueue(self, worker_class, worker_params, delay=0):\n if self.status != 'running':\n return False\n task_params = {\n 'job_id': self.id,\n 'worker_class': worker_class,\n 'worker_params': json.dumps(worker_params),\n }\n task_name = '%s_%s_%s' % (self.pipeline.name, self.name, self.worker_class)\n escaped_task_name = re.sub(r'[^-_0-9a-zA-Z]', '-', task_name)\n unique_task_name = '%s_%s' % (escaped_task_name, str(uuid.uuid4()))\n task = taskqueue.add(\n target='job-service',\n name=unique_task_name,\n url='/task',\n params=task_params,\n countdown=delay)\n self.enqueued_workers_count += 1\n self.save()\n return task\n\n @property\n def finished_workers_count(self):\n return self.succeeded_workers_count + self.failed_workers_count\n\n def _start_dependent_jobs(self):\n if self.dependent_jobs:\n for job in self.dependent_jobs:\n job.start()\n self.pipeline.job_finished()\n\n def worker_succeeded(self):\n self.succeeded_workers_count += 1\n if self.finished_workers_count >= self.enqueued_workers_count:\n if self.failed_workers_count < 1:\n self.status = 'succeeded'\n else:\n self.status = 'failed'\n self.status_changed_at = datetime.now()\n self.save()\n self._start_dependent_jobs()\n else:\n self.save()\n\n def worker_failed(self):\n self.failed_workers_count += 1\n if self.finished_workers_count >= self.enqueued_workers_count:\n self.status = 'failed'\n self.status_changed_at = datetime.now()\n self.save()\n self._start_dependent_jobs()\n else:\n self.save()\n\n def assign_attributes(self, attributes):\n for key, value in attributes.iteritems():\n if key in ['params', 'start_conditions', 'id', 'hash_start_conditions']:\n continue\n self.__setattr__(key, value)\n\n def save_relations(self, relations):\n for key, value in relations.iteritems():\n if key == 'params':\n self.assign_params(value)\n elif key == 'start_conditions':\n self.assign_start_conditions(value)\n\n def add_start_conditions(self, items):\n for item in items:\n self.start_conditions.append(item)\n\n def assign_params(self, parameters):\n Param.update_list(parameters, self)\n\n def assign_hash_start_conditions(self, arg_start_conditions, job_mapping):\n for arg_start_condition in arg_start_conditions:\n preceding_job_id = job_mapping[arg_start_condition['preceding_job_id']]\n StartCondition.create(\n job_id=self.id,\n preceding_job_id=preceding_job_id,\n condition=arg_start_condition['condition']\n )\n\n def assign_start_conditions(self, arg_start_conditions):\n scs = []\n for arg_start_condition in arg_start_conditions:\n scs.append(StartCondition.parse_value(arg_start_condition))\n\n arg_sc_ids = set([sc['id'] for sc in scs])\n cur_sc_ids = set([sc.preceding_job_id for sc in self.start_conditions])\n\n sc_intersection_ids = set(arg_sc_ids) & set(cur_sc_ids)\n new_sc_ids = set(arg_sc_ids) - set(cur_sc_ids)\n for v in scs:\n # Add new start conditions\n if v['id'] in new_sc_ids:\n StartCondition.create(\n job_id=self.id,\n preceding_job_id=v['id'],\n condition=v['condition']\n )\n # Update current start conditions\n elif v['id'] in sc_intersection_ids:\n sc = StartCondition.where(\n job_id=self.id,\n preceding_job_id=v['id']\n ).first()\n sc.condition = v['condition']\n sc.save()\n # Delete extra start conditions\n delete_sc_ids = set(cur_sc_ids) - set(arg_sc_ids)\n StartCondition.where(\n job_id=self.id,\n preceding_job_id__in=delete_sc_ids\n ).delete(synchronize_session=False)\n\n\nclass Param(BaseModel):\n __tablename__ = 'params'\n id = Column(Integer, primary_key=True, autoincrement=True)\n name = Column(String(255), nullable=False)\n type = Column(String(50), nullable=False)\n pipeline_id = Column(Integer, ForeignKey('pipelines.id'))\n job_id = Column(Integer, ForeignKey('jobs.id'))\n is_required = Column(Boolean, nullable=False, default=False)\n description = Column(Text)\n label = Column(String(255))\n value = Column(Text())\n\n _INLINER_REGEX = re.compile(r'{%.+?%}')\n\n def _expand_vars(self, value):\n names = {'True': True, 'False': False}\n if self.job_id is not None or self.pipeline_id is not None:\n for param in Param.where(pipeline_id=None, job_id=None).all():\n names[param.name] = param.val\n if self.job_id is not None:\n for param in self.job.pipeline.params:\n names[param.name] = param.val\n inliners = self._INLINER_REGEX.findall(value)\n for inliner in inliners:\n result = simple_eval(inliner[2:-2], functions=inline.functions,\n names=names)\n value = value.replace(inliner, str(result))\n return value\n\n @property\n def val(self):\n if self.type == 'boolean':\n return self.value == '1'\n val = self._expand_vars(self.value)\n if self.type == 'number':\n return _parse_num(val)\n if self.type == 'string_list':\n return val.split('\\n')\n if self.type == 'number_list':\n return [_parse_num(l) for l in val.split('\\n') if l.strip()]\n return val\n\n @property\n def api_val(self):\n if self.type == 'boolean':\n return self.value == '1'\n return self.value\n\n def __init__(self, name=None, type=None):\n self.name = name\n self.type = type\n\n @classmethod\n def update_list(cls, parameters, obj=None):\n arg_param_ids = []\n for arg_param in parameters:\n param = None\n if arg_param.get('id') is not None:\n # Updating\n param = Param.find(arg_param.get('id'))\n else:\n # Creating\n param = Param()\n if obj and obj.__class__.__name__ == 'Pipeline':\n param.pipeline_id = obj.id\n elif obj and obj.__class__.__name__ == 'Job':\n param.job_id = obj.id\n param.name = arg_param['name']\n param.type = arg_param['type']\n if arg_param['type'] == 'boolean':\n param.value = arg_param['value']\n else:\n param.value = arg_param['value'].encode('utf-8')\n param.save()\n arg_param_ids.append(param.id)\n # Removing\n ids_for_removing = []\n params = obj.params if obj else Param.where(pipeline_id=None,\n job_id=None).all()\n for param in params:\n if param.id not in arg_param_ids:\n ids_for_removing.append(param.id)\n Param.destroy(*ids_for_removing)\n\n\nclass StartCondition(BaseModel):\n __tablename__ = 'start_conditions'\n id = Column(Integer, primary_key=True, autoincrement=True)\n job_id = Column(Integer, ForeignKey('jobs.id'))\n preceding_job_id = Column(Integer, ForeignKey('jobs.id'))\n condition = Column(String(255))\n\n job = relationship(\"Job\", foreign_keys=[job_id])\n preceding_job = relationship(\"Job\", foreign_keys=[preceding_job_id])\n\n def __init__(self, job_id=None, preceding_job_id=None, condition=None):\n self.job_id = job_id\n self.preceding_job_id = preceding_job_id\n self.condition = condition\n\n @property\n def preceding_job_name(self):\n return self.preceding_job.name\n\n @property\n def value(self):\n return ','.join([str(self.preceding_job_id), self.condition])\n\n @classmethod\n def parse_value(cls, value):\n return {\n \"id\": int(value['preceding_job_id']),\n \"condition\": value['condition']\n }\n\n\nclass Schedule(BaseModel):\n __tablename__ = 'schedules'\n id = Column(Integer, primary_key=True, autoincrement=True)\n pipeline_id = Column(Integer, ForeignKey('pipelines.id'))\n cron = Column(String(255))\n\n pipeline = relationship('Pipeline', foreign_keys=[pipeline_id])\n\n\nclass GeneralSetting(BaseModel):\n __tablename__ = 'general_settings'\n id = Column(Integer, primary_key=True, autoincrement=True)\n name = Column(String(255))\n value = Column(Text())\n\n\nclass Stage(BaseModel):\n __tablename__ = 'stages'\n id = Column(Integer, primary_key=True, autoincrement=True)\n sid = Column(String(255))\n\n def assign_attributes(self, attributes):\n for key, value in attributes.iteritems():\n self.__setattr__(key, value)\n","sub_path":"backends/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":18419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"370537579","text":"'''\nBasic Feature set\n1. Total dom num;\n2. Is IP in hostname;\n3. The creation date of URL;\n4. Is there a creation date for URL.\n'''\n\nfrom urllib.parse import urlparse\nimport whois\nimport tldextract\nimport pandas as pd\nimport numpy as np\nfrom tempfile import TemporaryFile\n\npd.set_option('display.max_columns', 10000)\npd.set_option('display.max_rows', 10000)\npd.set_option('display.max_colwidth', 10000)\npd.set_option('display.width',1000)\nnp.set_printoptions(threshold=np.inf)\n\nAll_Known_TLD = ['com', 'at', 'uk', 'pl', 'be', 'biz', 'co', 'jp', 'co_jp', 'cz', 'de', 'eu', 'fr', 'info', 'it', 'ru', 'lv', 'me', 'name', 'net', 'nz', 'org', 'us']\n\ndataset_path = '../Data/train_dataset.csv'\nBasic_Feature_path = 'Basic_FeatureSet.npy'\n\n# Get total dot num in URL\ndef get_dot_num(url):\n\n dot = '.'\n count = 0\n for i in url:\n if i == dot:\n count += 1\n return count\n\n# Whether IP in host-name.\n# If IP in host-name, return 0; else 1\ndef is_ip_hostname(url):\n\n hostname = urlparse(url).netloc\n for i in hostname:\n if i.isdigit() == False:\n return 0\n else:\n return 1\n\n# Whois Creation date\ndef whois_creation_date(url):\n\n try:\n cd = whois.query(url).creation_date\n if cd is not None or 'None':\n year = str(cd.year)\n month = str(cd.month)\n if len(month) == 1:\n month = '0' + month\n day = str(cd.day)\n if len(day) == 1:\n day = '0'+ day\n return (year+month+day)\n else:\n return 0\n except Exception as e:\n return 0\n\n# Is Creation date\ndef is_creation_date(url):\n\n cd = whois_creation_date(url)\n if cd is not 0:\n return 1\n else:\n return 0\n\nif __name__ == '__main__':\n\n ## 1. Read the training Dataset file\n df = pd.read_csv(dataset_path, header=0)\n # print(df.head())\n\n ## 2. Get the Basic Feature set\n url = df['URL']\n total_dot = []\n is_ip_in_hostname = []\n creation_date = []\n is_creation_date_value = []\n\n for i in url:\n total_dot.append(get_dot_num(i))\n is_ip_in_hostname.append(is_ip_hostname(i))\n creation_date.append(whois_creation_date(i))\n # if whois_creation_date(i) is not 0:\n # print('creation date: ',whois_creation_date(i))\n # print('url index', creation_date.index(whois_creation_date(i)))\n # creation date / index: 20070905 / 1482\n # creation date / index: 19860902 / 6734\n is_creation_date_value.append(is_creation_date(i))\n\n # print(len(total_dot))\n # print(len(is_ip_in_hostname))\n # print(len(creation_date))\n # print(len(is_creation_date_value))\n # print('total dot: ',total_dot[:10])\n # print('is ip in hostname: ',is_ip_in_hostname[:10])\n # print('creation date: ',creation_date[:10])\n # print('is creation date: ',is_creation_date_value[:10])\n\n\n ## 3. Form the Basic Feature Set\n Basic_Feature = np.array((total_dot,is_ip_in_hostname,creation_date,is_creation_date_value)).T\n\n # print('Basic_Feature.shape=',Basic_Feature.shape)\n # (4,7000)\n\n\n ## 4. Save the Basic Feature set\n np.save('Basic_FeatureSet.npy', Basic_Feature)\n\n\n ## 5. Load the Basic Feature set\n basic = np.load(Basic_Feature_path)\n # print('basic.shape=',basic.shape)\n # print(basic)","sub_path":"Feature Comparison/Basic.py","file_name":"Basic.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"342482119","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport theano\nimport theano.tensor as T\nimport numpy as np\nimport numbers\nfrom product_space import ProductSpace\nfrom tools import format_table, SwallowInitArgs\nimport debug\n\nlogger = debug.get_logger(__name__)\n\n\nclass LogLinearModel(SwallowInitArgs):\n\n pretty_print_feature_set = True\n sort_by_abs = True\n sort_reversed = True\n\n def __init__(self,\n prediction_space=None,\n feature_set=None,\n feature_weights=None,\n l1_init=0,\n l1_limit=None,\n l1_transition_scale=1,\n l2=0,\n hyper1=0,\n hyper2=0,\n data=None,\n conditional_data=None,\n adapt_prediction_space=None,\n verbosity=0,\n **kwargs):\n \"\"\"\n Initialize a log-linear model\n :param prediction_space: Domain of the predictive function represented by the model. This can\n either be a list of values explicitly defining the domain or a list of lists of values defining\n separate factors where the actual predictions space is the product space of the factor's spaces.\n If prediction_space is None (default) and data is given the prediction space is adapted by computing\n the unique values occurring in the data (beware: this might not be what you want, especially for sparse data)\n :param feature_set: The initial feature set.\n :param feature_weights: The weights for the initial feature set. If None (default) weights will be initialized as zero.\n :param l1_init: The L1 regularization strength. If a scalar is given (default: 0) it is applied to all features.\n If a vector is given it is applied to each feature separately.\n :param l2: The L2 regularization strength. If a scalar is given (default: 0) it is applied to all features.\n If a vector is given it is applied to each feature separately.\n :param hyper1: a hyperbolic regularization (using absolute values)\n :param hyper1: a hyperbolic regularization (using squared values)\n :param data: The data to be predicted.\n :param conditional_data: Data to condition the prediction on.\n :param adapt_prediction_space: whether to adapt the prediction space when setting data\n :param verbosity: a level of verbosity for progress information\n \"\"\"\n super(LogLinearModel, self).__init__(**kwargs)\n self._feature_matrix_outdated = True\n self._prediction_space = None\n self.set_prediction_space(prediction_space)\n if feature_set is None:\n feature_set = []\n self._feature_set = None\n self._feature_weights = None\n self.set_features(feature_set, feature_weights)\n self._l1_init = None\n self._l1_limit = None\n self._l1_transition_scale = None\n self.set_l1(l1_init, l1_limit, l1_transition_scale)\n self._l2 = None\n self.set_l2(l2)\n self._hyper1 = None\n self._hyper2 = None\n self.set_hyper(hyper1, hyper2)\n self._data = None\n self._conditional_data = None\n if adapt_prediction_space is None:\n adapt_prediction_space = data is not None and self._prediction_space is None\n self.set_data(data=data,\n conditional_data=conditional_data,\n adapt_prediction_space=adapt_prediction_space)\n self._feature_matrix = np.array([[]])\n self._output_indices = np.array([], dtype=np.int32)\n self._cross_entropy = None\n self._cross_entropy_grad = None\n self._cross_entropy_split = None\n self._cross_entropy_grad_split = None\n self._data_predictions = None\n self._objective_initalized = False\n self._verbosity = verbosity\n\n def __repr__(self):\n s = \"Log-Linear-Model:\\n\" \\\n \" prediction space: {}\\n\" \\\n \" L1:\\n\" \\\n \" init: {}\\n\" \\\n \" limit: {}\\n\" \\\n \" trans: {}\\n\" \\\n \" L2: {}\\n\" \\\n \" hyper1: {}\\n\" \\\n \" hyper2: {}\".format(\n self._prediction_space,\n self._l1_init,\n self._l1_limit,\n self._l1_transition_scale,\n self._l2,\n self._hyper1,\n self._hyper2\n )\n if LogLinearModel.pretty_print_feature_set:\n s += \" feature set (size: {}):\\n\".format(len(self._feature_set))\n if self._feature_set:\n feature_list = []\n for w, f in sorted(zip(self._feature_weights, self._feature_set),\n key=lambda wf: abs(wf[0]) if\n LogLinearModel.sort_by_abs else wf[0],\n reverse=LogLinearModel.sort_reversed):\n feature_list.append((str(w), str(f)))\n max_w_width = max([len(wf[0]) for wf in feature_list])\n max_f_width = max([len(wf[1]) for wf in feature_list])\n for wf in feature_list:\n s += \" {} : {}\\n\".format(wf[0].ljust(max_w_width), wf[1].ljust(max_f_width))\n else:\n s += \" empty\"\n else:\n s += \" feature set (size: {}): {}\\n\" \\\n \" feature weights: {}\\n\".format(\n len(self._feature_set),\n self._feature_set,\n self._feature_weights,\n )\n return s\n\n def set_prediction_space(self, prediction_space):\n if prediction_space is None or isinstance(prediction_space, ProductSpace):\n self._prediction_space = prediction_space\n else:\n self._prediction_space = ProductSpace(factors=prediction_space)\n self._feature_matrix_outdated = True\n\n def get_features(self):\n return self._feature_set\n\n def set_features(self, feature_set, feature_weights=None):\n self._feature_set = list(feature_set)\n self._feature_matrix_outdated = True\n if feature_weights is None:\n feature_weights = np.zeros(len(self._feature_set))\n self.set_parameters(feature_weights)\n\n def get_parameters(self):\n return self._feature_weights\n\n def set_parameters(self, feature_weights):\n self._feature_weights = np.array(feature_weights)\n if len(self._feature_weights) != len(self._feature_set):\n raise UserWarning(\"Length of weight vector does not match number of features\")\n\n def set_l1(self, l1=None, l1_limit=None, l1_transition_scale=None):\n if l1 is not None:\n self._l1_init = l1\n if l1_limit is not None:\n self._l1_limit = l1_limit\n if l1_transition_scale is not None:\n self._l1_transition_scale = l1_transition_scale\n\n def set_l2(self, l2):\n \"\"\"\n Set L2 regularization\n :param l2: L2 regularization strength (scalar or length-n vector for feature set of size n) \n \"\"\"\n self._l2 = l2\n\n def set_hyper(self, hyper1=None, hyper2=None):\n \"\"\"\n Set hyperbolic regularization. Either one can be left unchanged by passing None.\n :param hyper1: hyperbolic regularization strength (scalar, length-n vector, or nxn-matrix for\n feature set of size n)\n :param hyper2: like hyper1 but using squared values instead of absolute values\n \"\"\"\n if hyper1 is not None:\n self._hyper1 = hyper1\n if hyper2 is not None:\n self._hyper2 = hyper2\n\n def vectorize_regularization(self, reg):\n n = len(self._feature_weights)\n if reg is None:\n pass\n elif callable(reg):\n # invoke callable with index and feature set\n reg = np.array([reg(f_idx, self._feature_set) for f_idx in range(n)])\n elif isinstance(reg, numbers.Number):\n # fill vector with value\n reg = np.ones(n) * reg\n else:\n # directly use as vector\n reg = np.array(reg)\n return reg\n\n def generate_hyper_regularization(self, reg):\n # generate hyperbolic regularization matrix\n n = len(self._feature_weights)\n if callable(reg):\n reg = np.array([\n [reg(f1_idx, f2_idx, self._feature_set) for f1_idx in\n range(len(self._feature_set))]\n for f2_idx in range(len(self._feature_set))\n ])\n elif isinstance(reg, numbers.Number):\n # construct uniformly filled matrix with zero diagonal\n reg = np.ones((n, n)) * reg\n np.fill_diagonal(reg, 0)\n else:\n # expect vector or matrix\n h = np.array(reg)\n if len(h.shape) == 1:\n # construct matrix as outer product of vector\n reg = np.outer(h, h)\n # set diagonal to zero\n np.fill_diagonal(reg, 0)\n elif len(h.shape) == 2:\n # apply given matrix directly\n reg = h\n else:\n raise UserWarning(\"Hyperbolic regularization has unexpected shape: {}\".format(reg.shape))\n return reg\n\n def get_effective_l1(self, l1_init=True, l1_limit=False, l1_transition_scale=False):\n # compute effective values, check for non-negativity, and construct return tuple\n ret = ()\n if l1_init:\n eff_l1_init = self.vectorize_regularization(self._l1_init)\n if min(eff_l1_init) < 0:\n raise UserWarning(\"L1-regularization (init) should be non-negative but is {}\".format(eff_l1_init))\n ret += (eff_l1_init,)\n if l1_limit:\n eff_l1_limit = self.vectorize_regularization(\n self._l1_limit if self._l1_limit is not None else self._l1_init\n )\n if min(eff_l1_limit) < 0:\n raise UserWarning(\"L1-regularization (limit) should be non-negative but is {}\".format(eff_l1_limit))\n ret += (eff_l1_limit,)\n if l1_transition_scale:\n eff_l1_transition_scale = self.vectorize_regularization(self._l1_transition_scale)\n if min(eff_l1_transition_scale) < 0:\n raise UserWarning(\"L1-regularization (transition scale) should be non-negative but is {}\".format(\n eff_l1_transition_scale))\n ret += (eff_l1_transition_scale,)\n # return single value or tuple\n if len(ret) == 1:\n return ret[0]\n else:\n return ret\n\n def get_effective_l2(self):\n return self.vectorize_regularization(self._l2)\n\n def get_effective_hyper(self, hyper1=True, hyper2=False):\n ret = ()\n if hyper1:\n ret += (self.generate_hyper_regularization(self._hyper1),)\n if hyper2:\n ret += (self.generate_hyper_regularization(self._hyper2),)\n if len(ret) == 1:\n return ret[0]\n else:\n return ret\n\n def ensure_objective_is_initialized(self):\n if not self._objective_initalized:\n feature_matrix = T.tensor3(name='feature_matrix')\n feature_weights_pos = T.vector(name='feature_weights_pos')\n feature_weights_neg = T.vector(name='feature_weights_neg')\n feature_weights = feature_weights_pos - feature_weights_neg\n l1_init = T.vector(name='l1_init')\n l1_limit = T.vector(name='l1_limit')\n l1_transition_scale = T.vector(name='l1_transition_scale')\n l2 = T.vector(name='l2')\n hyper1 = T.matrix(name='hyper1')\n hyper2 = T.matrix(name='hyper2')\n l1_rescale = T.scalar('l1_rescale')\n output_indices = T.ivector(name='output_indices')\n for split in [None, True, False]:\n # take exp of scalar product\n cross_entropy = np.exp(feature_matrix.dot(feature_weights))\n # normalize along output dimension\n cross_entropy /= cross_entropy.sum(axis=1, keepdims=True)\n # pick output matching data (see:\n # https://stackoverflow.com/questions/33947726/indexing-tensor-with-index-matrix-in-theano)\n cross_entropy = cross_entropy[T.arange(cross_entropy.shape[0]), output_indices]\n if split is None:\n self._data_predictions = theano.function(\n [feature_matrix,\n feature_weights,\n output_indices],\n cross_entropy)\n else:\n # compute expected neg-log-probability i.e. cross-entropy\n cross_entropy = - np.log(cross_entropy).mean()\n # add l2\n cross_entropy += (feature_weights ** 2).dot(l2)\n # add hyperbolic\n cross_entropy += l1_rescale * abs(feature_weights).dot(hyper1).dot(abs(feature_weights))\n cross_entropy += (feature_weights ** 2).dot(hyper2).dot(feature_weights ** 2)\n # add l1 (limiting term)\n cross_entropy += l1_rescale * abs(feature_weights).dot(\n (l1_limit - l1_init) * abs(feature_weights) / (abs(feature_weights) + l1_transition_scale)\n )\n if split:\n cross_entropy += l1_rescale * feature_weights_pos.dot(l1_init)\n cross_entropy += l1_rescale * feature_weights_neg.dot(l1_init)\n # create functions\n self._cross_entropy_split = theano.function(\n [feature_matrix,\n feature_weights_pos,\n feature_weights_neg,\n output_indices,\n l1_init,\n l1_limit,\n l1_transition_scale,\n l2,\n hyper1,\n hyper2,\n l1_rescale],\n cross_entropy)\n self._cross_entropy_grad_split = theano.function(\n [feature_matrix,\n feature_weights_pos,\n feature_weights_neg,\n output_indices,\n l1_init,\n l1_limit,\n l1_transition_scale,\n l2,\n hyper1,\n hyper2,\n l1_rescale],\n theano.grad(cross_entropy, [feature_weights_pos, feature_weights_neg]))\n else:\n cross_entropy += l1_rescale * abs(feature_weights).dot(l1_init)\n # create functions\n self._cross_entropy = theano.function(\n [feature_matrix,\n feature_weights,\n output_indices,\n l1_init,\n l1_limit,\n l1_transition_scale,\n l2,\n hyper1,\n hyper2,\n l1_rescale],\n cross_entropy)\n self._cross_entropy_grad = theano.function(\n [feature_matrix,\n feature_weights,\n output_indices,\n l1_init,\n l1_limit,\n l1_transition_scale,\n l2,\n hyper1,\n hyper2,\n l1_rescale],\n theano.grad(cross_entropy, [feature_weights]))\n self._objective_initalized = True\n\n def evaluate_features(self, prediction_data, conditional_data, **kwargs):\n \"\"\"\n Evaluate features on given data.\n \n Features have to be evaluated on the actual prediction_data as well as on all other possible\n predictions (for the normalization) hence the returned is \n a x-matrix\n \n :param prediction_data: data to be predicted; prediction_data may be None (then the returned output_idx\n is -1)\n :param conditional_data: data to condition the prediction on\n :param kwargs: additional key-word arguments that methods in derived classes may take \n :return: feature values and output index of prediction_data\n \"\"\"\n feature_values = np.empty(shape=[len(self._prediction_space), len(self._feature_weights)])\n output_index = -1\n for out_idx, pred in enumerate(self._prediction_space.iterate()):\n if prediction_data == pred:\n output_index = out_idx\n for f_idx, f in enumerate(self._feature_set):\n if conditional_data is None:\n feature_val = f(pred)\n else:\n feature_val = f(pred, conditional_data)\n logger.debug(\"f_idx={}, out_idx={}: f={}\".format(f_idx, out_idx, feature_val))\n feature_values[out_idx, f_idx] = feature_val\n if prediction_data is not None and output_index == -1:\n raise UserWarning(\"Could not find matching output index for '{}'\".format(prediction_data))\n return feature_values, output_index\n\n def prediction(self, prediction_data, conditional_data=None, return_output_index=False, **kwargs):\n \"\"\"\n Return the probability for the given prediction_data conditional on conditional_data\n :param prediction_data: data to be predicted; if None the whole distribution is returned\n and the output index (if returned) is -1\n :param conditional_data: data to condition the prediction on\n :param return_output_index: whether to return the output index of the prediction_data\n :param kwargs: additional key-word arguments that methods in derived classes may take\n :return: probability for given prediction_data or complete distribution; and possibly output index\n \"\"\"\n feature_values, output_index = self.evaluate_features(prediction_data=prediction_data,\n conditional_data=conditional_data,\n **kwargs)\n p = np.exp(np.dot(feature_values, self._feature_weights))\n logger.debug(\"feature values:\\n\"\n \" {}\\n\"\n \"unnormalized distribution:\\n\"\n \" {}\".format(feature_values, p))\n if prediction_data is None:\n if return_output_index:\n return p / p.sum(), output_index\n else:\n return p / p.sum()\n else:\n if return_output_index:\n return p[output_index] / p.sum(), output_index\n else:\n return p[output_index] / p.sum()\n\n def set_data(self, data, conditional_data, adapt_prediction_space, **kwargs):\n self._data = data\n self._conditional_data = conditional_data\n if adapt_prediction_space:\n self._prediction_space = ProductSpace(factors=[sorted(np.unique(data))])\n self._feature_matrix_outdated = True\n\n def data_predictions(self, weights=None, **kwargs):\n # check for missing data\n if self._data is None:\n raise UserWarning(\"Cannot compute data predictions: Data is 'None'\")\n # handle empty feature set or compute\n if not self._feature_set:\n return []\n else:\n if weights is None:\n weights = self._feature_weights\n self.ensure_feature_matrix_is_up_to_date()\n self.ensure_objective_is_initialized()\n return self._data_predictions(self._feature_matrix,\n weights,\n self._output_indices)\n\n def quality(self,\n weights=None,\n weights_pos=None,\n weights_neg=None,\n l1_rescale=1,\n quality=True,\n gradient=False,\n **kwargs):\n \"\"\"quality returns the negative cross-entropy\"\"\"\n # check for missing data\n if self._data is None:\n raise UserWarning(\"Cannot compute model quality: Data is 'None'\")\n # determine whether to use split weights\n split = False\n if weights_pos is None and weights_neg is None and weights is None:\n # use stored weights\n weights = self._feature_weights\n elif weights_pos is None and weights_neg is None and weights is not None:\n # use provided weights\n pass\n elif weights_pos is not None and weights_neg is not None and weights is None:\n # use split weights\n split = True\n else:\n raise UserWarning(\"Contradicting weight information provided. Provide either 'weights' or \"\n \"'weights_pos' and 'weights_neg' or none of all. Provided weights are:\\n\"\n \" weights: {}\\n\"\n \" weights_pos: {}\\n\"\n \" weights_neg: {}\".format(weights, weights_pos, weights_neg))\n # handle empty feature set or compute quality\n if not self._feature_set:\n # quality corresponds to the neg-cross-entropy of the uniform distribution (regularization is zero)\n if quality:\n q = np.log(1 / len(self._prediction_space))\n if gradient:\n if split:\n g = np.array([[], []])\n else:\n g = np.array([])\n else:\n # get effective L1 and hyper regularization\n l1_init, l1_limit, l1_transition_scale = self.get_effective_l1(l1_init=True,\n l1_limit=True,\n l1_transition_scale=True)\n l2 = self.get_effective_l2()\n hyper1, hyper2 = self.get_effective_hyper(hyper1=True, hyper2=True)\n # update feature matrix\n self.ensure_feature_matrix_is_up_to_date()\n # initialize objective\n self.ensure_objective_is_initialized()\n if split:\n if quality:\n q = self._cross_entropy_split(self._feature_matrix,\n weights_pos,\n weights_neg,\n self._output_indices,\n l1_init,\n l1_limit,\n l1_transition_scale,\n l2,\n hyper1,\n hyper2,\n l1_rescale) * -1\n if gradient:\n g = np.array(self._cross_entropy_grad_split(self._feature_matrix,\n weights_pos,\n weights_neg,\n self._output_indices,\n l1_init,\n l1_limit,\n l1_transition_scale,\n l2,\n hyper1,\n hyper2,\n l1_rescale)) * -1\n else:\n if quality:\n q = self._cross_entropy(self._feature_matrix,\n weights,\n self._output_indices,\n l1_init,\n l1_limit,\n l1_transition_scale,\n l2,\n hyper1,\n hyper2,\n l1_rescale) * -1\n if gradient:\n g = self._cross_entropy_grad(self._feature_matrix,\n weights,\n self._output_indices,\n l1_init,\n l1_limit,\n l1_transition_scale,\n l2,\n hyper1,\n hyper2,\n l1_rescale)[0] * -1\n # return quality and/or gradient\n if quality and gradient:\n return q, g\n elif quality:\n return q\n elif gradient:\n return g\n else:\n return None\n\n def ensure_feature_matrix_is_up_to_date(self):\n if self._feature_matrix_outdated:\n if self._data is None:\n raise UserWarning(\"Cannot update feature matrix: Data is 'None'\")\n self._feature_matrix = np.zeros((len(self._data), len(self._prediction_space), len(self._feature_set)))\n self._output_indices = np.zeros(len(self._data), dtype=np.int32) - 1\n if self._feature_set:\n for data_idx, prediction_data in enumerate(self._data):\n conditional_data = self._conditional_data[data_idx] if self._conditional_data is not None else None\n feature_values, output_index = self.evaluate_features(prediction_data=prediction_data,\n conditional_data=conditional_data)\n self._feature_matrix[data_idx] = feature_values\n self._output_indices[data_idx] = output_index\n if self._output_indices[data_idx] == -1:\n raise UserWarning(\"Could not find output index for output '{}' in data point #{}\".format(prediction_data, data_idx))\n self._feature_matrix_outdated = False\n\n def analyze_data(self):\n table = []\n # go through data\n for data_idx, prediction_data in enumerate(self._data):\n # add new row for each data point\n table.append([])\n # determine conditional data and probability\n conditional_data = self._conditional_data[data_idx] if self._conditional_data is not None else None\n p = self.prediction(prediction_data=prediction_data,\n conditional_data=conditional_data)\n # add to table\n table[-1].append('p(')\n table[-1].append(prediction_data)\n if conditional_data is not None:\n table[-1].append('|')\n table[-1].append(conditional_data)\n table[-1].append('): ')\n table[-1].append(p)\n table[-1].append(' {')\n # determine feature values and add to table\n for f_idx, f in enumerate(self._feature_set):\n if conditional_data is None:\n feature_val = f(prediction_data)\n else:\n feature_val = f(prediction_data, conditional_data)\n if f_idx != 0:\n table[-1].append(', ')\n table[-1].append(feature_val)\n table[-1].append(' ← ')\n table[-1].append(f)\n table[-1].append('}')\n # format table and print\n for row in format_table(table):\n for col in row:\n print(col, end='')\n print('')","sub_path":"log_linear_model.py","file_name":"log_linear_model.py","file_ext":"py","file_size_in_byte":28780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"460426597","text":"from apps.API_VK.command.CommonCommand import CommonCommand\nfrom apps.service.models import Cat as CatModel\nfrom xoma163site.settings import MAIN_SITE\n\n\ndef add_cat(cat_image):\n cat = CatModel(author=cat_image['author'])\n cat.save_remote_image(cat_image['url'])\n cat.save()\n return MAIN_SITE + cat.image.url\n\n\nclass Cat(CommonCommand):\n def __init__(self):\n names = [\"кот\"]\n help_text = \"Кот - добавить всратого кота в базу\"\n detail_help_text = \"Кот + вложение/пересылаемое сообщение с вложением - добавляет кота в БД\"\n super().__init__(names, help_text, detail_help_text, api=False)\n\n def start(self):\n from apps.API_VK.VkBotClass import parse_attachments\n\n if not (self.vk_event.attachments or self.vk_event.fwd):\n return \"Пришлите фотографии или перешлите сообщения с фотографиями\"\n\n cat_images = []\n if self.vk_event.attachments:\n for attachment in self.vk_event.attachments:\n cat_images.append({'url': attachment['url'], 'author': self.vk_event.sender})\n\n if self.vk_event.fwd:\n for msg in self.vk_event.fwd:\n attachments = parse_attachments(msg['attachments'])\n if attachments:\n for attachment in attachments:\n if msg['from_id'] > 0:\n msg_user_id = int(msg['from_id'])\n author = self.vk_bot.get_user_by_id(msg_user_id)\n else:\n author = None\n cat_images.append({'url': attachment['url'], 'author': author})\n if len(cat_images) > 0:\n new_urls = []\n for cat_image in cat_images:\n new_url = add_cat(cat_image)\n new_urls.append(new_url)\n return \"\\n\".join(new_urls)\n else:\n return \"В пересланных сообщениях ��ет фотографий\"\n","sub_path":"apps/API_VK/command/commands/Cat.py","file_name":"Cat.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"30708260","text":"import logging\n\nfrom bs4 import BeautifulSoup\n\nfrom storescraper.categories import HEADPHONES, MOUSE, KEYBOARD\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy\n\n\nclass WarenHouse(Store):\n @classmethod\n def categories(cls):\n return [\n HEADPHONES,\n MOUSE,\n KEYBOARD\n ]\n\n @classmethod\n def discover_urls_for_category(cls, category, extra_args=None):\n url_extensions = [\n ['accesorios-pc-gaming-audifonos', HEADPHONES],\n ['computacion/perifericos-accesorios/mouses', MOUSE],\n ['computacion/perifericos-accesorios/teclados', KEYBOARD]\n ]\n session = session_with_proxy(extra_args)\n product_urls = []\n for url_extension, local_category in url_extensions:\n if local_category != category:\n continue\n page = 1\n while True:\n if page > 100:\n raise Exception('page overflow: ' + url_extension)\n url_webpage = 'https://www.warenhouse.cl/listado/{}/' \\\n '_Desde_{}'.format(url_extension, page)\n print(url_webpage)\n data = session.get(url_webpage).text\n soup = BeautifulSoup(data, 'html.parser')\n product_containers = soup.findAll('li',\n 'ui-search-layout__item')\n if not product_containers:\n if page == 1:\n logging.warning('Empty category: ' + url_extension)\n break\n for container in product_containers:\n product_url = container.find('a')['href']\n if product_url in product_urls:\n return product_urls\n product_urls.append(product_url)\n page += 48\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n from .mercado_libre_chile import MercadoLibreChile\n products = MercadoLibreChile.products_for_url(url, category,\n extra_args)\n for product in products:\n product.seller = None\n\n return products\n","sub_path":"storescraper/stores/waren_house.py","file_name":"waren_house.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"256546075","text":"import cv2\n#openCV无需知道算法逻辑,无需进行模型训练\n'''打开图像'''\nimg = cv2.imread('./img/meinv.png')\n\nif len(img.shape)==1:\n #转化为numpy数组\n gray = cv2.cvtColor(img,cv2.COLOR_BAYER_BG2GRAY)\nelse:\n gray = img\n#检测器\nface_cascade = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml')\nface = face_cascade.detectMultiScale(gray,1.01,3)\nprint(face)\nfor (x,y,w,h) in face:\n cut_face = cv2.rectangle(img,(x, y), (x+w, y+h),(255,0,0))\n#创建窗口\ncv2.namedWindow('Image')\n\n#在窗口中显示图像\ncv2.imshow('Image',img)\n\n#通过键盘关闭窗口\ncv2.waitKey(0)\n\n#释放窗口\ncv2.destroyAllWindows()","sub_path":"read_imgs.py","file_name":"read_imgs.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"330171870","text":"# Copyright 2013 Hewlett-Packard Development Company, L.P.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\nfrom mockito import mock, when, verify, unstub, any\nfrom testtools import TestCase\nfrom testtools.matchers import Equals, Is, Not\n\nfrom novaclient.v1_1 import Client\nfrom novaclient.v1_1.flavors import FlavorManager, Flavor\nfrom novaclient.v1_1.servers import Server, ServerManager\nfrom oslo.config.cfg import ConfigOpts\nfrom trove.backup.models import Backup\nfrom trove.common.context import TroveContext\nfrom trove.common import instance as rd_instance\nfrom trove.datastore import models as datastore_models\nfrom trove.db.models import DatabaseModelBase\nfrom trove.instance.models import DBInstance\nfrom trove.instance.models import InstanceServiceStatus\nfrom trove.instance.tasks import InstanceTasks\nimport trove.extensions.mgmt.instances.models as mgmtmodels\nfrom trove.openstack.common.notifier import api as notifier\nfrom trove.common import remote\nfrom trove.tests.util import test_config\n\n\nclass MockMgmtInstanceTest(TestCase):\n def setUp(self):\n super(MockMgmtInstanceTest, self).setUp()\n self.context = TroveContext()\n self.context.auth_token = 'some_secret_password'\n self.client = mock(Client)\n self.server_mgr = mock(ServerManager)\n self.client.servers = self.server_mgr\n self.flavor_mgr = mock(FlavorManager)\n self.client.flavors = self.flavor_mgr\n when(remote).create_admin_nova_client(self.context).thenReturn(\n self.client)\n when(ConfigOpts)._get('host').thenReturn('test_host')\n when(ConfigOpts)._get('exists_notification_ticks').thenReturn(1)\n when(ConfigOpts)._get('report_interval').thenReturn(20)\n when(ConfigOpts)._get('notification_service_id').thenReturn(\n {'mysql': '123'})\n\n def tearDown(self):\n super(MockMgmtInstanceTest, self).tearDown()\n unstub()\n\n @staticmethod\n def build_db_instance(status, task_status=InstanceTasks.DELETING):\n return DBInstance(task_status,\n created='xyz',\n name='test_name',\n id='1',\n flavor_id='flavor_1',\n datastore_version_id=\n test_config.dbaas_datastore_version_id,\n compute_instance_id='compute_id_1',\n server_id='server_id_1',\n tenant_id='tenant_id_1',\n server_status=status)\n\n\nclass TestNotificationTransformer(MockMgmtInstanceTest):\n def test_tranformer(self):\n transformer = mgmtmodels.NotificationTransformer(context=self.context)\n status = rd_instance.ServiceStatuses.BUILDING.api_status\n db_instance = MockMgmtInstanceTest.build_db_instance(\n status, InstanceTasks.BUILDING)\n\n when(DatabaseModelBase).find_all(deleted=False).thenReturn(\n [db_instance])\n stub_dsv_db_info = mock(datastore_models.DBDatastoreVersion)\n stub_dsv_db_info.id = \"test_datastore_version\"\n stub_dsv_db_info.datastore_id = \"mysql_test_version\"\n stub_dsv_db_info.name = \"test_datastore_name\"\n stub_dsv_db_info.image_id = \"test_datastore_image_id\"\n stub_dsv_db_info.packages = \"test_datastore_pacakges\"\n stub_dsv_db_info.active = 1\n stub_dsv_db_info.manager = \"mysql\"\n stub_datastore_version = datastore_models.DatastoreVersion(\n stub_dsv_db_info)\n when(DatabaseModelBase).find_by(id=any()).thenReturn(\n stub_datastore_version)\n\n when(DatabaseModelBase).find_by(instance_id='1').thenReturn(\n InstanceServiceStatus(rd_instance.ServiceStatuses.BUILDING))\n\n payloads = transformer()\n self.assertIsNotNone(payloads)\n self.assertThat(len(payloads), Equals(1))\n payload = payloads[0]\n self.assertThat(payload['audit_period_beginning'], Not(Is(None)))\n self.assertThat(payload['audit_period_ending'], Not(Is(None)))\n self.assertThat(payload['state'], Equals(status.lower()))\n\n def test_get_service_id(self):\n id_map = {\n 'mysql': '123',\n 'percona': 'abc'\n }\n transformer = mgmtmodels.NotificationTransformer(context=self.context)\n self.assertThat(transformer._get_service_id('mysql', id_map),\n Equals('123'))\n\n def test_get_service_id_unknown(self):\n id_map = {\n 'mysql': '123',\n 'percona': 'abc'\n }\n transformer = mgmtmodels.NotificationTransformer(context=self.context)\n self.assertThat(transformer._get_service_id('m0ng0', id_map),\n Equals('unknown-service-id-error'))\n\n\nclass TestNovaNotificationTransformer(MockMgmtInstanceTest):\n def test_transformer_cache(self):\n flavor = mock(Flavor)\n flavor.name = 'db.small'\n when(self.flavor_mgr).get('flavor_1').thenReturn(flavor)\n transformer = mgmtmodels.NovaNotificationTransformer(\n context=self.context)\n transformer2 = mgmtmodels.NovaNotificationTransformer(\n context=self.context)\n self.assertThat(transformer._flavor_cache,\n Not(Is(transformer2._flavor_cache)))\n\n def test_lookup_flavor(self):\n flavor = mock(Flavor)\n flavor.name = 'flav_1'\n when(self.flavor_mgr).get('1').thenReturn(flavor)\n transformer = mgmtmodels.NovaNotificationTransformer(\n context=self.context)\n self.assertThat(transformer._lookup_flavor('1'), Equals(flavor.name))\n self.assertThat(transformer._lookup_flavor('2'), Equals('unknown'))\n\n def test_tranformer(self):\n status = rd_instance.ServiceStatuses.BUILDING.api_status\n db_instance = MockMgmtInstanceTest.build_db_instance(\n status, task_status=InstanceTasks.BUILDING)\n\n stub_dsv_db_info = mock(datastore_models.DBDatastoreVersion)\n stub_dsv_db_info.id = \"test_datastore_version\"\n stub_dsv_db_info.datastore_id = \"mysql_test_version\"\n stub_dsv_db_info.name = \"test_datastore_name\"\n stub_dsv_db_info.image_id = \"test_datastore_image_id\"\n stub_dsv_db_info.packages = \"test_datastore_pacakges\"\n stub_dsv_db_info.active = 1\n stub_dsv_db_info.manager = \"mysql\"\n stub_datastore_version = datastore_models.DatastoreVersion(\n stub_dsv_db_info)\n when(DatabaseModelBase).find_by(id=any()).thenReturn(\n stub_datastore_version)\n\n server = mock(Server)\n server.user_id = 'test_user_id'\n mgmt_instance = mgmtmodels.SimpleMgmtInstance(self.context,\n db_instance,\n server,\n None)\n when(mgmtmodels).load_mgmt_instances(\n self.context,\n deleted=False,\n client=self.client).thenReturn(\n [mgmt_instance])\n flavor = mock(Flavor)\n flavor.name = 'db.small'\n when(self.flavor_mgr).get('flavor_1').thenReturn(flavor)\n\n # invocation\n transformer = mgmtmodels.NovaNotificationTransformer(\n context=self.context)\n payloads = transformer()\n # assertions\n self.assertIsNotNone(payloads)\n self.assertThat(len(payloads), Equals(1))\n payload = payloads[0]\n self.assertThat(payload['audit_period_beginning'], Not(Is(None)))\n self.assertThat(payload['audit_period_ending'], Not(Is(None)))\n self.assertThat(payload['state'], Equals(status.lower()))\n self.assertThat(payload['instance_type'], Equals('db.small'))\n self.assertThat(payload['instance_type_id'], Equals('flavor_1'))\n self.assertThat(payload['user_id'], Equals('test_user_id'))\n self.assertThat(payload['service_id'], Equals('123'))\n\n def test_tranformer_invalid_datastore_manager(self):\n status = rd_instance.ServiceStatuses.BUILDING.api_status\n db_instance = MockMgmtInstanceTest.build_db_instance(\n status, task_status=InstanceTasks.BUILDING)\n\n server = mock(Server)\n server.user_id = 'test_user_id'\n stub_datastore_version = mock()\n stub_datastore_version.id = \"stub_datastore_version\"\n stub_datastore_version.manager = \"m0ng0\"\n when(datastore_models.\n DatastoreVersion).load(any(), any()).thenReturn(\n stub_datastore_version)\n when(datastore_models.\n DatastoreVersion).load_by_uuid(any()).thenReturn(\n stub_datastore_version)\n\n stub_datastore = mock()\n stub_datastore.default_datastore_version = \"stub_datastore_version\"\n when(datastore_models.\n Datastore).load(any()).thenReturn(stub_datastore)\n mgmt_instance = mgmtmodels.SimpleMgmtInstance(self.context,\n db_instance,\n server,\n None)\n when(mgmtmodels).load_mgmt_instances(\n self.context,\n deleted=False,\n client=self.client).thenReturn(\n [mgmt_instance])\n flavor = mock(Flavor)\n flavor.name = 'db.small'\n when(self.flavor_mgr).get('flavor_1').thenReturn(flavor)\n\n # invocation\n transformer = mgmtmodels.NovaNotificationTransformer(\n context=self.context)\n payloads = transformer()\n # assertions\n self.assertIsNotNone(payloads)\n self.assertThat(len(payloads), Equals(1))\n payload = payloads[0]\n self.assertThat(payload['audit_period_beginning'], Not(Is(None)))\n self.assertThat(payload['audit_period_ending'], Not(Is(None)))\n self.assertThat(payload['state'], Equals(status.lower()))\n self.assertThat(payload['instance_type'], Equals('db.small'))\n self.assertThat(payload['instance_type_id'], Equals('flavor_1'))\n self.assertThat(payload['user_id'], Equals('test_user_id'))\n self.assertThat(payload['service_id'],\n Equals('unknown-service-id-error'))\n\n def test_tranformer_shutdown_instance(self):\n status = rd_instance.ServiceStatuses.SHUTDOWN.api_status\n db_instance = self.build_db_instance(status)\n\n server = mock(Server)\n server.user_id = 'test_user_id'\n mgmt_instance = mgmtmodels.SimpleMgmtInstance(self.context,\n db_instance,\n server,\n None)\n when(Backup).running('1').thenReturn(None)\n self.assertThat(mgmt_instance.status, Equals('SHUTDOWN'))\n when(mgmtmodels).load_mgmt_instances(\n self.context,\n deleted=False,\n client=self.client).thenReturn(\n [mgmt_instance])\n flavor = mock(Flavor)\n flavor.name = 'db.small'\n when(self.flavor_mgr).get('flavor_1').thenReturn(flavor)\n # invocation\n transformer = mgmtmodels.NovaNotificationTransformer(\n context=self.context)\n payloads = transformer()\n # assertion that SHUTDOWN instances are not reported\n self.assertIsNotNone(payloads)\n self.assertThat(len(payloads), Equals(0))\n\n def test_tranformer_no_nova_instance(self):\n status = rd_instance.ServiceStatuses.SHUTDOWN.api_status\n db_instance = MockMgmtInstanceTest.build_db_instance(status)\n\n mgmt_instance = mgmtmodels.SimpleMgmtInstance(self.context,\n db_instance,\n None,\n None)\n when(Backup).running('1').thenReturn(None)\n self.assertThat(mgmt_instance.status, Equals('SHUTDOWN'))\n when(mgmtmodels).load_mgmt_instances(\n self.context,\n deleted=False,\n client=self.client).thenReturn(\n [mgmt_instance])\n flavor = mock(Flavor)\n flavor.name = 'db.small'\n when(self.flavor_mgr).get('flavor_1').thenReturn(flavor)\n # invocation\n transformer = mgmtmodels.NovaNotificationTransformer(\n context=self.context)\n payloads = transformer()\n # assertion that SHUTDOWN instances are not reported\n self.assertIsNotNone(payloads)\n self.assertThat(len(payloads), Equals(0))\n\n def test_tranformer_flavor_cache(self):\n status = rd_instance.ServiceStatuses.BUILDING.api_status\n db_instance = MockMgmtInstanceTest.build_db_instance(\n status, InstanceTasks.BUILDING)\n\n server = mock(Server)\n server.user_id = 'test_user_id'\n mgmt_instance = mgmtmodels.SimpleMgmtInstance(self.context,\n db_instance,\n server,\n None)\n when(mgmtmodels).load_mgmt_instances(\n self.context,\n deleted=False,\n client=self.client).thenReturn(\n [mgmt_instance])\n flavor = mock(Flavor)\n flavor.name = 'db.small'\n when(self.flavor_mgr).get('flavor_1').thenReturn(flavor)\n transformer = mgmtmodels.NovaNotificationTransformer(\n context=self.context)\n transformer()\n # call twice ensure client.flavor invoked once\n payloads = transformer()\n self.assertIsNotNone(payloads)\n self.assertThat(len(payloads), Equals(1))\n payload = payloads[0]\n self.assertThat(payload['audit_period_beginning'], Not(Is(None)))\n self.assertThat(payload['audit_period_ending'], Not(Is(None)))\n self.assertThat(payload['state'], Equals(status.lower()))\n self.assertThat(payload['instance_type'], Equals('db.small'))\n self.assertThat(payload['instance_type_id'], Equals('flavor_1'))\n self.assertThat(payload['user_id'], Equals('test_user_id'))\n # ensure cache was used to get flavor second time\n verify(self.flavor_mgr).get('flavor_1')\n\n\nclass TestMgmtInstanceTasks(MockMgmtInstanceTest):\n def test_public_exists_events(self):\n status = rd_instance.ServiceStatuses.BUILDING.api_status\n db_instance = MockMgmtInstanceTest.build_db_instance(\n status, task_status=InstanceTasks.BUILDING)\n\n server = mock(Server)\n server.user_id = 'test_user_id'\n mgmt_instance = mgmtmodels.SimpleMgmtInstance(self.context,\n db_instance,\n server,\n None)\n when(mgmtmodels).load_mgmt_instances(\n self.context,\n deleted=False,\n client=self.client).thenReturn(\n [mgmt_instance, mgmt_instance])\n flavor = mock(Flavor)\n flavor.name = 'db.small'\n when(self.flavor_mgr).get('flavor_1').thenReturn(flavor)\n self.assertThat(self.context.auth_token, Is('some_secret_password'))\n when(notifier).notify(self.context,\n any(str),\n 'trove.instance.exists',\n 'INFO',\n any(dict)).thenReturn(None)\n # invocation\n mgmtmodels.publish_exist_events(\n mgmtmodels.NovaNotificationTransformer(context=self.context),\n self.context)\n # assertion\n verify(notifier, times=2).notify(self.context,\n any(str),\n 'trove.instance.exists',\n 'INFO',\n any(dict))\n self.assertThat(self.context.auth_token, Is(None))\n","sub_path":"trove/tests/unittests/mgmt/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":16664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"323081344","text":"#!/usr/bin/env python\n\nfrom ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_argspec\nfrom ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_auth_client\nfrom ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_init\nfrom ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashiwrapper\n\nANSIBLE_METADATA = {'status': ['deprecated'], 'supported_by': 'community', 'version': '1.1'}\nDOCUMENTATION = '''\n---\nmodule: hashivault_approle_role_secret_delete\nversion_added: \"3.8.0\"\nshort_description: Hashicorp Vault approle role secret id delete module\ndescription:\n - Module to delete a approle role secret id from Hashicorp Vault. Use hashivault_approle_role_secret instead.\noptions:\n name:\n description:\n - role name.\n secret:\n description:\n - secret id.\nextends_documentation_fragment: hashivault\n'''\nEXAMPLES = '''\n---\n- hosts: localhost\n tasks:\n - hashivault_approle_role_secret_delete:\n name: 'ashley'\n secret: 'ec4bedee-e44b-c096-9ac8-1600e52ed8f8'\n'''\n\n\ndef main():\n argspec = hashivault_argspec()\n argspec['name'] = dict(required=True, type='str')\n argspec['secret'] = dict(required=True, type='str')\n module = hashivault_init(argspec)\n result = hashivault_approle_role_secret_delete(module.params)\n if result.get('failed'):\n module.fail_json(**result)\n else:\n module.exit_json(**result)\n\n\n@hashiwrapper\ndef hashivault_approle_role_secret_delete(params):\n name = params.get('name')\n secret = params.get('secret')\n client = hashivault_auth_client(params)\n client.delete_role_secret_id(name, secret)\n return {'changed': True}\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"plugins/modules/_hashivault_approle_role_secret_delete.py","file_name":"_hashivault_approle_role_secret_delete.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"28408666","text":"import pytest\nfrom arc import ARC\n\n\n@pytest.fixture(scope=\"module\")\ndef decomposition_samples() -> ARC:\n return ARC(idxs={8, 10, 16, 17, 30})\n\n\n# NOTE: This test is a little ambiguous, as the red object\n# might reasonably be a rectangle missing 2 points, or a line trace.\ndef test_8(decomposition_samples: ARC):\n board = decomposition_samples.tasks[8].cases[0].input\n board.decompose()\n child_names = sorted([kid.id for kid in board.rep.children])\n assert child_names == [\n \"Cluster(2x4)@(2, 0, 2)\",\n \"Rect(14x9)@(0, 0, 0)\",\n \"Rect(2x2)@(10, 3, 8)\",\n ]\n\n\ndef test_10(decomposition_samples: ARC):\n board = decomposition_samples.tasks[10].cases[0].input\n board.decompose()\n child_names = sorted([kid.id for kid in board.rep.children])\n assert child_names == [\n \"Line(3x1)@(6, 7, 5)\",\n \"Line(6x1)@(3, 3, 5)\",\n \"Line(8x1)@(1, 1, 5)\",\n \"Line(9x1)@(0, 5, 5)\",\n \"Rect(9x9)@(0, 0, 0)\",\n ]\n\n\ndef test_16(decomposition_samples: ARC):\n board = decomposition_samples.tasks[16].cases[0].input\n board.decompose()\n child_names = sorted([kid.id for kid in board.rep.children])\n assert child_names == [\"Cell(1x3)@(0, 0, 10)\"]\n grandchild_names = sorted([kid.id for kid in board.rep.children[0]])\n assert grandchild_names == [\n \"Dot@(0, 0, 3)\",\n \"Dot@(0, 1, 1)\",\n \"Dot@(0, 2, 2)\",\n ]\n\n hier_repr = str(board).replace(\" \", \"\").split(\"\\n\")\n assert hier_repr == [\n \"[Tile]Pattern(3x3)@(0,0,10)(1ch,9pts,15p)\",\n \"Generating(V:2)\",\n \"[Cell]Cell(1x3)@(0,0,10)(3ch,3pts,10p)\",\n \"Dot@(0,0,3)\",\n \"Dot@(0,1,1)\",\n \"Dot@(0,2,2)\",\n ]\n\n # Repeating call with an empty processing queue should do nothing\n board.decompose()\n child_names = sorted([kid.id for kid in board.rep.children])\n assert child_names == [\"Cell(1x3)@(0, 0, 10)\"]\n grandchild_names = sorted([kid.id for kid in board.rep.children[0]])\n assert grandchild_names == [\n \"Dot@(0, 0, 3)\",\n \"Dot@(0, 1, 1)\",\n \"Dot@(0, 2, 2)\",\n ]\n\n # Initializing and allowing no processes should leave the board in raw state\n board.decompose(characteristic=\"\", init=True)\n assert board.current == \"\"\n assert board.proc_q == [\"\"]\n\n # Only allowing Processes.Background gives a different result\n board.decompose(characteristic=\"B\", init=True)\n child_names = sorted([kid.id for kid in board.rep.children])\n assert child_names == [\n \"Line(3x1)@(0, 1, 1)\",\n \"Rect(3x2)@(0, 1, 2)\",\n \"Rect(3x3)@(0, 0, 3)\",\n ]\n\n\ndef test_17(decomposition_samples: ARC):\n board = decomposition_samples.tasks[17].cases[0].input\n board.decompose(max_iter=3)\n child_names = sorted([kid.id for kid in board.rep.children])\n assert child_names == [\n \"Cluster(15x17)@(4, 3, 0)\",\n \"Pattern(21x21)@(0, 0, 10)\",\n ]\n\n\ndef test_30(decomposition_samples: ARC):\n board = decomposition_samples.tasks[30].cases[0].input\n board.decompose()\n child_names = sorted([kid.id for kid in board.rep.children])\n assert child_names == [\n \"Rect(2x2)@(0, 1, 2)\",\n \"Rect(2x2)@(1, 7, 1)\",\n \"Rect(2x2)@(2, 4, 4)\",\n \"Rect(5x10)@(0, 0, 0)\",\n ]\n","sub_path":"tests/test_decomposition.py","file_name":"test_decomposition.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"123561688","text":"\nimport numpy as np\nfrom mnist_load_data import *\nimport mxnet \nimport matplotlib.pyplot as plt\n\n## mnist data path \npath='http://yann.lecun.com/exdb/mnist/'\n\n(train_label, train_img) = read_data(\n path+'train-labels-idx1-ubyte.gz', path+'train-images-idx3-ubyte.gz')\n\t\n(test_label, test_img) = read_data(\n path+'t10k-labels-idx1-ubyte.gz', path+'t10k-images-idx3-ubyte.gz')\n\n\n\t\n## show the plot \nfig=plt.figure()\nplt.ioff()\n\nfor i in range(10):\n plt.subplot(1,10,i+1)\n plt.imshow(train_img[i])\n plt.axis('off')\n\n\t\nplt.savefig('mnist_sample.png')\nplt.close(fig)\n\nprint('label: %s' % (train_label[0:10]))\n","sub_path":"load_mnistdata_and_show.py","file_name":"load_mnistdata_and_show.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"84463364","text":"import pandas as pd\nimport numpy as np\nimport datetime as dt\nfrom datetime import timedelta\nimport math\nfrom functools import reduce\nfrom scipy.interpolate import interp1d\nfrom utility.decorators import my_time_decorator\nfrom option_model.Option_Module import Option, OptionPriceMC, get_implied_volatility, get_time_to_expiry\nfrom option_model.Timing_Module import event_prob_by_expiry\nfrom option_model.Event_Module import IdiosyncraticVol, Earnings\n\n\"\"\"------------------------------Calculations----------------------------------------\"\"\"\n#-------------------------------------------Original Formulas-----------------------------------------------#\n#@my_time_decorator\ndef get_total_mc_distribution(events, expiry = None, symbol = None, mc_iterations = 10**4):\n \"\"\"Add the simulation results of individual events to return the total simulated distribution.\"\"\"\n distributions = map(lambda evt: evt.get_distribution(expiry), events)\n mc_distributions = map(lambda dist: dist.mc_simulation(mc_iterations), distributions)\n return reduce(lambda x, y: np.multiply(x,y), mc_distributions)\n\n#@my_time_decorator\ndef get_option_sheet_from_mc_distribution(mc_distribution, expiry = None, strikes = None):\n if strikes is None:\n strikes = np.arange(.5, 2, .005)\n\n call_options = [Option('Call', strike, expiry) for strike in strikes]\n call_prices = list(map(lambda option: OptionPriceMC(option, mc_distribution), call_options))\n call_IVs = list(map(lambda option, option_price: get_implied_volatility(option, option_price), call_options, call_prices))\n \n put_options = [Option('Put', strike, expiry) for strike in strikes]\n put_prices = list(map(lambda option: OptionPriceMC(option, mc_distribution), put_options))\n put_IVs = list(map(lambda option, option_price: get_implied_volatility(option, option_price), put_options, put_prices))\n\n option_premiums = [min(call_price, put_price) for call_price, put_price in zip(call_prices, put_prices)]\n \n \"\"\"\n option_sheet_info = {'Strike': strikes, 'Price': option_premiums, 'IV': call_IVs}\n option_sheet = pd.DataFrame(option_sheet_info).set_index('Strike').loc[:, ['Price', 'IV']].round(2)\n \"\"\"\n \n option_sheet_info = list(zip(option_premiums, call_IVs))\n index_r = pd.Index(strikes, name = 'Strike')\n iterables_c = [[expiry], ['Premium', 'IV']]\n index_c = pd.MultiIndex.from_product(iterables_c, names = ['Expiry', 'Option_Info'])\n option_sheet = pd.DataFrame(option_sheet_info, index = index_r, columns = index_c)\n return option_sheet\n\n#@my_time_decorator\ndef get_option_sheet_by_event_groupings(event_groupings, expiry):\n# i = 0\n# for grouping in event_groupings:\n# mc_distribution = get_total_mc_distribution(grouping, expiry = expiry)\n# prices = get_option_sheet_from_mc_distribution(mc_distribution, strikes = np.arange(.5, 1.55, .05)).loc[:, ['Price','IV']]\n#\n# if event_groupings.index(grouping) == 0:\n# prices_df = prices\n# else:\n# prices_df = pd.merge(prices_df, prices, left_index=True, right_index=True)\n# \n# get_mc_histogram(mc_distribution)\n# \n# i += 1\n# return prices_df\n mc_distributions = list(map(lambda event_grouping: get_total_mc_distribution(event_grouping, expiry), event_groupings))\n option_sheets = list(map(lambda dist: get_option_sheet_from_mc_distribution(dist, expiry).loc[:, [(expiry,'IV')]], mc_distributions))\n \n #[get_histogram_from_array(mc_distribution) for mc_distribution in mc_distributions]\n #show_term_structure(mc_distributions)\n if len(option_sheets) >=2:\n return reduce(lambda x, y: pd.merge(x, y, left_index=True, right_index=True), option_sheets)\n else:\n return option_sheets[0]\n\"\"\"\n#@my_time_decorator\n# I don't think I need this function.\ndef option_sheet(event_groupings,\n expiry = None,\n mc_iterations = 10**5):\n option_sheet_by_groupings = get_option_sheet_by_event_groupings(event_groupings, expiry)\n return option_sheet_by_groupings\n\"\"\"\n\ndef get_vol_surface(events, expiry):\n return get_option_sheet_by_event_groupings([events], expiry)\n\ndef get_vol_surface_spline(vol_surface):\n strikes = vol_surface.index.values.tolist()\n vols = vol_surface.iloc[:, 0].values.tolist()\n return interp1d(strikes, vols, kind='cubic')\n\n\n#---------------------------------I optimize for speed below here---------------------------------------------#\n#@my_time_decorator\ndef get_total_mc_distribution(events, expiry = None, symbol = None, mc_iterations = 10**4):\n \"\"\"Add the simulation results of individual events to return the total simulated distribution.\"\"\"\n distributions = map(lambda evt: evt.get_distribution(expiry), events)\n mc_distributions = map(lambda dist: dist.mc_simulation(mc_iterations), distributions)\n return reduce(lambda x, y: np.multiply(x,y), mc_distributions)\n\n#@my_time_decorator\ndef get_vol_surface_from_mc_distribution(mc_distribution, expiry = None, strikes = None):\n if strikes is None:\n strikes = np.arange(.5, 1.5, .01)\n #strikes = np.arange(.5, 1.5, .005)\n\n call_options = [Option('Call', strike, expiry) for strike in strikes]\n call_prices = list(map(lambda option: OptionPriceMC(option, mc_distribution), call_options))\n call_IVs = list(map(lambda option, option_price: get_implied_volatility(option, option_price), call_options, call_prices))\n \n option_sheet_info = list(call_IVs)\n index_r = pd.Index(strikes, name = 'Strike')\n iterables_c = [[expiry], ['IV']]\n index_c = pd.MultiIndex.from_product(iterables_c, names = ['Expiry', 'Option_Info'])\n option_sheet = pd.DataFrame(option_sheet_info, index = index_r, columns = index_c)\n return option_sheet\n\ndef get_vol_surface_from_event_grouping(event_grouping, expiry):\n mc_distribution = get_total_mc_distribution(event_grouping, expiry)\n return get_vol_surface_from_mc_distribution(mc_distribution, expiry)\n\ndef get_vol_surface(events, expiry):\n return get_vol_surface_from_event_grouping(events, expiry)\n\ndef get_vol_surface_spline(vol_surface):\n strikes = vol_surface.index.values.tolist()\n vols = vol_surface.iloc[:, 0].values.tolist()\n return interp1d(strikes, vols, kind='cubic')\n\n\n\n#---------------------------------I optimize for speed again below here---------------------------------------------#\nEarningsDist = Earnings('CRBP', .05, 'Q2_2018').get_distribution(dt.date(2018, 7, 1)).mc_simulation(10**4)\nIdiosyncraticVolDist = IdiosyncraticVol('CRBP', .10).get_distribution(dt.date.today() + timedelta(365)).mc_simulation(10**4)\n\n#@my_time_decorator\ndef get_total_mc_distribution(events, expiry = None, symbol = None, mc_iterations = 10**4):\n \"\"\"Add the simulation results of individual events to return the total simulated distribution.\"\"\"\n \n \"\"\"\n events = [evt for evt in events if event_prob_by_expiry(evt.timing_descriptor, expiry) > 0]\n distributions = map(lambda evt: evt.get_distribution(expiry), events)\n mc_distributions = map(lambda dist: dist.mc_simulation(mc_iterations), distributions)\n \"\"\"\n \n #@my_time_decorator\n def establish_events(events, expiry):\n return [evt for evt in events if event_prob_by_expiry(evt.timing_descriptor, expiry) > 0]\n \n #@my_time_decorator\n def get_distributions(events, expiry):\n return [evt.get_distribution(expiry) for evt in events if event_prob_by_expiry(evt.timing_descriptor, expiry) >0]\n #return list(map(lambda evt: evt.get_distribution(expiry), events))\n #return list(map(lambda evt: evt.get_distribution(expiry), events))\n \n #@my_time_decorator\n def get_mc_distributions(distributions):\n mc_distributions = list(map(lambda dist: dist.mc_simulation(mc_iterations), distributions))\n return mc_distributions\n #return map(lambda dist: dist.mc_simulation(mc_iterations), distributions)\n \n #@my_time_decorator\n def get_tot_mc_distribution(mc_distributions):\n if len(mc_distributions) > 1:\n return reduce(lambda x, y: np.multiply(x,y), mc_distributions)\n else:\n return np.array(mc_distributions)\n\n #@my_time_decorator\n def new_methodology(events, expiry, mc_iterations = 10**4):\n events = establish_events(events, expiry)\n \n if not events:\n return np.ones(mc_iterations)\n \n mc_distributions = []\n for evt in events:\n if isinstance(evt, IdiosyncraticVol):\n mc_distribution = (IdiosyncraticVolDist - 1)*(evt.at_the_money_vol/.10)*math.sqrt(get_time_to_expiry(expiry)) + 1\n #print('IdioVol: {}'.format(np.average(mc_distribution)))\n elif isinstance(evt, Earnings):\n mc_distribution = (EarningsDist - 1)*(evt.mean_move/1.0504) + 1\n #print('Earnings: {}'.format(np.average(mc_distribution)))\n else:\n mc_distribution = evt.get_distribution(expiry).mc_simulation(mc_iterations)\n #print('Other: {}'.format(np.average(mc_distribution)))\n mc_distributions.append(mc_distribution)\n return get_tot_mc_distribution(mc_distributions)\n \n\n\n #events = establish_events(events)\n #distributions = get_distributions(events)\n #mc_distributions = get_mc_distributions(distributions)\n #total_mc_distribution = get_tot_mc_distribution(mc_distributions)\n total_mc_distribution = new_methodology(events, expiry)\n return total_mc_distribution\n #return reduce(lambda x, y: np.multiply(x,y), mc_distributions)\n\n#@my_time_decorator\ndef get_vol_surface_from_mc_distribution(mc_distribution, expiry = None, strikes = None):\n \n @my_time_decorator\n def establish_strike_range(mc_distribution: 'numpy array'):\n \"\"\"array.min() seems to be >70x faster than min(mc_distribution)\"\"\"\n strikeMin = mc_distribution.min()\n strikeMax = mc_distribution.max()\n #establish_strike_range(mc_distribution)\n \n if strikes is None:\n strikeMin = mc_distribution.min()\n strikeMax = mc_distribution.max()\n strikeInterval = (strikeMax - strikeMin) / 50\n strikes = pd.Series(np.arange(strikeMin, strikeMax, .01))\n #strikes = np.arange(strikeMin, strikeMax, strikeInterval)\n\n #@my_time_decorator\n def establish_call_options(expiry, strikes):\n return [Option('Call', strike, expiry) for strike in strikes]\n Option_Map = lambda strike: Option('Call', strike, expiry)\n return strikes.apply(Option_Map)\n \n #@my_time_decorator\n def get_call_prices(call_options, mc_distribution):\n return list(map(lambda option: OptionPriceMC(option, mc_distribution), call_options))\n OptionPriceMC_Map = lambda option: OptionPriceMC(option, mc_distribution)\n #return call_options.apply(OptionPriceMC_Map)\n \n #@my_time_decorator\n def get_call_IVs(call_options, call_prices):\n return list(map(lambda option, option_price: get_implied_volatility(option, option_price), call_options, call_prices))\n tuples = pd.concat([call_options, call_prices], axis=1).loc[:, [0,1]].apply(tuple, axis=1)\n IV_Map = lambda tup: get_implied_volatility(tup[0], tup[1])\n call_IVs = tuples.apply(IV_Map)\n #df = pd.concat([call_options, call_prices, call_IVs], axis=1).round(3)\n return call_IVs\n \n #@my_time_decorator\n def get_vol_surface_df(expiry, strikes, call_IVs):\n vol_surface_info = list(call_IVs)\n index_r = pd.Index(strikes, name = 'Strike')\n iterables_c = [[expiry], ['IV']]\n index_c = pd.MultiIndex.from_product(iterables_c, names = ['Expiry', 'Option_Info'])\n vol_surface = pd.DataFrame(vol_surface_info, index = index_r, columns = index_c)\n return vol_surface\n \n call_options = establish_call_options(expiry, strikes)\n call_prices = get_call_prices(call_options, mc_distribution)\n call_IVs = get_call_IVs(call_options, call_prices)\n #print(strikes)\n #print(call_IVs.to_string())\n #return get_vol_surface_df(expiry, strikes, call_IVs)\n return [strikes, call_IVs]\n \"\"\"\n call_options = [Option('Call', strike, expiry) for strike in strikes]\n call_prices = list(map(lambda option: OptionPriceMC(option, mc_distribution), call_options))\n call_IVs = list(map(lambda option, option_price: get_implied_volatility(option, option_price), call_options, call_prices))\n \n vol_surface_info = list(call_IVs)\n index_r = pd.Index(strikes, name = 'Strike')\n iterables_c = [[expiry], ['IV']]\n index_c = pd.MultiIndex.from_product(iterables_c, names = ['Expiry', 'Option_Info'])\n vol_surface = pd.DataFrame(vol_surface_info, index = index_r, columns = index_c)\n return vol_surface\n \"\"\"\n #return [strikes, call_IVs]\n\n#@my_time_decorator\ndef get_vol_surface_from_event_grouping(event_grouping, expiry):\n mc_distribution = get_total_mc_distribution(event_grouping, expiry)\n #print(np.average(mc_distribution))\n #print('Expiry:', expiry, 'Event Grouping:', event_grouping)\n return get_vol_surface_from_mc_distribution(mc_distribution, expiry)\n\n#@my_time_decorator\ndef get_vol_surface(events, expiry):\n if not events:\n return None\n return get_vol_surface_from_event_grouping(events, expiry)\n\n#@my_time_decorator\ndef get_vol_surface_spline(vol_surface):\n #strikes = vol_surface.index.values.tolist()\n #vols = vol_surface.iloc[:, 0].values.tolist()\n if vol_surface is None:\n return None\n strikes = vol_surface[0]\n vols = vol_surface[1]\n return interp1d(strikes, vols, kind='cubic')\n","sub_path":"biotech_class_run_orig_orig.py","file_name":"biotech_class_run_orig_orig.py","file_ext":"py","file_size_in_byte":13662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"82584139","text":"from django.conf.urls.defaults import *\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^pages/([\\w\\d-]+)/', 'userapp.views.page_detail', name=\"userapp_page_detail\"),\n url(r'^products/(\\d+)/', 'userapp.views.product_detail', name=\"userapp_product_detail\"),\n url(r'^my/view/(.+)/', 'userapp.views.my_view', name=\"userapp_my_view\"),\n url(r'^my/other/view/(.+)/', 'userapp.views.my_other_view', name=\"userapp_my_other_view\"),\n (r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"regressiontests/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"480255801","text":"from django.conf.urls.defaults import patterns,url\n\n\nurlpatterns = patterns('dideunerg.apps.home.views',\n url(r'^$','index_view',name='vista_principal'),\n #url(r'^atletas/$','atletas_view',name='vista_atletas'),\n #url(r'^entrenadores/$', 'entrenadores_view'),\n url(r'^entrenadores/page/(?P.*)/$','entrenadores_view'),\n #url(r'^add/atletas/$','add_atletas_view'),\n #url(r'^about/$','about_view',name='vista_about'),\n url(r'^atletas/page/(?P.*)/$','atletas_view',name='vista_atletas'),\n url(r'^atleta/(?P.*)/$','singleAtleta_view',name='vista_single_atleta'),\n url(r'^entrenador/(?P.*)/$','singleEntrenador_view'),\n url(r'^editar/atleta/(?P.*)/$','editarAtleta_view',name='vista_single_atleta'),\n url(r'^editar/entrenador/(?P.*)/$','editarEntrenador_view'),\n #url(r'^contacto/$','contacto_view',name='vista_contactos'),\n url(r'^login/$','login_view',name='vista_login'),\n url(r'^logout/$','logout_view',name='vista_logout'),\n\n)\n","sub_path":"dideunerg/apps/home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"579714646","text":"#!/bin/python3\r\n\r\nimport sys\r\n\r\ndef findDigits(n):\r\n digits = [int(i) for i in str(n)]\r\n \r\n result = []\r\n for i in range(len(digits)):\r\n if digits[i] == 0:\r\n continue\r\n elif n % digits[i] == 0:\r\n result.append(i)\r\n return len(result)\r\n\r\nif __name__ == \"__main__\":\r\n t = int(input().strip())\r\n for a0 in range(t):\r\n n = int(input().strip())\r\n result = findDigits(n)\r\n print(result)\r\n","sub_path":"HackerRank/Algorithm/newAlgorithm/Find_digits.py","file_name":"Find_digits.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"60392680","text":"#!/usr/bin/python3\n\"\"\"100-singly_linked_list\n\nDefine a linked list\n\n\"\"\"\n\n\nclass Node:\n \"\"\"A node in a Linked list\n\n Represent a Node\n\n \"\"\"\n\n __data = None\n __next_node = None\n\n def __verify_data(d):\n \"\"\"verify data function\n\n Verify data\n\n Args:\n d: the data\n\n Raises:\n TypeError\n\n \"\"\"\n\n if type(d) != int:\n raise TypeError(\"data must be an integer\")\n\n def __verify_next(n):\n \"\"\"verify next_node function\n\n Verify the next_node\n\n Args:\n n: the next_node\n\n Raises:\n TypeError\n\n \"\"\"\n\n if type(n) != Node and n is not None:\n raise TypeError(\"next_node must be a Node object\")\n\n def __init__(self, data, next_node=None):\n \"\"\"init function\n\n Inits\n\n Args:\n data: the data\n next_node: the next node\n\n Raises:\n TypeError\n\n \"\"\"\n\n Node.__verify_data(data)\n Node.__verify_next(next_node)\n self.__data = data\n self.__next_node = next_node\n\n @property\n def data(self):\n \"\"\"data getter\n\n Get data\n\n Raises:\n TypeError\n\n Returns:\n the data\n\n \"\"\"\n\n Node.__verify_data(self.__data)\n return self.__data\n\n @data.setter\n def data(self, value):\n \"\"\"data setter\n\n Set data\n\n Args:\n value: the value to set\n\n Raises:\n TypeError\n\n \"\"\"\n\n Node.__verify_data(value)\n self.__data = value\n\n @property\n def next_node(self):\n \"\"\"next_node getter\n\n Get next_node\n\n Raises:\n TypeError\n\n Returns:\n the next_node\n\n \"\"\"\n\n Node.__verify_next(self.__next_node)\n return self.__next_node\n\n @next_node.setter\n def next_node(self, value):\n \"\"\"next_node setter\n\n Set next_node\n\n Args:\n value: the next node to set\n\n Raises:\n TypeError\n\n \"\"\"\n\n Node.__verify_next(value)\n self.__next_node = value\n\n\nclass SinglyLinkedList:\n \"\"\"A singly linked list\n\n Represent the whole linked list\n\n \"\"\"\n\n __head = None\n\n def __init__(self):\n \"\"\"init function\n\n Inits\n\n \"\"\"\n\n pass\n\n def __str__(self):\n \"\"\"str function\n\n Make a string\n\n Returns:\n a string representation\n\n \"\"\"\n\n string = \"\"\n temp = self.__head\n if temp is None:\n string = \"\"\n return string\n while temp is not None:\n string = string + str(temp.data) + \"\\n\"\n temp = temp.next_node\n return string[:-1]\n\n def sorted_insert(self, value):\n \"\"\"sorted_insert function\n\n Insert into linked list sorted\n\n Args:\n value: the value to insert\n\n Raises:\n TypeError\n\n \"\"\"\n\n if self.__head is None or self.__head.data > value:\n x = Node(value, self.__head)\n self.__head = x\n return\n temp = self.__head\n while temp.next_node is not None and temp.next_node.data <= value:\n temp = temp.next_node\n x = Node(value, temp.next_node)\n temp.next_node = x\n return\n","sub_path":"0x06-python-classes/100-singly_linked_list.py","file_name":"100-singly_linked_list.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"431284823","text":"#!/usr/bin/python\n\n# matplotlib tutorial\n#\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx= np.arange(0,2*np.pi,.01)\ny=np.sin(x)\n\nplt.plot(x,y)\n\nplt.annotate('This is the peak point',xy=(np.pi/2.0,1),xytext=(np.pi/2.0-0.3,0.5),arrowprops=dict(facecolor='red',shrink=0.05))\n\nplt.show()\n","sub_path":"matplotlib/annotation.py","file_name":"annotation.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"134855729","text":"#!/usr/bin/env python3\n# 病歷查詢 2014.09.22\n#coding: utf-8\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QMessageBox, QPushButton\nfrom libs import ui_utils\nfrom libs import system_utils\nfrom libs import case_utils\nimport sys\n\nif sys.platform == 'win32':\n from classes import cshis_win32 as cshis\nelse:\n from classes import cshis\n\n\n# 主視窗\nclass DialogICCard(QtWidgets.QDialog):\n # 初始化\n def __init__(self, parent=None, *args):\n super(DialogICCard, self).__init__(parent)\n self.parent = parent\n self.database = args[0]\n self.system_settings = args[1]\n self.ui = None\n try:\n self.ic_card = cshis.CSHIS(self.database, self.system_settings)\n except NameError:\n self.ic_card = None\n\n self._set_ui()\n self._set_signal()\n\n # 解構\n def __del__(self):\n self.close_all()\n\n # 關閉\n def close_all(self):\n pass\n\n # 設定GUI\n def _set_ui(self):\n self.ui = ui_utils.load_ui_file(ui_utils.UI_DIALOG_IC_CARD, self)\n self.setFixedSize(self.size()) # non resizable dialog\n system_utils.set_css(self, self.system_settings)\n self.ui.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText('關閉')\n\n # 設定信號\n def _set_signal(self):\n self.ui.buttonBox.accepted.connect(self.accepted_button_clicked)\n self.ui.toolButton_verify_sam.clicked.connect(self.verify_sam)\n self.ui.toolButton_verify_hpc_pin.clicked.connect(self.verify_hpc_pin)\n self.ui.toolButton_set_hpc_pin.clicked.connect(self.set_hpc_pin)\n self.ui.toolButton_unlock_hpc_pin.clicked.connect(self.unlock_hpc_pin)\n self.ui.toolButton_update_ic_card.clicked.connect(self.update_ic_card)\n self.ui.toolButton_verify_ic_card_pin.clicked.connect(self.verify_ic_card_pin)\n self.ui.toolButton_set_ic_card_pin.clicked.connect(self.set_ic_card_pin)\n self.ui.toolButton_disable_ic_card_pin.clicked.connect(self.disable_ic_card_pin)\n self.ui.toolButton_ic_card_info.clicked.connect(self.ic_card_info)\n self.ui.toolButton_ic_card_record.clicked.connect(self.ic_card_record)\n self.ui.toolButton_reset_reader.clicked.connect(self.reset_reader)\n\n # 關閉\n def accepted_button_clicked(self):\n self.close()\n\n # 安全模組卡認證\n def verify_sam(self):\n self.ic_card.verify_sam()\n\n # 驗證醫事人員卡\n def verify_hpc_pin(self):\n self.ic_card.verify_hpc_pin()\n\n # 設定醫事人員卡密碼\n def set_hpc_pin(self):\n self.ic_card.input_hpc_pin()\n\n # 解鎖醫事人員卡密碼\n def unlock_hpc_pin(self):\n self.ic_card.unlock_hpc()\n\n # 更新病患健保卡內容\n def update_ic_card(self):\n self.ic_card.update_hc()\n\n # 驗證病患健保卡密碼\n def verify_ic_card_pin(self):\n self.ic_card.verify_hc_pin()\n\n # 設定病患健保卡密碼\n def set_ic_card_pin(self):\n self.ic_card.input_hc_pin()\n\n # 解除病患健保卡密碼\n def disable_ic_card_pin(self):\n self.ic_card.disable_hc_pin()\n\n # 讀取健保卡基本資料\n def ic_card_info(self):\n if not self.ic_card.read_register_basic_data():\n return\n\n # if not database.ic_card.read_critical_illness():\n # critical_illness_data = [\n # {'CI_CODE': '', 'CI_VALIDITY_START': '', 'CI_VALIDITY_END': ''},\n # {'CI_CODE': '', 'CI_VALIDITY_START': '', 'CI_VALIDITY_END': ''},\n # {'CI_CODE': '', 'CI_VALIDITY_START': '', 'CI_VALIDITY_END': ''},\n # {'CI_CODE': '', 'CI_VALIDITY_START': '', 'CI_VALIDITY_END': ''},\n # {'CI_CODE': '', 'CI_VALIDITY_START': '', 'CI_VALIDITY_END': ''},\n # {'CI_CODE': '', 'CI_VALIDITY_START': '', 'CI_VALIDITY_END': ''},\n # ]\n # else:\n self.ic_card.read_critical_illness()\n critical_illness_data = self.ic_card.critical_illness_data\n\n critical_illness_list = ''\n for i in range(len(critical_illness_data)):\n icd10 = critical_illness_data[i]['CI_CODE'].strip()\n disease_name = case_utils.get_disease_name(self.database, icd10)\n critical_illness_list += '''\n \n {sequence}\n {icd10}\n {disease_name}\n {start_date}\n {end_date}\n \n '''.format(\n sequence=i+1,\n icd10=icd10,\n disease_name=disease_name,\n start_date=critical_illness_data[i]['CI_VALIDITY_START'],\n end_date=critical_illness_data[i]['CI_VALIDITY_END'],\n )\n\n html = '''\n \n \n \n \n \n \n \n \n \n \n {critical_illness_list}\n \n \n
ICD-10重大傷病名稱有效起日有效訖日
\n '''.format(\n critical_illness_list=critical_illness_list,\n )\n\n msg_box = QMessageBox()\n msg_box.setIcon(QMessageBox.Information)\n msg_box.setWindowTitle('健保卡基本資料')\n msg_box.setText(\n '''\n \n 健保IC卡卡片基本資料內容如下:

\n
\n \n 卡片號碼: {0}
\n 病患姓名: {1}
\n 身分證號: {2}
\n 出生日期: {3}
\n 病患性別: {4}
\n 發卡日期: {5}
\n 卡片註記: {6}
\n 保險身分: {7}
\n 卡片效期: {8}
\n 可用次數: {9}
\n
\n {html}\n '''.format(\n self.ic_card.basic_data['card_no'],\n self.ic_card.basic_data['name'],\n self.ic_card.basic_data['patient_id'],\n self.ic_card.basic_data['birthday'],\n self.ic_card.basic_data['gender'],\n self.ic_card.basic_data['card_date'],\n self.ic_card.basic_data['cancel_mark'],\n self.ic_card.basic_data['insured_mark'],\n self.ic_card.basic_data['card_valid_date'],\n self.ic_card.basic_data['card_available_count'],\n html=html,\n )\n )\n msg_box.setInformativeText('健保IC卡卡片內容讀取完成')\n msg_box.addButton(QPushButton(\"確定\"), QMessageBox.AcceptRole)\n msg_box.exec_()\n\n # 讀取健保卡就醫資料\n def ic_card_record(self):\n self.ic_card.read_treatment_no_need_hpc()\n treatment_data = self.ic_card.treatment_data\n for treatment in treatment_data['treatments']:\n print(treatment)\n\n # 讀卡機裝置重新啟動\n def reset_reader(self):\n self.ic_card.reset_reader()\n","sub_path":"dialog/dialog_ic_card.py","file_name":"dialog_ic_card.py","file_ext":"py","file_size_in_byte":7737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"36552179","text":"from django.urls import path,include\r\nfrom . import views\r\napp_name='mainapp'\r\n\r\nurlpatterns=[\r\n path('',views.homepage,name='homepage'),\r\n path('stocks/',include('stocks.urls')),\r\n path('accounts/',include('accounts.urls')),\r\n path('customers/',include('customers.urls')),\r\n]\r\n","sub_path":"pharmacy/mainapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"202658050","text":"# -*- coding: utf-8 -*-\n\"\"\"\nShe35 Editor\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pandas import Series\nfrom pandas import DataFrame\nimport os\n\ndef get_markov(path_list,risk_free = 0.03):\n '''\n\n :param path_list:\n :return: df : 相对净值\n opts.x:sharp最优的权重。\n '''\n\n ser_list = [] # 存放Series的list,用来合并成DataFrame\n for path in path_list:\n path_name = path.split(os.sep)[-1][:-4] # 获取文件名\n _df = pd.read_csv(path, encoding='gbk', index_col=['price_date'], parse_dates=['price_date'])\n _ser = _df['nav'] # 获取净值\n _ser.name = path_name # 对Series重命名\n _ser.drop_duplicates(inplace=True) # 去重\n ser_list.append(_ser)\n\n\n df = pd.concat(ser_list,axis=1,join='outer') # 合并ser_list里面的Series\n df.sort_index(ascending=True, inplace=True)\n df.fillna(method='ffill',inplace=True) # 以前值来填充缺失值,因为不同产品的公布时间不同,所以在某个时间点对某个产品会存在缺失值现象\n\n df.dropna(inplace=True) # 去掉缺失值,考虑第一行为缺失值的情况。\n df = df / df.iloc[0, :] # 净值归一化。\n\n\n return df,w\n\n\nif __name__ == '__main__':\n path_list = [r'data\\昆仑信托-昆仑三十六号.csv',\n r'data\\时时安稳健1号.csv',\n r'data\\长城国瑞证券恒通23号.csv']\n\n df,w = get_markov(path_list)\n\n\n '''画产品组合信息表'''\n df['组合'] = (df * w).sum(axis=1)\n risk_free = 0.03\n\n std_year = df.std() * 50\n mean_year = df.pct_change().mean() * 50 - risk_free\n sharp_year = mean_year / std_year\n max_drawback = (df / df.cummax()).min()\n\n _temp = {i[0]:i[1] for i in zip(['风险', '均值', '夏普比','最大回撤'],[std_year, mean_year, sharp_year, max_drawback])}\n df_info = pd.concat(_temp,axis=1).T\n df_info.index.name = '指标'\n df_info = df_info.round(decimals=3)\n\n import plotly.offline as pyof\n from plotly import figure_factory as ff\n table = ff.create_table(df_info,index=True, index_title='指标')\n pyof.plot(table, filename='产品组合信息表.html')\n\n\n '''画饼图'''\n import plotly.graph_objs as go\n\n labels=df_info.columns[:-1]\n values=w\n trace=go.Pie(labels=labels,values=values,text='哈哈')\n layout = dict(title = '产品组合成分图')\n fig = dict(data=[trace],layout=layout)\n pyof.plot(fig,filename='组合成分图.html')\n\n\n '''画产品对比图'''\n import tushare as ts\n data_hs300 = ts.get_hist_data('hs300')\n data_hs300 = data_hs300.rename_axis(lambda x:pd.to_datetime(x))\n df_contra = pd.concat([data_hs300.close,df['组合']],axis=1,join='inner')\n df_contra = df_contra / df_contra.iloc[0,:]\n df_contra.rename(columns={'close':'沪深300'},inplace=True)\n\n\n import plotly.graph_objs as go\n trace1 = go.Scatter(x=df_contra.index,y=df_contra.iloc[:,0],mode = 'lines+markers',\n name = '沪深300',marker=dict(color='blue'))\n trace2 = go.Scatter(x=df_contra.index,y=df_contra.iloc[:,1],mode = 'lines+markers',\n name = '产品组合',marker=dict(color='red'))\n data = [trace1,trace2]\n layout = {'title' : '产品组合VS沪深300'}\n fig = dict(data=data,layout=layout)\n pyof.plot(fig,filename='产品组合VS沪深300.html')","sub_path":"Chapter11/opt_fund.py","file_name":"opt_fund.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"204376813","text":"# -*- coding=utf-8 -*-\nimport re\nimport logging\n\nfrom zettarepl.transport.interface import ExecException, Shell\nfrom zettarepl.utils.itertools import sortedgroupby\n\nfrom .snapshot import Snapshot\n\nlogger = logging.getLogger(__name__)\n\n__all__ = [\"destroy_snapshots\"]\n\n\ndef destroy_snapshots(shell: Shell, snapshots: [Snapshot]):\n for dataset, snapshots in sortedgroupby(snapshots, lambda snapshot: snapshot.dataset):\n names = [snapshot.name for snapshot in snapshots]\n\n logger.info(\"On %r for dataset %r destroying snapshots %r\", shell, dataset, names)\n\n while names:\n args = [\"zfs\", \"destroy\", f\"{dataset}@\" + \",\".join(names)]\n try:\n shell.exec(args)\n break\n except ExecException as e:\n m = re.search(r\"cannot destroy snapshot .+?@(.+?): dataset is busy\", e.stdout)\n if m is None:\n raise\n\n name = m.group(1)\n logger.info(\"Snapshot %r on dataset %r is busy, skipping\", name, dataset)\n names.remove(name)\n","sub_path":"zettarepl/snapshot/destroy.py","file_name":"destroy.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"382475778","text":"# coding:utf-8\nimport logging\nimport os\nimport sys\n\nfrom cloghandler import ConcurrentRotatingFileHandler\n\nPY3k = sys.version_info >= (3,)\nif not PY3k:\n reload(sys)\n sys.setdefaultencoding('utf-8')\n\n\nclass Logger(object):\n # 默认info级别\n level = logging.INFO\n\n # 存放目录名称\n folder = 'log'\n\n def __init__(self, filename):\n pwd = os.path.abspath(os.path.dirname(__file__))\n\n directory = os.path.join(pwd, self.folder)\n if not os.path.exists(directory):\n os.mkdir(directory)\n\n self.file_path = directory + '/' + filename\n\n self.log = logging.getLogger(filename)\n self.log.setLevel(self.level)\n\n handler = ConcurrentRotatingFileHandler(self.file_path, 'a', 1024 * 1024 * 100, backupCount=5, encoding='utf-8')\n # handler.suffix = \"%Y-%m-%d\"\n\n # 设置输出格式\n # format_log = \"%(asctime)s %(threadName)s %(funcName)s %(filename)s:%(lineno)s %(levelname)s %(message)s\"\n formatter = logging.Formatter(\n '%(asctime)s [%(processName)s %(threadName)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d] %(message)s')\n # fmt = logging.Formatter(formatter)\n handler.setFormatter(formatter)\n\n self.log.addHandler(handler)\n\n # 控制台输出\n stream = logging.StreamHandler()\n stream.setFormatter(formatter)\n\n self.log.addHandler(stream)\n\n def set_level(self, level):\n self.log.setLevel(level=level)\n return self.log\n\n def get_logger(self):\n return self.log\n\n\nif __name__ == '__main__':\n log = Logger('log.log').get_logger()\n log.info('text')\n log.error('text')\n","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"267758391","text":"import random\nfrom typing import Dict\nfrom typing import List\nfrom typing import Set\nfrom hlt import *\nimport logging\n\n\nclass HaliteBotCode:\n def __init__(self, game_map: GameMap, id: int, options=dict()):\n self.id = id\n self.game_map = game_map\n self.owned_sites = set() # type: Set[Square]\n self.moves_this_frame = []\n self.time_at_square = dict() # type: Dict[Square, int]\n self.expected_strength = dict() # type: Dict[Square, int]\n self.frame = 0\n\n self.DISTANCE_THRESHOLD = 3 if options[\"DISTANCE_THRESHOLD\"] is None else options[\"DISTANCE_THRESHOLD\"]\n self.MAX_DISTANCE = 11 if options[\"MAX_DISTANCE\"] is None else options[\"MAX_DISTANCE\"]\n self.ATTACK_DIST = 3 if options[\"ATTACK_DIST\"] is None else options[\"ATTACK_DIST\"]\n\n for square in self.game_map:\n self.time_at_square[square] = 0\n\n def update(self, game_map: GameMap):\n self.game_map = game_map\n\n logging.debug(\"reset the moves\")\n self.moves_this_frame = []\n\n logging.debug(\"update owned sites\")\n self.update_owned_sites()\n\n logging.debug(\"update the moves\")\n self.update_move_targets()\n\n self.frame += 1\n\n return\n\n def can_move_from(self, source:Square):\n # must stay at spot to build strength\n allow_move = True\n\n if source.strength < source.production * 5:\n allow_move = False\n\n return allow_move\n\n\n def is_move_allowed(self, move: Move) -> bool:\n\n allow_move = True\n\n source = move.square\n target = self.game_map.get_target(source, move.direction)\n\n # must stay for one turn to avoid constantly moving\n # if self.time_at_square[source] <= 1:\n # allow_move = False\n\n # this should prevent large blocks from combining\n if allow_move:\n if 280 - self.expected_strength[target] < source.strength:\n allow_move = False\n else:\n self.expected_strength[target] += source.strength\n self.expected_strength[source] -= source.strength\n\n return allow_move\n\n def can_attack_square(self, square:Square)->bool:\n # this will return a bool indicating if the square can be attacked\n return any(neighbor.owner not in [0,self.id] for neighbor in self.game_map.neighbors(square))\n\n def get_square_value(self, square: Square) -> float:\n\n border_value = 1000000\n\n # this needs to determine the value of a site, take the average of the\n if square.strength == 0:\n border_value = sum(neighbor.strength\n for neighbor in self.game_map.neighbors(square) if\n neighbor.owner not in [0, self.id])\n\n if border_value == 0:\n # nothing to attack\n border_value = min((self.get_square_metric(neighbor) for neighbor in self.game_map.neighbors(square) if\n neighbor.owner == 0), default=0)\n\n else:\n border_value = self.get_square_metric(square)\n\n return border_value\n\n def get_square_metric(self, square: Square):\n return square.production / (square.strength + 1)\n\n def update_move_targets(self):\n # this will go through spaces and find those that are accessible and then ranked by strength\n border_sites = self.get_unowned_border()\n\n # create a dict to assoc border sites\n border_assoc = dict() # type: Dict[Square, List[Square]]\n\n for border_square in border_sites:\n border_assoc[border_square] = []\n\n desired_moves = dict() # type: Dict[Square, Move]\n\n # update the can attack dict\n can_attack = dict() # type: Dict[Square, bool]\n for border_square in border_sites:\n can_attack[border_square] = self.can_attack_square(border_square)\n\n # loop through owned pieces and make the calls to move them\n for location in self.owned_sites:\n # find the closest border spot\n min_location = None\n max_value = 0\n\n must_attack = False\n\n if not self.can_move_from(location):\n continue\n\n for border_square in border_sites:\n\n if must_attack and not can_attack[border_square]:\n continue\n\n distance = self.game_map.get_distance(border_square, location)\n\n if distance > self.MAX_DISTANCE:\n continue\n\n # reset the best spot if this is the first to be attackable\n if distance < self.ATTACK_DIST and can_attack[border_square] and not must_attack:\n min_location = None\n max_value = 0\n must_attack = True\n\n # threshold the distance to allow for some movement\n if distance <= self.DISTANCE_THRESHOLD:\n distance = 1\n\n border_value = self.get_square_value(border_square) / distance\n\n if border_value > max_value:\n min_location = border_square\n max_value = border_value\n\n # add a check here to see if move should be made\n\n if min_location is not None:\n border_assoc[min_location].append(location)\n\n # iterate through the border sites now to determine if to move\n\n for border_square, locations in border_assoc.items():\n # get the sum of the strengths\n total_strength = 0\n for location in locations:\n total_strength += location.strength\n\n if total_strength > border_square.strength:\n # if so, move that direction\n for location in locations:\n move = self.get_next_move(location, border_square)\n\n logging.debug(\"move to make %s\", move)\n\n if move is not None:\n desired_moves[location] = move\n\n # this allows move to be checked a couple times to see if the situation improves\n max_check = 5\n times_checked = 0\n while len(desired_moves) > 0 and times_checked < max_check:\n for key in list(desired_moves.keys()):\n move = desired_moves[key]\n if self.is_move_allowed(move):\n desired_moves.pop(key)\n self.moves_this_frame.append(move)\n # reset move counter if leaving own territory\n if self.game_map.get_target(move.square, move.direction).owner != self.id:\n self.time_at_square[move.square] = 0\n\n times_checked += 1\n\n return\n\n def get_next_move(self, start: Square, target: Square) -> Move:\n\n # this will figure out how to get to the desired location, moving only through owned territory\n\n # get the desired direction(s), handling the edges\n if start.x == target.x:\n east_west = STILL\n elif start.x < target.x:\n if abs(target.x - start.x) <= self.game_map.width / 2:\n east_west = EAST\n else:\n east_west = WEST\n else:\n if abs(target.x - start.x) <= self.game_map.width / 2:\n east_west = WEST\n else:\n east_west = EAST\n\n if start.y == target.y:\n north_south = STILL\n elif start.y < target.y:\n if abs(target.y - start.y) <= self.game_map.height / 2:\n north_south = SOUTH\n else:\n north_south = NORTH\n else:\n if abs(target.y - start.y) <= self.game_map.height / 2:\n north_south = NORTH\n else:\n north_south = SOUTH\n\n # know the deisred direction, check if either is owned by self\n logging.debug(\"directions available from %s move %d %d\", start, north_south, east_west)\n\n # flip a coin here to see which direction to test first\n if random.random() > 0.5:\n test_directions = (north_south, east_west)\n else:\n test_directions = (east_west, north_south)\n\n for direction in test_directions:\n if direction != STILL:\n return Move(start, direction)\n\n return None\n\n def update_owned_sites(self):\n\n self.owned_sites = list()\n\n # this will update the list of sites that are owned by self (will contain locations)\n for square in self.game_map:\n if square.owner == self.id:\n self.owned_sites.append(square)\n self.time_at_square[square] += 1\n self.expected_strength[square] = square.strength\n logging.debug(\"added owned site %s\", square)\n else:\n self.time_at_square[square] = 0\n self.expected_strength[square] = -square.strength\n\n return\n\n def get_unowned_border(self) -> Set[Square]:\n # this will determine the spaces that border the owned pieces\n # iterate through the spaces\n\n border_sites = set()\n\n logging.debug(\"inside the getBorderCall, myID = %d\" % self.id)\n\n for location in self.game_map:\n\n # skip if already found or if owned by self\n if location in border_sites or location.owner == self.id:\n continue\n\n for neighbor in self.game_map.neighbors(location):\n # if a neighbor is owned by self, this is a neighbor, add to set\n if neighbor.owner == self.id:\n border_sites.add(location)\n break\n\n # do something with the border sites\n return border_sites\n","sub_path":"bots/newest/HaliteBotCode.py","file_name":"HaliteBotCode.py","file_ext":"py","file_size_in_byte":9760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"369269365","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 31 10:36:01 2019\r\n\r\n@author: K\r\n\"\"\"\r\n\r\n# 递归写法\r\ndef binary_search(ls,item):\r\n n=len(ls)\r\n mid=(n)//2 \r\n if n>0:\r\n if ls[mid]==item:\r\n return True\r\n elif ls[mid]>item:\r\n return binary_search(ls[:mid],item)\r\n elif ls[mid]item:\r\n last=mid-1\r\n elif ls[mid]item:\r\n last=mid-1\r\n elif ls[mid]item:\r\n last=mid-1\r\n elif ls[mid]item: \r\n if mid==1 or ls[mid-1]<=item: \r\n return mid\r\n else:\r\n last=mid-1 \r\n elif ls[mid]<=item:\r\n first=mid+1\r\n return None\r\n\r\n\r\n#查找最后一个小于等于某值的索引 \r\n\r\ndef binary_search_last_bigger_index(ls,item): \r\n \r\n first=0\r\n last=len(ls)-1\r\n \r\n while first<=last: \r\n mid=(first+last)//2 \r\n print('mid=',mid)\r\n\r\n if ls[mid]<=item:\r\n \r\n if mid==len(ls)-1: # 最后一个元素 \r\n return mid\r\n if ls[mid+1]>item: \r\n return mid \r\n \r\n else:\r\n first=mid+1 #往后移动\r\n elif ls[mid]>item: \r\n last=mid-1\r\n return None\r\n \r\nif __name__ == '__main__':\r\n ls=[1,2,3,4,5]\r\n print (binary_search(ls,3))\r\n print (binary_search(ls,10))\r\n print (binary_search2(ls,10))\r\n print (binary_search2(ls,1))\r\n \r\n ls2=[1,2,3,3,3,4,5]\r\n print('变形一的结果')\r\n print (binary_search_first_index(ls2,4)) #5\r\n print (binary_search_first_index(ls2,3)) #2\r\n \r\n print(binary_search_last_index(ls2,3)) # 4\r\n print(binary_search_last_index(ls2,4)) #6\r\n \r\n print('变形三的结果是: ')\r\n print( binary_search_first_bigger_index(ls2,3)) \r\n \r\n print('变形四的结果是: ')\r\n print( binary_search_last_bigger_index(ls2,3)) \r\n \r\n","sub_path":"二分法查找.py","file_name":"二分法查找.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"144586182","text":"# Given a linked list, swap every two adjacent nodes and return its head.\n# You may not modify the values in the list's nodes, only nodes itself may be changed.\n# Example:\n# Given 1->2->3->4, you should return the list as 2->1->4->3.\n\n# 为完成\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def swapPairs(self, head: ListNode) -> ListNode:\n dummyHead = ListNode(None)\n dummyHead.next = head\n p = dummyHead\n while (p.next and p.next.next):\n node1 = p.next\n node2 = node1.next\n next = node2.next\n\n node2.next = node1\n node1.next = next\n p.next = node2\n\n p = node1\n return dummyHead.next\n\n\n\n# output linkedlist val\ndef prinLinedList(head):\n curNode = head\n while (curNode is not None):\n print(curNode.val)\n curNode = curNode.next\n\n\nif __name__ == '__main__':\n s1 = ListNode(1)\n s2 = ListNode(2)\n s3 = ListNode(3)\n s4 = ListNode(4)\n s1.next = s2\n s2.next = s3\n s3.next = s4\n so = Solution()\n prinLinedList(so.swapPairs(s1))\n","sub_path":"lc024.py","file_name":"lc024.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"330082793","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom taggit.managers import TaggableManager\n\nclass TimeStampedModel(models.Model):\n\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n abstract = True\n\n# ------------------------------------------------------------------\n# TableName : ItemPostModel\n# Description : 중고 아이템 올리는 테이블\n# ------------------------------------------------------------------\nclass ItemPostModel(TimeStampedModel):\n class Meta:\n verbose_name_plural = \"중고 아이템 올리는 테이블\"\n\n TYPE_CHOICES = (\n ('여성의류', '여성의류'),\n ('남성의류', '남성의류'),\n ('뷰피/미용', '뷰피/미용'),\n ('유아동/출산', '유아동/출산'),\n ('스포츠/레저', '스포츠/레저'),\n ('디지털/가전', '디지털/가전'),\n ('도서/티켓/취미/애완', '도서/티켓/취미/애완'),\n ('생활/문구/가구/식품', '생활/문구/가구/식품'),\n ('차량/오토바이', '차량/오토바이'),\n ('스타굿즈', '스타굿즈'),\n ('기타', '기타'),\n ('평화나눔', '평화나눔'),\n )\n\n STATE_CHOICES = (\n ('중고', '중고'),\n ('중고 + 하자 (하자가 없는 중고)', '중고 + 하자 (하자가 없는 중고)'),\n ('새것 + 하자 (하자가 없는 새것)', '새것 + 하자 (하자가 없는 새것)'),\n ('거의 새것 (하자 없음)', '거의 새것 (하자 없음)'),\n ('새물품 (미사용)', '새물품 (미사용)'),\n )\n\n user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='유저')\n images = models.ImageField(null=True, blank=True)\n type_item = models.CharField(max_length=32, choices=TYPE_CHOICES , verbose_name='카테고리')\n state_item = models.CharField(max_length=32, choices=STATE_CHOICES , verbose_name='상태')\n location = models.CharField(max_length=32, verbose_name='거래지역')\n title = models.CharField(max_length=64, verbose_name='제품명')\n cost = models.PositiveIntegerField(verbose_name='예상금액')\n contents = models.TextField(verbose_name='내용')\n amount = models.PositiveIntegerField(verbose_name='갯수')\n tags = TaggableManager()\n\n\n def __str__(self):\n return '상품명: {} / 판매자: {}'.format(self.title, self.user)\n \n# ------------------------------------------------------------------\n# TableName : ItemPickModel\n# Description : 내가 찜한 중고 아이템 테이블\n# ------------------------------------------------------------------\nclass ItemPickModel(models.Model):\n class Meta:\n verbose_name_plural = \"내가 찜한 중고 아이템 테이블\"\n\n user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='유저')\n item = models.ForeignKey(ItemPostModel, on_delete=models.CASCADE, verbose_name='프로젝트')\n","sub_path":"peace/_give/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"309230657","text":"\n\n\nfrom m5stack import *\nfrom m5ui import *\nfrom uiflow import *\nimport network\nimport os\nfrom machine import UART\nimport time\nimport struct\nimport ujson\n\n\n\n# Parte de python-------onda-----------\n\nser = UART(1, 9600, tx=17, rx=16,bits=8, parity=None, stop=1, timeout=100)\nWAVEFORM=bytes(':GWAV35\\r','utf-8')#Peticion de onda\nABRT=bytes(':ABRT29\\r','utf-8') #Aborta comando en ejecucion\nDUMP=bytes(':DUMP36\\r','utf-8')# Petición vp, average, points, distance, window length, probe length, probe offset\n\nSVP=bytes(':S_VP','utf-8') #set vp\nSNAV=bytes(':SNAV','utf-8')# set number average points\nSPLR=bytes(':SPRL','utf-8')#set probe length\nSPRO=bytes(':SPRO','utf-8')#set probe offset\nSPCC =bytes(':SPCC','utf-8')#set probe cell constant\nSDIS=bytes(':SDIS','utf-8')#set distance (cable length)\nSPNT =bytes(':SPNT','utf-8')#set number of points\nSWLN=bytes(':SWLN','utf-8')#set window length\n\n\ndef urldecode(str):\n dic = {\"%21\":\"!\",\"%22\":'\"',\"%23\":\"#\",\"%24\":\"$\",\"%26\":\"&\",\"%27\":\"'\",\"%28\":\"(\",\"%29\":\")\",\"%2A\":\"*\",\"%2B\":\"+\",\"%2C\":\",\",\"%2F\":\"/\",\"%3A\":\":\",\"%3B\":\";\",\"%3D\":\"=\",\"%3F\":\"?\",\"%40\":\"@\",\"%5B\":\"[\",\"%5D\":\"]\",\"%7B\":\"{\",\"%7D\":\"}\"}\n for k,v in dic.items(): str=str.replace(k,v)\n return str\n\n\ndef HL(datos):\n sum=-58\n mv=memoryview(datos)\n for el in mv:\n sum+=el\n sum=sum % 256\n hl = hex(sum)[2:].upper()\n return (datos+bytes(hl,'utf-8')+bytes([13]))\n\ndef darValor(comando, valor):\n comando=comando+b' '+bytes(str(valor),'utf-8')\n return HL(comando)\n\ndef getWaveForm(ser):#si esperamos antes de pedir la onda ser.any()!=\n ser.write(WAVEFORM)\n while ser.any()<1: \n time.sleep(0.1)\n\n header = ser.read(6)\n if header[1] !=35:\n M5TextBox(24, 134, \"Cant recive wave. Retrying\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n return \"Error\"+ str(header[1])\n data = ser.read()\n time.sleep(0.1)\n \n while ser.any()>0: \n data+=ser.read()\n time.sleep(0.1)\n \n ondaBin=data.replace((bytes([34])+bytes([243])), bytes([13]))#0x22 0xf3 > 0x0d\n ondaBin=ondaBin.replace((bytes([34])+bytes([222])), bytes([34]))#0x22 0xde > 0x22\n ondaBin=ondaBin.replace((bytes([34])+bytes([198])), bytes([58]))#0x22 0xc6 > 0x3a\n try: \n onda=struct.unpack('>251f',ondaBin)\n M5TextBox(100, 120, \"Done\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n return onda\n except: \n M5TextBox(100, 120, \"Unexpected Error. Retrying\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n return \"Error Unknow: Expected 1007 Bytes an recive \"+str(len(ondaBin))\n #Este error parece ser que solo ocurre con el tdr a 57600 Baudios. Cuando esto ocurre\n #no hay ningun byte que recibir, ser.any()=0, pero sin embargo no ha recibido 251 puntos. \n #Aun no he encontrado el porque del error\n \ndef getWaveJsonFich(ser):\n\twave=getWaveForm(ser)\n\tf=open(\"onda.json\", \"w\")\n\tf.write(ujson.dumps(wave))\n\t#lcd.print('ok')\n\tf.close()\n\n\treturn\n\ndef peticion(ser, pe):\n try:\n ser.write(pe)\n time.sleep(0.1)\n i=0\n while(ser.any()==0 and i<25):\n time.sleep(0.1)\n i+=1\n recibido=ser.readline()\n if(str(recibido)[3]!='$'):\n M5TextBox(24, 134, \"Error sending configuration\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n return False\n lcd.print('.')\n time.sleep(0.3)\n return True\n except SerialException():\n M5TextBox(24, 134, \"Cant configurate\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n return False\n\n\ndef configEC(ser): \n if(not peticion(ser, ABRT)):\n return False\n if(not peticion(ser, darValor(SVP, 0.99))):\n return False\n if(not peticion(ser, darValor(SNAV,1))):\n return False\n if(not peticion(ser, darValor(SPLR,0.3))):\n return False\n if(not peticion(ser, darValor(SPRO,0.09))):\n return False\n if(not peticion(ser, darValor(SPCC,1))):\n return False\n if(not peticion(ser, darValor(SDIS,0))):\n return False\n if(not peticion(ser, darValor(SPNT,251.0000000))):\n return False\n if(not peticion(ser, darValor(SWLN,50))):\n return False\n return True\n \n\ndef requestToJson(req): \n datos=req[req.find('myData')+7:-1] \n return urldecode(datos)\n \ndef configTdr100(json):\n if(not peticion(ser, ABRT)):\n return False\n dic=ujson.loads(json)\n if(not peticion(ser, darValor(SVP, dic['vp']))):\n return False\n if(not peticion(ser, darValor(SNAV,dic['averagePoints']))):\n return False\n if(not peticion(ser, darValor(SPLR,dic['probeLength']))):\n return False\n if(not peticion(ser, darValor(SPRO,dic['probeOffset']))):\n return False\n if(not peticion(ser, darValor(SPCC,dic['probeCell']))):\n return False\n if(not peticion(ser, darValor(SDIS,dic['cableLength']))):\n return False\n if(not peticion(ser, darValor(SPNT,dic['numberPoints']))):\n return False\n if(not peticion(ser, darValor(SWLN,dic['windowLength']))):\n return False\n return True\n \n\ndef saveConfig(json):\n config=ujson.loads(urldecode(json))\n f=open('web/json/config.json', 'r')\n configs = ujson.loads(f.read())\n f.close()\n if str(config['configName']) in configs:\n return False\n else: \n configs[str(config['configName'])] = config\n f = open('web/json/config.json', 'w') \n f.write(ujson.dumps(configs))\n f.close()\n return True\n \ndef deleteConfig(key): #dada una key elmina del fichero la configuracion\n f=open('web/json/config.json', 'r')\n configs = ujson.loads(f.read())\n f.close()\n if str(key) in configs:\n del configs[str(key)] \n f = open('web/json/config.json', 'w') \n f.write(ujson.dumps(configs))\n f.close()\n return True\n else: \n return False\n\ndef keyConfigJson(key): #dada una key devuelve una configuración en json\n f=open('web/json/config.json', 'r')\n configs = ujson.loads(f.read())\n return ujson.dumps(configs[str(key)])\n\n#parte server -------------------\n\n\n\ntry:\n import usocket as socket\nexcept:\n import socket\n\n\n\nap = network.WLAN(network.AP_IF)\nap.active(True)\nap.config(essid='TDR_WIFI')\nap.config(authmode=3, password='123456789')\nlcd.clear()\n\nresponse = None\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('192.168.4.1',80))\ns.listen(5)\n\nM5TextBox(43, 15, \"WELCOME TO TDR WIFI\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\nM5TextBox(21, 49, \"Connect to wifi: TDR_WIFI \", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\nM5TextBox(21, 79, \"Password: 123456789\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\nM5TextBox(24, 134, \"Then go to your navigator\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\nM5TextBox(25, 162, \"and enter page: 192.168.4.1\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\nrgb.setColorFrom(6 , 10 ,25)\nrgb.setColorFrom(1 , 5 ,25)\nrgb.setBrightness(100)\n\nwhile True:\n conn, addr = s.accept()\n request = conn.recv(1024)\n request = str(request)\n #print ('Content = %s' % request)\n #lcd.print('Content = %s' % request,0,50,0xffffff)\n if ap.isconnected() == True:\n lcd.clear()\n M5TextBox(55, 15, \"TDR WIFI\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n M5TextBox(21, 49, \"Connected\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n rgb.setBrightness(0)\n else:\n lcd.clear()\n M5TextBox(21, 49, \"Not Connected\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n\n\n\n\n\n if request.find('/js/scriptMedicion.js') > 0:\n f=open('web/js/scriptMedicion.js', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/javascript\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n\n elif request.find('/js/jquery-3.4.1.js') > 0:\n f=open('web/js/jquery-3.4.1.js.gz', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/javascript\\n')\n conn.send('Content-Encoding: gzip\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n\n elif request.find('/js/bootstrap.min.js') > 0:\n f=open('web/js/bootstrap.min.js.gz', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/javascript\\n')\n conn.send('Content-Encoding: gzip\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n\n elif request.find('/js/d3.js') > 0:\n f=open('web/js/d3.js.gz', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/javascript\\n')\n conn.send('Content-Encoding: gzip\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n\n elif request.find('/js/bootstrap.bundle.min.js') > 0:\n f=open('web/js/bootstrap.bundle.min.js.gz', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/javascript\\n')\n conn.send('Content-Encoding: gzip\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n\n elif request.find('/js/bootstrap-table.min.js') > 0:\n f=open('web/js/bootstrap-table.min.js.gz', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/javascript\\n')\n conn.send('Content-Encoding: gzip\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n\n\n elif request.find('/css/bootstrap-table.min.css') > 0:\n f=open('web/css/bootstrap-table.min.css.gz', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: text/css\\n')\n conn.send('Content-Encoding: gzip\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n\n elif request.find('/css/bootstrap.min.css') > 0:\n f=open('web/css/bootstrap.min.css.gz', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: text/css\\n')\n conn.send('Content-Encoding: gzip\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n \n elif request.find('/json/onda.json') > 0:\n M5TextBox(21, 79, \"Aquaring waveform...\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n key=requestToJson(request)\n config=keyConfigJson(key)\n configdic=ujson.loads(config)\n if(configTdr100(config)):\n onda=getWaveForm(ser)\n if onda[0]==\"E\":\n datos=dict(error=onda[5:])\n else:\n datos=dict(wave=onda,cL=configdic['cableLength'] ,wL=configdic['windowLength'], firstPeak=configdic['firstPeak'])\n else:\n datos=dict(error='config')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/json\\n')\n conn.send('Connection: close\\n\\n')\n conn.sendall(ujson.dumps(datos))\n conn.close()\n\n\n elif request.find('/configBaudRate') > 0: \n valor=requestToJson(request)\n try:\n ser.init(int(valor), tx=17, rx=16,bits=8, parity=None, stop=1, timeout=100)\n datos=dict(send=\"ok\")\n except:\n datos=dict(error=\"Cant change Baudrate\")\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/json\\n')\n conn.send('Connection: close\\n\\n')\n conn.sendall(ujson.dumps(datos))\n conn.close()\n\n \n elif request.find('/configOnda') > 0:\n M5TextBox(21, 79, \"Aquaring waveform...\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n if(configTdr100(requestToJson(request))):\n onda=getWaveForm(ser)\n if onda[0]==\"E\":\n datos=dict(error=onda[5:])\n else:\n datos=dict(wave=onda)\n else: \n datos=dict(error='config')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/json\\n')\n conn.send('Connection: close\\n\\n')\n conn.sendall(ujson.dumps(datos))\n conn.close()\n \n elif request.find('/saveConfig') > 0:\n M5TextBox(21, 79, \"Saving config...\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n lcd.clear()\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/json\\n')\n conn.send('Connection: close\\n\\n')\n if(saveConfig(urldecode(requestToJson(request)))):\n conn.sendall(ujson.dumps('Saved configuration'))\n else: \n conn.sendall(ujson.dumps('Cant save this configuration. Try to change name Configuration'))\n conn.close()\n\n elif request.find('/deleteConfig') > 0: \n M5TextBox(21, 79, \"Deleting config...\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/json\\n')\n conn.send('Connection: close\\n\\n')\n if(deleteConfig(urldecode(requestToJson(request)))):\n conn.sendall(ujson.dumps('Deleted configuration'))\n else: \n conn.sendall(ujson.dumps('Cant delete Configuration'))\n conn.close()\n \n elif request.find('/json/ec.json') > 0:\n M5TextBox(21, 79, \"Aquaring EC...\", lcd.FONT_DejaVu18,0xFFFFFF, rotate=0)\n if(configEC(ser)):\n onda=getWaveForm(ser)\n if onda[0]==\"E\":\n datos=dict(error=onda[5:])\n else:\n datos=dict(wave=onda,cL=configdic['cableLength'] ,wL=configdic['windowLength'], firstPeak=configdic['firstPeak'])\n else:\n datos=dict(error='config')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/json\\n')\n conn.send('Connection: close\\n\\n')\n conn.sendall(ujson.dumps(datos))\n conn.close()\n \n elif request.find('/parametrosTdr100.html') > 0:\n f=open('web/parametrosTdr100.html', 'r')\n parametrosTdr100=f.read()\n f.close()\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: text/html\\n')\n conn.send('Connection: close\\n\\n')\n conn.sendall(parametrosTdr100)\n conn.close()\n \n\n\n \n elif request.find('/parametrosTek.html') > 0:\n f=open('web/parametrosTek.html', 'r')\n parametrosTek=f.read()\n f.close()\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: text/html\\n')\n conn.send('Connection: close\\n\\n')\n conn.sendall(parametrosTek)\n \n \n elif request.find('/datosConfig') > 0:\n f=open('web/json/config.json', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: application/json\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n \n\n\n \n\n\n#cambiar el else final por un elif?\n else:\n f=open('web/medicion.html', 'r')\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: text/html\\n')\n conn.send('Connection: close\\n\\n')\n datos = f.read(1024)\n while datos != \"\":\n conn.sendall(datos)\n datos=f.read(1024)\n f.close()\n conn.close()\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"m5Comunication.py","file_name":"m5Comunication.py","file_ext":"py","file_size_in_byte":14909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"587326726","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#THE GOAL OF THIS PROJECT IS TO PROVE THE HIGHER THE GDP THE HIGHER THE AVERAGE LIFE EXPECTANCY IS#\n\n\n# In[1]:\n\n\n#IMPORTING THE NECESSARY LIBRARIES\n\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\n\n# In[93]:\n\n\n#GETTIN TO KNOW WITH THE DATA\n\ndf = pd.read_csv('all_data.csv')\nprint(df.head())\n\n#MAKING THE COLUMN NAMES EASIER TO USE\n\ndf.rename(columns={'Country':'country','Year':'year', 'Life expectancy at birth (years)':'life_exp_years','GDP':'gdp'}, inplace=True)\nprint(df.head())\n\n#CHECKING THE DATATYPES FOR FURTHER USE\n\nprint(df.dtypes)\n\n\ndf['gdp_int'] = df.gdp.apply(lambda x: int(x))\ndf['gdp_billion_dollar'] = df.gdp_int.apply(lambda x : x/1000000000)\n\ndel df['gdp_int']\ndel df['gdp']\n\n\n#OUR DATA IS CLEAN AND READY TO USE\n\n\n# In[222]:\n\n\n#CHECKING THE DIFFERENCE IN THE GDP FOR THE YEARS IN THE 6 NATIONS\nyears=[2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015]\n\nchile = df[df['country'] == 'Chile']\nchina = df[df['country'] == 'China']\nusa = df[df['country'] == 'United States of America']\nzim = df[df['country'] == 'Zimbabwe']\nmex = df[df['country'] == 'Mexico']\nger = df[df['country'] == 'Germany']\n\n\n\nplt.figure(figsize=(10,6))\nsns.set()\nsns.set_style('white')\nsns.set_palette('Pastel2')\nsns.set_context('talk')\nax = plt.subplot()\nax.set_title('The GDPs compared between the countries')\nplt.plot(years,chile['gdp_billion_dollar'],label='Chile')\nplt.plot(years,china['gdp_billion_dollar'],label='China')\nplt.plot(years,usa['gdp_billion_dollar'],label='United States of America')\nplt.plot(years,zim['gdp_billion_dollar'],label='Zimbabwe')\nplt.plot(years,mex['gdp_billion_dollar'],label='Mexico')\nplt.plot(years,ger['gdp_billion_dollar'],label='Germany')\nplt.legend()\nplt.savefig('gdp_between_countries.png')\nplt.show()\n\n\n# In[223]:\n\n\n#GDP FOR DIFFERENT NATIONS\nsns.set()\nsns.set_palette('Pastel1')\nsns.set_style('white')\nsns.set_context('talk')\n\nplt.figure(figsize=(20,25))\n\n\nax1 = plt.subplot(3,2,1)\nax1.set_title('Chiles GDP over the last 15 years')\nax1.set_yticks([])\nax1 = plt.plot(years,chile['gdp_billion_dollar'],label='Chile')\nplt.legend(loc='upper left')\n\nax2 = plt.subplot(3,2,2)\nax2.set_title('Chinas GDP over the last 15 years')\nax2.set_yticks([])\nax2 = plt.plot(years,china['gdp_billion_dollar'],label='China')\nplt.legend()\n \nax3= plt.subplot(3,2,3)\nax3.set_title('The USA\\'s GDP over the last 15 years')\nax3.set_yticks([]) \nax3 = plt.plot(years,usa['gdp_billion_dollar'],label='United States of America')\nplt.legend()\n \nax4 = plt.subplot(3,2,4)\nax4.set_title('Zimbabwes GDP over the last 15 years')\nax4.set_yticks([])\nax4 = plt.plot(years,zim['gdp_billion_dollar'],label='Zimbabwe')\nplt.legend()\n \nax5 = plt.subplot(3,2,5)\nax5.set_title('Mexicos GDP over the last 15 years')\nax5.set_yticks([])\nax5 = plt.plot(years,mex['gdp_billion_dollar'],label='Mexico')\nplt.legend()\n \nax6 = plt.subplot(3,2,6)\nax6.set_title('Germanys GDP over the last 15 years')\nax6.set_yticks([])\nax6 = plt.plot(years,ger['gdp_billion_dollar'],label='Germany')\nplt.legend()\nplt.savefig('gdp_countries.png')\nplt.show()\n\n\n# In[224]:\n\n\n#CHECKING THE AVERAGE LIFEEXPECTANCY OF THE NATIONS\n\ncountries_x = list(set(df['country']))\nplt.figure(figsize=(8,10))\nax = plt.subplot()\nax.set_xticks(range(6))\nax.set_xticklabels(countries_x, rotation=270)\n#ax.set_xlabel('Countries')\n#ax.set_ylabel('Years')\nax.set_title('Average Life Expectancy In The Countries')\nsns.set(style='whitegrid', palette='Pastel1', context='talk')\nsns.barplot(data=df, x=df['country'], y='life_exp_years', ci=None)\nplt.savefig('avg_life_exp.png')\nplt.show()\n\n\n# In[225]:\n\n\n#COMPARING LIFE ECPECTANCY\n\nsns.set(palette='Pastel1', style='whitegrid', context='talk')\nplt.figure(figsize=(30,5))\nsns.barplot(data=df, x='year', y='life_exp_years',hue='country')\nplt.savefig('avg_life_exp_by_year.png')\nplt.show()\n\n\n# In[226]:\n\n\nsns.set(palette=\"Pastel1\", style='white', context='talk')\nplt.figure(figsize=(10,8))\nax = plt.subplot()\nax.set_title('The life expectancy over the past 15 years')\nax.set_xlabel('Years')\nax.set_ylabel('Average life exepectancy')\n#ax.title('The Life Expectancy Over The PAst 15 Years')\nplt.plot(years, chile['life_exp_years'], label='Chile')\nplt.plot(years, usa['life_exp_years'],label='USA')\nplt.plot(years, zim['life_exp_years'], label='Zimbabwe')\nplt.plot(years, china['life_exp_years'], label='China')\nplt.plot(years, ger['life_exp_years'], label='Germany')\nplt.plot(years, mex['life_exp_years'], label='Mexico')\nplt.savefig('life_exp_lineplot.png')\nplt.legend()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n\n# In[227]:\n\n\n#AVERAGE LIFE EXPECTANCY FOR THE LAST 15 YEARS\n\n\n\nmean_life_exp = df.groupby('country').life_exp_years.mean().reset_index()\nprint(mean_life_exp)\n\n\nsns.set(style='dark', palette='Pastel1', context=\"talk\")\nplt.figure(figsize=(10,8))\nax=plt.subplot()\nax.set_title('Average life expectancy for the past 15 years')\nax.set_xticklabels(list(set(df['country'])), rotation=60)\nsns.barplot(data=df, x='country', y='life_exp_years')\nplt.savefig('avg_life_exp_bar.png')\nplt.show()\n\n\n# In[228]:\n\n\n#DISTRIBUTION FOR THE AVG LIFE EXPECTANCY AND THE AVERAGE GDP\n\n\nsns.set(palette='Pastel1', style='dark', context='talk')\nplt.figure(figsize=(10,8))\nax = plt.subplot()\nsns.violinplot(data=df, x='country', y='life_exp_years')\nplt.savefig('life_exp_dist_violin.png')\nplt.show()\n\n\n# In[230]:\n\n\n#ZIMBABWE LOOKS INTERESTING SO WE SHOULD TAKE A CLOSER LOOK AT IT\n\nsns.set(palette='Pastel1', style='dark', context='talk')\nplt.figure(figsize=(10,8))\nax = plt.subplot()\nplt.plot(zim['year'],zim['life_exp_years'],label='Life Expectancy')\nplt.plot(zim['year'],zim['gdp_billion_dollar'], label='GDP (Billion Dollar)')\nplt.legend()\nplt.savefig('zim_gdp_vs_life_exp1.png')\nplt.show()\n\n\nsns.violinplot(data=zim,x='country',y='life_exp_years')\nplt.savefig('zim_life_Exp_violin.png')\nplt.show()\nsns.boxplot(data=zim, x='country', y='life_exp_years')\nplt.savefig('zim_life_exp_box.png')\nplt.show()\n\n\n# In[232]:\n\n\ndef gdp_vs_life_exp(df):\n \n n = 1 # This is our first dataset (out of 2)\n t = 2 # Number of dataset\n d = 16 # Number of sets of bars\n w = 0.8 # Width of each bar\n bars1_x = [t*element + w*n for element\n in range(d)]\n\n n = 2 # This is our first dataset (out of 2)\n t = 2 # Number of dataset\n d = 16 # Number of sets of bars\n w = 0.8 # Width of each bar\n bars2_x = [t*element + w*n for element\n in range(d)]\n \n country_name = df.iloc[0,0]\n #print(country_name)\n middle_x = [ (a + b) / 2.0 for a, b in zip(bars1_x, bars2_x)]\n file_name= df.iloc[0,0] + '_bar_plot.png'\n \n if 'Zimbabwe' in country_name: #ONLY FOR ZIMBABWE IT HAS SO SMALL GDP IMPOSSIBLE TO COMPARE W/O THIS MODIFICATION\n bar1_y = [x*5 for x in list(set(df['gdp_billion_dollar']))]\n \n ax = plt.subplot()\n ax.set_yticks([])\n ax.set_title(country_name)\n plt.xticks(middle_x, years)\n ax.set_xticklabels(years,rotation=270)\n plt.bar(bars1_x,bar1_y, label='GDP')\n plt.bar(bars2_x,df['life_exp_years'], label='Life Expectancy')\n plt.legend()\n plt.savefig(file_name)\n plt.show()\n else:\n bar1_y = [x/40 for x in list(set(df['gdp_billion_dollar']))]\n \n ax = plt.subplot()\n ax.set_yticks([])\n ax.set_title(country_name)\n plt.xticks(middle_x, years)\n ax.set_xticklabels(years,rotation=270)\n plt.bar(bars1_x,bar1_y, label='GDP')\n plt.bar(bars2_x,df['life_exp_years'], label='Life Expectancy')\n plt.legend()\n plt.savefig(file_name)\n plt.show()\n\ngdp_vs_life_exp(zim)\ngdp_vs_life_exp(usa)\ngdp_vs_life_exp(ger)\ngdp_vs_life_exp(china)\ngdp_vs_life_exp(mex)\ngdp_vs_life_exp(chile)\n\n","sub_path":"life_expectancy_gdp (1).py","file_name":"life_expectancy_gdp (1).py","file_ext":"py","file_size_in_byte":7842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"594496158","text":"# Author: An Jiaoyang\n# 2018/6/2 16:40\n# =============================\n\"\"\"高层API\nTF 推荐使用 tf.keras 高层API\n换句话说,eager模式支持大部分的高层API\n\"\"\"\nimport tensorflow as tf\ntf.enable_eager_execution()\ntfe = tf.contrib.eager\n\n\ndef main():\n # Keras API\n layer = tf.keras.layers.Dense(10, input_shape=(None, 5))\n layer = tf.keras.layers.Dense(10) # 根据输入,自动推断输入大小\n\n # use the layer\n output = layer(tf.zeros([10, 5])) # input 10x5 output (10x5)x(5x10)=(10x10)\n print('output=', output, '\\nvariables=', layer.variables) # W (5x10) b (10)\n print(output.shape, layer.kernel.shape, layer.bias.shape)\n\n # 自定义 layer\n class MyDenseLayer(tf.keras.layers.Layer):\n def __init__(self, num_outputs):\n super(MyDenseLayer, self).__init__() # 等价于 super().__init__()\n self.num_outputs = num_outputs\n\n def build(self, input_shape):\n self.kernel = self.add_variable('kernel', shape=[input_shape[-1].value, self.num_outputs])\n\n def call(self, inputs):\n return tf.matmul(inputs, self.kernel)\n\n layer = MyDenseLayer(10)\n print(layer(tf.zeros([1, 10])))\n print(layer.variables)\n\n # 使用现有层组成新的层(封装)\n print('#' * 20)\n\n class ResnetIdentityBlock(tf.keras.Model):\n def __init__(self, kernel_size, filters):\n super(ResnetIdentityBlock, self).__init__(name='')\n filter1, filter2, filter3 = filters\n\n self.conv2a = tf.keras.layers.Conv2D(filter1, (1, 1)) # 输出通道数 滤波器大小\n self.bn2a = tf.keras.layers.BatchNormalization()\n\n self.conv2b = tf.keras.layers.Conv2D(filter2, kernel_size, padding='same')\n self.bn2b = tf.keras.layers.BatchNormalization()\n\n self.conv2c = tf.keras.layers.Conv2D(filter3, (1, 1))\n self.bn2c = tf.keras.layers.BatchNormalization()\n\n def call(self, input_tensor, training=False):\n x = self.conv2a(input_tensor)\n x = self.bn2a(x, training=training)\n x = tf.nn.relu(x)\n\n x = self.conv2b(x)\n x = self.bn2b(x, training=training)\n x = tf.nn.relu(x)\n\n x = self.conv2c(x)\n x = self.bn2c(x, training=training)\n\n x += input_tensor\n x = tf.nn.relu(x)\n return x\n\n block = ResnetIdentityBlock(1, [1, 2, 3])\n print(block(tf.zeros([1, 2, 3, 3])))\n for x in block.variables:\n print(x.name)\n\n # 如果模型每一层都是下一层的输出,可以使用序贯模型\n print('#' * 20)\n\n my_seq = tf.keras.Sequential([tf.keras.layers.Conv2D(1, (1, 1)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Conv2D(2, 1, padding='same'),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Conv2D(3, (1, 1)),\n tf.keras.layers.BatchNormalization()])\n print(my_seq(tf.zeros([1, 2, 3, 3])))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"eager_execution/1_basic/5_high_level_api.py","file_name":"5_high_level_api.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"226323195","text":"import os\n\nfrom flask import Flask, request, redirect, url_for\nfrom werkzeug.utils import secure_filename\nfrom flask import send_from_directory\n\nfrom PIL import Image as pil\n# Import python image library to handle images\nimport numpy as np\n# Import numpy library to convert the image to array\n\nUPLOAD_FOLDER = 'uploads'\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n@app.route('/uploads/')\ndef uploaded_file(filename):\n return send_from_directory(app.config['UPLOAD_FOLDER'],filename)\n\n#@app.route()\n\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(\"123.jpg\")\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n #return redirect(url_for('uploaded_file',filename=filename))\n #return img('uploaded_file',filename=filename)\n load_image()\n return '''\n \n Upload new File\n

Upload new File

\n
\n

\n \n

\n \n \n '''\n # def load_image():\n # im=pil.open(\"uploads/123.jpg\").convert(\"L\")\n # im=im.resize((28,28))\n # new_im=im.save(\"uploads/456.jpg\")\n # new_im=np.array(im,'f')\n # rows,cols=new_im.shape\n # for i in range(rows):\n # for j in range(cols):\n # if(new_im[i,j]<=128):\n # new_im[i,j]=0\n # else:\n # new_im[i,j]=1\n # new_im=np.reshape(new_im,(1,784))\n # print(new_im)\n # load_image()\n\n\n# @app.route('/')\ndef load_image():\n im=pil.open(\"uploads/123.jpg\").convert(\"L\")\n im=im.resize((28,28))\n #im.show()\n new_im=im.save(\"uploads/456.jpg\")\n #im=np.array(im,'f')\n new_im=np.array(im,'f')\n \n #im=np.reshape[28,28]\n #im=np.reshape(im,(28,28))\n \n\n rows,cols=new_im.shape\n for i in range(rows):\n for j in range(cols):\n if(new_im[i,j]<=128):\n new_im[i,j]=0\n else:\n new_im[i,j]=1\n new_array=np.reshape(new_im,(1,784))\n #im=pil.fromarray(im)\n\n #im.save(\"6.jpg\")\n print(new_array)\n #load_image()\n #data=im.getdata()\n #data=np.matrix(data)\n #return load_image()\n #data=np.reshape(data,(28,28))\n #new_im=pil.fromarray(data)\n #print(np.asarray(im))\n #new_im.save(\"aa.jpg\")\nif __name__==\"__main__\":\n app.run()","sub_path":"upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"458701515","text":"from django.shortcuts import render\nfrom django.utils.text import slugify\nfrom django.views import generic\n\nfrom .models import BlogEntry, EntryCategory\n\n# Create your views here.\n\n\nclass BlogView(generic.View):\n\n def get(self, request):\n blog_entries = BlogEntry.objects.get_queryset().order_by('-date_published')[0:4]\n categories = EntryCategory.objects.filter(visibility=True)\n context = {\n 'categories': categories,\n 'blog_entries': blog_entries,\n 'page_title': \"My Blog\",\n 'next_page': \"1\",\n }\n return render(request, 'Blog/index.html', context)\n\n\nclass BlogPageView(generic.View):\n\n def get(self, request, page_number):\n start = int(page_number) * 4\n end = start + 4\n blog_entries = BlogEntry.objects.get_queryset().order_by('-date_published')[start:end]\n categories = EntryCategory.objects.filter(visibility=True)\n prev_page = str(int(page_number) - 1)\n\n if int(page_number) == 0:\n prev_page = \"\"\n\n context = {\n 'categories': categories,\n 'blog_entries': blog_entries,\n 'page_title': \"My Blog\",\n 'next_page': str(int(page_number) + 1),\n 'prev_page': prev_page,\n }\n return render(request, 'Blog/index.html', context)\n\n\nclass ArchiveView(generic.View):\n\n def get(self, request):\n entries = BlogEntry.objects.get_queryset()\n categories = EntryCategory.objects.get_queryset()\n context = {\n 'entries': entries,\n 'categories': categories,\n }\n return render(request, 'Blog/archive.html', context)\n\n\nclass CategoryView(generic.View):\n\n def get(self, request, slug):\n categories = EntryCategory.objects.get_queryset()\n category = EntryCategory.objects.filter(slug=slug).get()\n entries = BlogEntry.objects.filter(category=category)\n context = {\n 'entries': entries,\n 'categories': categories,\n 'category_name': category.name,\n }\n return render(request, 'Blog/category.html', context)\n\n\nclass DetailView(generic.View):\n\n def get(self, request, slug):\n categories = EntryCategory.objects.get_queryset()\n entry = BlogEntry.objects.filter(slug=slug).get()\n context = {\n 'blogentry': entry,\n 'categories': categories,\n }\n return render(request, 'Blog/detail.html', context)","sub_path":"Blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"266283045","text":"# https://open.kattis.com/problems/dasort\n# p = number of datasets\n# k = data set number\n# n = length of array\n# positive integers only\n# 10 values per line, except for last line which may have less than 10 values\n\nimport math\n\np = int(input())\n\nfor _ in range(p):\n k, n = [int(x) for x in input().split(' ')]\n \n j = math.ceil(n / 10)\n l = []\n\n for _ in range(j):\n l += [int(x) for x in input().split(' ')]\n \n s = sorted(l)\n\n si = 0\n\n for item in l:\n if item == s[si]:\n si += 1\n print(f'{k} {len(l) - si}')","sub_path":"python/da_sort_3.0.py","file_name":"da_sort_3.0.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"101533908","text":"# from __future__ import print_function, division\n\n# from torch.utils.data import Dataset, DataLoader\n# import torchvision\n# from torchvision import transforms, utils\n\n# import os\n\n# from skimage import io, transform\n# import numpy as np\n# import matplotlib as plt\n\n# import argparse\n# import os\n\n\n\n# import torch.optim as optim\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# from torch.autograd import Variable\n\n# import pandas as pd\n# from sklearn.metrics import accuracy_score, precision_score, recall_score\n# import sklearn.utils\nimport torchvision\nfrom torchvision.models import DenseNet, ResNet\n\n\n# class Model(nn.Module):\n \n# def __init__(self, args):\n# super(Model, self).__init__()\n\n# self.backbone_model: DenseNet = torchvision.models.densenet121(pretrained=True)\n\n# self.fc1 = nn.Linear(in_features=self.backbone_model.classifier.in_features, out_features=args.classes_amount) # muzikas instrumentu klases\n\n# def forward(self, x):\n\n# out = self.backbone_model.features.forward(x)\n# out = F.adaptive_avg_pool2d(out, output_size=(1,1))\n# out = out.view(out.size(0), -1)\n# out = self.fc1.forward(out)\n\n# out = torch.softmax(out, dim=1)\n \n# return out\n\n\nclass Model(nn.Module):\n\n def __init__(self, args):\n super(Model, self).__init__()\n\n self.backbone_model: ResNet = torchvision.models.resnet50(pretrained=False)\n \n \n self.features = torch.nn.Sequential(\n self.backbone_model.conv1,\n self.backbone_model.bn1,\n self.backbone_model.relu,\n self.backbone_model.maxpool,\n\n\n self.backbone_model.layer1,\n # nn.Dropout(0.8),\n self.backbone_model.layer2,\n # nn.Dropout(0.8),\n self.backbone_model.layer3,\n # nn.Dropout(0.8),\n self.backbone_model.layer4,\n # nn.Dropout(0.8)\n\n \n )\n\n # self.fc1 = nn.Linear(in_features=self.backbone_model.fc.in_features, out_features=args.classes_amount)\n \n self.fc1 = nn.Sequential(\n \n nn.Linear(in_features=self.backbone_model.fc.in_features,out_features=args.classes_amount),\n # nn.Dropout(0.8),\n nn.BatchNorm1d(num_features=args.classes_amount),\n # nn.ReLU()\n\n )\n \n\n\n def forward(self, x):\n \n x = x.repeat(1,3,1,1)\n out = self.features.forward(x)\n out = F.adaptive_avg_pool2d(out, output_size=(1,1))\n out = out.view(out.size(0), -1)\n out = self.fc1.forward(out)\n\n out = torch.softmax(out, dim=1)\n\n return out","sub_path":"models_4_audio/ResNet50.py","file_name":"ResNet50.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"317872490","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nUse sklearn based API model to local run and tuning.\n\"\"\"\nimport platform\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport time\n\nfrom functools import reduce\nfrom sklearn.linear_model import Ridge\nfrom sklearn.base import BaseEstimator, RegressorMixin, ClassifierMixin\nfrom sklearn.metrics import explained_variance_score, mean_absolute_error, mean_squared_error, median_absolute_error\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils.estimator_checks import check_estimator\nfrom sklearn.utils.validation import check_X_y, check_array, check_is_fitted\nfrom keras.layers import Input, Dropout, Dense, BatchNormalization, \\\n Activation, concatenate, GRU, Embedding, Flatten\nfrom keras.models import Model\nfrom keras.callbacks import ModelCheckpoint, Callback, EarlyStopping#, TensorBoard\nfrom keras import backend as K\nfrom keras import optimizers\nimport logging\nimport logging.config\nimport lightgbm as lgb\n\nnp.random.seed(123)\n\nif platform.system() == 'Windows':\n N_CORE = 1\n LOCAL_FLAG = True\n import matplotlib.pyplot as plt\n plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签\n plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\n # 有中文出现的情况,需要u'内容'\nelif 's30' in platform.node():\n N_CORE = 1\n LOCAL_FLAG = True\nelse:\n LOCAL_FLAG = False\n\nif LOCAL_FLAG:\n CURR_DIR_Path = os.path.abspath(os.path.dirname(__file__))\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n ROOT_Path = CURR_DIR_Path.split('ProjectCodes')[0]\n sys.path.append(ROOT_Path)\n from ProjectCodes.model.DataReader import DataReader\n from ProjectCodes.model.DataReader import record_log\n RNN_VERBOSE = 10\nelse:\n RNN_VERBOSE = 1\n\n\nUSE_STACK = False\n\n\nif LOCAL_FLAG:\n def start_logging():\n # 加载前面的标准配置\n from ProjectCodes.logging_config import ConfigLogginfDict\n logging.config.dictConfig(ConfigLogginfDict(__file__).LOGGING)\n # 获取loggers其中的一个日志管理器\n logger = logging.getLogger(\"default\")\n logger.info('\\n\\n#################\\n~~~~~~Start~~~~~~\\n#################')\n print(type(logger))\n return logger\n if 'Logger' not in dir():\n Logger = start_logging()\n\nRECORD_LOG = lambda log_str: record_log(LOCAL_FLAG, log_str)\n\n\nclass SelfLocalRegressor(BaseEstimator, RegressorMixin):\n \"\"\" An sklearn-API regressor.\n Model 1: Embedding GRU ---- Embedding(text or cat) -> Concat[GRU(words) or Flatten(cat_vector)] -> Dense -> Output\n Parameters\n ----------\n demo_param : All tuning parameters should be set in __init__()\n A parameter used for demonstation of how to pass and store paramters.\n Attributes\n ----------\n X_ : array, shape = [n_samples, n_features]\n The input passed during :meth:`fit`\n y_ : array, shape = [n_samples]\n The labels passed during :meth:`fit`\n \"\"\"\n\n def __init__(self, data_reader:DataReader, name_emb_dim=20, item_desc_emb_dim=60, cat_name_emb_dim=20, brand_emb_dim=10,\n cat_main_emb_dim=10, cat_sub_emb_dim=10, cat_sub2_emb_dim=10, item_cond_id_emb_dim=5, desc_len_dim=5, name_len_dim=5,\n GRU_layers_out_dim=(8, 16), drop_out_layers=(0.25, 0.1), dense_layers_dim=(128, 64),\n epochs=3, batch_size=512*3, lr_init=0.015, lr_final=0.007):\n self.data_reader = data_reader\n self.name_emb_dim = name_emb_dim\n self.item_desc_emb_dim = item_desc_emb_dim\n self.cat_name_emb_dim = cat_name_emb_dim\n self.brand_emb_dim = brand_emb_dim\n self.cat_main_emb_dim = cat_main_emb_dim\n self.cat_sub_emb_dim = cat_sub_emb_dim\n self.cat_sub2_emb_dim = cat_sub2_emb_dim\n self.item_cond_id_emb_dim = item_cond_id_emb_dim\n self.desc_len_dim = desc_len_dim\n self.name_len_dim = name_len_dim\n self.GRU_layers_out_dim = GRU_layers_out_dim\n assert len(drop_out_layers) == len(dense_layers_dim)\n self.drop_out_layers = drop_out_layers\n self.dense_layers_dim = dense_layers_dim\n self.emb_GRU_model = self.get_GRU_model(data_reader)\n self.epochs = epochs\n self.batch_size = batch_size\n self.lr_init = lr_init\n self.lr_final = lr_final\n\n if USE_STACK:\n self.ridge_lgm_models_list = self.get_ridge_lgm_models()\n\n self.stack_last_model = Ridge(alpha=.6, copy_X=True, fit_intercept=False, max_iter=100, random_state=101, solver='auto', tol=0.01)\n\n def get_GRU_model(self, reader:DataReader):\n # Inputs\n name = Input(shape=[reader.name_seq_len], name=\"name\")\n item_desc = Input(shape=[reader.item_desc_seq_len], name=\"item_desc\")\n # category_name = Input(shape=[reader.cat_name_seq_len], name=\"category_name\")\n item_condition = Input(shape=[1], name=\"item_condition\")\n category_main = Input(shape=[1], name=\"category_main\")\n category_sub = Input(shape=[1], name=\"category_sub\")\n category_sub2 = Input(shape=[1], name=\"category_sub2\")\n brand = Input(shape=[1], name=\"brand\")\n num_vars = Input(shape=[1], name=\"num_vars\")\n desc_len = Input(shape=[1], name=\"desc_len\")\n name_len = Input(shape=[1], name=\"name_len\")\n desc_W_len = Input(shape=[1], name=\"desc_W_len\")\n\n # Embedding的作用是配置字典size和词向量len后,根据call参数的indices,返回词向量.\n # 类似TF的embedding_lookup\n # name.shape=[None, MAX_NAME_SEQ] -> emb_name.shape=[None, MAX_NAME_SEQ, output_dim]\n emb_name = Embedding(input_dim=reader.n_text_dict_words, output_dim=self.name_emb_dim)(name)\n emb_item_desc = Embedding(reader.n_text_dict_words, self.item_desc_emb_dim)(item_desc) # [None, MAX_ITEM_DESC_SEQ, emb_size]\n # emb_category_name = Embedding(reader.n_text_dict_words, self.cat_name_emb_dim)(category_name)\n emb_cond_id = Embedding(reader.n_condition_id, self.item_cond_id_emb_dim)(item_condition)\n emb_cat_main = Embedding(reader.n_cat_main, self.cat_main_emb_dim)(category_main)\n emb_cat_sub = Embedding(reader.n_cat_sub, self.cat_sub_emb_dim)(category_sub)\n emb_cat_sub2 = Embedding(reader.n_cat_sub2, self.cat_sub2_emb_dim)(category_sub2)\n emb_brand = Embedding(reader.n_brand, self.brand_emb_dim)(brand)\n emb_desc_len = Embedding(reader.n_desc_max_len, self.desc_len_dim)(desc_len)\n emb_name_len = Embedding(reader.n_name_max_len, self.name_len_dim)(name_len)\n emb_desc_W_len = Embedding(reader.n_desc_W_max_len, self.desc_len_dim)(desc_W_len)\n\n # GRU是配置一个cell输出的units长度后,根据call词向量入参,输出最后一个GRU cell的输出(因为默认return_sequences=False)\n rnn_layer_name = GRU(units=self.GRU_layers_out_dim[0])(emb_name)\n rnn_layer_item_desc = GRU(units=self.GRU_layers_out_dim[1])(emb_item_desc) # rnn_layer_item_desc.shape=[None, 16]\n # rnn_layer_cat_name = GRU(units=self.GRU_layers_out_dim[2])(emb_category_name)\n\n # main layer\n # 连接列表中的Tensor,按照axis组成一个大的Tensor\n main_layer = concatenate([Flatten()(emb_brand), # [None, 1, 10] -> [None, 10]\n Flatten()(emb_cat_main),\n Flatten()(emb_cat_sub),\n Flatten()(emb_cat_sub2),\n Flatten()(emb_cond_id),\n Flatten()(emb_desc_len),\n Flatten()(emb_name_len),\n Flatten()(emb_desc_W_len),\n rnn_layer_name,\n rnn_layer_item_desc,\n # rnn_layer_cat_name,\n num_vars])\n # Concat[all] -> Dense1 -> ... -> DenseN\n for i in range(len(self.dense_layers_dim)):\n main_layer = Dropout(self.drop_out_layers[i])(Dense(self.dense_layers_dim[i], activation='relu')(main_layer))\n\n # output\n output = Dense(1, activation=\"linear\")(main_layer)\n\n # model\n model = Model(inputs=[name, item_desc, brand, category_main, category_sub, category_sub2, item_condition, num_vars, desc_len, name_len, desc_W_len], # category_name\n outputs=output)\n # optimizer = optimizers.RMSprop()\n optimizer = optimizers.Adam(lr=0.001, decay=0.0)\n model.compile(loss=\"mse\", optimizer=optimizer)\n return model\n\n def get_ridge_lgm_models(self):\n ridge1 = Ridge(alpha=.6, copy_X=True, fit_intercept=True, max_iter=100, normalize=False, random_state=101, solver='auto', tol=0.01)\n ridge2 = Ridge(solver='sag', fit_intercept=True)\n lgb1 = None\n lgb2 = None\n return [ridge1, ridge2, lgb1, lgb2]\n\n\n def fit(self, X, y):\n \"\"\"A reference implementation of a fitting function for a regressor.\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n The training input samples.\n y : array-like, shape = [n_samples]\n The target values. An array of float.\n Returns\n -------\n self : object\n Returns self.\n \"\"\"\n # Check that X and y have correct shape\n # X, y = check_X_y(X, y) # ValueError: setting an array element with a sequence. This is caused by \"XXX_seq\"\n\n self.X_ = X\n self.y_ = y\n\n # FITTING THE MODEL\n steps = int(X.shape[0] / self.batch_size) * self.epochs\n # final_lr=init_lr * (1/(1+decay))**(steps-1)\n exp_decay = lambda init, final, step_num: (init / final) ** (1 / (step_num - 1)) - 1\n lr_decay = exp_decay(self.lr_init, self.lr_final, steps)\n log_subdir = '_'.join(['ep', str(self.epochs),\n 'bs', str(self.batch_size),\n 'lrI', str(self.lr_init),\n 'lrF', str(self.lr_final)])\n K.set_value(self.emb_GRU_model.optimizer.lr, self.lr_init)\n K.set_value(self.emb_GRU_model.optimizer.decay, lr_decay)\n\n # print('~~~~~~~~~~~~In fit() type(X): {}'.format(type(X)))\n keras_X = self.data_reader.get_keras_dict_data(X)\n history = self.emb_GRU_model.fit(keras_X, y, epochs=self.epochs, batch_size=self.batch_size, validation_split=0., # 0.01\n # callbacks=[TensorBoard('./logs/'+log_subdir)],\n verbose=RNN_VERBOSE)\n if USE_STACK:\n sparse_X = self.data_reader.get_ridge_sparse_data(X)\n print('sparse_X.shape={}'.format(sparse_X.shape))\n self.ridge_lgm_models_list[0].fit(sparse_X, y)\n self.ridge_lgm_models_list[1].fit(sparse_X, y)\n params = {\n 'learning_rate': 0.65,\n 'application': 'regression',\n 'max_depth': 3,\n 'num_leaves': 60,\n 'verbosity': -1,\n 'metric': 'RMSE',\n 'data_random_seed': 1,\n 'bagging_fraction': 0.5,\n 'nthread': 4\n }\n\n params2 = {\n 'learning_rate': 0.85,\n 'application': 'regression',\n 'max_depth': 3,\n 'num_leaves': 130,\n 'verbosity': -1,\n 'metric': 'RMSE',\n 'data_random_seed': 2,\n 'bagging_fraction': 1,\n 'nthread': 4\n }\n d_train = lgb.Dataset(sparse_X, label=y)\n self.ridge_lgm_models_list[2] = lgb.train(params, train_set=d_train, num_boost_round=7500, valid_sets=d_train, verbose_eval=1000)\n self.ridge_lgm_models_list[3] = lgb.train(params2, train_set=d_train, num_boost_round=6000, valid_sets=d_train, verbose_eval=500)\n\n # For stacking\n gru_y = self.emb_GRU_model.predict(keras_X)\n gru_y = gru_y.reshape(gru_y.shape[0])\n ridge1_y = self.ridge_lgm_models_list[0].predict(sparse_X)\n ridge2_y = self.ridge_lgm_models_list[1].predict(sparse_X)\n lgb1_y = self.ridge_lgm_models_list[2].predict(sparse_X)\n lgb2_y = self.ridge_lgm_models_list[3].predict(sparse_X)\n second_last_df = pd.DataFrame(data={'gru_y':gru_y, 'ridge1_y':ridge1_y, 'ridge2_y':ridge2_y, 'lgb1_y':lgb1_y, 'lgb2_y':lgb2_y},\n columns=['gru_y', 'ridge1_y', 'ridge2_y', 'lgb1_y', 'lgb2_y'])\n self.stack_last_model.fit(second_last_df, y)\n RECORD_LOG(\"In this fold train get stack_last_model's coefficients: {}\".format(self.stack_last_model.coef_))\n\n # Return the regressor\n return self\n\n def predict(self, X):\n \"\"\" A reference implementation of a prediction for a regressor.\n Parameters\n ----------\n X : array-like of shape = [n_samples, n_features]\n The input samples.\n Returns\n -------\n y : array of int of shape = [n_samples]\n The label for each sample is the label of the closest sample\n seen udring fit.\n \"\"\"\n # Check is fit had been called\n check_is_fitted(self, ['X_', 'y_'])\n\n # Input validation\n # X = check_array(X) # ValueError: setting an array element with a sequence. This is caused by \"XXX_seq\"\n\n keras_X = self.data_reader.get_keras_dict_data(X)\n gru_y = self.emb_GRU_model.predict(keras_X, batch_size=self.batch_size, verbose=RNN_VERBOSE)\n gru_y = gru_y.reshape(gru_y.shape[0])\n\n if USE_STACK:\n sparse_X = self.data_reader.get_ridge_sparse_data(X)\n print('sparse_X.shape={}'.format(sparse_X.shape))\n ridge1_y = self.ridge_lgm_models_list[0].predict(sparse_X)\n ridge2_y = self.ridge_lgm_models_list[1].predict(sparse_X)\n lgb1_y = self.ridge_lgm_models_list[2].predict(sparse_X)\n lgb2_y = self.ridge_lgm_models_list[3].predict(sparse_X)\n\n second_last_df = pd.DataFrame(data={'gru_y': gru_y, 'ridge1_y': ridge1_y, 'ridge2_y': ridge2_y, 'lgb1_y': lgb1_y, 'lgb2_y': lgb2_y},\n columns=['gru_y', 'ridge1_y', 'ridge2_y', 'lgb1_y', 'lgb2_y'])\n return self.stack_last_model.predict(X=second_last_df)\n else:\n return gru_y\n\n\nclass CvGridParams(object):\n scoring = 'neg_mean_squared_error' # 'r2'\n rand_state = 20180117\n\n def __init__(self, param_type:str='default'):\n if param_type == 'default':\n self.name = param_type\n self.all_params = {\n 'name_emb_dim': [20], # In name each word's vector length\n 'item_desc_emb_dim': [60],\n 'cat_name_emb_dim': [20],\n 'brand_emb_dim': [10],\n 'cat_main_emb_dim': [10],\n 'cat_sub_emb_dim': [10],\n 'cat_sub2_emb_dim': [10],\n 'item_cond_id_emb_dim': [5],\n 'desc_len_dim': [5],\n 'name_len_dim': [5],\n 'GRU_layers_out_dim': [(8, 16)], # GRU hidden units\n 'drop_out_layers': [(0.1, 0.1, 0.1, 0.1)],\n 'dense_layers_dim': [(512, 256, 128, 64)],\n 'epochs': [2],\n 'batch_size': [512*3],\n 'lr_init': [0.005],\n 'lr_final': [0.001],\n }\n else:\n print(\"Construct CvGridParams with error param_type: \" + param_type)\n\n def rm_list_dict_params(self):\n for key in self.all_params.keys():\n self.all_params[key] = self.all_params.get(key)[0]\n\n\ndef print_param(cv_grid_params:CvGridParams):\n RECORD_LOG('选取的模型参数为:')\n RECORD_LOG(\"param_name = '{}'\".format(cv_grid_params.name))\n RECORD_LOG(\"regression loss = {}\".format(cv_grid_params.scoring))\n RECORD_LOG(\"rand_state = {}\".format(cv_grid_params.rand_state))\n RECORD_LOG(\"param_dict = {\")\n search_param_list = []\n for k, v in cv_grid_params.all_params.items():\n RECORD_LOG(\"\\t'{}' = {}\".format(k, v))\n if len(v) > 1:\n search_param_list.append(k)\n RECORD_LOG(\"}\")\n return search_param_list\n\n\ndef train_model_with_gridsearch(regress_model:SelfLocalRegressor, sample_df, cv_grid_params):\n sample_X = sample_df.drop('target', axis=1)\n # sample_X = sample_X[['name_int_seq', 'desc_int_seq', 'brand_le', 'cat_main_le', 'cat_sub_le', 'cat_sub2_le', 'item_condition_id', 'shipping']] # , 'cat_int_seq'\n sample_y = sample_df['target']\n\n # Check the list of available parameters with `estimator.get_params().keys()`\n print(\"keys are:::: {}\".format(regress_model.get_params().keys()))\n\n reg = GridSearchCV(estimator=regress_model,\n param_grid=cv_grid_params.all_params,\n n_jobs=N_CORE,\n cv=StratifiedKFold(n_splits=3, shuffle=True, random_state=cv_grid_params.rand_state),\n scoring=cv_grid_params.scoring,\n verbose=2,\n refit=True)\n reg.fit(sample_X, sample_y)\n return reg\n\n\ndef get_cv_result_df(cv_results_:dict, adjust_paras:list, n_cv):\n cols = ['mean_test_score', 'mean_train_score', 'mean_fit_time']\n for param_ in adjust_paras:\n cols.append('param_{}'.format(param_))\n for i in range(n_cv):\n cols.append('split{}_test_score'.format(i))\n for i in range(n_cv):\n cols.append('split{}_train_score'.format(i))\n return pd.DataFrame(data={key: cv_results_[key] for key in cols}, columns=cols)\n\n\ndef show_CV_result(reg:GridSearchCV, adjust_paras, classifi_scoring):\n # pprint(reg.cv_results_)\n RECORD_LOG('XXXXX查看CV的结果XXXXXX')\n RECORD_LOG(\n '{}: MAX of mean_test_score = {}'.format(classifi_scoring, reg.cv_results_.get('mean_test_score').max()))\n RECORD_LOG(\n '{}: MAX of mean_train_score = {}'.format(classifi_scoring, reg.cv_results_.get('mean_train_score').max()))\n cv_result_df = get_cv_result_df(reg.cv_results_, adjust_paras, reg.cv.n_splits)\n with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None, 'display.height', None):\n RECORD_LOG('\\n对各组调参参数的交叉训练验证细节为:\\n{}'.format(cv_result_df))\n if len(adjust_paras) == 1 and platform.system() == 'Windows':\n every_para_score = pd.Series()\n every_para_score.name = adjust_paras[0]\n for i in range(len(reg.cv_results_.get('mean_test_score'))):\n # RECORD_LOG('+++++++++++')\n # RECORD_LOG('mean_test_score = {}'.format(reg.cv_results_.get('mean_test_score')[i]))\n # RECORD_LOG('mean_train_score = {}'.format(reg.cv_results_.get('mean_train_score')[i]))\n param_str = \"{\"\n for k in adjust_paras:\n param_str += \"'{}': {}, \".format(k, reg.cv_results_.get('params')[i][k])\n param_str = param_str[:-2] + \"}\"\n # RECORD_LOG('params = {}'.format(param_str))\n if len(adjust_paras) == 1 and platform.system() == 'Windows':\n record_param_value = reg.cv_results_.get('params')[i].get(adjust_paras[0])\n if isinstance(record_param_value, tuple):\n record_param_value = '{}'.format(reduce(lambda n_h, n_h1: str(n_h) + '_' + str(n_h1), record_param_value))\n every_para_score.loc[record_param_value] = reg.cv_results_.get('mean_test_score')[i]\n print('best_score_ = {}'.format(reg.best_score_))\n RECORD_LOG('reg.best_score_: %f' % reg.best_score_)\n for param_name in sorted(reg.best_params_.keys()):\n if param_name in adjust_paras:\n RECORD_LOG(\"调参选择为%s: %r\" % (param_name, reg.best_params_[param_name]))\n if len(adjust_paras) == 1 and platform.system() == 'Windows':\n every_para_score.plot(kind='line', title=u'模型参数{}和评分{}的变化图示'.format(adjust_paras[0], classifi_scoring),\n style='o-')\n plt.show()\n\n\ndef selfregressor_predict_and_score(reg, last_valida_df):\n print('对样本集中留出的验证集进行预测:')\n verify_X = last_valida_df.drop('target', axis=1)\n predict_ = reg.predict(verify_X)\n # print(predict_)\n verify_golden = last_valida_df['target'].values\n explained_var_score = explained_variance_score(y_true=verify_golden, y_pred=predict_)\n mean_abs_error = mean_absolute_error(y_true=verify_golden, y_pred=predict_)\n mean_sqr_error = mean_squared_error(y_true=verify_golden, y_pred=predict_)\n median_abs_error = median_absolute_error(y_true=verify_golden, y_pred=predict_)\n r2score = r2_score(y_true=verify_golden, y_pred=predict_)\n # RECORD_LOG('使用sklearn的打分评价得到explained_var_score={}, mean_abs_error={}, mean_sqr_error={}, median_abs_error={}, r2score={}'\n # .format(explained_var_score, mean_abs_error, mean_sqr_error, median_abs_error, r2score))\n return predict_, [explained_var_score, mean_abs_error, mean_sqr_error, median_abs_error, r2score]\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n # 1. Get sample and last validation data.\n # Get Data include some pre-process.\n # Initial get fillna dataframe\n # cat_fill_type= \"fill_paulnull\" or \"base_name\" or \"base_brand\"\n # brand_fill_type= \"fill_paulnull\" or \"base_other_cols\" or \"base_NB\" or \"base_GRU\"\n # item_desc_fill_type= 'fill_' or 'fill_paulnull' or 'base_name'\n data_reader = DataReader(local_flag=LOCAL_FLAG, cat_fill_type='fill_paulnull', brand_fill_type='base_other_cols', item_desc_fill_type='fill_')\n RECORD_LOG('[{:.4f}s] Finished handling missing data...'.format(time.time() - start_time))\n\n data_reader.del_redundant_cols()\n\n # PROCESS CATEGORICAL DATA\n RECORD_LOG(\"Handling categorical variables...\")\n data_reader.le_encode()\n RECORD_LOG('[{:.4f}s] Finished PROCESSING CATEGORICAL DATA...'.format(time.time() - start_time))\n with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None,\n 'display.height', None):\n RECORD_LOG('\\n{}'.format(data_reader.train_df.head(3)))\n\n # PROCESS TEXT: RAW\n RECORD_LOG(\"Text to seq process...\")\n RECORD_LOG(\" Fitting tokenizer...\")\n data_reader.tokenizer_text_col()\n with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None,\n 'display.height', None):\n RECORD_LOG('\\n{}'.format(data_reader.train_df.head(3)))\n RECORD_LOG('[{:.4f}s] Finished PROCESSING TEXT DATA...'.format(time.time() - start_time))\n\n # EMBEDDINGS MAX VALUE\n # Base on the histograms, we select the next lengths\n data_reader.ensure_fixed_value()\n RECORD_LOG('[{:.4f}s] Finished EMBEDDINGS MAX VALUE...'.format(time.time() - start_time))\n\n data_reader.del_redundant_cols()\n\n # Begin prepare ridge&lgb data input\n data_reader.train_ridge_numpy_data_condition()\n\n # EXTRACT DEVELOPMENT TEST\n sample_df, last_valida_df, test_df = data_reader.split_get_train_validation()\n last_valida_df.is_copy = None\n print(sample_df.shape)\n print(last_valida_df.shape)\n\n # 2. Check self-made estimator\n # check_estimator(LocalRegressor) # Can not pass because need default DataReader in __init__.\n\n # 3. Parameters of GridSearchCV use.\n cv_grid_params = CvGridParams()\n adjust_para_list = print_param(cv_grid_params)\n\n if len(adjust_para_list) > 0:\n # 4. Use GridSearchCV to tuning model.\n regress_model = SelfLocalRegressor(data_reader=data_reader)\n print('Begin to train self-defined sklearn-API regressor.')\n reg = train_model_with_gridsearch(regress_model, sample_df, cv_grid_params)\n RECORD_LOG('[{:.4f}s] Finished Grid Search and training.'.format(time.time() - start_time))\n\n # 5. See the CV result\n show_CV_result(reg, adjust_paras=adjust_para_list, classifi_scoring=cv_grid_params.scoring)\n\n # 6. Use Trained Regressor to predict the last validation dataset\n validation_scores = pd.DataFrame(columns=[\"explained_var_score\", \"mean_abs_error\", \"mean_sqr_error\", \"median_abs_error\", \"r2score\"])\n predict_y, score_list = selfregressor_predict_and_score(reg, last_valida_df)\n validation_scores.loc[\"last_valida_df\"] = score_list\n with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None, 'display.height', None):\n RECORD_LOG(\"对于样本集中留出的验证集整体打分有:\\n{}\".format(validation_scores))\n last_valida_df['predict'] = predict_y\n # analysis_predict_result(last_valida_df)\n\n # 7. Predict and submit\n test_preds = reg.predict(test_df)\n test_preds = np.expm1(test_preds)\n RECORD_LOG('[{:.4f}s] Finished predicting test set...'.format(time.time() - start_time))\n submission = test_df[[\"test_id\"]].copy()\n submission[\"price\"] = test_preds\n submission.to_csv(\"./csv_output/self_regressor_r2score_{:.5f}.csv\".format(validation_scores.loc[\"last_valida_df\", \"r2score\"]), index=False)\n RECORD_LOG('[{:.4f}s] Finished submission...'.format(time.time() - start_time))\n else:\n cv_grid_params.rm_list_dict_params()\n regress_model = SelfLocalRegressor(data_reader=data_reader, **cv_grid_params.all_params)\n\n train_X = sample_df.drop('target', axis=1)\n train_y = sample_df['target'].values\n regress_model.fit(train_X, train_y)\n\n # 6. Use Trained Regressor to predict the last validation dataset\n validation_scores = pd.DataFrame(\n columns=[\"explained_var_score\", \"mean_abs_error\", \"mean_sqr_error\", \"median_abs_error\", \"r2score\"])\n predict_y, score_list = selfregressor_predict_and_score(regress_model, last_valida_df)\n validation_scores.loc[\"last_valida_df\"] = score_list\n with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None, 'display.height', None):\n RECORD_LOG(\"对于样本集中留出的验证集整体打分有:\\n{}\".format(validation_scores))\n last_valida_df['predict'] = predict_y\n\n test_preds = regress_model.predict(test_df)\n test_preds = np.expm1(test_preds)\n RECORD_LOG('[{:.4f}s] Finished predicting test set...'.format(time.time() - start_time))\n submission = test_df[[\"test_id\"]].copy()\n submission[\"price\"] = test_preds\n file_path = './csv_output/' if LOCAL_FLAG else './'\n submission.to_csv(file_path + \"self_regressor_r2score_{:.5f}.csv\".format(validation_scores.loc[\"last_valida_df\", \"r2score\"]), index=False)\n RECORD_LOG('[{:.4f}s] Finished submission...'.format(time.time() - start_time))\n\n\n\n","sub_path":"ProjectCodes/model/LocalCvModel.py","file_name":"LocalCvModel.py","file_ext":"py","file_size_in_byte":27040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"483284192","text":"words_counts = dict()\nmax_words = []\nmax_value = 0\n\nn = int(input())\n\n# для всех слов во всех строках считаем их количество и добавляем их в словарь\nfor i in range(n):\n for word in input().split():\n if word in words_counts:\n words_counts[word] += 1\n else:\n words_counts[word] = 1\n if words_counts[word] > max_value:\n max_value = words_counts[word]\n\n# ищем слова, количество которых равно максимальному\nfor word, count in words_counts.items():\n if count == max_value:\n max_words.append(word)\n\n# сортируем слова в лексикографическом порядке\nmax_words.sort()\n\n# выводим первое слово в списке\nprint(max_words[0])\n","sub_path":"week 3/week3_9.py","file_name":"week3_9.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"348846053","text":"# Copyright (C) 2016-2018 Alibaba Group Holding Limited\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\n#/usr/bin/env python\n\n\nfrom __future__ import print_function\n\nimport sys\n\nfrom multiprocessing import Pool\n\nif sys.version_info[0] < 3:\n from copy_reg import pickle\nelse:\n from copyreg import pickle\n\nfrom types import MethodType\n\ndef _pickle_method(method):\n func_name = method.im_func.__name__\n obj = method.im_self\n cls = method.im_class\n return _unpickle_method, (func_name, obj, cls)\n\ndef _unpickle_method(func_name, obj, cls):\n for cls in cls.mro():\n try:\n func = cls.__dict__[func_name]\n except KeyError:\n pass\n else:\n break\n return func.__get__(obj, cls)\n\nclass FileReader(object):\n def __init__(self, filename, paral, proc=None):\n self.filename = filename\n self.paral = paral\n self.proc = proc\n\n def read(self):\n pool = Pool(processes=self.paral)\n splits = self._split_job()\n return pool.map(self._inner_read, splits)\n\n def _split_job(self):\n file_len = 0\n with open(self.filename) as f:\n f.seek(0, 2)\n file_len = f.tell()\n\n splits = []\n start = 0\n size = int(file_len / self.paral)\n with open(self.filename) as f:\n for _ in range(self.paral - 1):\n f.seek(size, 1)\n f.readline()\n splits.append((start, f.tell()))\n start = f.tell()\n splits.append((start, file_len))\n return splits\n\n def _inner_read(self, split):\n start = split[0]\n end = split[1]\n lines = []\n print(\"Read file {} from {} to {}\".format(\n self.filename, start, end))\n with open(self.filename) as f:\n f.seek(start)\n while f.tell() < end:\n lines.append(f.readline())\n if not self.proc:\n return lines\n\n return self.proc(lines)\n\npickle(MethodType, _pickle_method, _unpickle_method)\n\ndef process(lines):\n data = []\n for line in lines:\n data.append(int(line.strip()))\n return data\n\ndef main():\n if len(sys.argv) < 2:\n print(\"{} \".format(sys.argv[0]))\n sys.exit(1)\n\n # generate a tempory test file\n filename = \"/tmp/test_random\"\n with open(filename, \"w\") as f:\n for i in range(int(sys.argv[1])):\n f.write(\"{}\\n\".format(i))\n\n reader = FileReader(filename, 10, process)\n d = []\n for data in reader.read():\n d += data\n d.sort()\n print(d[:20])\n print(d[-20:])\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"xdl-algorithm-solution/TDM/src/python/cluster/file_reader.py","file_name":"file_reader.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"95713930","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom tools.sql_connect_tools import SQLConnectTools\nfrom GaoXiaoYiKe.items import ImageItem,CommentItem\nimport datetime\n\n\nclass GaoxiaoSpider(scrapy.Spider):\n name = 'gaoxiao'\n allowed_domains = ['bx1k.com']\n start_urls = ['http://www.bx1k.com/funnyimg/find-cate-1-p-1.html']\n\n def parse(self, response):\n images = response.css('.listcont .plist li')\n for image in images:\n # css写法\n detail_url = image.css('a::attr(href)').extract_first()\n # xpath写法\n # detail_url = image.xpath('//a/@href').extract_first()\n # 不需要meta信息了,直接在详情页取数据\n # image_url= image.css('img::attr(data-src)')\n yield scrapy.Request(url=detail_url,callback=self.parse_content)\n for i in range(50):\n next_url = 'http://www.bx1k.com/funnyimg/find-cate-1-p-{}.html'.format(i)\n yield scrapy.Request(url=next_url,callback=self.parse)\n\n\n # 爬取详情页的数据\n def parse_content(self,response):\n # print(response.text)\n # 这里出现问题是由于没有登陆得原因;\n url = response.css('ul#thumb-ul li img::attr(big_src)').extract()[0]\n # 他这里的id可能是通过渲染得来得;xpath取不到;\n # url2 = response.xpath(\"//ul[@id='thumb-ul']/li\")\n sql_tools = SQLConnectTools()\n user_id = sql_tools.get_user_id()\n created_date = datetime.datetime.now()\n image_item = ImageItem()\n image_item['url'] = url\n image_item['user_id'] = user_id\n image_item['created_date'] = created_date\n yield image_item\n\n\n\n","sub_path":"GaoXiaoYiKe/spiders/gaoxiao.py","file_name":"gaoxiao.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"331262217","text":"import os\n#11\n\n\ndef ListFilesToTxt(dir, file, wildcard, recursion):\n exts = wildcard.split(\" \")\n files = os.listdir(dir)\n for name in files:\n fullname = os.path.join(dir, name)\n if (os.path.isdir(fullname) & recursion):\n ListFilesToTxt(fullname, file, wildcard, recursion)\n else:\n for ext in exts:\n if (name.endswith(ext)):\n file.write(name + \"\\n\")\n break\n\n\ndef Test():\n dir = \"/home/zhenshiziben/pycharm_installation/pdf_to_txt\"\n outfile = \"hello.txt\"\n wildcard = \".txt .exe .dll .lib\"\n\n file = open(\"/home/zhenshiziben/pycharm_installation/pdf_to_txt/hello1.txt\", \"r\")\n # if not file:\n # print(\"cannot open the file %s for writing\" % outfile)\n\n # ListFilesToTxt(dir, file, wildcard, 1)\n temp_list = []\n content_list = file.readlines()\n j = 0\n temp = 0\n for c in content_list:\n j += 1\n if c.strip()== \"内容目录\":\n temp = j\n continue\n elif c.strip() == \"图表目录\":\n break\n print(j)\n print(temp)\n for i in range(temp-1,j-1):\n print(content_list[i])\n # str_temp = file.readline()\n # print(temp_list)\n\n file.close()\n\n\nTest()\n","sub_path":"dumuluv2.py","file_name":"dumuluv2.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"149689080","text":"# -*- coding:utf-8 -*-\nimport requests\nimport UserAgent_demo\nimport random\nfrom lxml import etree\nimport time\nimport csv\n#请求每一页跟数据\ndef start(url, area):\n #构造头部信息\n user_agent = UserAgent_demo.UserAgent()\n a = user_agent.getuseragent()\n headers = {\n 'User-Agent':random.choice(a)\n }\n\n urls = [(url+'pg{0}/').format(i) for i in range(1,35)]\n #每一页进行循环\n m = 0\n for url in urls:\n print(url)\n\n\n req = requests.get(url,headers=headers)\n html = etree.HTML(req.text)\n details_urls = html.xpath('//ul[@class=\"listContent\"]/li/a/@href')\n #地区\n area = area\n #详情页循环\n\n for details_url in details_urls:\n try:\n de_req = requests.get(details_url,headers=headers)\n de_html = etree.HTML(de_req.text)\n # 户型\n huxing = de_html.xpath('//div[@class=\"base\"]/div[@class=\"content\"]/ul/li[1]/text()')\n huxing = huxing[0].strip()\n #楼层高度\n loucenggaodu = de_html.xpath('//div[@class=\"base\"]/div[@class=\"content\"]/ul/li[2]/text()')\n loucenggaodu = loucenggaodu[0].strip()\n #建筑面积\n jianzhumianji = de_html.xpath('//div[@class=\"base\"]/div[@class=\"content\"]/ul/li[3]/text()')\n jianzhumianji = jianzhumianji[0].strip().replace('㎡','')\n #建成年代\n jianchengniandai = de_html.xpath('//div[@class=\"base\"]/div[@class=\"content\"]/ul/li[8]/text()')\n jianchengniandai = jianchengniandai[0].strip()\n #装修情况\n zhuangxiuqingkuang = de_html.xpath('//div[@class=\"base\"]/div[@class=\"content\"]/ul/li[9]/text()')\n zhuangxiuqingkuang = zhuangxiuqingkuang[0].strip()\n #有无电梯\n youwudianti = de_html.xpath('//div[@class=\"base\"]/div[@class=\"content\"]/ul/li[14]/text()')\n youwudianti = youwudianti[0].strip()\n #挂牌价\n guapaijia = de_html.xpath('//div[@class=\"msg\"]/span[1]/label/text()')\n guapaijia = guapaijia[0].strip()\n #成交周期\n chengjiaozhouqi = de_html.xpath('//div[@class=\"msg\"]/span[2]/label/text()')\n chengjiaozhouqi = chengjiaozhouqi[0].strip()\n #调价次数\n tiaojiacishu = de_html.xpath('//div[@class=\"msg\"]/span[3]/label/text()')\n tiaojiacishu = tiaojiacishu[0].strip()\n #带看次数\n daikancishu = de_html.xpath('//div[@class=\"msg\"]/span[4]/label/text()')\n daikancishu = daikancishu[0].strip()\n # 关注人数\n guanzhurenshu = de_html.xpath('//div[@class=\"msg\"]/span[5]/label/text()')\n guanzhurenshu = guanzhurenshu[0].strip()\n #浏览次数\n liulancishu = de_html.xpath('//div[@class=\"msg\"]/span[6]/label/text()')\n liulancishu = liulancishu[0].strip()\n #成交价\n chengjiaojia = de_html.xpath('//span[@class=\"dealTotalPrice\"]/i/text()')\n chengjiaojia = chengjiaojia[0].strip()\n data = [area,huxing,loucenggaodu,jianzhumianji,jianchengniandai,zhuangxiuqingkuang,\n youwudianti,guapaijia,chengjiaozhouqi,tiaojiacishu,daikancishu,\n guanzhurenshu,liulancishu,chengjiaojia]\n #文件逐行写如csv\n with open('./data.csv','a+',encoding='utf_8_sig',newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(data)\n print(data)\n except:\n continue\n#获取所有地区的url地址\ndef get_allurl():\n user_agent = UserAgent_demo.UserAgent()\n a = user_agent.getuseragent()\n headers = {\n 'User-Agent': random.choice(a)\n }\n req = requests.get('https://sh.lianjia.com/chengjiao/',headers=headers)\n html = etree.HTML(req.text)\n urls = html.xpath('//div[@data-role=\"ershoufang\"]/div[1]/a/@href')\n urls = ['https://sh.lianjia.com'+ url for url in urls]\n areas = html.xpath('//div[@data-role=\"ershoufang\"]/div[1]/a/text()')\n areas = [area.strip() for area in areas]\n # print(urls)\n # print(areas)\n for i in range(17):\n print('开始下载地区:'+areas[i])\n start(urls[i], areas[i])\n time.sleep(random.choice([1,1.5,2,2.5,3,3.5]))\n\n\nif __name__=='__main__':\n #构建列名\n # with open('./data.csv', 'a+', encoding='utf_8_sig',newline='') as f:\n # f_csv = csv.writer(f)\n # f_csv.writerow(['地区','户型','楼层高度','建筑面积/㎡','建成年代/年','装修情况','有无电梯\t','挂牌价/万','成交周期/天','调价次数/次'\n # ,'带看次数','关注人数','浏览次数','成交价/万'])\n get_allurl()","sub_path":"爬虫/链家成交/lianjia.py","file_name":"lianjia.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"496823923","text":"import wx\nfrom GoProStream import GoPro, GOPRO_IP, UDP_PORT\n\nclass SettingsPanel(wx.Panel):\n def __init__(self, parent):\n super(__class__, self).__init__(parent)\n sizerTop = wx.FlexGridSizer(3, 2, 35)\n\n # slider on the left\n slider_LCD_backlight = wx.Slider(self, minValue=0, maxValue=10,\n style=wx.SL_INVERSE | wx.SL_VERTICAL | wx.SL_VALUE_LABEL | wx.SL_LEFT,\n name='Display brightness')\n slider_LCD_backlight.SetBackgroundColour('#F000E511')\n label_slider_LCD_backlight = wx.StaticText(self, label=slider_LCD_backlight.GetName(), size=(1, -1),\n style=wx.ALIGN_CENTRE)\n label_slider_LCD_backlight.SetBackgroundColour('#efaaef55')\n\n # slider on the right\n slider_throughput = wx.Slider(self, style=wx.SL_VERTICAL | wx.SL_INVERSE | wx.SL_VALUE_LABEL, name='Quality')\n slider_throughput.SetBackgroundColour('#d0002511')\n label_slider_throughput = wx.StaticText(self, label=slider_throughput.GetName(), size=(1, -1),\n style=wx.ALIGN_CENTRE)\n label_slider_throughput.SetBackgroundColour('#f00055aa')\n\n sizerTop.AddGrowableRow(0, 0)\n sizerTop.AddGrowableCol(0, 0)\n sizerTop.AddGrowableCol(2, 0)\n\n sizerTop.AddMany([(slider_LCD_backlight, 1, wx.GROW),\n (wx.StaticText(self, label=\"RIGHT\"), 1, wx.ALIGN_RIGHT),\n (slider_throughput, 1, wx.GROW),\n (label_slider_LCD_backlight, 0, wx.EXPAND | wx.ALL, 5),\n (wx.StaticText(self, label=\"LEFT\"), 1, wx.ALIGN_LEFT),\n (label_slider_throughput, 0, wx.EXPAND | wx.ALL, 5)\n ])\n\n self.SetSizer(sizerTop)\n\n\nclass ConnectionPanel(wx.Panel):\n def __init__(self, parent):\n super(__class__, self).__init__(parent)\n sizer = wx.GridSizer(1, 2, 0)\n\n self.label_conn_status = wx.StaticText(self, label='', style=wx.ALIGN_CENTRE)\n self.label_conn_status.SetForegroundColour('#E2007D')\n sizer.Add(self.label_conn_status, wx.ID_ANY, wx.ALIGN_CENTRE)\n\n self.button_reconnect = wx.Button(self, label='Reconnect', id=wx.ID_REFRESH)\n sizer.Add(self.button_reconnect, wx.ID_ANY, wx.ALIGN_CENTRE | wx.RIGHT | wx.LEFT | wx.GROW, 34)\n\n self.SetSizer(sizer)\n self.Layout()\n\n self.button_reconnect.Bind(wx.EVT_BUTTON, self.OnReconnectPress)\n\n def connected(self, state):\n if state == True:\n model_name = 'domkamerka'\n self.label_conn_status.SetLabel(f'{model_name} connected')\n elif state == False:\n self.label_conn_status.SetLabel('not connected :C')\n self.Layout()\n\n def reconnect(self):\n self.label_conn_status.SetLabel('…connecting…')\n self.Layout()\n\n def OnReconnectPress(self, event):\n print(f'button pressed {event}')\n self.button_reconnect.Disable()\n\n # allow to handle more actions caused by this button press\n event.Skip()\n\n\nclass MainFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)\n size = (380, 500)\n super(__class__, self).__init__(*args, **kwargs, style=style, size=size)\n # override the styling\n from pathlib import Path\n self.SetIcon(wx.Icon(Path('res').joinpath(Path('iconka.png')).as_posix()))\n\n sizerV = wx.BoxSizer(wx.VERTICAL)\n\n self.panel_connection = ConnectionPanel(self)\n sizerV.Add(self.panel_connection, 2, wx.GROW)\n\n self.panel_settings = SettingsPanel(self)\n sizerV.Add(self.panel_settings, 9, wx.GROW)\n\n footer = wx.StaticText(self, label='authorship (~ownership) → amateusz @ github.com')\n footer.SetForegroundColour('#ffffff33')\n sizerV.Add(footer, 0, wx.ALIGN_CENTRE | wx.ALL, 10)\n\n self.SetSizer(sizerV)\n self.SetAutoLayout(1)\n # sizer.Fit(self) #\n\n # Binds\n self.Bind(wx.EVT_BUTTON, self.reconnect)\n\n def reconnect(self, event):\n if event.EventObject is self.panel_connection.button_reconnect or event.Id == wx.ID_REFRESH:\n # reconnect procedure\n self.panel_settings.Show(False)\n self.panel_connection.reconnect()\n\n # set state → not connected\n # perform actuall discovery\n\n # set timeout\n\n def disconnected(self):\n # set smuteczek\n self.panel_settings.Show(False)\n self.panel_connection.connected(False)\n\n\nclass GoProStreamGUI(wx.App):\n def OnInit(self):\n self.frame = MainFrame(None, wx.ID_ANY, \"GoPro LiveStream Tool\")\n self.frame.Show(True)\n # self.frame.Bind(wx.EVT_CLOSE, self.OnFrameClose)\n # self.frame.Bind(wx.EVT_MOUSEWHEEL, self.OnScrollInFrame)\n # self.frame.Bind(wx.EVT_SLIDER, self.OnSlider)\n\n # set default state: disconnected\n self.frame.disconnected()\n\n # but also trigger auto connection\n init_event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED,\n id=self.frame.panel_connection.button_reconnect.GetId())\n init_event.SetEventObject(self.frame.panel_connection.button_reconnect)\n\n wx.PostEvent(self.frame.panel_connection.button_reconnect, init_event)\n\n return True\n\n def OnSlider(self, event):\n print(event.GetSelection())\n event.Skip()\n\n def OnFrameClose(self, event):\n # gopro.quit()\n event.Skip()\n\n def OnScrollInFrame(self, event):\n # print(dir(event))\n scroll_amount = event.GetWheelRotation() / 120.0\n scroll_axis = event.GetWheelAxis()\n if scroll_axis == wx.MOUSE_WHEEL_HORIZONTAL:\n if scroll_amount < 0:\n print('→')\n else:\n print('←')\n elif scroll_axis == wx.MOUSE_WHEEL_VERTICAL:\n if scroll_amount < 0:\n print('↑')\n else:\n print('↓')\n\n event.Skip()\n\n\nif __name__ == '__main__':\n gopro = GoPro(UDP_IP, UDP_PORT)\n if gopro.present():\n gopro.connect()\n gui = GoProStreamGUI(useBestVisual=True)\n keep_alive_timer = wx.Timer(gopro)\n gui.Bind(wx.EVT_TIMER, gopro.keep_alive, keep_alive_timer)\n gopro.open_stream()\n gui.MainLoop()\n","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":6511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"646552973","text":"'''\nListas em python\nfatiamento\nappend, insert, pop, del, clear, extend, +\nmin, max\n'''\nlista = ['A','B','C']\nlista_2 = ['A', 'B', 'C', 'E', 10.7]\nnova_lista = lista[1:]\nprint(lista_2[::-2])\n\nl1 = [4, 3, 6, 8]\nl2 = [9, 6, 3]\n\nl3 = l1 + l2\nl1.extend(l2)\nprint(l1)\nl1.insert(0, 20)\nl1.insert(0, 'Hello word')\nprint(l1)\nl1.pop()\nprint(l1)\ndel(l1[0])\nprint(l1)\ndel(l1[2])\nprint(l1)\nprint(max(l1))\nprint(min(l1))\n\nsoma = 0\nfor valor in l1:\n soma = soma + valor\n\nprint(f'soma = {soma}')\nprint(f'soma do max e min = {max(l1) + min(l1)}')\n\nl = ['string', True, 6.8, 10]\nfor item in l:\n print(f'{item}', type(item))\n","sub_path":"curso python Udemy/Aula24_Listas/aula24.py","file_name":"aula24.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"297151867","text":"class Zoo:\n def __init__(self):\n self.animal_list = []\n self.animal_name = \"name\"\n self.food = \"\"\n \n def add_animal(self,obj):\n self.animal_list.append(obj)\n\n\nclass Animal(Zoo):\n def __init__(self,name):\n super().__init__()\n self.animal_name = name\n\n def add_food(self,food):\n self.food = food\n\n def add_names(self,names):\n self.names = names\n\n def add_catagory(self,catagory):\n self.catagory = catagory\n\n def add_noise(self,noise):\n self.noise = noise\n\n def show_animals(self):\n print(self.animals_list)\n\nobj = Zoo()\n\n#for lion\n\nn=int(input(\"Enter the count of lion\"))\n\n\nfor i in range(0,n):\n ani = Animal(f\"lion{i+1}\")\n names = input(f\"Enter the name for Lion {i+1}\")\n catagory = input(f\"Enter the catagory for Lion {i+1}\")\n noise = input(f\"Enter Noise made by lion {i+1}\")\n food = input(f\"Enter Food Loved by lion {i+1}\") \n\n ani.add_noise(noise)\n ani.add_food(names)\n ani.add_catagory(catagory)\n ani.add_names(names)\n obj.add_animal(ani)\n\n\n#for giraffe\nn=int(input(\"Enter the count of giraffe\"))\n\n\nfor i in range(0,n):\n ani = Animal(f\"giraffe{i+1}\")\n name = input(f\"Enter the name for giraffe {i+1}\")\n catagory = input(f\"Enter the catagory for giraffe {i+1}\")\n noise = input(f\"Enter Noise made by giraffe {i+1}\")\n food = input(f\"Enter Food Loved by giraffe {i+1}\") \n\n ani.add_noise(noise)\n ani.add_food(name)\n ani.add_names(names)\n ani.add_catagory(catagory)\n obj.add_animal(ani)\n\n#for tiger\nn=int(input(\"Enter the count of tiger\"))\n\n\nfor i in range(0,n):\n ani = Animal(f\"tiger{i+1}\")\n name = input(f\"Enter the name for tiger {i+1}\")\n catagory = input(f\"Enter the catagory for tiger {i+1}\")\n noise = input(f\"Enter Noise made by tiger {i+1}\")\n food = input(f\"Enter Food Loved by tiger {i+1}\") \n\n ani.add_noise(noise)\n ani.add_food(name)\n ani.add_names(names)\n ani.add_catagory(catagory)\n obj.add_animal(ani)\n\n\n#for elephant\nn=int(input(\"Enter the count of elephant\"))\n\n\nfor i in range(0,n):\n ani = Animal(f\"elephant{i+1}\")\n name = input(f\"Enter the name for elephant {i+1}\")\n catagory = input(f\"Enter the catagory for elephant {i+1}\")\n noise = input(f\"Enter Noise made by elephant {i+1}\")\n food = input(f\"Enter Food Loved by elephant {i+1}\") \n\n ani.add_noise(noise)\n ani.add_food(name)\n ani.add_names(names)\n ani.add_catagory(catagory)\n obj.add_animal(ani)\n\n\n#for deer\nn=int(input(\"Enter the count of deer\"))\n\n\nfor i in range(0,n):\n ani = Animal(f\"deer{i+1}\")\n name = input(f\"Enter the name for deer {i+1}\")\n catagory = input(f\"Enter the catagory for deer {i+1}\")\n noise = input(f\"Enter Noise made by deer {i+1}\")\n food = input(f\"Enter Food Loved by deer {i+1}\") \n\n ani.add_noise(noise)\n ani.add_food(name)\n ani.add_names(names)\n ani.add_catagory(catagory)\n obj.add_animal(ani)\n\n\n\n\nfor i in obj.animal_list:\n print(i.animal_name)\n print(\"name\",i.names)\n print(\"catagoty\",i.catagory)\n print(\"noise\",i.noise)\n print(\"food\",i.food)","sub_path":"Python_4/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"400492434","text":"#!/usr/bin/env python3\n#\n# Copyright 2014 - 2016 The GSMI Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE.txt file.\n#\n\nimport gsmi.external.base as _ex_base\n\n\nclass GitCommandFactory:\n \"\"\"Factory of git commands.\"\"\"\n\n def __init__(self, cwd, hidden):\n \"\"\"Initialize the factory.\n\n :type cwd: str\n :type hidden: bool\n :param cwd: The working directory.\n :param hidden: True if the hidden mode is enabled.\n \"\"\"\n\n self.__cwd = cwd\n self.__hidden = hidden\n\n def get_working_directory(self):\n \"\"\"Get the working directory.\n\n :rtype: str\n :return: The directory.\n \"\"\"\n\n return self.__cwd\n\n def set_working_directory(self, cwd):\n \"\"\"Set the working directory.\n\n :type cwd: str\n :param cwd: The directory.\n \"\"\"\n\n self.__cwd = cwd\n\n def fetch_all(self):\n \"\"\"Fetch all commits from the remote.\n\n :rtype: gsmi.external.base.ExternalProgram\n :return: The program instance.\n \"\"\"\n\n return _ex_base.ExternalProgram(\n [\"git\", \"fetch\", \"--all\", \"-ftp\"],\n self.__cwd,\n self.__hidden\n )\n\n def clone(self, url, target, mirror=False):\n \"\"\"Clone a source tree.\n\n :type url: str\n :type target: str\n :type mirror: bool\n :param url: The URL.\n :param target: The target directory.\n :param mirror: True if to run in mirror mode.\n :rtype: gsmi.external.base.ExternalProgram\n :return: The program instance.\n \"\"\"\n\n # Create the command.\n cmd = [\"git\", \"clone\"]\n if mirror:\n cmd.append(\"--mirror\")\n cmd.append(url)\n cmd.append(target)\n\n return _ex_base.ExternalProgram(\n cmd,\n self.__cwd,\n self.__hidden\n )\n\n def add(self, target=\".\"):\n \"\"\"Add file(s) to the tree.\n\n :type target: str\n :param target: The target file(s).\n :rtype: gsmi.external.base.ExternalProgram\n :return: The program instance.\n \"\"\"\n\n return _ex_base.ExternalProgram(\n [\"git\", \"add\", target],\n self.__cwd,\n self.__hidden\n )\n\n def commit(self, msg=None):\n \"\"\"Commit changes.\n\n :type msg: str | None\n :param msg: The commit message.\n :rtype: gsmi.external.base.ExternalProgram\n :return: The program instance.\n \"\"\"\n\n # Create the command.\n cmd = [\"git\", \"commit\"]\n\n # Add the message parameter.\n if msg is not None:\n cmd.append(\"-m\")\n cmd.append(msg)\n\n return _ex_base.ExternalProgram(\n cmd,\n self.__cwd,\n self.__hidden\n )\n","sub_path":"gsmi/external/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"336531653","text":"#-*-coding:utf-8-*-\nimport pandas as pd\nimport numpy as np\nimport torch, os\nfrom spo_dataset import SPO, get_mask, collate_fn\nfrom spo_model import SPOModel\nfrom torch.utils.data import DataLoader, RandomSampler, TensorDataset\nfrom tokenize_pkg.tokenize import Tokenizer\nfrom tqdm import tqdm as tqdm\nimport torch.nn as nn\nfrom utils import seed_torch, load_glove, save_checkpoint\nimport logging\nimport time\n\n\ndef read_data(path):\n data = []\n label = []\n with open(path,'r') as f:\n for line in f.readlines():\n line = line.strip().split(',')\n text = line[1].split()\n if not text:continue\n if line[0] =='positive':\n label.append(1)\n data.append(text)\n elif line[0] == 'negative':\n label.append(0)\n data.append(text)\n else:\n continue\n data_df = pd.DataFrame()\n data_df['text'] = data\n data_df['label'] = label\n return data_df\n\n\ntrain_data = read_data('data/sentiment_XS_30k.txt')\nvalid_data = read_data('data/sentiment_XS_test.txt')\nprint(train_data.sample(100))\n\n\ncurrent_name = 'log/%s.txt' % time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\nlogging.basicConfig(filename=current_name,\n filemode='w',\n format='%(asctime)s - %(message)s',\n datefmt='%d-%b-%y %H:%M:%S',\n level=logging.INFO)\n\n\nseed_torch(2019)\n\nt = Tokenizer(max_feature=500000, segment=False)\nt.fit(list(train_data['text'].values) + list(valid_data['text'].values))\n## save t\nimport pickle\npickle.dump(t, open('tokenizer.pkl','wb'))\n\nprint('一共有%d 个词' % t.num_words)\ntrain_data = train_data.append(valid_data).reset_index(drop=True)\ntrain_dataset = SPO(train_data['text'].values, t, label=train_data['label'])\n\nbatch_size = 40\n\n\n# 准备embedding数据\n#embedding_file = 'embedding/miniembedding_engineer_baike_word.npy'\nembedding_file = 'embedding/miniembedding_engineer_qq_att.npy'\n\nif os.path.exists(embedding_file):\n embedding_matrix = np.load(embedding_file)\nelse:\n #embedding = '/home/zhukaihua/Desktop/nlp/embedding/baike'\n embedding = '/home/zhukaihua/Desktop/nlp/embedding/Tencent_AILab_ChineseEmbedding.txt'\n embedding_matrix = load_glove(embedding, t.num_words+100, t)\n np.save(embedding_file, embedding_matrix)\n\nprint(embedding_matrix.shape)\nmodel = SPOModel(vocab_size=embedding_matrix.shape[0],\n word_embed_size=embedding_matrix.shape[1], encoder_size=128, dropout=0.5,\n seq_dropout=0.0, init_embedding=embedding_matrix,\n dim_num_feat=1)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)\n\ntrain_dataloader = DataLoader(train_dataset, collate_fn=collate_fn, shuffle=True, batch_size=batch_size)\n\nloss_fn = nn.BCELoss()\noptimizer = torch.optim.Adam(model.parameters())\nclip = 50\n\nfor epoch in range(10):\n model.train()\n train_loss = 0\n for index, X, length, numerical_features, label in tqdm(train_dataloader):\n X = nn.utils.rnn.pad_sequence(X, batch_first=True).type(torch.LongTensor)\n X = X.cuda()\n\n n_feats = numerical_features.type(torch.float).cuda()\n label = label.type(torch.float).cuda()\n mask_X = get_mask(X, length, is_cuda=True).type(torch.float)\n pred = model(X, mask_X, length, n_feats)\n\n loss = loss_fn(pred, label)\n optimizer.zero_grad()\n loss.backward()\n # Clip gradients: gradients are modified in place\n _ = nn.utils.clip_grad_norm_(model.parameters(), clip)\n #_ = nn.utils.clip_grad_norm_(model.parameters(), clip)\n optimizer.step()\n train_loss += loss.item()\n #break\nsave_checkpoint('model/senti.pth',model)","sub_path":"sentiment_analysis_generate.py","file_name":"sentiment_analysis_generate.py","file_ext":"py","file_size_in_byte":3776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"329637044","text":"#!/usr/bin/env python3\r\nfrom collections import defaultdict\r\n\r\nimport sys\r\n\r\n\r\nclass Point:\r\n x = 0\r\n y = 0\r\n\r\n def __str__(self):\r\n return \"X:\" + str(self.x) + \" Y:\" + str(self.y)\r\n\r\n def __hash__(self):\r\n return hash((self.x, self.y))\r\n\r\n def __eq__(self, other):\r\n if (self.x == other.x and self.y == other.y):\r\n return true\r\n else:\r\n return false\r\n #return (self.x, self.y) == (other.x, other.y)\r\n\r\n def __ne__(self, other):\r\n return not self == other\r\n\r\ncurrentLocation = Point()\r\ncurrentLocationRobo = Point()\r\n\r\n#visitList = defaultdict(int)\r\nvisitList = [(0,0)]\r\ntotalHouses = 1\r\n\r\n#visitList[currentLocation] += 1\r\n\r\nindex = 0\r\nfor line in sys.stdin:\r\n for character in line:\r\n if (index % 2 == 0):\r\n if (character == '^'):\r\n currentLocation.y += 1\r\n elif (character == 'v'):\r\n currentLocation.y -= 1\r\n elif (character == '>'):\r\n currentLocation.x += 1\r\n elif (character == '<'):\r\n currentLocation.x -= 1\r\n else:\r\n if (character == '^'):\r\n currentLocationRobo.y += 1\r\n elif (character == 'v'):\r\n currentLocationRobo.y -= 1\r\n elif (character == '>'):\r\n currentLocationRobo.x += 1\r\n elif (character == '<'):\r\n currentLocationRobo.x -= 1\r\n\r\n #visitList[currentLocation] += 1\r\n index += 1\r\n\r\n if ((currentLocation.x, currentLocation.y) not in visitList):\r\n totalHouses += 1\r\n visitList.append((currentLocation.x, currentLocation.y))\r\n if ((currentLocationRobo.x, currentLocationRobo.y) not in visitList):\r\n totalHouses += 1\r\n visitList.append((currentLocationRobo.x, currentLocationRobo.y))\r\n\r\n#print(visitList)\r\n#print (len(visitList))\r\nprint(totalHouses)\r\n","sub_path":"3/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"390408506","text":"from typing import Optional\n\nimport pandas as pd\n\nfrom pandas_genomics.arrays import GenotypeDtype\n\n\n@pd.api.extensions.register_dataframe_accessor(\"genomics\")\nclass GenotypeDataframeAccessor:\n \"\"\"\n DataFrame accessor for GenotypeArray methods\n \"\"\"\n\n def __init__(self, pandas_obj):\n for colname in pandas_obj.columns:\n if not GenotypeDtype.is_dtype(pandas_obj[colname].values.dtype):\n raise AttributeError(\n f\"Incompatible datatype: column {colname} is '{pandas_obj[colname].values.dtype}',\"\n f\" but must be a GenotypeDtype\"\n )\n self._obj = pandas_obj\n\n ######################\n # Variant Properties #\n ######################\n @property\n def variant_info(self) -> pd.DataFrame:\n \"\"\"Return a DataFrame with variant info indexed by the column name\"\"\"\n return pd.DataFrame.from_dict(\n {\n colname: self._obj[colname].genomics.variant_info\n for colname in self._obj.columns\n },\n orient=\"index\",\n )\n\n #########################\n # Calculated Properties #\n #########################\n @property\n def maf(self):\n \"\"\"Return the minor allele frequency\n\n See :py:attr:`GenotypeArray.maf`\"\"\"\n return pd.Series(\n {col: self._obj[col].genomics.maf for col in self._obj.columns}\n )\n\n ############\n # Encoding #\n ############\n def encode_additive(self) -> pd.DataFrame:\n \"\"\"Additive encoding of genotypes.\n\n See :meth:`GenotypeArray.encode_additive`\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n return pd.concat(\n [self._obj[col].genomics.encode_additive() for col in self._obj.columns],\n axis=1,\n )\n\n def encode_dominant(self) -> pd.DataFrame:\n \"\"\"Dominant encoding of genotypes.\n\n See :meth:`GenotypeArray.encode_dominant`\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n return pd.concat(\n [self._obj[col].genomics.encode_dominant() for col in self._obj.columns],\n axis=1,\n )\n\n def encode_recessive(self) -> pd.DataFrame:\n \"\"\"Recessive encoding of genotypes.\n\n See :meth:`GenotypeArray.encode_recessive`\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n return pd.concat(\n [self._obj[col].genomics.encode_recessive() for col in self._obj.columns],\n axis=1,\n )\n\n def encode_codominant(self) -> pd.DataFrame:\n \"\"\"Codominant encoding of genotypes.\n\n See :meth:`GenotypeArray.encode_codominant`\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n return pd.concat(\n [self._obj[col].genomics.encode_codominant() for col in self._obj.columns],\n axis=1,\n )\n\n ###########\n # Filters #\n ###########\n def filter_maf(self, keep_min_freq: Optional[float] = None) -> pd.DataFrame:\n \"\"\"\n Drop variants with a MAF less than the specified value (0.01 by default)\n \"\"\"\n if keep_min_freq is None:\n keep_min_freq = 0.01\n return self._obj.drop(\n columns=[\n c\n for c in self._obj.columns\n if self._obj[c].genomics.maf < keep_min_freq\n ]\n )\n","sub_path":"pandas_genomics/accessors/dataframe_accessor.py","file_name":"dataframe_accessor.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"74626755","text":"from datetime import datetime, timedelta\nfrom time import sleep\n\nfrom actstream import action\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.db import transaction\nfrom django.db.models import Model\nfrom django.utils.functional import cached_property\nfrom django_tqdm import BaseCommand\n\nfrom server.apps.main.models import KEY_TYPE, Commit, Consent, LegalBasis\nfrom server.apps.poller.api_client.dynamics import DynamicsClient\n\nqueryset = LegalBasis.objects.filter(current=True)\n\n\nclass Command(BaseCommand):\n help = \"\"\"\n Start polling for dynamics subs.\n\n e.g. ./manage.py poll_dynamics\n \"\"\"\n\n def add_arguments(self, parser):\n # Named (optional) arguments\n parser.add_argument(\n \"--forever\",\n action=\"store_true\",\n help=\"Run in a loop forever\",\n )\n\n parser.add_argument(\n \"--sleep-time\",\n action=\"store\",\n type=int,\n help=\"How long to sleep for (seconds), default: 60\",\n default=60,\n )\n\n @cached_property\n def email_consent(self) -> Consent:\n email_consent, _ = Consent.objects.get_or_create(name=\"email_marketing\")\n return email_consent\n\n @transaction.atomic()\n def update_consent(self, email_address, meta=None) -> None:\n self.write(f\"Updating consent for {self._masked_email(email_address)}\")\n if meta is None:\n meta = {}\n commit = Commit(extra=meta)\n commit.source = meta.get(\"url\", settings.DYNAMICS_INSTANCE_URI)\n commit.save()\n\n self._update_email_consent(commit, email_address, False)\n\n @transaction.atomic()\n def create_consent(self, email_address, meta=None) -> None:\n self.write(f\"Creating consent for {self._masked_email(email_address)}\")\n if meta is None:\n meta = {}\n commit = Commit(extra=meta)\n commit.source = meta.get(\"url\", settings.DYNAMICS_INSTANCE_URI)\n commit.save()\n\n self._update_email_consent(commit, email_address, True)\n\n @staticmethod\n def _masked_email(full_email: str) -> str:\n email_parts = full_email.split(\"@\")\n return f\"{email_parts[0][:2]}...@...{email_parts[1][-4:]}\"\n\n def _send_action(self, instance: Model) -> None:\n dynamics_user, _ = get_user_model().objects.get_or_create(username=\"dynamics\")\n action_kwargs = {\n \"sender\": dynamics_user,\n \"action_object\": instance,\n \"verb\": \"Create\",\n }\n action.send(**action_kwargs)\n\n def _update_email_consent(\n self, commit, email_address, email_contact_consent\n ) -> None:\n if email_address:\n obj: LegalBasis = LegalBasis(\n email=email_address, commit=commit, key_type=KEY_TYPE.EMAIL\n )\n obj.save()\n if email_contact_consent:\n obj.consents.add(self.email_consent)\n else:\n obj.consents.remove(self.email_consent)\n\n self._send_action(obj)\n\n def _should_update(self, email_address) -> bool:\n # check if there is already a legal basis for this email address\n try:\n lb: LegalBasis = queryset.get(email=email_address)\n except LegalBasis.DoesNotExist:\n return True\n\n # check if it is already opted out\n if self.email_consent in lb.consents.all():\n return True\n\n return False\n\n def _should_create(self, email_address) -> bool:\n return not queryset.filter(\n key_type=KEY_TYPE.EMAIL, email=email_address\n ).exists()\n\n def _sync_unsubs(self) -> None:\n self.write(\"Syncing unsubscribed users\")\n client = DynamicsClient()\n record_count = update_count = 0\n for contact in client.get_unsubscribed_contacts():\n record_count += 1\n email_address = contact[\"emailaddress1\"]\n self.write(\n f\"Got unsubbed email address {self._masked_email(email_address)}\"\n )\n if self._should_update(email_address):\n self.update_consent(email_address)\n update_count += 1\n self.write(f\"Updated {update_count} records out of {record_count} in total\")\n\n def _sync_unmanaged_users(self) -> None:\n self.write(\"Syncing unmanaged users\")\n client = DynamicsClient()\n record_count = created_count = 0\n for contact in client.get_unmanaged_contacts(created_since_days=7):\n record_count += 1\n email_address = contact[\"emailaddress1\"]\n self.write(\n f\"Got unmanaged email address {self._masked_email(email_address)}\"\n )\n # If this email address doesn't exist, create an opted in record for it\n if self._should_create(email_address):\n self.create_consent(email_address)\n created_count += 1\n\n self.write(f\"Created {created_count} records out of {record_count} in total\")\n\n def run(self, *args, **options) -> None:\n self._sync_unsubs()\n self._sync_unmanaged_users()\n\n def handle(self, *args, **options):\n run_forever = options.pop(\"forever\")\n sleep_time = options.pop(\"sleep_time\")\n\n if run_forever:\n while True:\n self.write(\"Polling dynamics 365\")\n self.run(args, options)\n self.write(\n f\"sleeping until {datetime.now() + timedelta(seconds=sleep_time)}\"\n )\n sleep(sleep_time)\n else:\n self.run(args, options)\n","sub_path":"server/apps/poller/management/commands/poll_dynamics.py","file_name":"poll_dynamics.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"309696030","text":"#!/usr/bin/env python3\n\nimport re\nimport subprocess\nfrom subprocess import CalledProcessError\nimport urllib.request\nfrom urllib.error import URLError\n\n\ndef path_autoload_decorator(steps_up=2):\n def decorate(func):\n func(steps_up)\n return func\n return decorate\n\n\n@path_autoload_decorator(2)\ndef add_module_path(steps_up):\n import os\n import inspect\n _cur_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n for step in range(steps_up):\n _cur_dir = os.path.dirname(_cur_dir)\n os.sys.path.insert(0, _cur_dir)\n\n\nfrom common import question_loop, get_quoted_file_path\nfrom common import run_sudo_command, run_sys_command\n\nparams_file_name = \"kernel_params.txt\"\n\nsource = None\ndeb_packages = ()\n\n\ndef print_error(error):\n if len(error.args) == 1:\n print(\"Error: \" + error.args[0])\n elif len(error.args) == 2:\n print(\"Error({}): {}\".format(error.args[0], error.args[1]))\n else:\n for arg in error.args:\n if arg:\n print(arg, end=\" \")\n print()\n\n\ndef yes_no_question(question):\n ans = question_loop(question, [[\"y\", \"yes\"], [\"n\", \"no\"]], [\"yes\", \"no\"])\n return ans[1] == 0\n\n\ndef make_headers_all(version_str, deb_date):\n return \"linux-headers-\" + version_str + \"_\" + version_str + \".\" + deb_date + \"_all.deb\"\n\n\ndef make_headers_x64(version_str, deb_date):\n return \"linux-headers-\" + version_str + \"-generic_\" + version_str + \".\" + deb_date + \"_amd64.deb\"\n\n\ndef make_image_x64(version_str, deb_date):\n return \"linux-image-\" + version_str + \"-generic_\" + version_str + \".\" + deb_date + \"_amd64.deb\"\n\n\ndef parse_deb_address(address):\n start_ver = re.match(r\"http://kernel.ubuntu.com/~kernel-ppa/mainline/v[^/]+/linux-(headers|image)-\", address);\n address = address[start_ver.end()::]\n\n version = re.match(r\"[^-]+\", address).group(0)\n parts = version.split(\".\")\n if parts[-1] == \"0\":\n parts.pop()\n version = \".\".join(parts)\n\n version_str = re.match(r\"[^-]+-\\d+\", address)\n address = address[version_str.end()::]\n\n start_date = re.search(version_str.group(0), address)\n address = address[start_date.end()::]\n\n deb_date = re.match(r\".(\\d+)\", address)\n\n return version, version_str.group(0), deb_date.group(1)\n\n\ndef check_files_existence(files):\n if not (isinstance(files, tuple) or isinstance(files, list)):\n files = (files,)\n import os\n for file in files:\n if not os.path.isfile(file):\n raise FileExistsError(\"File \\\"\" + file + \"\\\" does not exist\")\n\n\ndef get_kernel_params(file_name):\n try:\n check_files_existence(file_name)\n with open(file_name) as file:\n address = file.readline()\n if not address:\n raise IOError(\"File is empty\")\n return parse_deb_address(address)\n except IOError as error:\n print_error(error)\n raise Exception\n\n\ndef make_deb_paths():\n global source, deb_packages\n if source is None:\n try:\n version, version_str, deb_date = get_kernel_params(params_file_name)\n except Exception:\n raise\n\n source = 'http://kernel.ubuntu.com/~kernel-ppa/mainline/v' + version + '/'\n\n headers_all = make_headers_all(version_str, deb_date)\n headers_x64 = make_headers_x64(version_str, deb_date)\n image_x64 = make_image_x64(version_str, deb_date)\n deb_packages = (headers_all, headers_x64, image_x64)\n\n\ndef remove_debs():\n if not yes_no_question(\"Do you want to remove all previous debs?\"):\n return\n\n import os\n files_list = os.listdir(os.path.dirname(os.path.realpath(__file__)))\n is_removed = False\n for item in files_list:\n if item.endswith(\".deb\"):\n os.remove(item)\n is_removed = True\n\n if is_removed:\n print(\"Deb packages were removed\")\n else:\n print(\"Nothing to remove\")\n\n\ndef download_packages():\n if not yes_no_question(\"Do you want to download kernel from repository?\"):\n print(\"Kernel will not be downloaded\")\n return\n\n remove_debs()\n\n try:\n make_deb_paths()\n except Exception:\n raise\n\n print('Start downloading')\n for package in deb_packages:\n try:\n urllib.request.urlretrieve(source + package, package)\n except URLError:\n print(\"Error while downloading: \\\"\" + package + \"\\\"\")\n raise Exception\n print('Download is complete')\n\n\ndef update_grub():\n run_sudo_command(\"update-grub\")\n\n\ndef show_current_kernel():\n print(\"Current kernel:\")\n try:\n run_sys_command(\"uname -r\")\n except CalledProcessError as error:\n print_error(error)\n\n\ndef show_kernels():\n ans = yes_no_question(\"Do you want to see only active kernels?\")\n try:\n if ans:\n update_grub()\n else:\n run_sudo_command(\"dpkg --list | grep linux-image\")\n except CalledProcessError as error:\n print_error(error)\n\n\ndef install_packages():\n if not yes_no_question(\"Do you want to start installing?\"):\n print(\"Kernel will not be installed\")\n return\n\n try:\n make_deb_paths()\n except Exception:\n raise\n\n try:\n check_files_existence(deb_packages)\n except FileExistsError as error:\n print_error(error)\n return\n\n print(\"Start installation\")\n try:\n for package in deb_packages:\n run_sudo_command(\"dpkg -i \" + get_quoted_file_path(package))\n update_grub()\n except CalledProcessError as error:\n print_error(error)\n return\n\n print(\"Kernel is installed\")\n\n remove_debs()\n\n if yes_no_question(\"Do you want to reboot?\"):\n print(\"Reboot system\")\n subprocess.run(\"reboot\")\n\n\ndef install_kernel():\n try:\n download_packages()\n install_packages()\n except Exception:\n return\n\n\ndef remove_kernel():\n version = input(\"Enter kernel version: \")\n print(\"Start removing\")\n try:\n run_sudo_command(\"apt purge linux-headers-\" + version)\n run_sudo_command(\"apt purge linux-image-\" + version)\n run_sudo_command(\"apt autoremove --purge\")\n update_grub()\n except CalledProcessError as error:\n print_error(error)\n return\n\n print(\"Removing is complete\")\n\n\ndef main():\n ans = question_loop(\"Do you want to install, show or remove kernel\",\n [[\"i\", \"install\"], [\"s\", \"show\"], [\"c\", \"current\"], [\"r\", \"remove\"]],\n [\"i - install\", \"s - show list\", \"c - current kernel\", \"r - remove\"])\n\n switcher = {\n 0: install_kernel,\n 1: show_kernels,\n 2: show_current_kernel,\n 3: remove_kernel,\n }\n\n switcher[ans[1]]()\n\n print(\"Exit\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Linux_system/Ubuntu_kernel/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":6798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"552270299","text":"# Meses transcurridos desde el nacimiento hasta el mes actual\nfrom datetime import date\n\nfecha_actual = date.today()\non = True\nwhile on:\n anio_nacido = int(float(input(\"Año en que nació: \")))\n mes_nacido = int(float(input(\"Del 1 al 12, ingrese el mes en el que nació:\\n\\n \")))\n if mes_nacido >= 12:\n print(\"Ingresa un número dentro del rango: del 1 al 12\")\n on = True\n else:\n meses_transcurridos = ((fecha_actual.year - anio_nacido) * 12) + (fecha_actual.month - mes_nacido)\n on = False\nelse:\n print(meses_transcurridos)\n","sub_path":"ejercicios conceptos basicos/ejercicio9.py","file_name":"ejercicio9.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"63485206","text":"import math\r\n\r\n\"------------------------------ABILITIES------------------------------\"\r\n\r\nclass ability:\r\n def __init__(self,label,dmg,acc,boom=1,rlevel=1,t='A'):\r\n self.label = label\r\n self.dmg = dmg\r\n self.acc = acc\r\n self.boom = boom\r\n self.type = t\r\n self.colour = '#f00' if dmg > 20 else '#f30' if dmg >= 15 else '#fc0'\r\n self.rlevel = rlevel\r\n c = 'A powerful recursive attack' if boom > 1 else 'A strong attack' if dmg > 20 else 'A moderately powerful attack' if dmg > 15 else 'An attack' if dmg > 0 else ''\r\n c += ' with high accuracy' if acc > 0.8 else ' with moderate accuracy' if acc > 0.7 else ''\r\n if boom > 1: dmg=f'{dmg}x{boom}'\r\n self.comment = f\"{c}\\nAttack Power: {dmg}\\nAccuracy: {(int(acc*100))}%\"\r\n abilitylist[self.label.lower()] = self\r\n def __str__(self):\r\n return self.label\r\n\r\nabilitylist = {}\r\n\r\nstupefy = ability(\"Stupefy\",dmg=10,acc=1)\r\n\r\nconfringo = ability(\"Confringo\",dmg=20,acc=0.7)\r\n\r\nreducto = ability(\"Reducto\",dmg=30,acc=0.45)\r\n\r\nbombarda = ability(\"Bombarda\",dmg=15,acc=0.8)\r\n\r\nincendio = ability(\"Incendio\",dmg=10,acc=0.9)\r\nincendio.comment += \"\\nImproves ability power by 2\"\r\n\r\nexpulso = ability(\"Expulso\",dmg=23,acc=0.65,rlevel=6)\r\n\r\nreparo = ability(\"Reparo\",dmg=0,acc=0.9,t='H',rlevel=8)\r\nreparo.comment = \"Heal: +15 health\\nAccuracy: 90%\"\r\n\r\nrevelio = ability(\"Revelio\",dmg=12,acc=0.85,rlevel=9)\r\nrevelio.comment += \"\\n20% Chance of wreak havoc\"\r\n\r\nlevicorpus = ability(\"Levicorpus\",dmg=10,acc=0.75,rlevel=12)\r\nlevicorpus.comment = \"An attack with healing powers\\nAttack Power: 10\\nHeal: 15\\n Accuracy: 70%\"\r\n\r\nlumosmaxima = ability(\"LumosMaxima\",dmg=0,acc=0.7,rlevel=13,t='N')\r\nlumosmaxima.comment = \"Reduces the opponent's accuracy by 10%\\nAccuracy: 70%\"\r\n\r\nprotego = ability(\"Protego\",dmg=0,acc=0.95,rlevel=15,t='B')\r\nprotego.comment = \"Improves player's defence by 10\\nAccuracy: 95%\"\r\n\r\nsectumsempra = ability(\"Sectumsempra\",dmg=18,acc=0.6,boom=2,rlevel=15)\r\n\r\nsalviohexia = ability(\"SalvioHexia\",dmg=4,acc=0.7,boom=4,rlevel=17)\r\nsalviohexia.comment = \"An ability that transfers the opponent's health to you\\nAttack Power: 4x4\\nAccuracy: 70%\"\r\nsalviohexia.colour = '#1f0'\r\n\r\ndiffindo = ability(\"Diffindo\",dmg=25,acc=0.5,rlevel=18)\r\ndiffindo.comment += \"\\nImproves defence by 5\"\r\n\r\nimperio = ability(\"Imperio\",dmg=0,acc=0.5,t='C',rlevel=19)\r\nimperio.comment = \"A curse that causes the opponent to lose control for 2 turns\\nAccuracy: 50%\"\r\n\r\npetrificustotalus = ability(\"PetrificusTotalus\",0,0.5,rlevel=20,t='C')\r\npetrificustotalus.comment = \"A curse that prevents the opponent from playing next 2 turns\\nAccuracy: 50%\"\r\n\r\ndissendium = ability(\"Dissendium\",dmg=0,acc=0.9,t='N',rlevel=21)\r\ndissendium.comment = \"Reduces the opponent's defence by 10\\nAccuracy: 90%\"\r\n\r\ncrucio = ability(\"Crucio\",dmg=0,acc=0.8,t='C',rlevel=24)\r\ncrucio.comment = \"The opponent takes damage over time\\nDamage: 10x3\\nAccuracy: 80%\"\r\n\r\nbombardamaxima = ability(\"BombardaMaxima\",dmg=3,acc=0.85,boom=10,rlevel=25)\r\n\r\nenrage = ability(\"Enrage\",dmg=0,acc=1,rlevel=30,t='B') # FINAL BOSS ONLY, +50 ability and defence\r\n\r\n\"-----------------------------BOSS DATA-----------------------------\"\r\n\r\nclass Boss:\r\n def __init__(self,name,health,atk,block,level,a1,a2,a3,a4,a5):\r\n self.maxHealth = health\r\n self.name = name\r\n self.maxAtk = atk\r\n self.maxBlock = block\r\n self.level = level\r\n self.colour = \"brown\"\r\n self.a1 = a1\r\n self.a2 = a2\r\n self.a3 = a3\r\n self.a4 = a4\r\n self.a5 = a4\r\n\r\nboss1=Boss(\"Marrow\",130,40,40,10,confringo,bombarda,reducto,incendio,levicorpus)\r\nboss2=Boss(\"Gabriel\",140,80,35,15,levicorpus,stupefy,confringo,bombarda,incendio)\r\nboss3=Boss(\"Le Raux\",150,55,50,20,reducto,expulso,confringo,protego,bombarda)\r\nboss4=Boss(\"Wolvington\",170,60,60,25,bombardamaxima,stupefy,levicorpus,protego,confringo)\r\nboss5=Boss(\"Overlord\",200,70,70,30,sectumsempra,bombardamaxima,expulso,enrage,bombarda)\r\nbosslist = ['boss1','boss2','boss3','boss4','boss5']\r\n\r\n\"-----------------------------USER DATA-----------------------------\"\r\n\r\nclass Player:\r\n \r\n def __init__(self, username, password,xp=1):\r\n self.name = username\r\n self.password = password\r\n self.ladder = 1\r\n self.xp = xp\r\n \r\n self.a1 = stupefy\r\n self.a2 = confringo\r\n self.a3 = bombarda\r\n self.a4 = reducto\r\n self.a5 = incendio\r\n \r\n self.colour = \"#00f\"\r\n \r\n self.hbuff = 0\r\n self.abuff = 0\r\n self.bbuff = 0\r\n self.xhbuff = 0\r\n self.xabuff = 0\r\n self.xbbuff = 0\r\n \r\n self.coins = 0\r\n \r\n @property\r\n def level(self):\r\n return int(self.xp ** 0.5)\r\n @property\r\n def maxHealth(self):\r\n return 99 + self.level + (self.hbuff+self.xhbuff)*5\r\n @property\r\n def maxBlock(self):\r\n return 19 + self.level + (self.bbuff+self.xbbuff)*5\r\n @property\r\n def maxAtk(self):\r\n return 19 + self.level + (self.abuff+self.xabuff)*5\r\n @property\r\n def boss(self):\r\n if self.ladder == 1: return boss1\r\n elif self.ladder == 2: return boss2\r\n elif self.ladder == 3: return boss3\r\n elif self.ladder == 4: return boss4\r\n else: return boss5\r\n @property\r\n def buff(self):\r\n return (self.level//3) + (self.level//5) - (self.hbuff + self.abuff + self.bbuff + (self.level//15))\r\n @property\r\n def skillset(self):\r\n return [self.a1 , self.a2 , self.a3 , self.a4 , self.a5]\r\n\r\nuserlist = {}\r\n\r\n# there is automated code below this...\r\n\r\nDivyam=Player(\"Divyam\",\"0xaee4b272ce\")\r\nuserlist[\"Divyam\"]=Divyam\r\nDivyam.xp+=624\r\nSPARTACUS=Player(\"SPARTACUS\",\"0x43c026e3f0a7aaa57\")\r\nuserlist[\"SPARTACUS\"]=SPARTACUS\r\nSPARTACUS.xp+=624\r\na=Player(\"a\",\"0x0\")\r\nuserlist[\"a\"]=a\r\na.xp += 200\r\nDivyam.a1 = salviohexia\r\nDivyam.a2 = bombardamaxima\r\nDivyam.a3 = crucio\r\nDivyam.a4 = sectumsempra\r\nDivyam.a5 = reparo\r\nDivyam.hbuff += 1\r\nDivyam.bbuff += 1\r\nDivyam.bbuff += 1\r\nDivyam.bbuff += 1\r\nDivyam.bbuff += 1\r\nDivyam.abuff += 1\r\nDivyam.abuff += 1\r\nDivyam.abuff += 1\r\nDivyam.abuff += 1\r\nDivyam.abuff += 1\r\nDivyam.abuff += 1\r\nDivyam.abuff += 1\r\nDivyam.coins+=10\r\nDivyam.coins+=7\r\nDivyam.coins+=7\r\nDivyam.coins+=5\r\na.a1 = reparo\r\na.a3 = revelio\r\na.a2 = expulso\r\na.coins+=2\r\na.xp+=2\nSPARTACUS.a5 = bombardamaxima\nSPARTACUS.a3 = dissendium\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.bbuff += 1\nSPARTACUS.coins+=10\nTestUser=Player(\"TestUser\",\"0x44bf764093d0e49a35aa57\")\nuserlist[\"TestUser\"]=TestUser\nSPARTACUS.colour = \"#00f\"\nSPARTACUS.coins+=12","sub_path":"TANKS/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"314982878","text":"from CrawlEngine import CrawlEngine\nimport config\n\n# Araxni\n# main object\nclass Araxni(object):\n\n # init\n # create a CrawlEngine to process the given entry points and handle the crawl.\n def __init__(self):\n self.crawler = CrawlEngine(config.entry_points, config.depth)\n\n def run(self):\n print(\"Running Araxni...\")\n for count, url in enumerate(self.crawler.run()):\n print(\"URL {0}: {1}\".format(count, url))\n\n# starts the crawler\nif __name__ == \"__main__\":\n araxni = Araxni()\n try:\n araxni.run()\n except KeyboardInterrupt:\n quit()\n","sub_path":"Araxni.py","file_name":"Araxni.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"102105733","text":"import django\nfrom django.forms.utils import flatatt\nfrom django.utils.html import format_html\nfrom django.utils.encoding import force_text\nfrom django.utils import formats\n\n\nclass AjaxUploadInput(django.forms.FileInput):\n input_type = 'file'\n needs_multipart_form = True\n\n def render(self, name, value, attrs=None):\n #add class for javascript event\n attrs['class'] = 'upload'\n\n if value is None:\n value = ''\n final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)\n if value != '':\n # Only add the 'value' attribute if a value is non-empty.\n final_attrs['value'] = force_text(self._format_value(value))\n return format_html('
', flatatt(final_attrs))\n\n\n def value_from_datadict(self, data, files, name):\n \"File widgets take data from FILES, not POST\"\n return files.get(name, None)\n\n\nclass DateDropDownInput(django.forms.DateTimeInput):\n\n class Media:\n css = {\n 'all': ('/static/lib/jquery.datetimepicker.css',)\n }\n js = ('/static/lib/jquery.datetimepicker.js', '/static/lib/init_datetimepicker.js')\n\n\n def _format_value(self, value):\n return formats.localize_input(value,\n self.format or formats.get_format(self.format_key)[0])\n\n\n def render(self, name, value, attrs=None):\n if value is None:\n value = ''\n\n if attrs is None:\n attrs = []\n\n attrs['class'] = 'datetimepicker'\n final_attrs = self.build_attrs(attrs, name=name)\n\n if value != '':\n # Only add the 'value' attribute if a value is non-empty.\n final_attrs['value'] = force_text(self._format_value(value))\n\n # return format_html(str(self.media) + '')\n\n return format_html(str(self.media) + '', flatatt(final_attrs))\n","sub_path":"lib/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"173680227","text":"'''\nCreated on Jun 13, 2020\n\n@author: mark\n'''\nimport os\nimport GetOldTweets3 as got\nimport pandas as pd\n\n# Function the pulls tweets from a specific username and turns to csv file\n\n# Parameters: (list of twitter usernames), (max number of most recent tweets to pull from)\ndef username_tweets_to_csv(username, count):\n # Creation of query object\n tweetCriteria = got.manager.TweetCriteria().setUsername(username)\\\n .setMaxTweets(count)\n # Creation of list that contains all tweets\n tweets = got.manager.TweetManager.getTweets(tweetCriteria)\n\n # Creating list of chosen tweet data\n user_tweets = [[tweet.date, tweet.text] for tweet in tweets]\n\n # Creation of dataframe from tweets list\n tweets_df = pd.DataFrame(user_tweets, columns = ['Datetime', 'Text'])\n\n # Converting dataframe to CSV\n tweets_df.to_csv('{}-{}k-tweets.csv'.format(username, int(count/1000)), sep=',')\n \n# Function that pulls tweets based on a general search query and turns to csv file\n\n# Parameters: (text query you want to search), (max number of most recent tweets to pull from)\ndef text_query_to_csv(text_query, since_date, until_date, count):\n \n pn=os.path.abspath(__file__)\n pn=pn.split(\"src\")[0] \n \n path=os.path.join(pn,'output')\n\n # Creation of query object\n tweetCriteria = got.manager.TweetCriteria().setQuerySearch(text_query).setSince(since_date).setUntil(until_date).setMaxTweets(count)\n \n # Creation of list that contains all tweets\n tweets = got.manager.TweetManager.getTweets(tweetCriteria)\n \n # Creating list of chosen tweet data\n text_tweets = [[tweet.date, tweet.text, tweet.retweets, tweet.hashtags,tweet.username,tweet.geo] for tweet in tweets]\n \n # Creation of dataframe from tweets\n tweets_df = pd.DataFrame(text_tweets, columns = ['Datetime', 'Text','Retweets','Hashtags','Username','Geolocation'])\n\n # Converting tweets dataframe to csv file\n tweets_df.to_csv(path+'/{}-{}k-tweets.csv'.format(text_query, int(count/1000)), sep=',')\n \n'''\nMethod to run the module\n''' \ndef run():\n\n # Max recent tweets pulls x amount of most recent tweets from that user\n text_query = 'colston statue'\n count = 50000\n\n since_date = '2020-06-07'\n until_date = '2020-06-08'\n\n # Calling function to query X amount of relevant tweets and create a CSV file\n text_query_to_csv(text_query, since_date, until_date, count)\n\n print('Finished')\n \nif __name__ == '__main__':\n run()\n \n","sub_path":"src/twitter/tweets.py","file_name":"tweets.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"388780659","text":"class Solution:\r\n\tdef combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\r\n\t\tans = []\r\n\t\tdef helps(x, path):\r\n\t\t\tif sum(path) == target:\r\n\t\t\t\tans.append(path[:])\r\n\t\t\t\treturn\r\n\t\t\tif sum(path) > target:\r\n\t\t\t\treturn\r\n\t\t\tfor i in range(x, len(candidates)):\r\n\t\t\t\tpath.append(candidates[i])\r\n\t\t\t\thelps(i, path)\r\n\t\t\t\tpath.pop()\r\n\t\thelps(0, [])\r\n\t\treturn ans\r\n","sub_path":"Combination Sum Leetcode.py","file_name":"Combination Sum Leetcode.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"468992503","text":"# coding=utf-8\nimport operator\nfrom math import log\nimport numpy as np\n\n\ndef majorityCnt(classList):\n classCount = {}\n for vote in classList:\n if vote not in classCount.keys():\n classCount[vote] = 0\n classCount[vote] += 1\n return max(classCount)\n\n\ndef splitDataSet(dataSet, axis, value):\n retDataSet = []\n for featVec in dataSet:\n if featVec[axis] == value:\n reducedFeatVec = featVec[:axis]\n reducedFeatVec.extend(featVec[axis + 1:])\n retDataSet.append(reducedFeatVec)\n return retDataSet\n\n\ndef cal_infoGain(dataSet, feat_idx):\n def cal_Ent(dataSet): #计算熵\n labelCounts = {}\n for feaVec in dataSet:\n currentLabel = feaVec[-1]\n if currentLabel not in labelCounts:\n labelCounts[currentLabel] = 0\n labelCounts[currentLabel] += 1\n shannonEnt = 0.0\n for key in labelCounts:\n prob = float(labelCounts[key]) / len(dataSet)\n shannonEnt -= prob * log(prob, 2)\n return shannonEnt\n\n\n def cal_CondiEnt(dataSet, feat_idx): # 计算条件熵\n n_sample = len(dataSet); condiEnt = 0\n featCol = [example[feat_idx] for example in dataSet]\n\n for val in set(featCol):\n subDataSet = splitDataSet(dataSet, feat_idx, val)\n n_subSample = len(subDataSet)\n prob = n_subSample / n_sample\n subEnt = cal_Ent(subDataSet)\n condiEnt += prob * subEnt\n\n return condiEnt\n\n return cal_Ent(dataSet) - cal_CondiEnt(dataSet, feat_idx) #信息增益\n\n\ndef chooseBestFeature(dataSet):\n numFeatures = len(dataSet[0]) - 1; bestInfoGain = 0.0; bestFeature = -1\n\n for feat_idx in range(numFeatures):\n infoGain = cal_infoGain(dataSet, feat_idx)\n if infoGain > bestInfoGain: #选择“信息增益”最大的特征\n bestInfoGain = infoGain\n bestFeature = feat_idx\n return bestFeature, bestInfoGain\n\n\ndef createTree(dataSet, featNames, min_gain):\n classList = [example[-1] for example in dataSet]\n if len(set(classList)) == 1: #如果类别相同则停止划分,并输出类别标记\n return classList[0]\n if len(dataSet[0]) == 1: #如果所有特征已经用完,输出最多的类别\n return majorityCnt(classList)\n\n bestFeat_idx, bestInfoGain = chooseBestFeature(dataSet) #计算信息增益,并选出使“信息增益”最大的特征\n bestFeat = featNames[bestFeat_idx]\n\n if bestInfoGain < min_gain: #如果信息增益小于阈值,则输出最多的类别\n return majorityCnt(classList)\n\n myTree = {}\n myTree['bestFeat'] = bestFeat #根据最佳特征,建立节点\n\n bestFeat_ValuesSet = set([example[bestFeat_idx] for example in dataSet])\n for value in bestFeat_ValuesSet:\n sub_dataset = splitDataSet(dataSet, bestFeat_idx, value) #对于最佳特征的每种取值,划分出子数据集\n sub_featNames = featNames[0: bestFeat_idx] + featNames[bestFeat_idx+1: ]\n\n # 每个取值生成一个分支;并且分支下面的“子数据集”继续按同样的方式划分;直到满足停止条件,输出类别标签\n myTree[value] = createTree(sub_dataset, sub_featNames, min_gain=0.1)\n return myTree\n\n\n\n\ndef classify(inputTree, featNames, testVec):\n bestFeat = inputTree['bestFeat']\n bestFeat_idx = featNames.index(bestFeat)\n\n for key in list(inputTree.keys())[1:]:\n if testVec[bestFeat_idx] == key:\n if type(inputTree[key]).__name__ == 'dict':\n classLabel = classify(inputTree[key], featNames, testVec)\n else:\n classLabel = inputTree[key]\n return classLabel\n\n\nclass DecisionTree():\n def __init__(self, featNames):\n self.featNames = featNames\n\n def fit(self, X_train, y_train):\n dataSet = [X + [y] for (X, y) in zip(X_train, y_train)]\n self.myTree = createTree(dataSet, self.featNames, min_gain=0.1)\n print(self.myTree)\n\n def predict(self, X):\n Y_pred = [0] * len(X)\n\n for row_idx in range(0, len(X)):\n y_label = classify(self.myTree, self.featNames, X[row_idx])\n Y_pred[row_idx] = y_label\n\n return Y_pred\n\n\nif __name__ == '__main__':\n #注意,数据必须是list的形式,全部都是基于list实现的\n\n featNames = ['A1', 'A2']\n train_data = [[1, 1, 'yes'],\n [1, 1, 'yes'],\n [1, 0, 'no'],\n [0, 1, 'no'],\n [0, 1, 'no']]\n X_train = [example[0: -1] for example in train_data]\n y_train = [example[-1] for example in train_data]\n X_test = X_train\n\n DT = DecisionTree(featNames)\n DT.fit(X_train, y_train)\n y_pred = DT.predict(X_test)\n print(y_pred)\n\n\n {'bestFeat': 'A1',\n 0: 'no',\n 1: {'bestFeat': 'A2',\n 0: 'no', 1:\n 'yes'}}\n","sub_path":"machine_learning_model/id3_简化树结构.py","file_name":"id3_简化树结构.py","file_ext":"py","file_size_in_byte":4905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"508341504","text":"import socket\nimport threading\nimport logging\nimport signal\nimport sys\n\n# 47.56.177.220 (Ubuntu instance on Alibaba Cloud)\n# Configure the http proxy settings of your OS/browser to target the\n# IP and PORT of the server. If ther server is deployed on the Cloud,\n# remember to activate the incoming traffic on PORT.\nPORT = 55555\nMAX_CONNECTION = 10\nBUF_SIZE = 2048\n\n\ndef signal_handler(sig, frame):\n if sig == signal.SIGINT:\n logging.info(\"stop http proxy...\")\n sys.exit(0)\n\n\nclass HttpProxy(threading.Thread):\n def __init__(self, sock):\n super().__init__()\n self.sock = sock\n\n def run(self):\n try:\n request = self.sock.recv(BUF_SIZE)\n # forward the http request to the original server\n host = str()\n for line in request.decode().split('\\r\\n'):\n if line[:5].upper() == 'HOST:':\n host = line.split()[1]\n\n if host:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_sock:\n server_sock.connect((host, 80))\n logging.debug(\n \"forwarding the http request to {0}:\\r\\n{1}\".format(host, request))\n server_sock.send(request)\n\n reply = server_sock.recv(BUF_SIZE)\n logging.debug(\n \"forwarding the http reply to client:\\r\\n{}\".format(reply))\n self.sock.send(reply)\n else:\n logging.error(\"can not determine host\")\n\n except OSError as err:\n logging.error(err)\n finally:\n self.sock.close()\n\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.DEBUG)\n logging.info(\"start http proxy...\")\n # CTRL+C to stop the server\n signal.signal(signal.SIGINT, signal_handler)\n\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n # prevent '[Errno 98] Address already in use' in case of too short delay between executions\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(('', PORT))\n sock.listen(MAX_CONNECTION)\n while True:\n try:\n conn_sock, _ = sock.accept()\n HttpProxy(conn_sock).start()\n except OSError as err:\n logging.error(\"can not serve http request\\r\\n{}\".format(err))\n","sub_path":"http-proxy/multi_threaded_proxy.py","file_name":"multi_threaded_proxy.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"191841487","text":"import numpy as np\nimport cv2\nimport pathlib\nimport glob\nfrom scipy.sparse.linalg import lsqr\nfrom form_matrices import *\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n#import to register the 3D projection, but is not used directly\nfrom mpl_toolkits.mplot3d import Axes3D\n\n#3d surface plot\ndef plot_3D(X, Y, Z):\t\t\n\tfig = plt.figure()\n\tax = fig.gca(projection=\"3d\")\n\tsurf = ax.plot_surface(X,Y,Z, cmap= cm.coolwarm,linewidth=0, antialiased=False)\n\tfig.colorbar(surf, shrink=0.5, aspect=5)\n\tplt.show()\n\n#Function to calculate depth\ndef extract_and_save_DepthMap(folder, mask_set):\t\n\t\"\"\"\n\tInput:\n\tfolder: \tLocation of the dataset containing subfolder output etc\n\tmask_set: \tIf set to None, a mask is initialized using the dimensions of normal\n\t\t\t\tOr set it with a mask of shape (normal.shape[0], normals.shape[1])\n\tOutput:\n\t\n\t\n\t\"\"\"\n\tnormal_npy_name = str(pathlib.Path(folder) / \"outputs\" / \"normals.npy\")\n\talbedo_name = str(pathlib.Path(folder) / \"outputs\" / \"albedo.png\")\n\n\t#log names\n\tdepth_name = str(pathlib.Path(folder) / \"outputs\" / \"depth.png\")\n\tdepth_npy_name = str(pathlib.Path(folder) / \"outputs\" / \"depth.npy\")\n\t\n\talbedo = cv2.imread(albedo_name, 0)\n\tnormals = np.load(normal_npy_name)\n\tif mask_set:\n\t\tmask = mask_set\n\telse:\n\t\tmask = np.ones(normals.shape[:2])\n\t\n\tprint(\"Normals shape: \", normals.shape)\n\tprint(\"Mask shape: \", mask.shape)\n\t\t\n\theight = mask.shape[0]\n\twidth = mask.shape[1]\n\talpha = mask\n\tdepth_weight = 1.0\n\t# ~ depth = deepcopy(mask)\n\tdepth = albedo\n\t\n\tprint(\"Forming Linear equation coefficients...\")\n\tM, b = matrices_for_linear_equation(alpha, normals, depth_weight, depth, height, width)\n\t\n\tprint(\"Solving for Least squares solution...\")\t\n\tsolution = lsqr(M,b)\n\tx = solution[0]\n\tdepth = x.reshape(mask.shape)\n\t\n\tprint(\"Depth values range from \", depth.min(), \" to \", depth.max() )\n\tnp.save(depth_npy_name, depth)\n\tcv2.imwrite(depth_name, np.clip(np.array(depth), 0,255).astype(np.uint8) )\n\t\n\tX, Y = np.meshgrid(np.arange(height), np.arange(width))\n\tZ = depth.T\n\tprint(\"\\n Use Mouse to view the visualized 3D information from different perspectives.\")\n\tplot_3D(X, Y, Z)\n\tprint(\"End.\")\n","sub_path":"Chapter11/Activity11.03/estimate_depth_map.py","file_name":"estimate_depth_map.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"109660180","text":"import os\nimport argparse\nimport json\nimport pandas as pd\nimport numpy as np\nimport sys\n\n# options = [\"h_rank\",\n# \"l_rank\",\n# \"l_rank_identity\",\n# \"HL\",\n# \"HL_identity\"]\n\noptions = [\n \"baseline\",\n \"h_rank\",\n \"l_rank\",\n \"l_rank_identity\",\n ]\n\nidentity_options = [\"l_rank_identity\",\n \"HL_identity\",\n \"dual_low_zi_v\",\n \"dual_low_z_vi\",\n \"dual_low_zi_vi\"\n ]\n\nmetrics = [\"loss\", \"accuracy\", \"val_loss\",\"val_accuracy\"]\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Run aggregation.\")\n parser.add_argument('--agg_option', nargs='?', default='multiple_runs',\n help='Option for aggregation.')\n parser.add_argument('--history_path', nargs='?', default='./history_old/',\n help='The folder path to save history_old.')\n parser.add_argument('--target_folder', nargs='?', default='./aggregated_results',\n help='Option for Conv weight matrix.')\n parser.add_argument('--target_rank', type=int, default=1,\n help='Target rank for Conv low rank weight matrix.')\n parser.add_argument('--dataset', nargs='?', default='mnist',\n help='Choose a Dataset')\n parser.add_argument('--epoch', type=int, default=100,\n help='Training Epoch')\n parser.add_argument('--channel', type=int, default=1,\n help='Number of channel.')\n parser.add_argument('--kernel', type=int, default=1,\n help='Number of kernel.')\n parser.add_argument('--observation_size', type=int, default=40,\n help='observe last number of epoches.')\n parser.add_argument('--kernel_size', type=int, default=3,\n help='The dimension for a kernel.')\n parser.add_argument('--metric', nargs='?', default='val_loss',\n help='option for metric')\n return parser.parse_args()\n\ndef evaluate_stabilization_rate(args):\n print('evaluate stabilization')\n global options\n global metrics\n observation_size = args.observation_size\n mean_rec = list()\n median_rec = list()\n std_rec = list()\n for option in options:\n if option == 'h_rank':\n target_rank = 1\n else:\n target_rank = args.target_rank\n if option in identity_options:\n history_path = './history_updated_identity/'\n else:\n history_path = args.history_path\n target_folder = os.path.join(history_path, args.dataset)\n file = \"_\".join([option, \"kernel_size\", str(args.kernel_size),\n \"num_kernel\", str(args.kernel),\n \"channel\", str(args.channel),\n \"rank\",str(target_rank),\n \"epoch\", str(args.epoch)])\n target_file = os.path.join(target_folder, file+'.csv')\n df_target = pd.read_csv(target_file)\n df_subset = df_target.iloc[-observation_size:]\n col_mean = df_subset.mean(axis=0)[args.metric]\n col_median = df_subset.median(axis=0)[args.metric]\n col_std = df_subset.std(axis=0)[args.metric]\n mean_rec.append(col_mean)\n median_rec.append(col_median)\n std_rec.append(col_std)\n final_rec = dict()\n final_rec['approach'] = options\n final_rec['mean'] = mean_rec\n final_rec['median'] = median_rec\n final_rec['std'] = std_rec\n df_final_rec = pd.DataFrame(final_rec)\n config = '_'.join(['Last', str(observation_size),'epoches', args.metric,'statistics',\n 'kernel_size',str(args.kernel_size),\n 'rank', str(args.target_rank)])\n results_folder = os.path.join(args.target_folder, args.dataset)\n if not os.path.isdir(results_folder):\n os.makedirs(results_folder)\n df_final_rec.to_csv(os.path.join(results_folder,config+'.csv'), index=False)\n print(config)\n\ndef hit_checking(mean, std, range, val, is_loss):\n if range == 0:\n if is_loss:\n return val <= mean\n else:\n return val >= mean\n else:\n boundary_min = max([mean - (range * std), 0])\n if is_loss:\n boundary_max = mean + (range * std)\n else:\n boundary_max = min([mean + (range * std), 1])\n return (val <= boundary_max) and (val >= boundary_min)\n\ndef evaluate_converge_rate(args):\n # Fetch last 40 epoch statistic\n stablilization_config = '_'.join(['Last', str(args.observation_size),'epoches', args.metric,'statistics',\n 'kernel_size',str(args.kernel_size),\n 'rank', str(args.target_rank)])\n stablilization_folder = os.path.join(args.target_folder, args.dataset)\n stabilization_file = os.path.join(stablilization_folder, stablilization_config+'.csv')\n df_stable = pd.read_csv(stabilization_file, index_col='approach')\n hit_list = list()\n for option in options:\n # Fetch all 100 epoch history_old\n if option in identity_options:\n all_history_folder = os.path.join('history_updated_identity', args.dataset)\n else:\n all_history_folder = os.path.join(args.history_path, args.dataset)\n if option == 'h_rank':\n history_config = \"_\".join([option, \"kernel_size\", str(args.kernel_size),\n \"num_kernel\", str(args.kernel),\n \"channel\", str(args.channel),\n \"rank\",str(1),\n \"epoch\", str(args.epoch)]) + '.csv'\n else:\n history_config = \"_\".join([option, \"kernel_size\", str(args.kernel_size),\n \"num_kernel\", str(args.kernel),\n \"channel\", str(args.channel),\n \"rank\", str(args.target_rank),\n \"epoch\", str(args.epoch)]) + '.csv'\n\n print(history_config)\n history_file = os.path.join(all_history_folder , history_config)\n df_history = pd.read_csv(history_file, usecols=[str(args.metric)])\n hit_flags = [False, False, False, False]\n hit_rec = np.zeros(len(hit_flags))\n mean = df_stable['mean'][option]\n std = df_stable['std'][option]\n is_loss = (args.metric == 'val_loss')\n for idx, row in df_history.iterrows():\n if all(hit_flags):\n break\n for i in range(len(hit_flags)):\n if not hit_flags[i]:\n hit_flags[i] = hit_checking(mean, std, i, row[args.metric], is_loss)\n if hit_flags[i]:\n hit_rec[i] = idx\n hit_list.append(hit_rec)\n df_hit_rec = pd.DataFrame(hit_list, index=options)\n df_hit_rec.columns = [\"0_sigma\", \"1_sigma\", \"2_sigma\", \"3_sigma\"]\n df_final = df_stable.merge(df_hit_rec, left_index=True, right_index=True)\n config = '_'.join(['Converge_rate_Last', str(args.observation_size), 'epoches', args.metric, 'statistics',\n 'kernel_size', str(args.kernel_size),\n 'rank', str(args.target_rank)])\n df_final.to_csv(os.path.join(args.target_folder, args.dataset, config+'.csv'))\n\ndef evaluate_afterward(args):\n print('check afterward epoch')\n global options\n # read file\n loss_rec = list()\n accuracy_rec = list()\n loss_idx_rec = list()\n accuracy_idx_rec = list()\n for option in options:\n if option == 'h_rank':\n target_rank = 1\n else:\n target_rank = args.target_rank\n if option in identity_options:\n history_path = './history_updated_identity/'\n else:\n history_path = args.history_path\n target_folder = os.path.join(history_path, args.dataset)\n file = \"_\".join([option, \"kernel_size\", str(args.kernel_size),\n \"num_kernel\", str(args.kernel),\n \"channel\", str(args.channel),\n \"rank\",str(target_rank),\n \"epoch\", str(args.epoch)])\n target_file = os.path.join(target_folder, file+'.csv')\n df_target = pd.read_csv(target_file)\n max_accuracy = -1\n min_loss = sys.maxsize\n max_acc_idx = 0\n min_loss_idx = 0\n accuracy_cnt = 0\n loss_cnt = 0\n accuracy_flag = False\n loss_flag = False\n\n for idx, row in df_target.iterrows():\n val_loss = row['val_loss']\n val_accuracy = row['val_accuracy']\n\n # Check accuracy\n if accuracy_flag == False:\n if max_accuracy < val_accuracy:\n max_accuracy = val_accuracy\n accuracy_cnt = 0\n max_acc_idx = idx\n else:\n accuracy_cnt = accuracy_cnt + 1\n if accuracy_cnt == 5:\n accuracy_flag = True\n\n # Check loss\n if loss_flag == False:\n if min_loss > val_loss:\n min_loss = val_loss\n loss_cnt = 0\n min_loss_idx = idx\n else:\n loss_cnt = loss_cnt + 1\n if loss_cnt == 5:\n loss_flag = True\n\n\n if loss_flag and accuracy_flag:\n break\n\n accuracy_rec.append(max_accuracy)\n accuracy_idx_rec.append(max_acc_idx)\n loss_rec.append(min_loss)\n loss_idx_rec.append(min_loss_idx)\n tmp_rec = dict()\n tmp_rec['approach'] = options\n tmp_rec['max_accuracy'] = accuracy_rec\n tmp_rec['max_accuracy_epoch'] = accuracy_idx_rec\n tmp_rec['min_loss'] = loss_rec\n tmp_rec['min_loss_epoch'] = loss_idx_rec\n df_rec = pd.DataFrame.from_dict(tmp_rec)\n config = \"_\".join([\"converge_afterward\",\"kernel_size\", str(args.kernel_size),\n \"num_kernel\", str(args.kernel),\n \"channel\", str(args.channel),\n \"rank\", str(args.target_rank),\n \"epoch\", str(args.epoch)])\n results_folder = os.path.join(args.target_folder, args.dataset)\n if not os.path.isdir(results_folder):\n os.makedirs(results_folder)\n df_rec.to_csv(os.path.join(results_folder, config + '.csv'), index=False)\n print('done... ' + str(config))\n\ndef evaluate_multiple_runs(args):\n history_folder = os.path.join(args.history_path, args.dataset)\n aggregation_folder = os.path.join(args.target_folder, args.dataset)\n if not os.path.exists(aggregation_folder):\n os.makedirs(aggregation_folder)\n for root, directories, files in os.walk(history_folder):\n if len(directories) != 0:\n avg_rec = dict()\n std_rec = dict()\n for option in options:\n history_rec = dict()\n if option == 'h_rank' or option == 'baseline':\n rank = 10\n else:\n rank = args.target_rank\n config = \"_\".join([\n \"rank\", str(rank),\n \"epoch\", str(args.epoch)])\n for d in directories:\n seed_folder = os.path.join(history_folder, d)\n target_file = os.path.join(seed_folder, option+'_'+config+'.csv')\n df_history = pd.read_csv(target_file)\n history_rec[d] = df_history[args.metric].values\n df_res = pd.DataFrame.from_dict(history_rec)\n option_folder = os.path.join(aggregation_folder, option)\n if not os.path.exists(option_folder):\n os.makedirs(option_folder)\n df_res.to_csv(os.path.join(option_folder, str(args.metric)+'_multi_runs_'+ str(option) + '_'+config+'.csv'))\n avg_res = df_res.mean(axis=1)\n std_res = df_res.std(axis=1)\n avg_rec[option] = avg_res\n std_rec[option] = std_res\n df_avg_rec = pd.DataFrame.from_dict(avg_rec)\n df_std_rec = pd.DataFrame.from_dict(std_rec)\n\n df_avg_rec.to_csv(os.path.join(aggregation_folder, 'avg_' + str(args.metric) + '_multi_runs_' + config + '.csv'))\n df_std_rec.to_csv(os.path.join(aggregation_folder, 'std_' + str(args.metric) + '_multi_runs_' + config + '.csv'))\n print('dsd')\n\ndef run_aggregation(args):\n agg_option = args.agg_option\n if agg_option == 'converge_rate':\n evaluate_converge_rate(args)\n elif agg_option == 'stablization_rate':\n evaluate_stabilization_rate(args)\n elif agg_option == 'stablization_afterward':\n evaluate_afterward(args)\n elif agg_option == 'multiple_runs':\n evaluate_multiple_runs(args)\n\n\nif __name__ == '__main__':\n args = parse_args()\n run_aggregation(args)\n\n","sub_path":"feedforward/results_aggregation.py","file_name":"results_aggregation.py","file_ext":"py","file_size_in_byte":12955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"501925231","text":"import multiprocessing\nfrom functools import partial\n\nimport os\n\nfrom skopt.space import Categorical, Real, Integer\n\nfrom course_lib.ParameterTuning.SearchBayesianSkopt import SearchBayesianSkopt\nfrom course_lib.ParameterTuning.SearchAbstractClass import SearchInputRecommenderArgs\n\n\ndef run_KNNRecommender_on_similarity_type(similarity_type, parameterSearch,\n parameter_search_space,\n recommender_input_args,\n n_cases,\n n_random_starts,\n resume_from_saved,\n save_model,\n output_folder_path,\n output_file_name_root,\n metric_to_optimize,\n allow_weighting=False,\n recommender_input_args_last_test=None):\n original_parameter_search_space = parameter_search_space\n\n hyperparameters_range_dictionary = {}\n hyperparameters_range_dictionary[\"topK\"] = Integer(5, 1000)\n hyperparameters_range_dictionary[\"shrink\"] = Integer(0, 2000)\n hyperparameters_range_dictionary[\"similarity\"] = Categorical([similarity_type])\n hyperparameters_range_dictionary[\"normalize\"] = Categorical([True, False])\n\n is_set_similarity = similarity_type in [\"tversky\", \"dice\", \"jaccard\", \"tanimoto\"]\n\n if similarity_type == \"asymmetric\":\n hyperparameters_range_dictionary[\"asymmetric_alpha\"] = Real(low=0, high=2, prior='uniform')\n hyperparameters_range_dictionary[\"normalize\"] = Categorical([True])\n\n elif similarity_type == \"tversky\":\n hyperparameters_range_dictionary[\"tversky_alpha\"] = Real(low=0, high=2, prior='uniform')\n hyperparameters_range_dictionary[\"tversky_beta\"] = Real(low=0, high=2, prior='uniform')\n hyperparameters_range_dictionary[\"normalize\"] = Categorical([True])\n\n elif similarity_type == \"euclidean\":\n hyperparameters_range_dictionary[\"normalize\"] = Categorical([True, False])\n hyperparameters_range_dictionary[\"normalize_avg_row\"] = Categorical([True, False])\n hyperparameters_range_dictionary[\"similarity_from_distance_mode\"] = Categorical([\"lin\", \"log\", \"exp\"])\n\n if not is_set_similarity:\n\n if allow_weighting:\n hyperparameters_range_dictionary[\"feature_weighting\"] = Categorical([\"none\", \"BM25\", \"TF-IDF\"])\n\n local_parameter_search_space = {**hyperparameters_range_dictionary, **original_parameter_search_space}\n\n parameterSearch.search(recommender_input_args,\n parameter_search_space=local_parameter_search_space,\n n_cases=n_cases,\n n_random_starts=n_random_starts,\n resume_from_saved=resume_from_saved,\n save_model=save_model,\n output_folder_path=output_folder_path,\n output_file_name_root=output_file_name_root + \"_\" + similarity_type,\n metric_to_optimize=metric_to_optimize,\n recommender_input_args_last_test=recommender_input_args_last_test)\n\n\ndef run_parameter_search_user_similarity_rs(recommender_class, helper_model, URM_train, UCM_object, UCM_name,\n URM_train_last_test=None,\n n_cases=30, n_random_starts=5, resume_from_saved=False, save_model=\"best\",\n evaluator_validation=None, evaluator_test=None,\n metric_to_optimize=\"PRECISION\",\n output_folder_path=\"result_experiments/\", parallelizeKNN=False,\n allow_weighting=True,\n similarity_type_list=None):\n # If directory does not exist, create\n if not os.path.exists(output_folder_path):\n os.makedirs(output_folder_path)\n\n URM_train = URM_train.copy()\n UCM_object = UCM_object.copy()\n\n if URM_train_last_test is not None:\n URM_train_last_test = URM_train_last_test.copy()\n\n ##########################################################################################################\n\n output_file_name_root = recommender_class.RECOMMENDER_NAME + \"_{}\".format(UCM_name)\n\n parameterSearch = SearchBayesianSkopt(recommender_class, evaluator_validation=evaluator_validation,\n evaluator_test=evaluator_test)\n\n if similarity_type_list is None:\n similarity_type_list = ['cosine', 'jaccard', \"asymmetric\", \"dice\", \"tversky\"]\n\n recommender_input_args = SearchInputRecommenderArgs(\n CONSTRUCTOR_POSITIONAL_ARGS=[URM_train, UCM_object, helper_model],\n CONSTRUCTOR_KEYWORD_ARGS={},\n FIT_POSITIONAL_ARGS=[],\n FIT_KEYWORD_ARGS={}\n )\n\n if URM_train_last_test is not None:\n recommender_input_args_last_test = recommender_input_args.copy()\n recommender_input_args_last_test.CONSTRUCTOR_POSITIONAL_ARGS[0] = URM_train_last_test\n else:\n recommender_input_args_last_test = None\n\n run_KNNCBFRecommender_on_similarity_type_partial = partial(run_KNNRecommender_on_similarity_type,\n recommender_input_args=recommender_input_args,\n parameter_search_space={},\n parameterSearch=parameterSearch,\n n_cases=n_cases,\n n_random_starts=n_random_starts,\n resume_from_saved=resume_from_saved,\n save_model=save_model,\n output_folder_path=output_folder_path,\n output_file_name_root=output_file_name_root,\n metric_to_optimize=metric_to_optimize,\n allow_weighting=allow_weighting,\n recommender_input_args_last_test=recommender_input_args_last_test)\n\n if parallelizeKNN:\n pool = multiprocessing.Pool(processes=int(multiprocessing.cpu_count()), maxtasksperchild=1)\n pool.map(run_KNNCBFRecommender_on_similarity_type_partial, similarity_type_list)\n\n pool.close()\n pool.join()\n\n else:\n\n for similarity_type in similarity_type_list:\n run_KNNCBFRecommender_on_similarity_type_partial(similarity_type)\n","sub_path":"src/tuning/holdout_validation/run_parameter_search_user_similarity_rs.py","file_name":"run_parameter_search_user_similarity_rs.py","file_ext":"py","file_size_in_byte":7051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"555169506","text":"from os import path, listdir, makedirs, remove\nimport os\n\nfiles = []\nif path.isdir('./data'):\n fs = listdir('./data')\n for f in fs:\n if path.splitext(f)[1] == '.in':\n files.append('./data/' + f)\nelse:\n raise \"Not found\"\n\nimport subprocess as sub\nimport time\n\nfiles = sorted(files)\n\neasy = []\ndiff = []\nfor file in files:\n with open(file, 'r') as f:\n tick = time.time()\n try:\n sub.run('../a.out', stdin=f, stdout=sub.DEVNULL, timeout=1.0)\n except sub.TimeoutExpired as exp:\n pass\n if time.time() - tick <= 1:\n easy.append(file)\n else:\n diff.append(file)\n print(time.time() - tick)\n\n\nif path.isdir('../data'):\n fs = listdir('../data')\nelse:\n makedirs('../data')\n\n\nsize = 8\n\ndatas = []\nfor file in easy:\n with open(file, 'r') as f:\n data = f.read()\n datas.append(data)\n\n\ncnt = 0\nf_cnt = 1\nfor d in datas:\n with open('../data/data-' + str(f_cnt) + '.in', 'a+') as f:\n f.write(d)\n\n cnt += 1\n if cnt == size:\n cnt = 0\n f_cnt += 1\n\ndatas = []\nfor file in diff:\n with open(file, 'r') as f:\n data = f.read()\n datas.append(data)\n\nfor d in datas:\n with open('../data/data-' + str(f_cnt) + '.in', 'a+') as f:\n f.write(d)\n cnt += 1\n\n if cnt == size:\n cnt = 0\n f_cnt += 1\n ","sub_path":"week4/q3/origin/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"150734418","text":"import logging\n\n\nLOG_FORMAT = '[%(levelname)s][%(asctime)s][%(processName)s][%(threadName)s] %(message)s'\n\n\ndef configure(log_path: str = None, silent: bool = False):\n root = logging.getLogger()\n formatter = logging.Formatter(LOG_FORMAT)\n\n if not silent:\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(formatter)\n root.addHandler(stream_handler)\n\n if log_path:\n file_handler = logging.FileHandler(log_path)\n file_handler.setFormatter(formatter)\n root.addHandler(file_handler)\n\n if not root.handlers:\n root.addHandler(logging.NullHandler())\n\n logging.getLogger('alembic').setLevel(logging.WARNING)\n\n root.setLevel(logging.INFO)\n","sub_path":"satellite/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"500459025","text":"#!/usr/bin/env python3\n# cython: language_level=3\n# By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.\n# That is, 3 + 7 + 4 + 9 = 23.\n# Find the maximum total from top to bottom of the triangle below:\nimport json\nwith open(\"data/triangle.json\") as f:\n triangle = json.load(f)\n# NOTE: As there are only 16384 routes, it is possible to solve this\n# problem by trying every route. However, Problem 67, is the same\n# challenge with a triangle containing one-hundred rows; it cannot be\n# solved by brute force, and requires a clever method! ;o)\n\n\ndef bruteforce():\n global triangle\n for y in range(98, -1, -1): # last row is already inited\n for x in range(y + 1):\n triangle[y][x] += max(triangle[y + 1][x], triangle[y + 1][x + 1])\n\nbruteforce()\nprint(triangle[0][0])\n","sub_path":"_0067.py","file_name":"_0067.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"586001445","text":"# bu iki satır console ekranını temizlemek için\nimport os\nos.system(\"cls\") \n\nprint(\"Bu program girdiğiniz sayının tek mi çift mi olduğunu söyler.\")\n\n# sayı tek mi çift mi\nsayi = int(input(\"Sayı: \"))\n\nif sayi % 2 == 0:\n print(\"çift\")\nelse:\n print(\"tek\")\n\n\"\"\"\nbu yorum\nçok satırlı bir yorumdur\n\"\"\"","sub_path":"TekMiCiftMi.py","file_name":"TekMiCiftMi.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"39764869","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"拡張モデル 検索\"\"\"\n\n# ##########################################################\n# Copyright 2016 Miyamoto. All Rights Reserved.\n#\n# app.extension_models.search\n#\n# 履歴:\n# Date Version Updater Description\n# 2016/03/19 1.0.0 Miyamoto 初版。\n# ##########################################################\n\nfrom config import Config\n\nfrom app.models import User, UserMeta, UserCommodity, UserCommodityComment, UserCommodityInterchange\n\n\nclass Search:\n \"\"\"検索 モデル\"\"\"\n\n @staticmethod\n def users_keyword(request_data):\n \"\"\"\n ユーザ キーワード検索\n\n NOTE:\n LIKE 検索は \"nick_name\", \"profile\" が検索対象\n User.updated_at 降順ソート\n\n :param request_data: リクエストデータ\n :return:\n \"\"\"\n\n # 検索キーワード\n search_keyword = request_data['search_keyword']\n\n # オフセット\n if 'offset' in request_data:\n offset = request_data['offset']\n else:\n offset = 0\n\n from sqlalchemy import desc\n from sqlalchemy.sql import or_\n\n # LIKE 検索\n users = User.query \\\n .order_by(desc(User.updated_at),\n User.id) \\\n .filter(or_(UserMeta.nick_name.like(\"%{}%\".format(search_keyword)),\n UserMeta.profile.like(\"%{}%\".format(search_keyword)))) \\\n .offset(offset) \\\n .limit(Config.EC_USER_SEARCH_PER_PAGE) \\\n .all()\n\n if users:\n result = {\n 'users': [user.to_search_json() for user in users]\n }\n else:\n result = {\n 'users': []\n }\n\n return result\n\n @staticmethod\n def users_user(request_data):\n \"\"\"\n ユーザ 検索 ユーザ 詳細\n\n :param request_data: リクエストデータ\n :return:\n \"\"\"\n\n user = User.query.filter_by(user_identifier=request_data['search_identifier']).first()\n\n if user:\n return user.to_search_description_json()\n\n return []\n\n @staticmethod\n def commodities(request_data):\n \"\"\"\n 商品 検索\n\n Keyword > Category > User 検索\n\n NOTE:\n LIKE 検索は \"keyword\", \"title\" が検索対象\n UserCommodity.updated_at 降順ソート\n\n :param request_data: リクエストデータ\n :return:\n \"\"\"\n\n # 検索キーワード\n if 'search_keyword' in request_data:\n search_keyword = request_data['search_keyword']\n else:\n search_keyword = None\n # カテゴリid\n if 'search_category_identifier' in request_data:\n search_category_identifier = request_data['search_category_identifier']\n else:\n search_category_identifier = None\n # ユーザid\n if 'search_user_identifier' in request_data:\n search_user_identifier = request_data['search_user_identifier']\n else:\n search_user_identifier = None\n\n # オフセット\n if 'offset' in request_data:\n offset = request_data['offset']\n else:\n offset = 0\n # リミット\n per_page = Config.EC_COMMODITY_SEARCH_PER_PAGE\n\n from sqlalchemy import desc\n from sqlalchemy.sql import and_, or_\n\n # 取得する商品一覧を保持する変数\n commodities = None\n\n if search_keyword and search_category_identifier and search_user_identifier:\n # LIKE 検索 及び カテゴリ 検索 及び ユーザ商品 検索\n\n # ユーザ取得\n user = User.query.filter_by(user_identifier=search_user_identifier).first()\n if user:\n # ユーザ商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .filter(and_(or_(UserCommodity.keyword.like(\"%{}%\".format(search_keyword)),\n UserCommodity.title.like(\"%{}%\".format(search_keyword))),\n or_(UserCommodity.category_identifier_1 == search_category_identifier,\n UserCommodity.category_identifier_2 == search_category_identifier),\n user_meta_id=user.user_meta.id)) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n elif search_keyword and search_category_identifier:\n # LIKE 検索 及び カテゴリ 検索\n\n # 商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .filter(and_(or_(UserCommodity.keyword.like(\"%{}%\".format(search_keyword)),\n UserCommodity.title.like(\"%{}%\".format(search_keyword))),\n or_(UserCommodity.category_identifier_1 == search_category_identifier,\n UserCommodity.category_identifier_2 == search_category_identifier))) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n elif search_keyword and search_user_identifier:\n # LIKE 検索 及び ユーザ商品 検索\n\n # ユーザ取得\n user = User.query.filter_by(user_identifier=search_user_identifier).first()\n if user:\n # ユーザ商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .filter(and_(or_(UserCommodity.keyword.like(\"%{}%\".format(search_keyword)),\n UserCommodity.title.like(\"%{}%\".format(search_keyword))),\n user_meta_id=user.user_meta.id)) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n elif search_user_identifier and search_category_identifier:\n # カテゴリ 検索 及び ユーザ商品 検索\n\n # ユーザ取得\n user = User.query.filter_by(user_identifier=search_user_identifier).first()\n if user:\n # ユーザ商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .filter(and_(or_(UserCommodity.category_identifier_1 == search_category_identifier,\n UserCommodity.category_identifier_2 == search_category_identifier),\n user_meta_id=user.user_meta.id)) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n elif search_keyword:\n # LIKE 検索\n\n # 商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .filter(or_(UserCommodity.keyword.like(\"%{}%\".format(search_keyword)),\n UserCommodity.title.like(\"%{}%\".format(search_keyword)))) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n elif search_category_identifier:\n # カテゴリ 検索\n\n # 商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .filter(or_(UserCommodity.category_identifier_1 == search_category_identifier,\n UserCommodity.category_identifier_2 == search_category_identifier)) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n elif search_user_identifier:\n # ユーザ商品 検索\n\n # ユーザ取得\n user = User.query.filter_by(user_identifier=search_user_identifier).first()\n if user:\n if 'commodity_status' in request_data:\n # 出品状態 指定\n\n # ユーザ商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .filter_by(and_(user_meta_id=user.user_meta.id,\n commodity_status=request_data['commodity_status'])) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n elif 'interchange_status' in request_data:\n # 交換状態 指定\n\n # ユーザ商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .join(UserCommodityInterchange) \\\n .filter(and_(UserCommodityInterchange.commodity_status == request_data['interchange_status'],\n user_meta_id=user.user_meta.id)) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n else:\n # 指定なし\n\n # ユーザ商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .filter_by(user_meta_id=user.user_meta.id) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n else:\n # 空の場合は 全件 検索\n\n # 商品取得\n commodities = UserCommodity.query \\\n .order_by(desc(UserCommodity.updated_at),\n UserCommodity.id) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n\n if commodities:\n result = {\n 'commodities': [commodity.to_search_json() for commodity in commodities]\n }\n else:\n result = {\n 'commodities': []\n }\n\n return result\n\n @staticmethod\n def commodities_commodity(request_data):\n \"\"\"\n 商品 検索 商品 詳細\n\n :param request_data: リクエストデータ\n :return:\n \"\"\"\n\n commodity = UserCommodity.query.filter_by(commodity_identifier=request_data['search_identifier']).first()\n\n if commodity:\n return commodity.to_search_description_json()\n\n return []\n\n @staticmethod\n def commodity_comment_list(request_data):\n \"\"\"\n 商品コメント一覧\n\n :param request_data: リクエストデータ\n :return:\n \"\"\"\n\n # オフセット\n if 'offset' in request_data:\n offset = request_data['offset']\n else:\n offset = 0\n # リミット\n per_page = Config.EC_COMMODITY_SEARCH_PER_PAGE\n\n # ユーザ商品取得\n commodity = UserCommodity.query \\\n .filter_by(commodity_identifier=request_data['commodity_identifier']) \\\n .first()\n\n if not commodity:\n raise ValueError('Not found commodity')\n\n from sqlalchemy import desc\n\n # 商品コメント一覧取得\n user_commodity_comments = UserCommodityComment.query \\\n .order_by(desc(UserCommodityComment.created_at),\n UserCommodityComment.id) \\\n .filter(UserCommodityComment.user_commodity_meta_id == commodity.user_commodity_meta.id) \\\n .offset(offset) \\\n .limit(per_page) \\\n .all()\n\n if not user_commodity_comments:\n return {'comments': []}\n\n return {\n 'comments': [user_commodity_comment.to_json() for user_commodity_comment in user_commodity_comments]\n }\n","sub_path":"app/extension_models/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":12398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"557074205","text":"\"\"\"Stochastic variants of Lookup table based-strategies, trained with particle\nswarm algorithms.\n\nFor the original see:\n https://gist.github.com/GDKO/60c3d0fd423598f3c4e4\n\"\"\"\n\nfrom axelrod.actions import Actions, Action\nfrom axelrod.load_data_ import load_pso_tables\nfrom axelrod.player import Player\nfrom axelrod.random_ import random_choice\nfrom .lookerup import LookerUp, Plays\n\n\nC, D = Actions.C, Actions.D\ntables = load_pso_tables(\"pso_gambler.csv\", directory=\"data\")\n\n\nclass Gambler(LookerUp):\n \"\"\"\n A stochastic version of LookerUp which will select randomly an action in\n some cases.\n \"\"\"\n\n name = 'Gambler'\n classifier = {\n 'memory_depth': float('inf'),\n 'stochastic': True,\n 'makes_use_of': set(),\n 'long_run_time': False,\n 'inspects_source': False,\n 'manipulates_source': False,\n 'manipulates_state': False\n }\n\n def strategy(self, opponent: Player) -> Action:\n actions_or_float = super(Gambler, self).strategy(opponent)\n if isinstance(actions_or_float, Action):\n return actions_or_float\n return random_choice(actions_or_float)\n\n\nclass PSOGamblerMem1(Gambler):\n \"\"\"\n A 1x1x0 PSOGambler trained with pyswarm. This is the 'optimal' memory one\n strategy trained against the set of short run time strategies in the\n Axelrod library.\n\n Names:\n - PSO Gambler Mem1: Original name by Marc Harper\n \"\"\"\n\n name = \"PSO Gambler Mem1\"\n\n def __init__(self) -> None:\n pattern = tables[(\"PSO Gambler Mem1\", 1, 1, 0)]\n parameters = Plays(self_plays=1, op_plays=1, op_openings=0)\n\n super().__init__(parameters=parameters, pattern=pattern)\n\n\nclass PSOGambler1_1_1(Gambler):\n \"\"\"\n A 1x1x1 PSOGambler trained with pyswarm.\n\n Names:\n - PSO Gambler 1_1_1: Original name by Marc Harper\n \"\"\"\n\n name = \"PSO Gambler 1_1_1\"\n\n def __init__(self) -> None:\n pattern = tables[(\"PSO Gambler 1_1_1\", 1, 1, 1)]\n parameters = Plays(self_plays=1, op_plays=1, op_openings=1)\n\n super().__init__(parameters=parameters, pattern=pattern)\n\n\nclass PSOGambler2_2_2(Gambler):\n \"\"\"\n A 2x2x2 PSOGambler trained with pyswarm. Original version by @GDKO.\n\n Names:\n - PSO Gambler 2_2_2: Original name by Marc Harper\n \"\"\"\n\n name = \"PSO Gambler 2_2_2\"\n\n def __init__(self) -> None:\n pattern = tables[(\"PSO Gambler 2_2_2\", 2, 2, 2)]\n parameters = Plays(self_plays=2, op_plays=2, op_openings=2)\n\n super().__init__(parameters=parameters, pattern=pattern)\n\n\nclass PSOGambler2_2_2_Noise05(Gambler):\n \"\"\"\n A 2x2x2 PSOGambler trained with pyswarm with noise=0.05.\n\n Names:\n - PSO Gambler 2_2_2 Noise 05: Original name by Marc Harper\n\n \"\"\"\n\n name = \"PSO Gambler 2_2_2 Noise 05\"\n\n def __init__(self) -> None:\n pattern = tables[(\"PSO Gambler 2_2_2 Noise 05\", 2, 2, 2)]\n parameters = Plays(self_plays=2, op_plays=2, op_openings=2)\n\n super().__init__(parameters=parameters, pattern=pattern)\n","sub_path":"axelrod/strategies/gambler.py","file_name":"gambler.py","file_ext":"py","file_size_in_byte":3029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"429431704","text":"#import modules\nimport numpy as np\nimport scipy.special as sp\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy.stats as spstat\n\n#set matplotlib rc parameters\nrc={'lines.linewidth':2, 'axes.labelsize':18, 'axes.titlesize':18}\nsns.set(rc=rc)\n\ndef ecdf(data):\n '''\n compute x, y values for an empirical distribution function\n '''\n x=np.sort(data)\n y=np.arange(1, 1+len(x))/len(x)\n\n return x, y\n\n#load data\nxa_high=np.loadtxt('data/xa_high_food.csv', comments='#')\nxa_low=np.loadtxt('data/xa_low_food.csv', comments='#')\n\nx_high, y_high=ecdf(xa_high)\nx_low, y_low=ecdf(xa_low)\n\nplt.plot(x_high, y_high, marker='.', linestyle='none', markersize=18, alpha=0.5)\nplt.plot(x_low, y_low, marker='.', linestyle='none', markersize=18, alpha=0.5)\nplt.xlabel('Cross-sectional area (µm$^$)')\nplt.ylabel('eCDF')\nplt.legend(('high food', 'low food'), loc='lower right')\nplt.show()\n","sub_path":"lesson23-23_ex3.py","file_name":"lesson23-23_ex3.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"439224527","text":"#!/usr/bin/env python\n\nfrom boto.s3.connection import S3Connection, Key\nimport shlex\nimport json\nimport sys\nimport os.path\nfrom ansible.module_utils.basic import *\n\nmodule = AnsibleModule(\n argument_spec = dict(\n bucket = dict( required=True ),\n object = dict( required=True ),\n dest = dict( required=True ),\n aws_access_key = dict( required=False,default=False),\n aws_secret_key = dict( required=False,default=False),\n mode = dict( required=False )\n )\n)\nif 'aws_access_key' in module.params and 'aws_secret_key' in module.params and module.params.get('aws_access_key') and module.params.get('aws_secret_key'):\n conn = S3Connection(module.params.get('aws_access_key'),module.params.get('aws_secret_key'))\nelse:\n conn = S3Connection()\nbucket = conn.get_bucket(module.params.get('bucket'), validate=False)\nk = bucket.new_key(module.params.get('object'))\n# a file in which we can cache the etag; if etag matches, don't download\nk_etag = \"%s\" % k.etag\netag_cache_file = \"%s.etag\" % module.params.get('dest')\n# try to get the cached etag; if it fails, we know we need to download.\nneed_to_download = True\ncached_etag = None\nif os.path.isfile(etag_cache_file) and os.path.isfile(module.params.get('dest')):\n with open(etag_cache_file, 'r' ) as f:\n cached_etag = f.read()\n if cached_etag == k_etag:\n need_to_download = False\n \nif need_to_download: \n k.get_contents_to_filename(module.params.get('dest'))\n with open(etag_cache_file, 'w') as f:\n f.write( k_etag )\n module.exit_json(failed=False,changed=True,msg=(\"Redownloaded object because etag cache %s does not equal %s\" % (cached_etag,k_etag)))\nelse:\n module.exit_json(failed=False,changed=False,msg=(\"Etag cache matches; file not downloaded\") )\n","sub_path":"roles/java/library/s3_file.py","file_name":"s3_file.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"304697157","text":"# 6. Write a program which will find all such numbers which are divisible by 7 but are\n# not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained\n# should be printed in a comma-separated sequence on a single line.\n\nlower_limit = 2000\nupper_limit = 3200 + 1\n\nfor number in range(lower_limit, upper_limit):\n if number % 7 == 0:\n if number % 5 != 0:\n print(number, end=\",\")\n\n","sub_path":"cs4/6_divisible_by_7.py","file_name":"6_divisible_by_7.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"139931488","text":"# -*- coding: utf-8 -*-\n\nimport sys,getopt,got,datetime,codecs\nusers=[]\npre_processed=[]\ndef main(argv):\n\t\n\t\n\tif len(argv) == 0:\n\t\tprint ('You must pass some parameters. Use \\\"-h\\\" to help.')\n\t\treturn\n\t\t\n\tif len(argv) == 1 and argv[0] == '-h':\n\t\tprint (\"\"\"\\nTo use this jar, you can pass the folowing attributes:\n username: Username of a specific twitter account (without @)\n since: The lower bound date (yyyy-mm-aa)\n until: The upper bound date (yyyy-mm-aa)\n querysearch: A query text to be matched\n maxtweets: The maximum number of tweets to retrieve\n\n \\nExamples:\n # Example 1 - Get tweets by username [barackobama]\n python Exporter.py --username \"barackobama\" --maxtweets 1\\n\n\n # Example 2 - Get tweets by query search [europe refugees]\n python Exporter.py --querysearch \"europe refugees\" --maxtweets 1\\n\n\n # Example 3 - Get tweets by username and bound dates [barackobama, '2015-09-10', '2015-09-12']\n python Exporter.py --username \"barackobama\" --since 2015-09-10 --until 2015-09-12 --maxtweets 1\\n\n \n # Example 4 - Get the last 10 top tweets by username\n python Exporter.py --username \"barackobama\" --maxtweets 10 --toptweets\\n\"\"\")\n\t\treturn\n \n\ttry:\n\t\topts, args = getopt.getopt(argv, \"\", (\"username=\", \"since=\", \"until=\", \"querysearch=\", \"toptweets\", \"maxtweets=\"))\n\t\t\n\t\ttweetCriteria = got.manager.TweetCriteria()\n\t\t\n\t\tfor opt,arg in opts:\n\t\t\tif opt == '--username':\n\t\t\t\ttweetCriteria.username = arg\n\t\t\t\t\n\t\t\telif opt == '--since':\n\t\t\t\ttweetCriteria.since = arg\n\t\t\t\t\n\t\t\telif opt == '--until':\n\t\t\t\ttweetCriteria.until = arg\n\t\t\t\t\n\t\t\telif opt == '--querysearch':\n\t\t\t\ttweetCriteria.querySearch = arg\n\t\t\t\t\n\t\t\telif opt == '--toptweets':\n\t\t\t\ttweetCriteria.topTweets = True\n\t\t\t\t\n\t\t\telif opt == '--maxtweets':\n\t\t\t\ttweetCriteria.maxTweets = int(arg)\n\t\t\t\t\n\t\t\n\t\toutputFile = codecs.open(\"pre_processing.csv\", \"w+\", \"utf-8\")\n\t\t\n\t\toutputFile.write('username;date;text;mentions;hashtags;id')\n\t\t\n\t\tprint ('Searching...\\n')\n\t\t\n\t\tdef receiveBuffer(tweets):\n\t\t\tusernameRef=\"SkypeSupport\"\t\n\t\t\tfor t in tweets:\n\t\t\t\t\n\t\t\t\tmentions=t.mentions.split(' ')\n\t\t\t\tusername=t.username\n\t\t\t\tpre_processed.append([t.username,t.date.strftime(\"%Y-%m-%d %H:%M\"),t.text,mentions,t.hashtags,t.id])\n\t\t\t\tif(mentions and (username==usernameRef )): #or username==\"tatapower_ddl\"\n\t\t\t\t\tfor m in mentions:\n\t\t\t\t\t\tif(not (m in users)):\n\t\t\t\t\t\t\tusers.append(m[1:])\n\n\n\t\t\t\toutputFile.write(('\\n%s;%s;\"%s\";%s;%s;\"%s\"' % (t.username, t.date.strftime(\"%Y-%m-%d %H:%M\"), t.text, t.mentions, t.hashtags, t.id)))\n\t\t\toutputFile.flush();\n\t\t\t\n\t\t\tprint ('More %d saved on file...\\n' % len(tweets))\n\t\t\n\t\tgot.manager.TweetManager.getTweets(tweetCriteria, receiveBuffer)\n\t\t\n\t\t\n\n\n\texcept arg:\n\t\tprint ('Arguments parser error, try -h' + arg)\n\tfinally:\n\t\toutputFile.close() \n\t\tprint ('Done. Output file generated \"pre_processing.csv\".')\n\t\tprocessTweets() \n\t\t\n\n\ndef processTweets():\n\t#file handling code first try catch finally\n\t#1) Extract all tweets which mention user or are made by user \n\t#2) Store tweets into file which \n\t#3) Optional later--> Label as question and answer\n\t#user is a list of users mentioned by tata\n\t# pre_processed structure--> [[username(str),date(str),text(str),mentions(list),hashtags(str),id(str)],[.......]]\n\t\n\n\n\ttry:\t\t\t\n\t\toutputFileT = codecs.open(\"post_processing.csv\", \"w+\", \"utf-8\")\n\t\t\n\t\toutputFileT.write('username,date,text')\n\t\tpost_processed=[]\n\t\tif(len(users)):\n\t\t\tusers.pop(0)\n\t\t#print(users)\n\n\t\tfor us in users:\n\n\t\t\tfor tw in pre_processed:\n\t\t\t\tprint(tw[3])\n\t\t\t\tprint(\"-------------\"+us)\n\t\t\t\tif(us==tw[0] or ((('@'+us) in tw[3]) and (tw[0]==usernameRef ) )): # or tw[0]=='tatapower_ddl' comparing whether user is mentioned or has made a tweet\n\t\t\t\t\tpost_processed.append(tw)\n\t\t\t\t\t#possible to have a better storage representation here\n\t\t\t\t\toutputFileT.write(('\\n%s,%s,\"%s\"' % (tw[0], tw[1], tw[2]))) #outputFileT.write(('\\n%s;%s;\"%s\";%s;%s;\"%s\"' % (tw[0], tw[1], tw[2], tw[3], tw[4], tw[5])))\n\t\t#print(post_processed)\n\texcept Exception as e:\n\t\tprint (e)\n\tfinally:\n\t\toutputFileT.close() \n\t\tprint ('Done. Output file generated \"post_processing.csv\".')\n\t\nif __name__ == '__main__':\n\tmain(sys.argv[1:])\n","sub_path":"Exporter.py","file_name":"Exporter.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"57398071","text":"#辐射追迹画图\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom mpl_toolkits.axisartist.axislines import SubplotZero\nplt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False # 用来正常显示负号\n#原则性参数\nmr = 50\nresidual_r = 30\n\n\ndef pointu(pointa, pointb, x): #两点连线,确定y坐标\n y = (x-pointa[0])/(pointb[0]-pointa[0])*(pointb[1]-pointa[1])+pointa[1]\n return y\n\ndef line(pointa, pointb, x_axis, apertures): #确定可以通过口径的光线 \n y_axis = pointu(pointa, pointb, x)\n x_max = [max(x)]\n for aperture in apertures:\n y = pointu(pointa, pointb, aperture[2])\n if (y < aperture[0])|(y > aperture[1]): #在口径外的将不画出\n x_max.append(aperture[2])\n \n x_end = min(x_max) #最大横坐标位置\n for i0, aperture in enumerate(apertures): #定位挡光位置\n if x_end == max(x):\n indexi = len(apertures)+1\n if x_end == aperture[2]:\n indexi = i0\n x_axis_new = x_axis[x_axis <= x_end]\n y_axis_new = y_axis[x_axis <= x_end] \n return x_axis_new, y_axis_new, indexi\n\ndef plot_Radiation_2p(point_rc, point_rbc, x, apertures): #画出所有的线\n x_new, y_new, indexi = line(point_rc, point_rbc, x, apertures)\n if max(x_new) == max(x):\n plt.plot(x_new, y_new, 'r-', linewidth=linwidth1) \n else:\n plt.plot(x_new, y_new, 'k-' ,linewidth=linwidth2) \n\ndef plot_Radiation(sr, C, x, apertures):\n plot_Radiation_2p(sr.point_rc, C.point_rbc, x, apertures)\n plot_Radiation_2p(sr.point_rc, C.point_lbc, x, apertures)\n plot_Radiation_2p(sr.point_lc, C.point_rbc, x, apertures)\n plot_Radiation_2p(sr.point_lc, C.point_lbc, x, apertures)\n\ndef plot_Radiation2(sr, Cs, x, aper): #画出所有的线,近画出分布特征线\n index0 = []\n x0 = []\n y0 =[]\n for C in Cs: #记录每条光线的截至位置,寻找最大y值光线\n x_new, y_new, indexi = line(sr.point_rc, C.point_rbc, x, aper)\n x0.append(x_new)\n y0.append(y_new) \n index0.append(indexi) \n x_new, y_new, indexi = line(sr.point_rc, C.point_lbc, x, aper)\n x0.append(x_new)\n y0.append(y_new) \n index0.append(indexi) \n x_new, y_new, indexi = line(sr.point_lc, C.point_rbc, x, aper)\n x0.append(x_new)\n y0.append(y_new) \n index0.append(indexi) \n x_new, y_new, indexi = line(sr.point_lc, C.point_lbc, x, aper)\n x0.append(x_new)\n y0.append(y_new)\n index0.append(indexi) \n \n #获得每个屏上的光线极限,步骤:1.把在同一平面截至的光线统计到一起,2.寻找边界光线\n \n for indexi in list(set(index0)):\n #1.把在同一平面截至的光线统计到一起\n yi = []\n xi = []\n for x_new, y_new, indexii in zip(x0, y0, index0):\n if indexi == indexii:\n yi.append(y_new)\n xi.append(x_new)\n yi = np.array(yi)\n xi = np.array(xi)\n \n #寻找极限边界光线,在狭缝的上下界\n if (indexi < len(aper)) & (indexi > 0) :\n yi_max = max(yi[:,-1])\n xii = xi[yi[:,-1] == yi_max][0]\n yii = yi[yi[:,-1] == yi_max][0]\n plt.plot(xii,yii, 'k-' ,linewidth = linwidth1)\n if yi_max > aper[indexi][1]:\n plt.plot([xii[-1], xii[-1]],[yii[-1], yii[-1] + mr],color = 'red',linewidth = 2)\n Cs[indexi].wailunkuo = yii[-1] + mr - Cs[indexi].center[1]\n \n yi_min = min(yi[:,-1])\n xii = xi[yi[:,-1] == yi_min][0]\n yii = yi[yi[:,-1] == yi_min][0]\n plt.plot(xii,yii, 'k-' ,linewidth = linwidth1)\n if yi_min < aper[indexi][0]: \n plt.plot([xii[-1], xii[-1]],[yii[-1], yii[-1] - mr],color = 'red',linewidth = 2)\n Cs[indexi].wailunkuo = -yii[-1] + mr + Cs[indexi].center[1]\n\n if indexi == (len(aper)-1):\n angle = np.rad2deg(np.arctan(yi[:,1]-yi[:,0])/(xi[:,1]-xi[:,0]))\n \n return angle\n \n \ndef line_range(pointa, pointb, x_axis, apertures): #横坐标x_axis,纵坐标y_axis \n y_axis = pointu(pointa, pointb, x)\n x_min = [0]\n for aperture in apertures:\n y = pointu(pointa, pointb, aperture[2])\n if (y < aperture[0])|(y > aperture[1]): #在口径外的将不画出\n x_min.append(aperture[2]) #记录位置 \n x_axis_new = x_axis[(x_axis>=max(x_min))]#\n y_axis_new = y_axis[(x_axis>=max(x_min))]# \n \n return x_axis_new, y_axis_new\n\n\ndef plot_Radiation_2p_range(point_a, point_b, x, apertures):\n x_new, y_new = line_range(point_a, point_b, x, apertures)\n if min(x_new) == min(x):\n plt.plot(x_new[x_new<=point_a[0]], y_new[x_new<=point_a[0]], 'blue', linewidth=linwidth1) \n else:#光线被截止\n # print('no plot')\n plt.plot(x_new[x_new<=point_a[0]], y_new[x_new<=point_a[0]], 'gray' ,linewidth=linwidth1) \n \ndef plot_Radiation_range(C1, C2, x, apertures):\n plot_Radiation_2p_range(C1.point_rfc, C2.point_lbc, x, apertures)\n plot_Radiation_2p_range(C1.point_rfc, C2.point_rbc, x, apertures)\n #plot_Radiation_2p_range(C1.point_lfc, C2.point_lbc, x, apertures)\n #plot_Radiation_2p_range(C1.point_lfc, C2.point_rbc, x, apertures)\n\ndef plot_Radiation_range2(Ce, Cs, x, C_end, apertures):\n \n x0 = []\n y0 =[]\n for i0, Ci in enumerate(Cs):\n if i0 > 0:\n plot_Radiation_2p_range(Ce.point_rfc, Ci.point_lbc, x, apertures)\n plot_Radiation_2p_range(Ce.point_lfc, Ci.point_rbc, x, apertures) \n \n x_new1, y_new1= line_range(Ce.point_rfc, Ci.point_lbc, x, apertures)\n x_new2, y_new2 = line_range(Ce.point_rfc, Ci.point_rbc, x, apertures)\n if min(x_new1) == min(x):\n x0.append(x_new1)\n y0.append(y_new1)\n if min(x_new2) == min(x):\n x0.append(x_new2)\n y0.append(y_new2) \n \n y0 = np.array(y0)\n x0 = np.array(x0)\n ymin = min(y0[:,0])\n\n for i, yi in enumerate(y0):\n if yi[0] == ymin:\n x_new = x0[i,:]\n y_new = yi\n plt.plot(x_new[x_new\", size = 2.0)\n ax.axis[\"y\"].set_axisline_style(\"->\", size = 2.0)\n\n new_axisline = ax.get_grid_helper().new_fixed_axis\n ax.axis[\"new2\"] = new_axisline(loc=\"right\", offset=(0, 0), axes=ax)\n \n new_axisline = ax.get_grid_helper().new_fixed_axis\n ax.axis[\"new3\"] = new_axisline(loc=\"left\", offset=(0, 0), axes=ax) \n #画图参数\n linwidth1 = 1\n linwidth2 = 0.1\n \n#%%#画器件\nif True:\n #%%准直器件\n plt.text(ur.point_lc[0]+600,y_limit[1]*0.5,ur.name,fontdict={'size':'12','color':'b','rotation':'90'})\n plt.gca().add_patch(plt.Rectangle((sr.point_lc[0],sr.point_lc[1]), 100, sr.width, color = 'red')) \n #光源\n plt.text(sr.point_lc[0]+600,y_limit[1]*0.5,sr.name,fontdict={'size':'12','color':'b','rotation':'90'})\n plt.gca().add_patch(plt.Rectangle((sr.point_lc[0],sr.point_lc[1]), 100, sr.width, color = 'blue'))\n \n #准直器类\n \n for C in [C1, C2, C3, C4, C5, C6]:\n if C.name == 'Ratched Wall & C4':\n color_block = 'black'\n elif C.name == 'SS & C3':\n color_block = 'yellow'\n elif C.name == 'C5':\n color_block = 'yellow'\n else:\n color_block = 'blue' \n plt.gca().add_patch(plt.Rectangle((C.point_rbc[0], C.point_rbc[1]), C.thickness, C.wailunkuo, color = color_block))\n plt.gca().add_patch(plt.Rectangle((C.point_lbc[0], C.point_lbc[1] - C.wailunkuo), C.thickness, C.wailunkuo, color = color_block))\n plt.text(C.point_rbc[0]-400,y_limit[1]*0.6,\"{}\".format(C.name),fontdict={'size':'12','color':'b','rotation':'90'}) \n\n #%%光学器件\n #白光狭缝\n L = 20\n plt.gca().add_patch(plt.Rectangle((aper_WB.point_rbc[0], aper_WB.point_rbc[1]), 300, L, color='gray'))\n plt.gca().add_patch(plt.Rectangle((aper_WB.point_lbc[0], aper_WB.point_lbc[1] - L), 300, L, color='gray')) \n plt.text(aper_WB.point_lbc[0]-600,y_limit[1]*0.3,\"White Slit\",fontdict={'size':'12','color':'g','rotation':'90'}) \n #白光镜\n plt.plot([WBM.point_lbc[0],WBM.point_rbc[0]], [WBM.point_lbc[1],WBM.point_rbc[1]],linewidth =2,color = 'gray')\n plt.text(WBM.point_lbc[0]-00,y_limit[1]*0.2,\"WBM\",fontdict={'size':'12','color':'g','rotation':'90'}) \n #单色器\n plt.plot([DCM01.point_lbc[0],DCM01.point_rbc[0]], [DCM01.point_lbc[1],DCM01.point_rbc[1]],linewidth =2,color = 'g')\n plt.plot([DCM02.point_lbc[0],DCM02.point_rbc[0]], [DCM02.point_lbc[1],DCM02.point_rbc[1]],linewidth =2,color = 'g')\n plt.text(DCM02.point_lbc[0]-600,y_limit[1]*0.6,\"DCM\",fontdict={'size':'12','color':'g','rotation':'90'}) \n #谐波镜\n plt.plot([HRM01.point_lbc[0],HRM01.point_rbc[0]], [HRM01.point_lbc[1],HRM01.point_rbc[1]],linewidth =2,color = 'g')\n plt.plot([HRM02.point_lbc[0],HRM02.point_rbc[0]], [HRM02.point_lbc[1],HRM02.point_rbc[1]],linewidth =2,color = 'g')\n plt.text(HRM02.point_lbc[0]-600,y_limit[1]*0.8,\"HRMS\",fontdict={'size':'12','color':'g','rotation':'90'}) \n #VFM\n plt.plot([VFM.point_lbc[0],VFM.point_rbc[0]], [VFM.point_lbc[1],VFM.point_rbc[1]],linewidth =2,color = 'g')\n plt.text(VFM.point_lbc[0]-600,y_limit[1]*0.8,\"VFM\",fontdict={'size':'12','color':'g','rotation':'90'}) \n\n#%%准直器画线 \nif True: \n #\n #辐射追迹option1:画出所有线\n# for C in fs_components:\n# plot_Radiation(sr, C, x, apertures[0:4])\n #辐射追迹option2:画出部分光线\n angle1 = plot_Radiation2(sr, fs_components, x, apertures)\n \n #从墙器件C4出发,投射光线 \n angle2 = plot_Radiation_range2(C4, [C1, C2], x, C6, apertures[0:2]) \n \n #视场角\n field_angle = max([max(angle1), angle2]) - min(angle1)\n \n # for C in [C1,C2,C3]:\n # plot_Radiation_range(C4, C, x, apertures[0:3])\n\n#%%画光轴,主要辅助光线\nif True:\n plt.plot(centers[:,0], centers[:,1], 'r-', linewidth = 2)\n\n labelx = []\n for item in xticks:\n labelx.append('{0:.1f}m'.format(item*1e-3)) \n plt.xticks(xticks,labelx,rotation='vertical')\n plt.grid(axis='x',linewidth = 0.2)\n ax.axis[\"x\"].major_ticklabels.set_visible(False)\n plt.annotate(s='', xy=(VFM.center[0],VFM.center[1]), xytext=(VFM.center[0]+4e3,VFM.center[1]), arrowprops=dict(arrowstyle='<-',linewidth =2,color ='red'))\n #plt.arrow(VFM.center[0], VFM.center[1], 4e3, 0,length_includes_head=True, head_width=0.2, lw=2) #画箭头方式2\n\n plt.axhline(y = VFM.center[1]-25, color = 'k', linestyle = '--', linewidth = 1)\n # plt.axvline(x = ur.center[0], color = 'k', linestyle = '--', linewidth = 2)\n\n#%%补充辅助信息\nif True:\n text_positionx = 5e3\n text_positiony = y_limit[1]*0.6\n \n text_indicator = 'Collimator Info:' + '\\n' + '\\n' + sr.info \n for C in [C1, C2, C3, C4, C6]:\n if C.name == 'C1':\n C.wailunkuo = 0\n if C.name == 'C3':\n C.wailunkuo = 0 \n if C.name == 'C5':\n C.wailunkuo = 0 \n C.update_info()\n text_indicator = text_indicator+ '\\n' + C.info\n text_indicator = text_indicator+ '\\n' + 'Field_angle = {0:.2f} Degree'.format(field_angle)\n plt.text(text_positionx,text_positiony, text_indicator,color = 'black', fontsize = 12,bbox={'facecolor':'green', 'alpha':0.5, 'pad':10})\n\nplt.show()\nplt.savefig('Radiation_protection.png', dpi =300)\n\n\"\"\"\n# ax.spines['right'].set_color('black')\n# ax.yaxis.set_label_position(\"right\")\n# ax.spines['top'].set_color('none')\n #默认ax里面的x轴和y轴\n# ax.xaxis.set_ticks_position('bottom')\n# ax.yaxis.set_ticks_position('left')\n #移动x轴y轴的位置\n# ax.spines['bottom'].set_position(('data',0))#0,就是移到0的位置\n# ax.spines['bottom'].set_linewidth(1.5)\n# ax.spines['left'].set_position(('data',0))#0,就是移到0的位置\n# ax.spines['left'].set_linewidth(1.5)\n\n# #墙\n# C = C4\n# plt.gca().add_patch(plt.Rectangle((C.point_rbc[0], C.point_rbc[1]), C.thickness, L, color = 'black'))\n# plt.gca().add_patch(plt.Rectangle((C.point_lbc[0], C.point_lbc[1] - L), C.thickness, L, color = 'black'))\n# plt.text(C.point_rbc[0]-600,y_limit[1]*0.5,\"{}\".format(C.name),fontdict={'size':'12','color':'b','rotation':'90'}) \n\n\n\"\"\"","sub_path":"Simulations/Radiation Shielding Design/tracing/Ray_tracing_2D.py","file_name":"Ray_tracing_2D.py","file_ext":"py","file_size_in_byte":20458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"77393498","text":"#Resume Phrase Matcher code\n\n \n#importing all required libraries\n\nimport PyPDF2\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nfrom io import StringIO\nfrom nltk_operation import *\nimport pandas as pd\nfrom collections import Counter\nimport spacy\nnormalize_sapcy = spacy.load(\"en_core_web_sm\")\nfrom spacy.matcher import PhraseMatcher\nimport matplotlib\nfrom parsedocx import *\nimport textract\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nimport docx2txt\nimport docx \n\nmatplotlib.use('Agg')\nskills = \"Sills :\"\ndef sysout(msgLine,data):\n print('\\n--------',msgLine,' Start ----------\\n');\n print(data);\n print('\\n--------',msgLine,' End ----------\\n');\n#function to read resume Start \ndef pdfextract(file):\n # Read Pdf File \n fileReader = PyPDF2.PdfFileReader(open(file,'rb'))\n #fileReader = PyPDF2.PdfFileReader(open(file,'w', encoding=\"utf-8\"))\n # Check for the pages int Pdf and read all pages\n countpage = fileReader.getNumPages()\n count = 0\n text = []\n while count < countpage: \n pageObj = fileReader.getPage(count)\n count +=1\n t = pageObj.extractText()\n #print (t)\n text.append(t)\n return text\n\n#function to read resume ends\n\n\n\n#function that does phrase matching and builds a candidate profile\ndef create_profile(file):\n\tfilename, file_extension = os.path.splitext(file)\n\tprint('filename: ' + filename);\n\tprint('file_extension: ' + file_extension);\n\t\n\tif file_extension=='.pdf':\n\t\ttext = pdfextract(file) \n\telse:\n\t\ttext = getText(file)\n\t\t\n\ttext = str(text)\n\ttext = text.replace(\"\\\\n\", \" \")\n\ttext = text.lower()\n\t\n\t\n\tsysout('Input Text',text.encode(\"utf-8\")) \n\t\n\t#below is the csv where we have all the keywords, you can customize your own\n\tkeyword_dict = pd.read_csv('template.csv',sep=\",\", encoding=\"iso-8859-1\")\n\tprint('template.csv readed and stored data in keyword_dict');\n\tsysout('keyword_dict',keyword_dict) \n\theader = keyword_dict.columns\n\tsysout(\"header \",header)\n\t#genTFIDF(keyword_dict,header)\n\tcollDict = {}\n\t#print(keyword_dict)\n\tfor coll in header:\n\t\tcollDict[coll] = [normalize_sapcy(text) for text in keyword_dict[coll].dropna(axis = 0)]\n\t\t#normalize_sapcy_words = [normalize_sapcy(text) for text in keyword_dict['normalize_sapcy'].dropna(axis = 0)]\n\t\t#ML_words = [normalize_sapcy(text) for text in keyword_dict['Machine Learning'].dropna(axis = 0)]\n\t\t#DL_words = [normalize_sapcy(text) for text in keyword_dict['Deep Learning'].dropna(axis = 0)]\n\t\t#R_words = [normalize_sapcy(text) for text in keyword_dict['R Language'].dropna(axis = 0)]\n\t\t#python_words = [normalize_sapcy(text) for text in keyword_dict['Python Language'].dropna(axis = 0)]\n\t\t#Data_Engineering_words = [normalize_sapcy(text) for text in keyword_dict['Data Engineering'].dropna(axis = 0)]\n \n\tsysout(\"collDict \",collDict)\n\tprint('Matching sequences of tokens, based on documents using PhraseMatcher');\n\t#Match sequences of tokens, based on documents using PhraseMatcher\n\tmatcher = PhraseMatcher(normalize_sapcy.vocab)\n\t# Add Collumns to phrase matcher wich you want to match with documents\n # the data format should be in lower case for more accurate match.\n\tfor coll in header:\n\t\tmatcher.add(coll, None, *collDict[coll])\n\t#matcher.add('Stats', None, *stats_words)\n\t#matcher.add('NLp', None, *normalize_sapcy_words)\n\t#matcher.add('ML', None, *ML_words)\n\t#matcher.add('DL', None, *DL_words)\n\t#matcher.add('R', None, *R_words)\n\t#matcher.add('Python', None, *python_words)\n\t#matcher.add('DataEngineering', None, *Data_Engineering_words)\n\t\n \n\tdoc = preprocess(text)\n\tsysout('Input Text After Preprocesses',doc.encode(\"utf-8\")) \n\tdoc = normalize_sapcy(doc)\n\t#sysout('Input Text After Applyting normalize_sapcy',doc) \n\t#doc = spacy.tokens.doc.Doc(normalize_sapcy.vocab, words=doc, spaces=[False, False])\n \n\tglobal skills \n\td = [] \n\t#Give document to matcher in lower case to match with the created criteria \n\tmatches = matcher(doc)\n\tprint('A list of (match_id, start, end) tuples, describing the matches.');\n\tsysout(\"matches for data \",matches)\n\t\n\n #PhraseMatcher Return the 3 values :\n\t#A list of (match_id, start, end) tuples, describing the matches. \n\t#A match tuple describes a span doc[start:end]. \n\t#The match_id is the ID of the added match pattern.\n #In our case Match_Id will be collumn names of template.csv [DataEngineering, DL, ML, normalize_sapcy ]\t\n\tfor match_id, start, end in matches:\n \n\t\trule_id = normalize_sapcy.vocab.strings[match_id] # get the unicode ID, i.e. 'COLOR'\n\t\tspan = doc[start : end] # get the matched slice of the doc.\n\t\t#res = findTFIDF(header,span.text)\n\t\tprint(\"TFIDF is %d \",(start),\" %d \",(end),\" %s \",span)\n\t\tskills = skills + span.text +\",\"\n\t\t#print(span.text)\n\t\td.append((rule_id, span.text)) \n\tkeywords = \"\"\n\t\n\tsysout('Mathces of Input Text After Applying PhraseMatcher',d)\n\t\n\t# \"\\n\".join(f'{i[0]} {i[1]} ({j})' for i,j in Counter(d).items())\n\tfor i,j in Counter(d).items():\n\t\tkeywords = keywords + \"\\n\" + str(i[0]) +' ' + str(i[0]) +' (' + str(j)+\")\"\n\t\n\t## convertimg string of keywords to dataframe\n\tdf = pd.read_csv(StringIO(keywords),names = ['Keywords_List'])\n\tdf1 = pd.DataFrame(df.Keywords_List.str.split(' ',1).tolist(),columns = ['Subject','Keyword'])\n\tdf2 = pd.DataFrame(df1.Keyword.str.split('(',1).tolist(),columns = ['Keyword', 'Count'])\n\tdf3 = pd.concat([df1['Subject'],df2['Keyword'], df2['Count']], axis =1) \n\tdf3['Count'] = df3['Count'].apply(lambda x: x.rstrip(\")\"))\n\t\n\tbase = os.path.basename(file)\n\tfilename = os.path.splitext(base)[0]\n\t\n\tname = filename.split('_')\n\tname2 = name[0]\n\tname2 = name2.lower()\n\t## converting str to dataframe\n\tname3 = pd.read_csv(StringIO(name2),names = ['Candidate Name'])\n \n\tdataf = pd.concat([name3['Candidate Name'], df3['Subject'], df3['Keyword'], df3['Count']], axis = 1)\n\tdataf['Candidate Name'].fillna(dataf['Candidate Name'].iloc[0], inplace = True)\n\n\treturn(dataf)\n \n#function that does phrase matching and builds a candidate profile ends\n \n#code to execute/call the above functions\ndef predict(filename):\n\tglobal skills \n\tskills=\"\"\n\t#Function to read resumes from the folder one by one\n\t#mypath='./resume' #enter your path here where you saved the resumes\n\t#onlyfiles = [os.path.join(mypath, f) for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]\n\tfile = \"./resume/\"+filename\n\tfinal_database=pd.DataFrame()\n\ti = 0 \n\t#while i < len(onlyfiles):\n\t#\tfile = onlyfiles[i]\n\tdat = create_profile(file)\n\tfinal_database = final_database.append(dat)\n\ti +=1\n\tsysout('Final Data Extracted From Resume ',final_database)\n\t#print('data ',final_database)\n\n\t\t\n\t#code to count words under each category and visulaize it through Matplotlib\n\n\tfinal_database2 = final_database['Keyword'].groupby([final_database['Candidate Name'], final_database['Subject']]).count().unstack()\n\tfinal_database2.reset_index(inplace = True)\n\tfinal_database2.fillna(0,inplace=True)\n\tnew_data = final_database2.iloc[:,1:]\n\tnew_data.index = final_database2['Candidate Name']\n\tsysout('new_data', new_data)\n\t#execute the below line if you want to see the candidate profile in a csv format\n\t#sample2=new_data.to_csv('sample.csv')\n\timport matplotlib.pyplot as plt\n\t\n\tplt.rcParams.update({'font.size': 10})\n\t#ax = new_data.plot.barh(title=\"keywords by category\", legend=False, figsize=(25,7), stacked=True)\n\tlabels = []\n\taxis = []\n\tdataPlot = []\n\tfor j in new_data.columns:\n\t\tfor i in new_data.index:\n\t\t\tlabel = str(j)+\" :\" + str(new_data.loc[i][j])\n\t\t\tlabels.append(label)\n\t\t\taxis.append(str(j))\n\t\t\tdataPlot.append(new_data.loc[i][j])\n\t#patches = ax.patches\n\tsysout(' Labes Extracted from Resume ',labels)\n\tlabels.append(\";\"+skills)\n\t#print(skills)\n\t#print(labels)\n\tsysout(' Skills Extracted from Resume ',skills)\n\t\n\t#for label, rect in zip(labels, patches):\n\t#\twidth = rect.get_width()\n\t#\tif width > 0:\n\t#\t\tx = rect.get_x()\n\t#\t\ty = rect.get_y()\n\t#\t\theight = rect.get_height()\n\t#\t\tax.text(x + width/2., y + height/2., label, ha='center', va='center')\n \n\tfig = plt.figure()\n\tax = fig.add_axes([0,0,1,1])\n\tax.axis('equal')\n\t#langs = ['C', 'C++', 'Java', 'Python', 'PHP']\n\t#students = [23,17,35,29,12]\n\tax.pie(dataPlot, labels = axis,autopct='%1.2f%%')\n\t#plt.show()\n\timgname, file_extension = os.path.splitext(filename)\n\tprint('final to image: ' + imgname);\n\tplt.savefig(\"./resume/\"+imgname+'.png')\n\treturn labels\n\nprint(predict('neha123.docx'))","sub_path":"ResumeClassify.py","file_name":"ResumeClassify.py","file_ext":"py","file_size_in_byte":8403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"581099145","text":"# Importacion de librerias\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n# Leer archivo excel \r\narchivo_excel = pd.read_excel('Futbol_Partidos.xlsx')\r\n\r\ndef menu():\r\n\t\"\"\"\r\n\tFunción que limpia la pantalla y muestra nuevamente el menu\r\n\t\"\"\"\r\n\tprint (\"Selecciona una opción\")\r\n\tprint (\"\\n\\t1 - Cantidad de goles de los equipos locales y grafica \\n\\n\\t2 - Cantidad de goles de los equipos visitantes y grafica\")\r\n\tprint (\"\\n\\t3 - Cantidad total de goles de todos los partidos y grafica \\n\\n\\t4 - Cantidad de goles de los equipos locales por campeonato y grafica\")\r\n\tprint (\"\\n\\t5 - Cantidad de goles de los equipos visitantes por campeonato y grafica \\n\\n\\t6 - Cantidad total de goles por campeonato y grafica\")\r\n\tprint (\"\\n\\t7 - Gráfico de barras de cantidad de partidos por selección \\n\\n\\t8 - Gráfico de barras apiladas horizontales de cantidad de partidos local y visitante por selección\")\r\n\tprint (\"\\n\\t9 - Selección que más goles realizó y selección que mas goles recibió en todos los campeonatos\")\r\n \r\n\t# Mostramos el menu\r\nmenu()\r\n\r\n # solicitamos una opción al usuario\r\nopcionMenu = input(\"inserta un numero valor >> \")\r\n\r\n\r\n# Funcion para hacer las graficas\r\ndef graficar(xlabel, ylabel, title, groupby, count, graph, colors = ['BLUE','MAGENTA']):\r\n # Generar el grafico\r\n fig, ax = plt.subplots()\r\n ax.set_title(title)\r\n\r\n# Crear el grafico\r\n archivo_excel.groupby(groupby, sort = True)[count].count().plot(kind = graph, color = colors)\r\n ax.set_xlabel(xlabel)\r\n ax.set_ylabel(ylabel)\r\n plt.show()\r\n\r\n# Funciones que resuelven las preguntas\r\ndef cantidad_goles_locales(): # Ejercicio 1\r\n equipo_local = archivo_excel['goles_local'].sum()\r\n print(\"Los goles totales de los equipos locales son: \", equipo_local)\r\n graficar('cantidad de gooles', 'equipos', 'goles locales', 'local', 'goles_local', 'barh')\r\n \r\n\r\n \r\ndef cantidad_goles_visitantes(): # Ejercicio 2\r\n equipo_visitante = archivo_excel['goles_visita'].sum()\r\n print(\"Los goles totales de los equuipos visitantes son: \", equipo_visitante)\r\n graficar('cantidad de goles', 'equipos', 'goles visitantes', 'visitante', 'goles_visita', 'barh')\r\n \r\n\r\n\r\ndef cantidad_goles_totales(): # Ejercicio 3\r\n total_goles = archivo_excel['goles_local'].sum() + archivo_excel['goles_visita'].sum() \r\n print(\"La suma total de los goles de los equipos locales y visitantes es: \", total_goles)\r\n \r\n equipo_local = archivo_excel.groupby(\"local\", sort=True)[\"goles_local\"].count()\r\n equipo_visitante = archivo_excel.groupby(\"visitante\", sort=True)[\"goles_visita\"].count()\r\n equipos = sorted(archivo_excel['local'].unique())\r\n\r\n total = []\r\n for a, b in zip(equipo_local, equipo_visitante):\r\n total.append(a+b)\r\n\t\r\n # Generar el grafico \r\n fig, ax = plt.subplots()\r\n ax.set_title('Total goles de todos los partidos')\r\n ax.set_ylabel('Equipos')\r\n ax.set_xlabel('Total de goles')\r\n\r\n plt.barh(equipos,total)\r\n plt.show()\r\n \r\n\r\n\r\ndef goles_local_por_campeonato(): # Ejercicio 4\r\n goles_local_por_campeonato = archivo_excel.groupby('torneo')['goles_local'].sum()\r\n print(\"Los goles totales por campeonato de los locales son:\\n\" , goles_local_por_campeonato) \r\n graficar('goles locales', 'equipos', 'goles por campeonato local', 'torneo', 'goles_local', 'barh')\r\n \r\n\r\n\r\ndef goles_visitante_por_campeonato(): # Ejercicio 5\r\n goles_visita_por_campeonato = archivo_excel.groupby('torneo')['goles_visita'].sum()\r\n print(\"Los goles totales por campeonato de los visitantes son:\\n\" , goles_visita_por_campeonato) \r\n graficar('goles visitantes', 'equipos', 'goles por campeonato visita', 'torneo', 'goles_visita', 'barh')\r\n \r\n\r\n\r\ndef goles_totales_por_campeonato(): # Ejercicio 6\r\n total_goles_por_campeonato = archivo_excel.groupby('torneo')['goles_local'].sum() + archivo_excel.groupby('torneo')['goles_visita'].sum()\r\n print(\"La cantidad de goles por torneo es: \", total_goles_por_campeonato)\r\n \r\n \r\n total_torneo_local = archivo_excel.groupby(\"torneo\", sort=True)[\"goles_local\"].count()\r\n total_torneo_visitante = archivo_excel.groupby(\"torneo\", sort=True)[\"goles_visita\"].count()\r\n equipos = sorted(archivo_excel['torneo'].unique())\r\n\r\n total = []\r\n for a, b in zip(total_torneo_local, total_torneo_visitante):\r\n total.append(a+b)\r\n\t\r\n # generar el grafico\r\n fig, ax = plt.subplots()\r\n ax.set_title('goles totales por campeonato')\r\n ax.set_xlabel('goles totales')\r\n ax.set_ylabel('torneos')\r\n\r\n plt.barh(equipos,total)\r\n plt.show()\r\n \r\n\r\n \r\ndef partidos_por_seleccion(): # Ejercicio 7\r\n total_partidos = archivo_excel.groupby('local', sort=True)['gana_local'].count()\r\n print(\"La cantidad de partidos por equipo en total es:\" , total_partidos)\r\n graficar('cantidad partidos', 'selecciones', 'partidos totales por seleccion', 'local', 'gana_local', 'barh')\r\n \r\n\r\n\r\ndef partidos_local_y_visitante(): # Ejercicio 8\r\n\tlocales = archivo_excel[['local', 'gana_local']]\r\n\tvisitantes = archivo_excel[['visitante', 'gana_visita']]\r\n\tequipos = sorted(archivo_excel['local'].unique())\r\n \r\n # Declaracion de variables\r\n\tgano = 0\r\n\tperdio = 0\r\n\tequipos_resultados = []\r\n\tresultados = []\r\n\r\n # Proceso \r\n\tfor equipo in equipos:\r\n\t\tfor index, row in locales.iterrows():\r\n\t\t\tif row.local == equipo:\r\n\t\t\t\tif row.gana_local == 1:\r\n\t\t\t\t\tgano+= 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tperdio+=1\r\n\t\tresultados.append(equipo + 'G')\r\n\t\tresultados.append(equipo + 'P')\r\n\t\tequipos_resultados.append(gano)\r\n\t\tequipos_resultados.append(perdio)\r\n\r\n # Generar el grafico\r\n\tfig, ax = plt.subplots()\r\n\tax.set_title('Total de todos los resultados')\r\n\tax.set_ylabel('Equipos')\r\n\tax.set_xlabel('Margen de victoria y derrota por equipo')\r\n\r\n\tplt.barh(resultados,equipos_resultados)\r\n\tplt.show()\r\n \r\n\r\n\r\ndef test(x): # Ejercicios 9 y 10\r\n return x[1]\r\n\r\ndef selecciones_que_mas_goles_hiciereon_y_recibieron():\r\n datos_local = archivo_excel[['local', 'goles_local', 'visitante', 'goles_visita']]\r\n equipos = sorted(archivo_excel['local'].unique())\r\n \r\n # Declaracion de variables\r\n metio = 100\r\n metieron = 120\r\n equipos_resultados = []\r\n resultados_metidos = []\r\n resultados_metieron = []\r\n \r\n # Proceso\r\n for equipo in equipos:\r\n for index, row in datos_local.iterrows():\r\n if row.local == equipo:\r\n metio+= row.goles_local\r\n metieron+= row.goles_visita\r\n resultados_metidos.append([equipo, metio])\r\n resultados_metieron.append([equipo, metieron])\r\n \r\n metio = 0\r\n metieron = 0\r\n \r\n print(\"El equipo que mas goles metio fue: \", sorted(resultados_metidos, key = test, reverse=True)[0])\r\n print(\"El equipo que mas goles recibio fue: \", sorted(resultados_metieron, key = test, reverse=True)[0])\r\n\r\n\r\nif opcionMenu==1:\r\n\tprint (cantidad_goles_locales())\r\n\tinput(\"Has pulsado la opción 1...\\npulsa una tecla para continuar\")\r\nelif opcionMenu==\"2\":\r\n\tprint (cantidad_goles_visitantes())\r\n\tinput(\"Has pulsado la opción 2...\\npulsa una tecla para continuar\")\r\nelif opcionMenu==\"3\":\r\n\tprint (cantidad_goles_totales())\r\n\tinput(\"Has pulsado la opción 3...\\npulsa una tecla para continuar\")\r\nelif opcionMenu==\"4\":\r\n\tprint (goles_local_por_campeonato())\r\n\tinput(\"Has pulsado la opción 4...\\npulsa una tecla para continuar\")\r\nelif opcionMenu==\"5\":\r\n\tprint (goles_visitante_por_campeonato())\r\n\tinput(\"Has pulsado la opción 5...\\npulsa una tecla para continuar\")\r\nelif opcionMenu==\"6\":\r\n\tprint (goles_totales_por_campeonato())\r\n\tinput(\"Has pulsado la opción 6...\\npulsa una tecla para continuar\")\r\nelif opcionMenu==\"7\":\r\n\tprint (partidos_por_seleccion())\r\n\tinput(\"Has pulsado la opción 7...\\npulsa una tecla para continuar\")\r\nelif opcionMenu==\"8\":\r\n\tprint (partidos_local_y_visitante())\r\n\tinput(\"Has pulsado la opción 8...\\npulsa una tecla para continuar\")\r\nelif opcionMenu==\"9\":\r\n\tprint (selecciones_que_mas_goles_hiciereon_y_recibieron())\r\n\tinput(\"Has pulsado la opción 9...\\npulsa una tecla para continuar\")\r\nelse:\r\n print(\"Introduce una opción correcta\")\r\n","sub_path":"desarrollo parcial.py","file_name":"desarrollo parcial.py","file_ext":"py","file_size_in_byte":8128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"594079157","text":"from sklearn import datasets\nfrom sklearn.neighbors import KNeighborsClassifier\n\niris = datasets.load_iris()\nprint(iris.keys())\nprint(iris.data[0], iris.target[0])\n\nfeatures = iris.data\nlabels = iris.target\n\nclf = KNeighborsClassifier()\nclf.fit(features, labels)\n\nprediction = clf.predict([[1, 1, 2, 3]])\nprint(prediction)\n","sub_path":"classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"58968340","text":"def load_file(path):\n with open(path) as fp:\n return fp.readline()\n\npolymer = load_file('input/input-5a.txt').strip()\n\ndef same_unit(a,b):\n different_polarity = (a.isupper() and b.islower()) or (a.islower() and b.isupper())\n same_type = (a.lower() == b.lower())\n return same_type and different_polarity\n\ndef extract_lower_units(polymer):\n units = set()\n for c in polymer:\n units.add(c.lower())\n return units\n\ndef react(polymer):\n units = extract_lower_units(polymer)\n changed = True\n while changed:\n before = len(polymer)\n for c in units:\n repstr = c + c.upper()\n repstr2 = c.upper() + c\n polymer = polymer.replace(repstr, '').replace(repstr2, '')\n after = len(polymer)\n changed = (before != after)\n \n return polymer\n \ndef part1(polymer):\n return len(react(polymer))\n\ndef part2(polymer):\n units = extract_lower_units(polymer)\n scores = {}\n for c in units:\n candidate = polymer.replace(c, '').replace(c.upper(), '')\n scores[c] = len(react(candidate))\n return min(scores.values())\n\nprint(part1(polymer))\nprint(part2(polymer))\n","sub_path":"2018/solutions/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"267993659","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 12 20:59:16 2017\n\n@author: xiaoling\n\"\"\"\n\n#!/usr/bin/python\n#-*- coding:UTF-8 -*-\n'''\nimport time\n#from sklearn import sys\nfrom numpy import shape\nimport sklearn\n\nticks = time.time()\n#print(ticks)\n\n#print(dir(time))\n#print(dir(sklearn))\n\nr1 = map((lambda x: x**2), range(10,15)) \nre = list(r1)\nprint(re)\n\n\nal = [21, 36, 69, 88]\nal.append(33)\nal.extend([1,3])\nal.append([22,99])\n\nprint(al)\n\nal = [21, 36, 69, 88]\nprint(max(al))\n\n#str1 = raw_input(\"input a string:\")\nstr2 = input(\"input a string:\")\n#print(str1)\nprint(str2)\n'''\nfd = open(\"E:\\PY\\py.txt\", \"a+\")\nprint(fd.name)\nfd.write(\"I am learning Python!\\n Not for a long time!\")\nfd.close\nds = fd.read(20)\nprint(ds)\n\n","sub_path":"normalPractise/pyfoundation.py","file_name":"pyfoundation.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"435257826","text":"import scrapy\nfrom ..items import JobItem\n\nclass JobSpider(scrapy.Spider):\n name = 'jobs'\n headers = {\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'max-age=0'\n }\n\n def start_requests(self):\n urls = ['https://www.lagou.com/zhaopin/{}/?filterOption=2'.format(i) for i in range(1, 31)]\n for i in urls:\n yield scrapy.Request(url=i, callback=self.parse, headers=self.headers)\n\n def parse(self, response):\n for i in response.css('li.con_list_item.default_list'):\n yield JobItem({\n 'title': i.css('h3::text').extract_first(),\n 'city': i.css('em::text').extract_first(),\n 'salary': i.css('span.money::text').extract_first(),\n 'exp_edu': i.css('div.li_b_l::text').extract()[2].strip(),\n 'tags': i.css('div.industry::text').extract_first(),\n 'company': i.css('div.company_name a::text').extract_first()\n })\n","sub_path":"dazuoye/34_拉钩网职位数据抓取/seiya/seiya/spider/spiders/jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"205341827","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 25 17:50:00 2019\n\n@author: mandy\n\"\"\"\nimport json\nimport numpy as np\nfrom Model import *\nfrom AI2 import AI2\nfrom AI3 import AI3\nclass game:\n def __init__(self,client1,client2):\n self.client1=client1\n self.client2=client2\n self.beforeworld=None\n self.currentworld=World();\n self.world_init()\n #self.AI=AI\n self.possibleaction=None\n self.possiblemove=None\n def world_init(self,mapjson=None):\n if(mapjson==None):\n with open(\"C:/Users/mandy/Desktop/aichallengeofsharif/map/AIC19-Maps-1.0/practice/DiagonalOnline1.map\") as mapf:\n mapjson=json.load(mapf)\n self.currentworld.map_init(mapjson[\"map\"])\n self.currentworld.Envgame_constant_init(mapjson[\"gameConstants\"])\n self.currentworld.ability_constants_init(mapjson[\"abilityConstants\"])\n self.currentworld.Env_hero_constant_init(mapjson[\"heroConstants\"])\n #this is for init hero\n self.handel_pick()\n\n\n def make_action(self,action): \n self.beforesworld=self.currentworld\n if self.currentworld.current_phase==Phase.MOVE:\n self.currentworld.Env_move_hero(action)\n elif self.currentworld.current_phase==Phase.ACTION:\n self.currentworld.Env_action_hero(action)\n def update_score(self):\n pass\n def undo_action(self):\n self.currentworld=self.beforeworld\n def get_possible_action(self):\n actions={}\n l=[]\n heros=[]#contain heros that make action \n heros1=[]#contain other heros\n if(self.currentworld.myturn==1):\n heros=self.currentworld.get_my_live_heroes()\n heros1=self.currentworld.get_opp_live_heroes()\n else:\n heros=self.currentworld.get_opp_live_heroes()\n heros1=self.currentworld.get_my_live_heroes()\n \n if self.currentworld.current_phase==Phase.MOVE:\n heroscells=[]\n for hero in heros:\n heroscells+=[hero.current_cell]\n for hero in heros:\n if(self.currentworld.ap>hero.move_ap_cost):\n row = hero.current_cell.row - 1\n cell=self.currentworld.map.get_cell(row=row, column=hero.current_cell.column)\n if((cell==None)and(cell.is_wall is not True )and not cell in heroscells):\n l+=[Direction.UP]\n row=hero.current_cell.row+1\n cell = self.currentworld.map.get_cell(row=row, column=hero.current_cell.column)\n if ((cell == None) and (cell.is_wall is not True) and not cell in heroscells):\n l+=[Direction.DOWN]\n column=hero.current_cell.column-1\n cell = self.currentworld.map.get_cell(row=hero.current_cell.row,column=column)\n if ((cell == None) and (cell.is_wall is not True) and not cell in heroscells):\n l+=[Direction.LEFT]\n column=hero.current_cell.column+1\n cell = self.currentworld.map.get_cell(row=hero.current_cell.row,column=column)\n if ((cell == None) and (cell.is_wall is not True) and not cell in heroscells):\n l+=[Direction.RIGHT]\n l+=[None]\n actions[hero.id]=l\n l=[]\n else:\n actions[hero.id] = [None]\n self.collect_possible_action(heros, actions)\n if self.currentworld.current_phase==Phase.ACTION:\n actions={}\n heroscells=[]\n heros1cells=[]\n for hero in heros:\n heroscells+=[hero.current_cell]\n for hero in heros1:\n heros1cells+=[hero.current_cell]\n ATTACK=[AbilityName.BLASTER_ATTACK,AbilityName.GUARDIAN_ATTACK,AbilityName.HEALER_ATTACK,AbilityName.SENTRY_ATTACK]\n for hero in heros:\n abilitis={}\n for ability in hero.abilities:\n if(ability.is_ready and ability.type== AbilityType.DODGE and ability.ap_cost EPSILON) or ((state_actions == 0).all()): # act non-greedy or state-action have no value\n action_name=np.random.choice(ACTIONS)\n else: # act greedy\n action_name = state_actions.idxmax() # replace argmax to idxmax as argmax means a different function in newer version of pandas\n return action_name\n\n\ndef get_env_feedback(S,A):\n global sample_features\n global model\n global timesteps\n\n if S == 0:\n sample_features[S, 29] = A\n sample_trans = sample_features.reshape((np.shape(sample_features)[0], timesteps+1, 10))\n R_ref = model.predict(sample_trans)\n R = 0 - abs(21 - R_ref[S, -1]) # this is the final rewards to evaluate how close the operative temperature is to 21 centi-degree\n S_ = S + 1\n \n elif S == 1:\n sample_features[S, 19], sample_features[S, 29] = sample_features[S-1, 29], A\n sample_trans = sample_features.reshape((np.shape(sample_features)[0], timesteps+1, 10))\n R_ref = model.predict(sample_trans)\n R = 0 - abs(21 - R_ref[S, -1]) # this is the final rewards to evaluate how close the operative temperature is to 21 centi-degree\n S_ = S + 1\n \n elif S >= 2 and S < 8760:\n sample_features[S, 9], sample_features[S, 19], sample_features[S, 29] = sample_features[S-2, 29], sample_features[S-1, 29], A\n sample_trans = sample_features.reshape((np.shape(sample_features)[0], timesteps+1, 10))\n R_ref = model.predict(sample_trans)\n R = 0 - abs(21 - R_ref[S, -1]) # this is the final rewards to evaluate how close the operative temperature is to 21 centi-degree\n S_ = S + 1\n \n elif S == 8760:\n sample_features[S, 9], sample_features[S, 19], sample_features[S, 29] = sample_features[S-2, 29], sample_features[S-1, 29], A\n sample_trans = sample_features.reshape((np.shape(sample_features)[0], timesteps+1, 10))\n R_ref = model.predict(sample_trans)\n R = 0 - abs(21 - R_ref[S, -1]) # this is the final rewards to evaluate how close the operative temperature is to 21 centi-degree\n S_ = 'terminal'\n \n print(S) # current state\n print(R_ref[S, -1]) # real predicted indoor operative temperature of the current state\n print(\"\\n\",end=\"\")\n return S_, R\n\n\ndef update_env(S,episode,step_counter):\n env_list = ['-']*(N_STATES-1)+['T']\n if S=='terminal':\n interaction = 'Episode %s:total_steps = %s'%(episode+1,step_counter)\n print('\\r{}'.format(interaction))\n time.sleep(2)\n print('\\r ',end='\\r')\n else:\n env_list[S]='o'\n interaction = ''.join(env_list)\n print('\\r{}'.format(interaction),end='\\r')\n time.sleep(FRESH_TIME)\n \n\ndef rl():\n # main part of RL loop\n q_table = build_q_table(N_STATES, ACTIONS)\n for episode in range(MAX_EPISODES):\n step_counter = 0\n S = 0\n is_terminal = False\n update_env(S, episode, step_counter)\n while not is_terminal:\n A = choose_action(int(S), q_table)\n S_,R = get_env_feedback(S, A)\n #q_predict = q_table.ix[S,A]\n q_predict = q_table.iat[S, int(A*10)]\n if S_ !='terminal':\n q_target = R+LAMBDA*q_table.iloc[int(S_), :].max()\n else:\n q_target = R\n is_terminal = True\n \n #q_table.ix[S,A]+= ALPHA*(q_target-q_predict)\n q_table.iat[S, int(A*10)]+= ALPHA*(q_target-q_predict)\n S = S_\n \n update_env(S, episode, step_counter+1)\n step_counter += 1\n print(q_table)\n return q_table\n\n\nif __name__ == '__main__':\n q_table = rl()\n q_table = q_table.values\n ref_1 = 0\n updated = np.array([])\n actions_updated = np.zeros((8761, 2)) # 8761 time points should be updated \n for i in range(np.shape(q_table)[0]):\n for j in range(np.shape(q_table)[1]):\n if q_table[i, j] == 0:\n q_table[i, j] = -100 # to make the one without updated to be -100\n for i in range(np.shape(q_table)[0]): \n actions_updated[i, 0] = ref_1\n actions_updated[i, 1] = np.argmax(q_table[i, :]) * 0.1 \n updated = np.append(updated, np.max(q_table[i, :]))\n ref_1 += 1\n print(actions_updated)\n print(updated)\n print('\\r\\nQ_table:\\n')\n print(q_table)\n \nnp.savetxt('Updated_Q_Table.txt', q_table, delimiter=';') # q_table is saved in a txt file named 'Updated_Q_Table'\nnp.savetxt('Updated_Windowopening_Actions.txt', actions_updated, delimiter=';') # window opening actions are also saved in a txt file\n\n\n\n \n","sub_path":"Q-learning aiming whole year.py","file_name":"Q-learning aiming whole year.py","file_ext":"py","file_size_in_byte":9227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"538109061","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nThis module contains Farthest Point Sampling (FPS) classes for sub-selecting\nfeatures or samples from given datasets. Each class supports a Principal\nCovariates Regression (PCov)-inspired variant, using a mixing parameter and\ntarget values to bias the selections.\n\nAuthors: Rose K. Cersonsky\n Michele Ceriotti\n\n\"\"\"\n\nfrom abc import abstractmethod\nimport numpy as np\nfrom skcosmo.pcovr.pcovr_distances import pcovr_covariance, pcovr_kernel\nfrom sklearn.utils import check_X_y, check_array\nfrom skcosmo.utils import get_progress_bar\n\n\ndef _calc_distances_(K, ref_idx, idxs=None):\n \"\"\"\n Calculates the distance between points in ref_idx and idx\n\n Assumes\n\n .. math::\n d(i, j) = K_{i,i} - 2 * K_{i,j} + K_{j,j}\n\n : param K : distance matrix, must contain distances for ref_idx and idxs\n : type K : array\n\n : param ref_idx : index of reference points\n : type ref_idx : int\n\n : param idxs : indices of points to compute distance to ref_idx\n defaults to all indices in K\n : type idxs : list of int, None\n\n \"\"\"\n if idxs is None:\n idxs = range(K.shape[0])\n return np.array(\n [np.real(K[j][j] - 2 * K[j][ref_idx] + K[ref_idx][ref_idx]) for j in idxs]\n )\n\n\nclass _BaseFPS:\n \"\"\"\n Base Class defined for FPS selection methods\n\n :param idxs: predetermined indices; if None provided, first index selected\n is random\n :type idxs: list of int, None\n\n :param progress_bar: option to use `tqdm `_\n progress bar to monitor selections\n :type progress_bar: boolean\n\n \"\"\"\n\n def __init__(self, tol=1e-12, idxs=None, progress_bar=False):\n\n if not hasattr(self, \"tol\"):\n self.tol = tol\n\n if idxs is not None:\n self.idx = idxs\n else:\n self.idx = [np.random.randint(self.product.shape[0])]\n self.distances = np.min([self.calc_distance(i) for i in self.idx], axis=0)\n self.distance_selected = np.nan * np.zeros(self.product.shape[0])\n\n if progress_bar:\n self.report_progress = get_progress_bar()\n else:\n self.report_progress = lambda x: x\n\n def select(self, n):\n \"\"\"Method for FPS select based upon a product of the input matrices\n\n Parameters\n ----------\n n : number of selections to make, must be > 0\n\n Returns\n -------\n idx: list of n selections\n \"\"\"\n\n if n <= 0:\n raise ValueError(\"You must call select(n) with n > 0.\")\n\n if len(self.idx) > n:\n return self.idx[:n]\n\n # Loop over the remaining points...\n for i in self.report_progress(range(len(self.idx) - 1, n - 1)):\n for j in np.where(self.distances > 0)[0]:\n self.distances[j] = min(\n self.distances[j], self.calc_distance(self.idx[i], [j])\n )\n\n self.idx.append(np.argmax(self.distances))\n self.distance_selected[i + 1] = self.distances[i + 1]\n\n if np.abs(self.distances).max() < self.tol:\n return self.idx\n return self.idx\n\n @abstractmethod\n def calc_distance(self, idx_1, idx_2=None):\n \"\"\"\n Abstract method to be used for calculating the distances\n between two indexed points. Should be overwritten if default\n functionality is not desired\n\n : param idx_1 : index of first point to use\n : type idx_1 : int\n\n : param idx_2 : index of first point to use; if None, calculates the\n distance between idx_1 and all points\n : type idx_2 : list of int or None\n \"\"\"\n return _calc_distances_(self.product, idx_1, idx_2)\n\n\nclass SampleFPS(_BaseFPS):\n \"\"\"\n\n For sample selection, traditional FPS employs a row-wise Euclidean\n distance, which can be expressed using the Gram matrix\n :math:`\\\\mathbf{K} = \\\\mathbf{X} \\\\mathbf{X}^T`\n\n .. math::\n \\\\operatorname{d}_r(i, j) = K_{ii} - 2 K_{ij} + K_{jj}.\n\n When mixing < 1, this will use PCov-FPS, where a modified Gram matrix is\n used to express the distances\n\n .. math::\n \\\\mathbf{\\\\tilde{K}} = \\\\alpha \\\\mathbf{XX}^T +\n (1 - \\\\alpha)\\\\mathbf{\\\\hat{Y}\\\\hat{Y}}^T\n\n :param idxs: predetermined indices; if None provided, first index selected\n is random\n :type idxs: list of int, None\n\n :param X: Data matrix :math:`\\\\mathbf{X}` from which to select a\n subset of the `n` rows\n :type X: array of shape (n x m)\n\n :param mixing: mixing parameter, as described in PCovR as\n :math:`{\\\\alpha}`, defaults to 1\n :type mixing: float\n\n :param progress_bar: option to use `tqdm `_\n progress bar to monitor selections\n :type progress_bar: boolean\n\n :param tol: threshold below which values will be considered 0,\n defaults to 1E-12\n :type tol: float\n\n :param Y: array to include in biased selection when mixing < 1;\n required when mixing < 1, throws AssertionError otherwise\n :type Y: array of shape (n x p), optional when :math:`{\\\\alpha = 1}`\n\n \"\"\"\n\n def __init__(self, X, mixing=1.0, tol=1e-12, Y=None, **kwargs):\n\n self.mixing = mixing\n self.tol = tol\n\n if mixing < 1:\n try:\n self.A, self.Y = check_X_y(X, Y, copy=True, multi_output=True)\n except AssertionError:\n raise Exception(r\"For $\\alpha < 1$, $Y$ must be supplied.\")\n else:\n self.A, self.Y = check_array(X, copy=True), None\n\n self.product = pcovr_kernel(self.mixing, self.A, self.Y)\n super().__init__(tol=tol, **kwargs)\n\n\nclass FeatureFPS(_BaseFPS):\n \"\"\"\n\n For feature selection, traditional FPS employs a column-wise Euclidean\n distance, which can be expressed using the covariance matrix\n :math:`\\\\mathbf{C} = \\\\mathbf{X} ^ T \\\\mathbf{X}`\n\n .. math::\n \\\\operatorname{d}_c(i, j) = C_{ii} - 2 C_{ij} + C_{jj}.\n\n When mixing < 1, this will use PCov-FPS, where a modified covariance matrix\n is used to express the distances\n\n .. math::\n \\\\mathbf{\\\\tilde{C}} = \\\\alpha \\\\mathbf{X}^T\\\\mathbf{X} +\n (1 - \\\\alpha)(\\\\mathbf{X}^T\\\\mathbf{X})^{-1/2}\\\\mathbf{X}^T\n \\\\mathbf{\\\\hat{Y}\\\\hat{Y}}^T\\\\mathbf{X}(\\\\mathbf{X}^T\\\\mathbf{X})^{-1/2}\n\n :param idxs: predetermined indices; if None provided, first index selected\n is random\n :type idxs: list of int, None\n\n :param X: Data matrix :math:`\\\\mathbf{X}` from which to select a\n subset of the `n` columns\n :type X: array of shape (n x m)\n\n :param mixing: mixing parameter, as described in PCovR as\n :math:`{\\\\alpha}`, defaults to 1\n :type mixing: float\n\n :param progress_bar: option to use `tqdm `_\n progress bar to monitor selections\n :type progress_bar: boolean\n\n :param tol: threshold below which values will be considered 0,\n defaults to 1E-12\n :type tol: float\n\n :param Y: array to include in biased selection when mixing < 1;\n required when mixing < 1, throws AssertionError otherwise\n :type Y: array of shape (n x p), optional when :math:`{\\\\alpha = 1}`\n\n\n \"\"\"\n\n def __init__(self, X, mixing=1.0, tol=1e-12, Y=None, **kwargs):\n\n self.mixing = mixing\n self.tol = tol\n\n if mixing < 1:\n try:\n self.A, self.Y = check_X_y(X, Y, copy=True, multi_output=True)\n except AssertionError:\n raise Exception(r\"For $\\alpha < 1$, $Y$ must be supplied.\")\n else:\n self.A, self.Y = check_array(X, copy=True), None\n\n self.product = pcovr_covariance(self.mixing, self.A, self.Y, rcond=self.tol)\n super().__init__(tol=tol, **kwargs)\n","sub_path":"skcosmo/selection/FPS.py","file_name":"FPS.py","file_ext":"py","file_size_in_byte":7969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"644150087","text":"import urllib.request\nfrom bs4 import BeautifulSoup\n\n\ndef get_soup(url):\n\t# Делаем запрос на сайт\n\tresponse = urllib.request.urlopen(url)\n\t# Получаем html страницы\n\thtml = response.read()\n\treturn BeautifulSoup(html)\n\ndef pars_centers():\n\tsoup = get_soup(\"http://e-a-s-y.ru/contacts/\")\n\tcenters_list = soup.find('div', class_=\"contacts__list\")\n\tcenters_list = centers_list.find_all('div', class_=\"contacts-card\")\n\toutput = []\n\t# Добавляем все школы в список\n\tfor center in centers_list:\n\t\tname = center.find('h3').text\n\t\tadress = center.find_all('p')[0].text\n\t\temail = center.find_all('p')[1].text[1:]\n\t\twork_time = center.find_all('div', class_=\"contacts-card__schedule\")\n\t\ttime_list = [time.text for time in work_time]\n\t\toutput.append({\n\t\t\t'name': name,\n\t\t\t'adress': adress,\n\t\t\t'email': email,\n\t\t\t'time': time_list})\n\treturn output\n\ndef pars_events():\n\tsoup = get_soup(\"http://e-a-s-y.ru/events/\")\n\tevents_list = soup.find_all('div', class_=\"events-list__item\")\n\toutput = []\n\t# Добавляем все мероприятия в список\n\tfor event in events_list:\n\t\tlink = event.find('a')['href']\n\t\tdescription = event.find('div', class_=\"card-current__excerpt\").text\n\t\tage = event.find('small').text\n\t\tif age == '':\n\t\t\tage = \"0+\"\n\t\tname = event.find('h3', class_=\"card-current__title\").text\n\t\tdate = event.find('span').text\n\t\toutput.append({\n\t\t\t'name': name + \" (\" + age + \") \",\n\t\t\t'date': date,\n\t\t\t'link': link,\n\t\t\t'description': description})\n\treturn output\n","sub_path":"parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"13638132","text":"# -------------------------------------------------------------------------- #\n# http://www.reddit.com/r/dailyprogrammer/comments/2snhei/\n# 20150116_challenge_197_hard_crazy_professor/\nimport itertools as it\nimport operator as op\n\nPRIMES = frozenset({2, 3, 5, 7, 11, 13, 17, 19})\nCOUNT = 1000\n\n# -------------------------------------------------------------------------- #\ndef take_one(): # slow\n\tso_far = {1}\n\twhile True:\n\t\tnext_p = min(a*b for a, b in it.product(PRIMES, so_far)\n\t\t\tif a*b not in so_far)\n\t\tso_far.add(next_p)\n\t\tyield next_p\n\ndef take_two(): # slow\n\tso_far = {1}\n\twhile True:\n\t\tnext_p = min(n*p for n in so_far for p in PRIMES if n*p not in so_far)\n\t\tso_far.add(next_p)\n\t\tyield next_p\n\n# -------------------------------------------------------------------------- #\ndef main(n=1):\n\ttakes = {1: take_one, 2: take_two}\n\tprime_gen = takes[n]()\n\tfor _ in range(COUNT):\n\t\tnext(prime_gen)\n\tprint(next(prime_gen))\n\nif __name__ == \"__main__\":\n\tmain(2)","sub_path":"Challenge #197/Hard - Crazy Primes.py","file_name":"Hard - Crazy Primes.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"593619904","text":"class HappyNumber(object):\n def is_happy(self, n):\n \"\"\"\n obvious solution is to use a set!\n :type n: int\n :rtype: bool\n \"\"\"\n slow = n\n fast = n\n while True:\n # this is how do-while is implemented (while True: stuff() if fail_condition: break)\n # similar to cycle detection in linked lists\n slow = self.__next(slow)\n fast = self.__next(fast)\n fast = self.__next(fast)\n if slow == 1 or fast == 1: # although checking just fast == 1 is enough\n return True\n elif slow == fast:\n return False\n\n @staticmethod\n def __next(n):\n total = 0\n while n > 0:\n rem = n % 10\n total += (rem * rem)\n n = int(n / 10)\n return total\n","sub_path":"Python/dev/maps/happy_number.py","file_name":"happy_number.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"345180869","text":"# Copyright 2017 - Nokia Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom cliff import command\nfrom datetime import datetime\n\nfrom vitrageclient.common import exc\n\n\n# noinspection PyAbstractClass\nclass EventPost(command.Command):\n \"\"\"Show the event of the system\"\"\"\n\n def get_parser(self, prog_name):\n parser = super(EventPost, self).get_parser(prog_name)\n\n parser.add_argument('--type',\n help='The type of the event')\n\n parser.add_argument('--time',\n default='',\n help='The timestamp of the event in ISO 8601 '\n 'format: YYYY-MM-DDTHH:MM:SS.mmmmmm. '\n 'If not specified, the current time is used')\n\n parser.add_argument('--details',\n default='{}',\n help='A json string with the event details')\n\n return parser\n\n def formatter_default(self):\n return 'json'\n\n def take_action(self, parsed_args):\n if not parsed_args.type:\n raise exc.CommandException(\n message='Missing event type, please add --type')\n\n if parsed_args.time:\n event_time = parsed_args.time\n else:\n event_time = datetime.now().isoformat()\n\n event_type = parsed_args.type\n details = parsed_args.details\n\n self.app.client.event.post(event_time=event_time,\n event_type=event_type,\n details=details)\n","sub_path":"python-vitrageclient-1.1.2/vitrageclient/v1/cli/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"501638786","text":"# -*- coding: utf-8 -*-\n\n##\n##\n## Example of a Learning Activity Tree\n##\n##\n\n__author__ = 'mario'\n\nif __name__ == \"__main__\":\n import os\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"protoboard.settings\")\n import django\n from django.conf import settings\n django.setup()\n\nfrom activitytree.models import LearningStyleInventory, LearningActivity, Course, UserLearningActivity\n\n#LearningActivity.objects.all().delete()\n\nstartup = LearningActivity( name = 'Como construir un startup', slug = 'como_construir_un_startup',\n uri = \"/activity/startup\",\n heading=\"Como construir un startup\",\n secondary_text = \"Tutorial\",\n description = \"\"\"Este tutorial te brinda los conocimientos para que inicies tu propia startup, en particular se centra en\n explicarnos el como desarrollar el Buissiness Model Camvas\"\"\",\n\n image = \"https://s3.amazonaws.com/learning-python/python-logo.png\",\n\n parent = None,\n root = None,\n\n choice_exit = False,\n is_container = True,\n order_in_container = 0\n)\n\nstartup.save()\ndescription= u\"\"\"\n

Como Construir un Startup

\n\"\"\"\n\n\ncursoStartUP = Course(short_description=description, root=startup)\ncursoStartUP.save()\n\n\n\nintro = LearningActivity( name = 'Lo que ahora sabemos',\n uri = \"/activity/startup/lo-que-ahora-sabemos\",\n parent = startup, root = startup,\n heading=\"Lo que ahora sabemos\",\n description = \"Las reglas que se aplican a las empresas son muy diferentes a los startups.\",\n image = \"https://s3.amazonaws.com/learning-python/python-logo.png\",\n secondary_text = \"Lección 1\",\n is_container = True,\n is_visible = True,\n order_in_container = 0\n\n)\nintro.save()\n\ntema_1_1 = LearningActivity( name = 'Lo que ahora sabemos', slug = '',\n uri = '/activity/video/lo-que-ahora-sabemos',\n lom = '/activity/video/lo-que-ahora-sabemos',\n\n heading=\"Lo que ahora sabemos\",\n description = \"¿En qué son distintas las startups y la empresas?\",\n image = \"https://s3.amazonaws.com/learning-python/IntroVideo.png\",\n\n parent = intro, root = startup,\n pre_condition_rule = \"\",\n post_condition_rule = \"\",\n\n rollup_objective = True,\n rollup_progress = True,\n\n is_container = False,\n is_visible = True, order_in_container = 0\n )\ntema_1_1.save()\n\n\nbmc = LearningActivity( name = 'El Lienzo del Modelo de Negocio',\n uri = \"/activity/startup/business-model-canvas\",\n parent = startup, root = startup,\n heading=\"El Lienzo del Modelo de Negocio\",\n description = \"Un lenguaje común para describir, visualizar, evaluar y modificar modelos de negocio.\",\n image = \"https://s3.amazonaws.com/learning-python/python-logo.png\",\n secondary_text = \"Lección 2\",\n is_container = True,\n is_visible = True,\n order_in_container = 1\n)\nbmc.save()\n\ncustomer = LearningActivity( name = 'El Desarrollo del Cliente',\n uri = \"/activity/startup/customer-development\",\n parent = startup, root = startup,\n heading=\"El Desarrollo del Cliente\",\n description = \"Sabemos lo que el cliente necesita.. Ni cerca, debemos salir del edificio para entenderlo.\",\n image = \"https://s3.amazonaws.com/learning-python/python-logo.png\",\n secondary_text = \"Lección 3\",\n is_container = True,\n is_visible = True,\n order_in_container = 2\n)\ncustomer.save()","sub_path":"scripts/como_construir_un_startup.py","file_name":"como_construir_un_startup.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"216917122","text":"import tkinter.ttk as ttk\nfrom tkinter import *\nfrom uiBuilderView import UIBuilderApp\nimport os\nimport tkinter.messagebox as messagebox\n\nclass UIBuilderLogic():\n \"\"\"\n UIBuilderで組み立てたUIのサンプルコードを出力するロジッククラス\n \"\"\"\n def __init__(self,canvas_parts):\n \"\"\"\n 初期化\n 出力ディレクトリはこのファイルと同じ階層\n 出力ファイル名はtest.pyとして出力する\n canvas_parts:パーツを配置した親フレーム\n \"\"\"\n self.output_dir = os.path.dirname(__file__)\n self.output_file_name = os.path.join(self.output_dir,\"test.py\")\n self.canvas_parts = canvas_parts\n\n def outputCommand(self):\n \"\"\"\n 実際に出力させるメインメソッド\n ①インポート文出力\n ②UISampleクラス出力\n ③main文出力\n \"\"\"\n ret = False\n try:\n fo = open(self.output_file_name,\"w\",newline= \"\\n\")\n self.writeImport(fo)\n self.writeUISample(fo)\n self.writeMain(fo)\n fo.close()\n ret = True\n except IOError as e:\n print(e)\n print(\"ファイルの出力に失敗しました。\")\n ret = False\n return ret\n\n def writeImport(self,file):\n \"\"\"\n import文の出力\n file:ファイルオブジェクト\n \"\"\"\n import_list =[\n \"import tkinter.ttk as ttk\",\n \"from tkinter import *\",\n ]\n for item in import_list:\n print(item,file=file)\n\n def writeUISample(self,file):\n \"\"\"\n 実際のWidget作成\n UISampleクラスを作成しCanvasに配置したWidgetを組み立てる\n フレームサイズは指定サイズで作成\n file:ファイルオブジェクト\n \"\"\"\n width = self.canvas_parts[\"width\"]\n height = self.canvas_parts[\"height\"]\n print(\"class UISample(ttk.Frame):\",file=file)\n print(\"\\tdef __init__(self, master):\",file=file)\n print(\"\\t\\tsuper().__init__(master,width='{}',height='{}')\".format(width,height),file=file)\n print(\"\\t\\tself.createWidgets()\",file=file)\n print(\"\\t\\tself.propagate(False)\",file=file)\n print(\"\\t\\tself.pack()\",file=file)\n print(\"\\tdef createWidgets(self):\",file=file)\n child_idx = 0\n button_command = []\n for child in self.canvas_parts.winfo_children():\n place_info = child.place_info()\n x = place_info['x']\n y = place_info['y']\n class_name = child.__class__.__name__\n\n option = \"\"\n target_key = (\"width\",\"height\",\"text\",\"state\",\"command\")\n for ck in child.keys():\n if ck in target_key:\n if ck == \"command\":\n command_function = \"self.commandFunction{}\".format(child_idx)\n button_command.append(command_function)\n option = option + \"{} = {},\".format(ck,command_function)\n else:\n option =option + \"{} = \\\"{}\\\",\".format(ck,child[ck])\n print(\"\\t\\twidget_{} = ttk.{}(self,{})\".format(child_idx,class_name,option),file=file)\n print(\"\\t\\twidget_{}.place(x={},y={})\".format(child_idx,x,y),file=file)\n child_idx +=1\n self.writeCommandFunction(file,button_command)\n\n def writeCommandFunction(self,file,command_list):\n \"\"\"\n ボタンコマンドを作成する\n とりあえずなにもしないpass文を書いておく\n command_list:ボタンの関数リスト\n \"\"\"\n for command in command_list:\n func_name = command.replace(\"self.\",\"\")\n print(\"\\tdef {}(self):\".format(func_name),file=file)\n print(\"\\t\\tpass\",file=file)\n\n def writeMain(self,file):\n \"\"\"\n main文の作成\n file:ファイルオブジェクト\n \"\"\"\n width = self.canvas_parts[\"width\"]\n height = self.canvas_parts[\"height\"]\n main_list=[\n \"if __name__ == '__main__':\",\n \"\\tmaster = Tk()\",\n \"\\tmaster.title('UISample')\",\n \"\\tmaster.geometry(\\\"{}x{}\\\")\".format(width,height),\n \"\\tUISample(master)\",\n \"\\tmaster.mainloop()\"\n ]\n for item in main_list:\n print(item,file=file)\n\n\nclass UIBuilderControl():\n \"\"\"\n UIBuilderのViewとLogicの管理を行うコントロール\n \"\"\"\n def __init__(self):\n \"\"\"\n UIBilderの起動を行う\n \"\"\"\n master = Tk()\n master.title(\"UIBuilder\")\n master.geometry(\"800x600\")\n self.view =view= UIBuilderApp(master)\n self.logic = UIBuilderLogic(view.getCanvasParts())\n self.setupMenu()\n master.mainloop()\n def setupMenu(self):\n \"\"\"\n 作成メニューのoutputにsetOutputCommandを紐づける\n \"\"\"\n self.view.setOutputCommand(self.setOutputCommand)\n\n def setOutputCommand(self):\n \"\"\"\n ロジックの出力メソッドを実行する\n 実行結果によってメッセージボックスを切り替え\n \"\"\"\n ret = self.logic.outputCommand()\n if ret:\n messagebox.showinfo(\"output\", \"succeed\")\n else:\n messagebox.showerror(\"output\", \"failed\")\n\n\nif __name__ == '__main__':\n UIBuilderControl()\n","sub_path":"UIBuilder/uiBuilderControl.py","file_name":"uiBuilderControl.py","file_ext":"py","file_size_in_byte":5455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"611667698","text":"import funciones as f\nimport numpy as np\nimport pandas as pd\n\n\n#El objetivo de este este ejercicio es obtener una descomposición armónica mediante la FFT, \n#y obtener los coeficientes de fourier a partir de las N armónicos elegidos del ejercicio anterior\nN_armonicos = 4\nmediciones_alturas = f.leer_archivo_maine()['Verified (m)']\nN_samples = int(len(mediciones_alturas))\ntiempo = np.arange(N_samples)\nmediciones_alturas_fft = f.fft_datos(mediciones_alturas)\nW_samples = int(len(mediciones_alturas_fft))\nomega = np.arange(W_samples) * (2*np.pi/N_samples)\nfreq = np.arange(W_samples) / N_samples\nindices_armonicos = f.obtener_indices_armonicos(mediciones_alturas_fft,N_armonicos)\nserie_fourier_alturas = f.sf_altura(mediciones_alturas_fft,tiempo,indices_armonicos)\n\necm_n = f.ECM(serie_fourier_alturas,mediciones_alturas)\n\nprint(\"El E.C.M para \"+str(N_armonicos)+\" armónicos es: \",ecm_n)\nprint(\"Las Frecuencias Usadas son: \", indices_armonicos/N_samples)\n","sub_path":"Informe/T`P1_86559_88019/tp1_ejercicio_b.py","file_name":"tp1_ejercicio_b.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"613697220","text":"# -*- coding: utf-8 -*-\nimport math\nimport numpy as np\nfrom PIL import Image\nfrom scipy.signal import convolve2d\nfrom skimage.draw import line\n\nfrom LineDictionary import LineDictionary\n\nlineLengths={3,5,7,9}\n# lineLengths =[3,5,7,9]\nlineTypes = [\"full\", \"right\", \"left\"]\n\nlineDict = LineDictionary()\n\n# def LinearMotionBlur_random(img):\n# lineLengthIdx = np.random.randint(0, len(lineLengths))\n# lineTypeIdx = np.random.randint(0, len(lineTypes)) \n# lineLength = lineLengths[lineLengthIdx]\n# lineType = lineTypes[lineTypeIdx]\n# lineAngle = randomAngle(lineLength)\n# return LinearMotionBlur(img, lineLength, lineAngle, lineType)\n\ndef DirectMove(img, dim):\n img_np = np.array(img)#hxw\n half = int(dim/2)\n # im_t1 = img_np[half:640,:]\n new_im_np = np.zeros(img_np.shape,dtype=\"uint8\")\n new_im_np[:,0:640-half] = (img_np[:,0:640-half]/2)\n new_im_np[:,half:640] += (img_np[:,0:640-half]/2)#(img_np[:,half:640]/2)\n #new_im_np[new_im_np > 255] = 255\n new_img = Image.fromarray(new_im_np)\n\n return new_img\n\ndef EdgeEnhance(img, dim, center_value):\n imgarray = np.array(img, dtype=\"float32\")\n kernel = EEKernel(dim, center_value)\n convolved = convolve2d(imgarray, kernel, mode='same', fillvalue=255.0).astype(\"uint8\")\n img = Image.fromarray(convolved)\n return img\n\ndef EEKernel(dim, center_value):\n kernelwidth = dim\n kernelCenter = int(math.floor(dim/2))\n kernel = -np.ones((kernelwidth, kernelwidth), dtype=np.float32)\n kernel[kernelCenter, kernelCenter] = center_value\n \n normalizationFactor = max(1,center_value-8)\n kernel = kernel / normalizationFactor \n return kernel\n\n\ndef LinearMotionBlur(img, dim, angle, linetype):\n imgarray = np.array(img, dtype=\"float32\")\n kernel = LineKernel(dim, angle, linetype)\n convolved = convolve2d(imgarray, kernel, mode='same', fillvalue=255.0).astype(\"uint8\")\n img = Image.fromarray(convolved)\n return img\n\ndef LineKernel(dim, angle, linetype):\n kernelwidth = dim\n kernelCenter = int(math.floor(dim/2))\n kernel = np.zeros((kernelwidth, kernelwidth), dtype=np.float32)\n # if dim in lineLengths:\n # angle = SanitizeAngleValue(kernelCenter, angle)\n # lineAnchors = lineDict.lines[dim][angle]\n # else:\n # lineAnchors = [kernelCenter,0,kernelCenter,int(dim-1)]\n # # starting point -> end point\n if(linetype == 'right'):\n lineAnchors[0] = kernelCenter\n lineAnchors[1] = kernelCenter\n if(linetype == 'left'):\n lineAnchors[2] = kernelCenter\n lineAnchors[3] = kernelCenter\n \n for i in range(dim):\n if i < kernelCenter:\n l = 2*i+1\n else:\n l = dim - 2*(i-kernelCenter) \n start = int((dim - l)/2)\n for j in range(l):\n kernel[i,start+j] = 1\n \n normalizationFactor = np.count_nonzero(kernel)\n kernel = kernel / normalizationFactor \n return kernel\n\ndef SanitizeAngleValue(kernelCenter, angle):\n numDistinctLines = kernelCenter * 4\n angle = math.fmod(angle, 180.0)\n if angle < 0:\n angle = 180.0 - angle\n # validLineAngles = np.linspace(0,180, numDistinctLines, endpoint = False)\n # angle = nearestValue(angle, validLineAngles)\n return angle\n\ndef nearestValue(theta, validAngles):\n idx = (np.abs(validAngles-theta)).argmin()\n return validAngles[idx]\n\ndef randomAngle(kerneldim):\n kernelCenter = int(math.floor(kerneldim/2))\n numDistinctLines = kernelCenter * 4\n validLineAngles = np.linspace(0,180, numDistinctLines, endpoint = False)\n angleIdx = np.random.randint(0, len(validLineAngles))\n return int(validLineAngles[angleIdx])\n","sub_path":"pyblur/LinearMotionBlur.py","file_name":"LinearMotionBlur.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"513062539","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport csv\nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nimport torch.utils.data\nimport torchvision.transforms as T\n# from torchvision.datasets.folder import *\n\nimport numpy as np\nimport pickle\n\n\nclass iPERLoader:\n\n def __init__(self, data_root, batch=2, workers=8, img_size=256, transform=None):\n self.data_root = data_root\n self.batch = batch\n self.workers = workers\n self.img_size = img_size\n\n # ToAdd: images transform\n if transform != None:\n self.t = transform\n else:\n self.t = T.Compose([\n T.Resize((self.img_size, self.img_size)),\n T.ToTensor()\n ])\n\n def data_load(self):\n train_set = iPERDataset(\n data_root=self.data_root,\n subset='train',\n transform=self.t,\n )\n\n val_set = iPERDataset(\n data_root=self.data_root,\n subset='val',\n transform=self.t,\n )\n\n test_set = iPERDataset(\n data_root=self.data_root,\n subset='test',\n transform=self.t,\n )\n\n train_loader = torch.utils.data.DataLoader(\n dataset=train_set,\n batch_size=self.batch,\n num_workers=self.workers,\n pin_memory=True,\n shuffle=True\n )\n\n val_loader = torch.utils.data.DataLoader(\n dataset=val_set,\n batch_size=self.batch,\n num_workers=self.workers,\n pin_memory=True\n )\n\n test_loader = torch.utils.data.DataLoader(\n dataset=test_set,\n batch_size=self.batch,\n num_workers=self.workers,\n pin_memory=True,\n shuffle=True\n )\n\n return train_loader, val_loader, test_loader\n # return train_loader, val_loader\n\n\nclass iPERDataset(torch.utils.data.Dataset):\n\n def __init__(self, data_root, subset, transform=None):\n\n super(iPERDataset, self).__init__()\n\n self.data_root = data_root\n self.subset = subset\n\n # load items from a txt file\n nm_file = os.path.join(data_root, f'{subset}.txt')\n self.lst_dir = []\n with open(nm_file, 'r') as f:\n self.lst_dir = f.readlines()\n\n # NOTE that all elements of self.lst_dir ends with '\\n'\n # NOTE that the train.txt file should end with only ONE SINGLE blank line\n\n self.input_nm_list = []\n for i in self.lst_dir:\n dir_img_root = os.path.join(self.data_root, 'images_HD', i[:-1])\n dir_img = os.listdir(dir_img_root)\n dir_img.sort()\n for j in range(len(dir_img)):\n dir_img[j] = os.path.join(self.data_root, 'images_HD', i[:-1], dir_img[j])\n self.input_nm_list += dir_img\n\n self.transform = transform\n\n def __getitem__(self, item):\n img_app_nm = self.input_nm_list[item]\n img_pose_nm = img_app_nm.replace('images_HD', 'skeletons').replace('.jpg', '.png')\n img_app = Image.open(img_app_nm)\n img_pose = Image.open(img_pose_nm)\n\n tsr_app = self.transform(img_app) # the tensor containing target image\n tsr_pose = self.transform(img_pose)\n\n return tsr_app, tsr_pose\n\n def __len__(self):\n return len(self.input_nm_list)\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/dataloader_v03.py","file_name":"dataloader_v03.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"230269808","text":"import sys, os\nimport speech_recognition\nfrom os import path\nfrom gtts import gTTS\nfrom datetime import date,datetime\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\nsys.stdout.reconfigure(encoding='utf-8')\nsys.stdin.reconfigure(encoding='utf-8')\nsys.stderr.reconfigure(encoding='utf-8')\n\nrobot_brain = \"\"\nrobot_ear = speech_recognition.Recognizer()\nyou = \"\"\n\ndef texttospeech(text):\n output = gTTS(text,lang=\"vi\", slow=False)\n output.save(sys.path[0] + \"\\\\TestAudio\\\\output.mp3\")\n mp3 = AudioSegment.from_mp3(sys.path[0] + \"\\\\TestAudio\\\\output.mp3\")\n play(mp3)\n # os.system(\"mpg123 \" + sys.path[0] + \"\\\\TestAudio\\\\output.mp3\")\n os.remove(sys.path[0] + \"\\\\TestAudio\\\\output.mp3\")\n print(\"Robot:...\" + text + \"\\n\")\n\ndef speechtotext(you = \"\"):\n\trobot_ear = speech_recognition.Recognizer()\n\twith speech_recognition.Microphone() as mic:\n\t\tprint(\"Robot: I'm listening...\")\n\t\taudio = robot_ear.listen(mic)\n\t\tprint(\"Robot:...\")\n\t\ttry:\n\t\t\tyou = robot_ear.recognize_google(audio,language=\"vi-VI\")\n\t\t\tprint(\"\\nYou: \" + you)\n\t\texcept:\n\t\t\trobot_brain = \"Tôi không hiểu bạn nói gì! ...\"\n\t\t\ttexttospeech(robot_brain)\n\treturn you\n\nwhile True:\n\n\tyou = speechtotext()\n\tif \"Xin\" in you:\n\t\ttexttospeech(\"chào bạn\")\n\t\t\n\n\telif \"meo\" in you:\n\t\ttexttospeech(\"Bạn rất thích con mèo\")\n\n\telif \"123\" in you:\n\t\ttexttospeech(\"tạm biệt, hẹn gặp lại\")\n\t\tbreak\n\n\telse: \n\t\trobot_brain = \"Tôi chưa được training câu hỏi này\"\n\t\ttexttospeech(robot_brain)\n\n\n","sub_path":"Audio/Pydub_PlayMp3.py","file_name":"Pydub_PlayMp3.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"507158729","text":"from flask import Flask, request\nfrom rq import Queue, get_current_job\nfrom fractions import Fraction\nfrom rq.job import Job\nimport pandas as pd\nimport redis\nimport time\n\napp = Flask(__name__)\n\nr = redis.Redis()\nqueue = Queue(connection=r)\njob_ids = []\ndata = pd.read_csv('test.csv')\ntotal_rows = data.shape[0]\n\ndef upload() :\n\tjob = get_current_job()\n\n\tcurrent = job.meta['job_progess'].numerator * (total_rows // job.meta['job_progess'].denominator)\n\n\tfor i in range(current, total_rows) :\n\t\tjob = queue.fetch_job(job.id)\n\n\t\tif job.meta['status'] == 'stopped' or job.meta['status'] == \"terminated\": \n\t\t\treturn \n\t\t\n\t\tprint(i)\n\t\t\n\t\tjob.refresh()\n\t\tjob.meta['job_progess']+= Fraction(1, total_rows)\n\t\tjob.save_meta()\n\n\t\ttime.sleep(1)\n\n\tjob.meta['job_progess'] = 'completed'\n\n\n@app.route('/task', methods=['GET', 'POST'])\ndef home() :\n\tjob_id = str(len(job_ids) + 1)\n\tjob_metadata = {\n\t\t'job_id' : job_id,\n\t\t'job_progess' : Fraction(0, total_rows),\n\t\t'status' : 'running'\n\t}\n\tjob_object = queue.enqueue(upload, job_id = job_metadata['job_id'], meta = job_metadata, result_ttl=999999, ttl=999999, job_timeout=999999)\n\tjob_ids.append(job_id)\n\t\n\treturn app.make_response(('Uploaded!!', 200))\n\n@app.route('/stop', methods=['GET', 'POST'])\ndef stop() :\n\tjob_id = str(request.get_json().get('id'))\n\tjob = queue.fetch_job(job_id)\n\tjob.refresh()\n\n\tif job.meta['status'] == 'terminated' :\n\t\treturn app.make_response(('Job has already been terminated', 400))\n\n\tif job.meta['status'] == 'stopped' :\n\t\treturn app.make_response(('Job has already been stopped', 400))\n\n\tif job.meta['status'] == 'completed' :\n\t\treturn app.make_response(('Job has already been stopped', 400))\n\n\tjob.meta['status'] = 'stopped'\n\tjob.save()\n\tjob.cancel()\n\n\treturn app.make_response(('Job was successfully stopped.', 200))\n\n\n@app.route('/resume', methods=['GET', 'POST'])\ndef resume() :\n\tjob_id = str(request.get_json().get('id'))\n\tjob = queue.fetch_job(job_id)\n\tjob.refresh()\n\n\tif job.meta['status'] == 'terminated' :\n\t\treturn app.make_response(('Job has already been terminated', 400))\n\n\tif job.meta['status'] == 'resume' :\n\t\treturn app.make_response(('Job is already in running.', 400))\n\n\tif job.meta['status'] == 'completed' :\n\t\treturn app.make_response(('Job has already been stopped', 400))\n\t\n\tjob.meta['status'] = 'resume'\n\tjob_object = queue.enqueue(upload, job_id = job.meta['job_id'], \n\t\t\t\t\tmeta = job.meta, \n\t\t\t\t\tresult_ttl=999999, ttl=999999, job_timeout=999999)\n\n\treturn app.make_response(('Job was successfully resumed.', 200))\n\n\n@app.route('/terminate', methods=['GET', 'POST'])\ndef terminate() :\n\tjob_id = str(request.get_json().get('id'))\n\tjob = queue.fetch_job(job_id)\n\tjob.refresh()\n\n\tif job.meta['status'] == 'terminated' :\n\t\treturn app.make_response(('Job has already been terminated.', 400))\n\n\tif job.meta['status'] == 'resume' :\n\t\treturn app.make_response(('Cant terminate the running app.', 400))\n\n\tif job.meta['status'] == 'completed' :\n\t\treturn app.make_response(('Job has already been stopped', 400))\n\n\tjob.meta['status'] = 'terminated'\n\tjob.save()\n\tjob.cancel()\n\n\treturn app.make_response(('Job was successfully terminated.', 200))\n\n\n\n@app.route('/list_tasks')\ndef list_task() :\n\tlist_of_tasks = {}\n\n\tfor i in job_ids :\n\t\tdata = {}\n\t\tjob = queue.fetch_job(i)\n\n\t\tdata['job_id'] = job.id\n\t\tdata['progress'] = str(round(float(job.meta['job_progess']) * 100, 2)) + '%'\n\t\tdata['status'] = job.meta['status']\n\n\t\tlist_of_tasks[i] = data\n\n\treturn list_of_tasks\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"578118770","text":"from preprocess.preprocess_util_1 import preprocess\nimport neuralNetworks.BPNN as BPNN\nfrom utils.file_utils.existence_utils import nn_res_existence\n\n#----------------------Load Data Set----------------------\n# Define Class csvParser, this calss is used to read csv file, extract useful information from csv file, and divide the whole data into train, validation, test data\n# trainArrList, validationArrList, testArrList = preprocess(scheme=0, csvPath='../../data/data_middle_total.CSV').txt2Arr()\n\ndata_range_pair_dict = {\n 'corrosion': [0,1040],\n 'temperature': [],\n 'tow': [],\n 'sulfur': [0, 175],\n 'chloride': [0, 260],\n 'year': []\n }\n\"\"\"\nThe preprocessing of original data was finished long time ago. \nThe preprocessed data (Training/Validation/Test) is:\n Training\n 2019_05_14_00_39_train_3.txt\n Validation\n 2019_05_14_00_39_validation_3.txt\n Test\n 2019_05_14_00_39_test_3.txt\n\"\"\"\ntrainArrList, validationArrList, testArrList = preprocess(scheme=3, data_range_pair_dict=data_range_pair_dict, csvPath='../data/data_middle_total.CSV').txt2Arr(input_folder='../data/data_txt',time_str='2019_05_14_00_39')\n\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nrank = comm.rank\n\nif rank == 0:\n\n paraList = nn_res_existence(nn_type='bpnn', res_folder='../results/res_scheme_3/bpnn_res').check_res()\n comm.send(paraList[int(len(paraList) / 7) * 0 : int(len(paraList) / 7) * 1], dest=1)\n comm.send(paraList[int(len(paraList) / 7) * 1 : int(len(paraList) / 7) * 2], dest=2)\n comm.send(paraList[int(len(paraList) / 7) * 2 : int(len(paraList) / 7) * 3], dest=3)\n comm.send(paraList[int(len(paraList) / 7) * 3 : int(len(paraList) / 7) * 4], dest=4)\n comm.send(paraList[int(len(paraList) / 7) * 4 : int(len(paraList) / 7) * 5], dest=5)\n comm.send(paraList[int(len(paraList) / 7) * 5 : int(len(paraList) / 7) * 6], dest=6)\n comm.send(paraList[int(len(paraList) / 7) * 6 : len(paraList)], dest=7)\n\nelse:\n recParaList = comm.recv(source=0)\n for recParaDict in recParaList:\n bpNN = BPNN.Network([5, recParaDict['hiddenNum'], 1])\n\n # Train 500 epoch for trial\n # bpNN.SGD(trainArrList, epochs=500, mini_batch=recParaDict['mini_batch'], eta=recParaDict['eta'], validationData=validationArrList, resPath='../results/res_scheme_3/bpnn_res')\n\n # Train 100000 epoch for real\n bpNN.SGD(trainArrList, epochs=100000, mini_batch=recParaDict['mini_batch'], eta=recParaDict['eta'], validationData=validationArrList, resPath='../results/res_scheme_3/bpnn_res')\n\n bpNN.save(filePath='../results/res_scheme_3/bpnn_res/bpnn_topology')\n#----------------------Scheme-3: Automatically Train BP Neural Network by using point-to-point communication-------------------------------","sub_path":"prj_src/BPmain_8p.py","file_name":"BPmain_8p.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"193330727","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\n\ndef tahmin_ayar(x):\n deneme = np.array([x])\n deneme.resize(1, 1)\n return deneme\n \nveriler=pd.read_csv(\"maaslar.csv\")\n\nx=veriler.iloc[:,1:2]\ny=veriler.iloc[:,2:]\n\nX=x.values\nY=y.values\n\npoly_reg=PolynomialFeatures(degree=3)\nx_poly=poly_reg.fit_transform(X)\n\nlin_reg=LinearRegression()\nlin_reg.fit(x_poly,y)\n\nplt.scatter(X,Y,c='red')\nplt.plot(X,lin_reg.predict(x_poly),c='blue')\nplt.show()\n\nprint(lin_reg.predict(poly_reg.fit_transform(tahmin_ayar(11))))\n","sub_path":"Poly_reg.py","file_name":"Poly_reg.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"116395971","text":"#!/usr/bin/env python3.4\n#coding:utf-8\n\n'''\nLeetcode一步一个脚印。\n\n258.Add Digits\n\nNote:\n 自己的想法是数字转换字符串,然后累加。用递归。\n 看了讨论区的一些方法,感觉自己差的太远。\n'''\n\nfrom functools import reduce\n\ndef addDigits_before(num):\n if num//10 < 1:\n return num\n num = reduce(lambda x, y: x + y, map(int, str(num)))\n return addDigits(num)\n\ndef addDigits_after(num):\n if num == 0:\n return 0\n else:\n return (num-1)%9 + 1\n\ndef run():\n num = int(input())\n print(addDigits(num))\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"2016-04-27/add_digits.py","file_name":"add_digits.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"94909605","text":"# -*-coding:utf-8-*-\r\nimport urllib.request\r\nimport time\r\nfrom multiprocessing.pool import Pool\r\nfrom time import sleep\r\nimport os\r\nfrom pyquery import PyQuery as pq\r\nimport pandas as pd\r\nimport numpy as np\r\nimport xlrd\r\nfrom config import filepath\r\n\r\n\r\nclass Crawl(object):\r\n\r\n page_url_list={}\r\n href_list =[] # 用列表的话会出现list assignment index out of range 报错\r\n lastPage=''\r\n attrs='' # 属性数量\r\n\r\n\r\n def requestUrl(self,url):\r\n req = urllib.request.Request(url)\r\n req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36')\r\n html = urllib.request.urlopen(req).read().decode()\r\n return html\r\n\r\n def getLastPage(self):\r\n start_url = 'http://www.sge.com.cn/sjzx/mrhqsj'\r\n try:\r\n html=self.requestUrl(start_url)\r\n result = pq(html)\r\n if result:\r\n PageNum = result('.border_ea.noLeft_border') # 页数对应的class\r\n self.lastPage = PageNum.eq(-3).text() #最后一页页码对应倒数第三个字符\r\n # print(self.lastPage)\r\n\r\n except Exception as e:\r\n print('getLastPage报错')\r\n print(e)\r\n\r\n def getPagelist(self):\r\n for i in range(int(self.lastPage)):\r\n page_url='http://www.sge.com.cn/sjzx/mrhqsj?p=%s' %(i+1)\r\n self.page_url_list[i]=page_url\r\n #print(self.page_url_list)\r\n\r\n def getURLlist(self,url):\r\n try:\r\n html=self.requestUrl(url)\r\n #用pyquery提取链接\r\n result=pq(html)\r\n if result:\r\n result1=result('.title.fs14.color333.clear') #提取class\r\n # print(result1)\r\n for i in range(10):\r\n href='http://www.sge.com.cn/%s' %result1.eq(i).attr('href')\r\n self.href_list.append(href)\r\n # print(self.href_list)\r\n except Exception as e:\r\n print('getURLlist报错')\r\n print(e)\r\n\r\n def savetoExcel(self,data_df,name):\r\n try:\r\n os.chdir(filepath)\r\n print('正在导出 %s.xlsx 表格..' %name)\r\n writer = pd.ExcelWriter('%s.xlsx' %name) # 存入excel\r\n data_df.to_excel(writer, 'Sheet1', float_format='%.5f')\r\n writer.save()\r\n print('导出完成')\r\n except Exception as e:\r\n print('导出失败')\r\n print(e)\r\n\r\n # def judgeAttr(self,str):\r\n #\r\n # # 2014年9月4日--2008年9月10日排版不同 属性 12\r\n # # 2008年9月9日--2003年4月16日 属性 11\r\n # # 2003年4月15日--2002年11月1日 属性 10\r\n # # 2002年10月31日 属性8\r\n # # 2014-9-4 : 1409760000.0\r\n # # 2008-9-9 : 1220889600.0\r\n # # 2003-4-15: 1050336000.0\r\n # # 2002-10-31 : 1035993600.0\r\n #\r\n # tmp=time.mktime(time.strptime(str,'%Y-%m-%d'))\r\n # if tmp>1409760000.0:\r\n # self.attrs=13\r\n # elif tmp>1220889600.0:\r\n # self.attrs=12\r\n # elif tmp>1050336000.0:\r\n # self.attrs=11\r\n # elif tmp>1035993600.0:\r\n # self.attrs=10\r\n # else:\r\n # self.attrs=8\r\n # # print('self.attrs=%s'%self.attrs)\r\n\r\n # def parse_page(self,url):\r\n # string=[]\r\n # tmp=[]\r\n # date=''\r\n # try:\r\n # html=self.requestUrl(url)\r\n # if html:\r\n # html1=pq(html)\r\n # result1=html1('tr td').text().split(' ') # 字符在tr td标签内 用空格分隔开\r\n # for i in result1:\r\n # string.append(i)\r\n #\r\n # date=html1('p span').eq(1).text().split(':')[1]\r\n # self.judgeAttr(date)\r\n #\r\n # length=int(len(string)/self.attrs)\r\n # result = [[0 for i in range(self.attrs)] for i in range(length-1)] # 定义二维数组,列的长度为string字符总数/self.length(属性数量),去除数字属性(合约 开盘价..)一行\r\n # tmp=string[self.attrs:] #去除字符中数据属性\r\n # for i in range(length-1):\r\n # for j in range(self.attrs):\r\n # result[i][j]=tmp[j]\r\n # tmp=tmp[self.attrs:]\r\n # # print(result)\r\n #\r\n # data=np.array(result)\r\n # # data=data[:,1:] #除去合约名称\r\n # # print(data)\r\n # data_df=pd.DataFrame(data) #创建列表\r\n # # print(data_df)\r\n #\r\n # columns=[]\r\n # indexs=[]\r\n # tmp1=string[self.attrs:]\r\n # for i in string[0:self.attrs]: #提取数据属性\r\n # columns.append(i)\r\n # for i in range(length-1): #提取合约名称\r\n # indexs.append(' ')\r\n #\r\n # # print(columns)\r\n # # print(indexs)\r\n #\r\n # data_df.columns=columns\r\n # data_df.index=indexs\r\n # data_df.loc['日期']='%s' %date #加入一行日期\r\n # data_df.loc['日期']['开盘价':]=' ' #只保留一列有日期,其它删去\r\n # # print(data_df)\r\n # name='上海黄金交易所'+date+'交易行情' #定义文件名字\r\n # # print(name)\r\n # self.savetoExcel(data_df,name)\r\n #\r\n # except Exception as e:\r\n # print('parse_page报错')\r\n # print(e)\r\n\r\n\r\n def parse_page(self,url):\r\n html1=self.requestUrl(url)\r\n try:\r\n if html1:\r\n html=pq(html1)\r\n date=html('p span').eq(1).text().split(':')[1]\r\n name = '上海黄金交易所' + date + '交易行情'\r\n data_df=pd.read_html(url)[0]\r\n # data_df.loc['日期'] = '%s' % date # 加入一行日期\r\n # data_df.loc['日期'][1:]=' ' # 只保留一列有日期,其它删去\r\n data_df['日期'] = '%s' % date # 加入一行日期\r\n # print(data_df)\r\n self.savetoExcel(data_df,name)\r\n except Exception as e:\r\n print('parse_page() BREAKS DOWN')\r\n\r\n print(e)\r\n\r\n\r\n def start(self):\r\n self.getLastPage()\r\n self.getPagelist()\r\n # print(self.page_url_list)\r\n for i in self.page_url_list:\r\n self.getURLlist(self.page_url_list[i])\r\n # print(self.href_list)\r\n\r\n for i in self.href_list:\r\n self.parse_page(i)\r\n\r\n\r\nif __name__=='__main__':\r\n test=Crawl()\r\n # test.getPagelist()\r\n # test.getLastPage()\r\n # test.tes()\r\n # test.getURLlist(url)\r\n # url='http://www.sge.com.cn/sjzx/mrhqsj/5143181?top=789398439266459648'\r\n # test.parse_page(url)\r\n\r\n pool=Pool()\r\n pool.map(test.start())\r\n\r\n","sub_path":"Order_1.py","file_name":"Order_1.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"363575738","text":"import numpy as np\n\nfrom revgraph.core.functions.operations.gradient.base.optimizer import Optimizer\n\n\nclass AdaDelta(Optimizer):\n def __init__(self, lr=1.0, rho=0.95, epsilon=1e-6, decay=0.0):\n super().__init__()\n self.lr = lr\n self.rho = rho\n self.epsilon = epsilon\n self.decay = decay\n self.iteration = 0\n\n def init_param_memory(self, param, memory, global_memory):\n memory['accumulator'] = np.zeros_like(param.data)\n memory['delta_accumulator'] = np.zeros_like(param.data)\n\n def before_update(self, global_memory):\n if self.decay > 0:\n global_memory['lr'] = self.lr * (1.0 / (1.0 + self.decay * self.iteration))\n else:\n global_memory['lr'] = self.lr\n self.iteration += 1\n\n def update(self, param, memory, global_memory):\n lr = global_memory['lr']\n g = param.gradient\n delta_accumulator = memory['delta_accumulator']\n memory['accumulator'] = self.rho * memory['accumulator'] + \\\n (1 - self.rho) * np.square(g)\n d = g * np.sqrt(delta_accumulator + self.epsilon) / \\\n np.sqrt(memory['accumulator'] + self.epsilon)\n param.data -= lr * d\n memory['delta_accumulator'] = self.rho * delta_accumulator + \\\n (1 - self.rho) * np.square(d)\n","sub_path":"revgraph/core/functions/operations/gradient/optimizers/adadelta.py","file_name":"adadelta.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"438101948","text":"#-*- coding: utf-8 -*-\n\n\"\"\"\nC3D + Conv\n\"\"\"\n\nimport numpy as np\nimport os\nimport sys\nimport time\n\nfrom PIL import Image\nimport tensorflow as tf\n\nfrom tensorflow.contrib.layers.python.layers import (\n initializers,\n convolution2d, fully_connected\n)\n\nfrom collections import OrderedDict\nimport cPickle as pkl\nimport crc_input_data_seq\n\nfrom util import log, override\nfrom models.base import ModelBase, BaseModelConfig\nfrom models.saliency_shallownet import SaliencyModel\n\nfrom models.model_util import tf_normalize_map, normalize_probability_map\nfrom models.model_util import tf_softmax_2d, tf_softmax_cross_entropy_with_logits_2d\nfrom evaluation_metrics import saliency_score, AVAILABLE_METRICS\n\nfrom easydict import EasyDict as E\n\nCONSTANTS = E()\nCONSTANTS.image_width = 98\nCONSTANTS.image_height = 98\nCONSTANTS.gazemap_width = 49\nCONSTANTS.gazemap_height = 49\nCONSTANTS.saliencymap_width = 49\nCONSTANTS.saliencymap_height = 49\n\nfrom models.gaze_rnn import GRUModelConfig, GazePredictionGRU\n\n\nclass GazePredictionConv(GazePredictionGRU):\n\n def __init__(self,\n session,\n data_sets,\n config=GRUModelConfig()\n ):\n\n super(self.__class__, self).__init__(session,\n data_sets,\n config=config)\n\n\n\n self.dropout_keep_prob = tf.placeholder(tf.float32,\n [],\n name='placeholder_dropout_keep_prob')\n\n\n @staticmethod\n def create_gazeprediction_network(frame_images, c3d_input,\n dropout_keep_prob = 1.0,\n net=None):\n '''\n Args:\n frame_images: a [B x T x IH x IW x 3] tensor (frame images)\n c3d_input : a [B x T x 1024 x 7 x 7] tensor for C3D convmap features\n gt_gazemap : a [B x T x GH x GW] tensor of ground truth per-frame gaze maps\n dropout_keep_prob : float tensor\n (optional) net : a dictionary to get intra-layer activations or tensors.\n\n Outputs:\n predicted_gazemaps : a [B x T x GH x GW] tensor,\n predicted gaze maps per frame\n '''\n\n if net is None: net = {}\n else: assert isinstance(net, dict)\n\n vars = E()\n\n # (0) input sanity check\n GH, GW = CONSTANTS.gazemap_height, CONSTANTS.gazemap_width\n IH, IW = CONSTANTS.image_height, CONSTANTS.image_width\n B, T = frame_images.get_shape().as_list()[:2]\n\n assert B > 0 and T > 0\n frame_images.get_shape().assert_is_compatible_with([B, T, IH, IW, 3])\n c3d_input.get_shape().assert_is_compatible_with([B, T, 1024, 7, 7])\n\n\n dim_cnn_proj = 512 # XXX FIXME (see __init__ in GazePredictionGRU)\n\n # some variables\n # --------------\n # not a proper name, it should be rnn_state_feature_size in # GRCN????????? FIXME\n rnn_state_size = 128 #dim_cnn_proj # filter size is more correct name\n\n ''' The RGP (Recurrent Gaze Prediction) model. '''\n\n with tf.variable_scope(\"RGP\"):\n\n\n # (2) C3D\n # -------\n # a. reduce filter size [7 x 7 x 1024] -> [7 x 7 x 32] via FC or CONV\n # b. apply RCN, and get the [7 x 7 x 32] outputs from RNN\n\n # c3d input.\n net['c3d_input'] = c3d_input # [B x T x 1024 x 7 x 7]\n # change axis and reshape to [B x T x 7 x 7 x 1024]\n net['c3d_input_reshape'] = tf.transpose(net['c3d_input'],\n perm=[0,1,3,4,2],\n name='c3d_input_reshape')\n log.info('c3d_input_reshape shape : %s', net['c3d_input_reshape'].get_shape().as_list())\n net['c3d_input_reshape'].get_shape().assert_is_compatible_with([B, T, 7, 7, 1024])\n\n\n # c3d_embedded: project each 1024 feature (per 7x7 c3d conv-feature map) into 12\n vars.proj_c3d_W = tf.Variable(tf.random_uniform([1024, dim_cnn_proj], -0.1, 0.1), name=\"proj_c3d_W\")\n vars.proj_c3d_b = tf.Variable(tf.random_uniform([dim_cnn_proj], -0.1, 0.1), name=\"proj_c3d_b\")\n\n net['c3d_embedded'] = tf.nn.xw_plus_b(\n tf.reshape(net['c3d_input_reshape'], [-1, 1024]),\n vars.proj_c3d_W, vars.proj_c3d_b\n ) # [(B*T*7*7) x 1024] --> [(B*T*7*7) x 12] by appling W:1024->12\n\n if dropout_keep_prob != 1.0:\n net['c3d_embedded'] = tf.nn.dropout(net['c3d_embedded'], dropout_keep_prob)\n\n # --> [B x T x 7 x 7 x 12]\n net['c3d_embedded'] = tf.reshape(net['c3d_embedded'], [B, T, 7, 7, dim_cnn_proj])\n log.info('c3d_embedded shape : %s', net['c3d_embedded'].get_shape().as_list())\n net['c3d_embedded'].get_shape().assert_is_compatible_with([B, T, 7, 7, dim_cnn_proj])\n\n\n # Instead of RNN part, we have deconvolution\n # -------------\n\n\n rcn_outputs = [None] * T\n for i in range(T):\n rcn_outputs[i] = net['c3d_embedded'][:, i, :, :, :]\n # B x 7 x 7 x 512(dim_cnn_proj)\n\n\n # (3) RCN output unpooling to 49x49 size\n # each of (7x7x32) maps are up-sampled to (49x49x8)\n vars.upsampling_filter1 = tf.get_variable('Upsampling/weight1',\n [5, 5,\n 64,\n dim_cnn_proj, # directly project 512->64\n #rnn_state_size\n ], # rnn_state_size bad name (indeed a channel size)\n initializer=initializers.xavier_initializer_conv2d(uniform=True)\n )\n vars.upsampling_filter2 = tf.get_variable('Upsampling/weight2',\n [5, 5,\n 32, 64], # rnn_state_size bad name (indeed a channel size)\n initializer=initializers.xavier_initializer_conv2d(uniform=True)\n )\n\n vars.upsampling_filter3 = tf.get_variable('Upsampling/weight3',\n [7, 7,\n 12, 32], # rnn_state_size bad name (indeed a channel size)\n initializer=initializers.xavier_initializer_conv2d(uniform=True)\n )\n vars.out_W = tf.Variable(tf.random_uniform([12, 1], -0.1, 0.1), name=\"out_W\")\n vars.out_b = tf.Variable(tf.random_uniform([1], -0.1, 0.1), name=\"out_b\")\n\n predicted_gazemaps = []\n for i in range(T):\n rcn_output_map = rcn_outputs[i] # [B x 7 x 7 x 128]\n\n rcn_upsampled_output = tf.nn.conv2d_transpose(rcn_output_map,\n vars.upsampling_filter1,\n output_shape=[B, 23, 23, 64],\n strides=[1, 3, 3, 1],\n padding='VALID',\n name='upsampled_rcn_output_' + str(i))\n #rcn_upsampled_output.get_shape().assert_is_compatible_with([B, GH, GW, upsampling_output_channel])\n rcn_upsampled_output = tf.nn.conv2d_transpose(rcn_upsampled_output,\n vars.upsampling_filter2,\n output_shape=[B, 49, 49, 32],\n strides=[1, 2, 2, 1],\n padding='VALID',\n name='upsampled_rcn_output_' + str(i))\n input_concat = tf.concat(concat_dim=3, # the last dimension\n values=[\n rcn_upsampled_output, # [B x 49 x 49 x 8]\n# net['frm_sal_cubic'][:, i, :, :, :], # [B x 49 x 49 x 1]\n # last_output_gazemap # [B x 49 x 49 x 1]\n ])\n\n output = tf.nn.conv2d_transpose(input_concat,\n vars.upsampling_filter3,\n output_shape=[B, 49, 49, 12],\n strides=[1, 1, 1, 1],\n padding='SAME',\n name='upsampled_rcn_output_' + str(i))\n\n output = tf.nn.xw_plus_b(tf.reshape(output,[-1,12]),vars.out_W,vars.out_b)\n output = tf.nn.dropout(output,dropout_keep_prob)\n\n predicted_gazemap = tf.reshape(output, [B, GH, GW]) # [B x 49 x 49 x 1] -> [B x 49 x 49] squeeze\n predicted_gazemaps.append(predicted_gazemap)\n # TODO should we normalize predicted_gazemap ????????????????????????????\n\n # pack as a tensor\n # T-list of [B x 49 x 49] --> [B x 49 x 49]\n net['predicted_gazemaps'] = tf.transpose(tf.pack(predicted_gazemaps), [1, 0, 2, 3], name='predicted_gazemaps')\n net['predicted_gazemaps'].get_shape().assert_is_compatible_with([B, T, GH, GW])\n\n return net['predicted_gazemaps']\n","sub_path":"models/gaze_c3d_conv.py","file_name":"gaze_c3d_conv.py","file_ext":"py","file_size_in_byte":10040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"594665346","text":"import numpy as np\nfrom keras.utils import plot_model\nfrom keras.layers import merge\nfrom keras.layers import BatchNormalization, InputLayer, RepeatVector, Permute\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers import Dense, Activation, Dropout, Input, LSTM, Flatten, Bidirectional\nfrom keras.models import Sequential, Model\nimport tensorflow as tf\n#from tensorflow import keras\nimport keras.backend as K\nimport keras\nimport os\nimport pandas as pd\nimport random\nimport os\nimport pandas as pd\nfrom collections import defaultdict\nimport zipfile\nimport requests\nimport re\nfrom keras.models import load_model\n\n\n# Load weights of trained model from disk\nmodel = load_model('model_b_2.h5')\n\nTRAINING_SAMPLE = 5000\n\ntrain_csv_file = 'imdb_train_5k.csv'\ntrain_y = np.zeros([TRAINING_SAMPLE, 1], dtype=np.int)\nlist_of_train_reviews = list()\n\nglove_file = \"glove.6B.zip\"\nEMBEDDING_SIZE = 100\n\n\n# This function is reused from model_2.py; refer to that script for more information\ndef download(url_):\n if not os.path.exists(glove_file):\n print(\"downloading glove embedding .....\")\n r = requests.get(url_, glove_file)\n glove_filename = \"glove.6B.{}d.txt\".format(EMBEDDING_SIZE)\n if not os.path.exists(glove_filename) and EMBEDDING_SIZE in [50, 100, 200, 300]:\n print(\"extract glove embeddings ...\")\n with zipfile.ZipFile(glove_file, 'r') as z:\n z.extractall()\n\n\n# See the note above the download function\ndef load_glove():\n with open(\"glove.6B.100d.txt\", 'r') as glove_vectors:\n word_to_int = defaultdict(int)\n int_to_vec = defaultdict(lambda: np.zeros([EMBEDDING_SIZE]))\n\n index = 1\n for line in glove_vectors:\n fields = line.split()\n word = str(fields[0])\n vec = np.asarray(fields[1:], np.float32)\n word_to_int[word] = index\n int_to_vec[index] = vec\n index += 1\n return word_to_int, int_to_vec\n\n\ndownload(\"http://nlp.stanford.edu/data/glove.6B.zip\")\nword_to_int, int_to_vec = load_glove()\n\n\nlist_of_filename = list()\nlist_of_y = list()\n\n\n# Load text data from a local file and run preprocessing/cleaning filters\n# This function reuses filters from create_training_sample in model_2.py;\n# refer to that script for more information\ndef create_training_sample(filename):\n df_train = pd.read_csv(train_csv_file)\n SAMPLE_SIZE = len(df_train)\n assert SAMPLE_SIZE == TRAINING_SAMPLE, 'training sample not complete....'\n\n for index in df_train.index:\n review = str(df_train['review'][index])\n label = int(df_train['label'][index])\n list_of_filename.append(df_train['file'][index])\n review = review.lower()\n '''\n review = review.replace(\"
\", \" \")\n review = re.sub(\"[,]\", \" ,\", review)\n review = re.sub(\"[.]\", \" .\", review)\n review = re.sub(\"[;]\", \" ;\", review)\n review = re.sub(\"[!]\", \" !\", review)\n review = re.sub(\"[/]\", \" / \", review)\n '''\n review = review.replace(\"
\", \" \")\n review = re.sub(r\"[^a-z ]\", \" \", review)\n review = re.sub(r\" +\", \" \", review)\n\n review = review.split(\" \")\n #for i in range(len(review)):\n # if review[i] == 'can't''\n\n list_of_train_reviews.append(review)\n list_of_y.append(label)\n\n #train_y[index] = label\n\n\n# See this function's documentation in model_2.py for more information\ndef encode_reviews(revs):\n train_data = []\n for review in revs:\n int_review = [word_to_int[word] for word in review]\n train_data.append(int_review)\n return train_data\n\n\ncreate_training_sample(filename=train_csv_file)\nprint(list_of_train_reviews[0])\n\nfor index in range(len(list_of_y)):\n train_y[index] = list_of_y[index]\n\nprint(train_y[0], train_y[6], train_y[8], train_y[10])\nprint(list_of_filename[0], list_of_filename[6],\n list_of_filename[8], list_of_filename[10])\ntrain_reviews = encode_reviews(list_of_train_reviews)\nprint(train_reviews[0])\n\nMAX_REVIEW_LEN = 1200\n\n\n# See this function's documentation in model_2.py for more information\ndef zero_pad_reviews(revs):\n _data_padded = []\n for review in revs:\n padded = [0] * MAX_REVIEW_LEN\n stop_index = min(len(review), MAX_REVIEW_LEN)\n padded[:stop_index] = review[:stop_index]\n _data_padded.append(padded)\n return _data_padded\n\n\ntrain_reviews = zero_pad_reviews(train_reviews)\n\n\n# See this function's documentation in model_2.py for more information\ndef review_ints_to_vecs(train_reviews):\n train_data = []\n for review in train_reviews:\n vec_review = [int_to_vec[word] for word in review]\n train_data.append(vec_review)\n return train_data\n\n\n# The prediction/inference routine here is very similar to the analogous code in model_2_predict_25ktest.py;\n# refer to that script for details about generating predictions, calculating model accuracy, etc.\n\ntrain_reviews = np.array(review_ints_to_vecs(train_reviews))\nprint(train_reviews.shape)\nprint(train_reviews[0])\n\nmodel.summary()\n\nprediction_results = None\nprediction_results = model.predict(train_reviews, verbose=1)\n\nlist_of_proba = []\nlist_of_file_names = []\nprint(\"predict shape\", prediction_results.shape)\ncorrect_pred = 0\nfor i in range(TRAINING_SAMPLE):\n proba = prediction_results[i][0]\n if (proba < float(0.5) and train_y[i] == 0) or (proba >= float(0.5) and train_y[i] == 1):\n correct_pred = correct_pred + 1\n list_of_proba.append(str(prediction_results[i][0]))\n list_of_file_names.append(list_of_filename[i])\n\nprint(\"Accuracy: \", float(correct_pred)/float(TRAINING_SAMPLE))\n\nd_prob = {'prob': list_of_proba}\nd_files = {'file': list_of_file_names}\n\ndd = {'prob': list_of_proba, 'file': list_of_file_names}\n\ndf = pd.DataFrame(dd, index=None)\ndf.to_csv('model_b_2_5ktrain.csv', index=False)\n","sub_path":"models/model_{1_2}/model_2_predict_5ktrain.py","file_name":"model_2_predict_5ktrain.py","file_ext":"py","file_size_in_byte":5866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"441975306","text":"count_examples = {\n '{}': 1,\n '{{{}}}': 3,\n '{{},{}}': 3,\n '{{{},{},{{}}}}': 6,\n '{<{},{},{{}}>}': 1,\n '{,,,}': 1,\n '{{},{},{},{}}': 5,\n '{{},{},{},{}}': 2\n}\n\nscore_examples = {\n '{}': 1,\n '{{{}}}': 6,\n '{{},{}}': 5,\n '{{{},{},{{}}}}': 16,\n \"{,,,}\": 1,\n \"{{},{},{},{}}\": 9,\n '{{},{},{},{}}': 9,\n \"{{},{},{},{}}\": 3\n}\n\ndef score(stream):\n gn = 0 # nesting level\n garbage = False\n escape = False # skip next character\n score = []\n garbage_size = 0\n for c in stream:\n if escape:\n escape = False\n continue\n\n if garbage:\n if c == '!':\n escape = True\n elif c == '>':\n garbage = False\n else:\n garbage_size += 1\n else:\n if c == '{':\n gn += 1\n if c == '}':\n score.append(gn)\n gn -= 1\n if c == '<':\n garbage = True\n return score, garbage_size\n\n\nfor example, expected in count_examples.items():\n s, _ = score(example)\n actual = sum(1 for _ in s)\n if actual == expected:\n print('✔ {}'.format(example))\n else:\n print('Expected {} but got {} for {}'.format(expected, actual, example))\n\n\nfor example, expected in score_examples.items():\n s, _ = score(example)\n actual = sum(s)\n if actual == expected:\n print('✔ {}'.format(example))\n else:\n print('Expected {} but got {} for {}'.format(expected, actual, example))\n\n\nwith open('input/9') as f:\n data = f.read()\n s, gc = score(data)\n print(sum(s))\n print(gc)\n","sub_path":"2017/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"496205230","text":"from django.urls import path\nfrom . import views\n#from django.conf.urls import url, include\n\n\nurlpatterns = [\n path('landing', views.landing, name='landing'),\n path('forsith', views.forsith, name='forsith'),\n path('forrecr', views.forrecr, name='forrecr'),\n]\n","sub_path":"recruit_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"566905646","text":"from flask import Flask\nfrom config import config\n\n\ndef create_app(config_type=None):\n # create and configure the app\n app = Flask(__name__)\n\n if config_type is None:\n app.config.from_object(config['development'])\n else:\n app.config.from_object(config[config_type])\n\n from .v1 import core\n core.init_app(app)\n\n from .v1 import modules\n modules.init_app(app)\n\n @app.route(\"/\")\n def index():\n return \"Hello World!\"\n\n return app\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"492624309","text":"from tkinter import *\nimport quit\nimport session\n\nclass VehicleRegPage(object):\n\t\"\"\"docstring for ClassName\n\t\tPage process flow: \n\t\t\t1. Check serial_no is not already in database\n\t\t\t2. Check owner is in database\n\t\t\t\t2.1. TRUE: --> Finalize\n\t\t\t\t2.2. FALSE: --> Add person in database\n\t\t\t\t\t2.2.1. Add in people table\n\t\t\t\t\t2.2.2. Add in owner table.\n\t\t\t\t\t2.2.3. --> Finalize\n\t\t\t3. Finalze\n\t\"\"\"\n\tdef __init__(self, master):\n\t\tframe = Frame(master, width = 500, height = 500)\n\t\tframe.grid()\n\t\tself.frame = frame\n\t\tself.successor = -1\n\t\tself.newOwnerIndex = 20\n\t\tself.addOwnerFormText = []\n\t\tself.addOwnerEntries = []\n\t\tself.personalEntries = []\n\t\tself.sin = {}\n\t\tself.primarySin = \"\"\n\n\t\tself.formData = {}\n\t\tself.ownerFormData = {}\n\t\tself.personalFormData = {}\n\t\tself.additionalOwnerFormData = {}\n\t\tself.numForms = 0\n\t\tself.nextButton = None\n\n\t\tself.formText = [\"serial_no\", \"maker\", \"model\", \"year\", \"color\", \"type_id\"]\n\t\tself.makeForm(frame)\n\t\tself.pageTitle = self.makeTitle(frame, \"Register a New Vehicle\", 0, 1)\n\n\t\tself.submitButton = Button(frame, text=\"Submit\", command=self.submitVehicleCallback)\n\t\tself.submitButton.grid(row=10, column=1)\n\n\t\tself.homeButton = Button(frame, text=\"Home\", command=self.homeCallback)\n\t\tself.homeButton.grid(row=10, column=2)\n\n\t\tself.quitButton = Button(frame, text=\"Quit\", command=lambda:quit.quit_callback(self.frame))\n\t\tself.quitButton.grid(row=10, column=0)\n\t\n\tdef homeCallback(self):\n\n\t\tself.successor = 0\n\n\tdef submitVehicleCallback(self):\n\t\tn=0\n\t\tfor entry in self.entries:\n\t\t\tself.formData[self.formText[n]] = entry.get()\n\t\t\tn+=1\n\n\t\tquerry = \"SELECT serial_no FROM vehicle where serial_no = '\" + str(self.formData[\"serial_no\"] )+ \"'\" \n\t\tvalidation = False\n\t\tnotNull = True\n\t\tif self.formData[\"serial_no\"] and notNull: \n\t\t\tvalidation = self.validateForm(querry)\n\n\t\tfor entry in self.entries:\n\t\t\tif not entry.get():\n\t\t\t\tentry.insert(0,\"null\")\n\n\t\tprint(self.entries[0].get())\n\t\tif self.entries[0].get() == \"null\":\n\t\t\tprint(\"Serial_no cannot be null\")\n\t\t\tnotNull = False \n\t\t\n\t\tif validation and notNull:\n\n\t\t\tfor entry in self.entries:\n\t\t\t\tentry.config(state=DISABLED)\n\t\t\tself.submitButton.config(state=DISABLED)\n\n\t\t\tself.makeOwnerForm(self.frame)\n\t\t\tself.displayText(\"Please Enter Owner Information\", 23, 1)\n\n\t\t\tself.ownerEntries[1].insert(0, self.formData[\"serial_no\"])\n\n\t\t\tself.addOwnerButton = Button(self.frame, text=\"Add Owner\", command=self.AddNewOwner)\n\t\t\tself.addOwnerButton.grid(row=20, column=2)\n\t\t\n\t\t\tself.submitOwnerButton = Button(self.frame, text=\"Submit Owner Data\", command=self.submitOwnerCallback)\n\t\t\tself.submitOwnerButton.grid(row=24, column=1)\n\t\telif notNull:\n\t\t\tprint(\"Vehicle already registered\")\n\t\t\n\t\n\tdef validateForm(self, statement): \n\t\trs = session.db.execute_sql(statement)\n\t\tprint(\"rs: \"+ str(rs)) \n\t\tif not rs: \n\t\t\tprint(\"NONE\") \n\t\t\treturn True\n\t\telse: return False\n\n\tdef submitOwnerCallback(self):\n\t\tself.addOwnerButton.config(state=DISABLED)\n\t\tself.submitOwnerButton.config(state=DISABLED)\n\t\tself.fetchOwnerFormData()\n\t\tself.fetchAdditionalOwnerFormData()\n\t\tself.sin[self.ownerFormData[\"owner_id\"]] = []\n\t\tself.primarySin = self.ownerFormData[\"owner_id\"]\n\n\t\t#print(self.personalEntries[0])\n\t\t\n\t\t# Grab id from additional owners\n\t\tfor entry in self.addOwnerEntries:\n\t\t\tself.sin[entry.get()] = []\n\n\t\tself.validateOwner()\n\n\t\tfor value in self.sin.values():\n\t\t\tif not value[0]:\n\t\t\t\tself.numForms += 1\n\n\t\tprint(\"Number of forms: \" + str( self.numForms))\n\t\tif self.numForms > 0:\n\t\t\t# make form\n\t\t\tself.makePersonalForm(self.frame, 30)\n\n\t\t\tfound = False\n\t\t\tfor key in self.sin.keys():\n\t\t\t\t\n\t\t\t\tif (( not self.sin[key][0] ) and ( not found ) ):\n\t\t\t\t\tself.sin[key] = []\n\t\t\t\t\tself.personalEntries[0].insert(0, key)\n\t\t\t\t\tself.personalEntries[0].config(state=DISABLED)\n\n\t\t\t\t\tfound = True\n\t\telse:\n\t\t\tprint(\"all owners exist\")\n\n\t\t\t# Insert into vehicle table\n\t\t\tself.updateVehicle()\n\n\t\t\t# Insert into Owner table\n\t\t\tself.updateOwner()\n\n\t\t\tsession.db.curs.connection.commit()\n\t\t\tself.successor = 0; # Go back home after\n\t\t\tself.quit()\n\n\n\tdef submitPersonalCallback(self):\n\t\tprint(\"Last Step\")\n\n\t\tfor key, value in self.sin.items():\n\t\t\tprint(key, value)\n\t\t\n\t\t# Insert into vehicle table\n\t\tself.updateVehicle()\n\t\t\n\t\t# Insert into people table\n\t\tself.updatePeople()\n\n\t\t# Insert into Owner table\n\t\tself.updateOwner()\n\n\t\tsession.db.curs.connection.commit()\n\t\tself.successor = 0; # Go back home after\n\t\tself.quit()\n\t\n\tdef displayText(self, text, row, column):\n\t\tresultText = text\n\t\tself.searchResults = Label(self.frame, text=resultText)\n\t\tself.searchResults.grid(row=row, column=column)\n\n\tdef makeButton(self, parent, caption, width, row, column):\n\t\tbutton = Button(parent, text=caption)\n\t\tbutton.grid(row=row, column=column)\n\t\treturn button\n\n\tdef makeentry(self, parent, caption, width, row, column):\n\t\tLabel(parent, text=caption, width=20, justify=RIGHT).grid(row=row,column=column[0])\n\t\tentry = Entry(parent)\n\t\tif width:\n\t\t\tentry.config(width=width)\n\t\tentry.grid(row=row, column=column[1], sticky=E)\n\t\treturn entry\n\n\tdef makeTitle(self, parent, text, row, column):\n\t\ttitle = Label(parent, text=text)\n\t\ttitle.grid(row=row, column=column)\n\t\treturn title\n\n\tdef quit(self):\n\t\tself.frame.destroy()\n\n\tdef makeForm(self, parent):\n\t\tbaseRow = 2\n\t\tself.entries = []\n\t\tfor text in self.formText:\n\t\t\tself.entries.append(self.makeentry(parent, text, 40, baseRow, [0,1]),)\n\t\t\tbaseRow += 1\n\t\n\tdef makePersonalForm(self, parent, baseRow):\n\t\tself.personalFormText = [\"sin\", \"name\", \"height\", \"weight\", \"eyecolor\", \"haircolor\", \"addr\", \"gender\", \"birthday\"]\n\t\t\n\t\tbaseRow = 30\n\t\tfor text in self.personalFormText:\n\t\t\tself.personalEntries.append(self.makeentry(parent, text, 40, baseRow, [0,1]),)\n\t\t\tbaseRow += 1 \n\n\t\tself.nextButton = self.makeButton(self.frame, \"Finalize\", 10, 50, 2)\n\t\tif self.numForms > 0:\n\t\t\tself.nextButton.config(command=self.saveAndClear, text=\"Next\")\n\t\telse:\n\t\t\tself.nextButton.config(command=self.submitPersonalCallback)\n\n\tdef saveAndClear(self):\n\t\t\"\"\"\n\t\t\tsin: {1:[False], 2: [False]}\n\t\t\t\t\t{1:[\"\", \"\" ...], 2: [False]}\n\t\t\"\"\"\n\t\t#print(self.personalEntries[1].get())\n\t\tcurrentKey = self.personalEntries[0].get()\n\t\tprint(currentKey)\n\t\tfor entry in self.personalEntries:\n\t\t\tself.sin[currentKey].append(entry.get())\n\t\tprint(currentKey, self.sin[currentKey])\n\t\tself.personalEntries[0].config(state=NORMAL)\n\n\t\tfound = False\n\t\tfor key in self.sin.keys():\n\t\t\tif (( not self.sin[key][0] ) and ( not found ) ):\n\t\t\t\tself.sin[key] = []\n\t\t\t\tself.personalEntries[0].delete(0, END)\n\t\t\t\tself.personalEntries[0].insert(0, key)\n\t\t\t\tself.personalEntries[0].config(state=DISABLED)\n\n\t\t\t\tfound = True\n\t\n\n\t\tif self.numForms == 1:\n\t\t\tself.nextButton.config(command=self.submitPersonalCallback, text=\"Finalize\")\n\n\t\t\tfor entry in self.personalEntries:\n\t\t\t\tentry.config(state=DISABLED)\t\t\n\t\telse:\n\t\t\t#clear forms\n\t\t\tself.numForms -= 1\n\t\t\n\t\tfor entry in self.personalEntries:\n\t\t\tentry.delete(0,END)\n\n\n\tdef makeOwnerForm(self, parent):\n\t\tself.ownerFormText = [\"owner_id\", \"vehicle_id\"]\n\t\tbaseRow = 20\n\t\tself.ownerEntries = []\n\t\tfor text in self.ownerFormText:\n\t\t\tself.ownerEntries.append(self.makeentry(parent, text, 40, baseRow, [0,1]),)\n\t\t\tbaseRow += 1 \n\n\tdef AddNewOwner(self):\n\t\tprint(\"Owner Added\")\n\t\ttext = \"Additional Owner \" + str(self.newOwnerIndex-19)\n\t\tself.addOwnerFormText.append(text)\n\t\tself.addOwnerEntries.append(self.makeentry(self.frame, text, 40, self.newOwnerIndex, [3,4])) \n\t\tself.newOwnerIndex += 1\n\n\tdef updatePeople(self):\n\t\t\"\"\"\n\t\t\tbuild \n\t\t\"\"\"\n\n\t\tfor key in self.sin.keys():\n\t\t\t#print(\"key: \" + str(key) + \"val: \" + str(self.sin[key]))\n\t\t\tif len(self.sin[key]) > 2:\n\t\t\t\tdata = [(self.sin[key][0], self.sin[key][1], self.sin[key][2], self.sin[key][3], self.sin[key][4], self.sin[key][5], self.sin[key][6], self.sin[key][7], self.sin[key][8])]\t\t\n\t\t\t\tsession.db.curs.executemany(\"INSERT INTO people( sin, name, height, weight, eyecolor, haircolor, addr, gender, birthday) \" \n\t\t\t\t\t\t\t\"VALUES(:1, :2, :3, :4, :5, :6, :7, :8, :9)\", data )\n\tdef updateOwner(self):\n\t\tfor key in self.sin.keys():\n\t\t\tif (self.primarySin == key):\n\t\t\t\tdata = [(key, self.ownerFormData[\"vehicle_id\"], \"y\")]\n\t\t\telse:\n\t\t\t\tdata = [(key, self.ownerFormData[\"vehicle_id\"], \"n\")]\n\n\t\t\tsession.db.curs.executemany(\"INSERT INTO owner( owner_id, vehicle_id, is_primary_owner) \" \n\t\t\t\t\t\t\"VALUES(:1, :2, :3)\", data )\n\n\tdef updateVehicle(self):\n\t\tdata = [(self.formData[\"serial_no\"], self.formData[\"maker\"], self.formData[\"model\"], self.formData[\"year\"], self.formData[\"color\"],self.formData[\"type_id\"])]\n\t\tprint(\"vehicle data: \" + str(data))\n\t\tsession.db.curs.executemany(\"INSERT INTO vehicle( serial_no, maker, model, year, color, type_id) \" \n\t\t\t\t\t\"VALUES(:1, :2, :3, :4, :5, :6)\", data )\n\n\tdef fetchOwnerFormData(self):\n\t\tn=0\n\t\tfor entry in self.ownerEntries:\n\t\t\tself.ownerFormData[self.ownerFormText[n]] = entry.get()\n\t\t\tn+=1\n\n\tdef fetchAdditionalOwnerFormData(self):\n\t\tn=0\n\t\tfor entry in self.addOwnerEntries:\n\t\t\tself.additionalOwnerFormData[self.addOwnerFormText[n]] = entry.get()\n\t\t\tn+=1\n\n\tdef fetchPersonalFormData(self):\n\t\tn=0\n\t\tfor entry in self.personalEntries:\n\t\t\tself.personalFormData[self.personalFormText[n]] = entry.get()\t\t\t\n\t\t\tif not entry.get():\n\t\t\t\tentry.insert(0,\"null\")\n\t\t\tn+=1\n\n\tdef addPersonalData(self):\n\t\tself.submitOwnerButton.config(state=DISABLED)\n\n\t\tself.makePersonalForm(self.frame, 30)\n\t\tself.displayText(\"Please Enter Personal Information\", 39, 1)\n\n\t\t#Copy owner_id to SIN field of people \n\t\tself.personalEntries[0].insert(0, self.ownerFormData[\"owner_id\"])\n\n\t\tself.submitButton2 = Button(self.frame, text=\"Submit Personal Data\", command=self.submitPersonalCallback)\n\t\tself.submitButton2.grid(row=50, column=1)\t\t\n\n\tdef validateOwner(self):\n\t\tfor key in self.sin.keys():\n\t\t\tquery = \"SELECT sin from people where sin = \" + str(key)\n\t\t\tif (self.validateForm(query)):\n\t\t\t\tself.sin[key].append(False) # not in database\n\t\t\telse:\n\t\t\t\tself.sin[key].append(True) # in database\n\t\t\n","sub_path":"vehicle_registration.py","file_name":"vehicle_registration.py","file_ext":"py","file_size_in_byte":9874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"619105759","text":"# -*- coding: utf-8 -*-\n\nfrom app.models import now, Setting\n\n\ndef unread_messages(request):\n try:\n count = request.user.get_unread_messages_count()\n except:\n count = 0\n return {\n 'unread_messages_count': count\n }\n\n\ndef settings(request):\n return {\n 'today': now(),\n 'processing': Setting.objects.get_or_create(name='processing')[0].value\n }\n\n\ndef alerts(request):\n try:\n return {\n 'alerts': request.user.get_alerts()\n }\n except:\n return {\n 'alerts': []\n }\n\n\ndef patterns(request):\n return {\n 'alpha_rus': \"^[А-ЯЁ][а-яё]*$\",\n }\n","sub_path":"app/processors.py","file_name":"processors.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"528815783","text":"'''\nThis is a script intended to make a raster plot of PN and LN activity.\n'''\nimport numpy as np\nimport glob\nimport scipy as sp\nimport pickle\nimport sys\n\n#sys.path.append('..')\n#import networks as net\n\nfolder_prefix = ''\n# Works for single voltage trace input\ndef get_spikes_PN(time_sampled_range,v_m):\n spike_thresh = -5\n\n spike_bool = sp.logical_and(v_m[:-1] < spike_thresh, v_m[1:] >= spike_thresh)\n spike_idx = [idx for idx, x in enumerate(spike_bool) if x]\n time_spikes = time_sampled_range[spike_idx] # in ms\n\n dt = np.diff(time_spikes)\n #isi_mean = np.mean(dt)\n #isi_dev = np.std(dt)\n return time_spikes\n\ndef get_spikes_LN(time_sampled_range,v_m):\n spike_thresh = -10\n\n spike_bool = sp.logical_and(v_m[:-1] < spike_thresh, v_m[1:] >= spike_thresh)\n spike_idx = [idx for idx, x in enumerate(spike_bool) if x]\n time_spikes = time_sampled_range[spike_idx] # in ms\n\n return time_spikes\nnum_odors = 3\n'''\nodor_file = open('stimuli.pickle','rb')\nodors = pickle.load(odor_file)\nodor_file.close()\n# Loaded to check stuff -- unnecessary for function\nnetwork_file = open('network.pickle','rb')\nnetwork = pickle.load(network_file)\nprint(np.shape(odors))\n\noutF = open('stimulus.txt','w')\n'''\nPN_odor = []\nLN_odor = []\nfor odor in range(num_odors):\n '''\n pn_stim = []\n ln_stim = []\n for j in range(15):\n pn_stim.append(list(np.asarray([int(k) for k in odors[0][odor][j] if k <6]) + j*6))\n ln_stim.append(list(np.asarray([int(k) for k in odors[0][odor][j] if k >5]) - 6 + j*2))\n pn_stim = list(np.hstack(pn_stim))\n ln_stim = list(np.hstack(ln_stim))\n\n outF.write('PN stimulus: {0}\\n'.format(pn_stim))\n outF.write('LN stimulus: {0}\\n'.format(ln_stim))\n '''\n # Load PN data\n for filename in sorted(glob.glob('{1}PN*_od{0}_inj*'.format(odor,folder_prefix))):\n data = np.load(filename)\n pn_num=data.shape[0]\n time = np.arange(np.shape(data)[1])*0.02\n PN_times = []\n for i in range(np.shape(data)[0]):\n spike_times = get_spikes_PN(time,data[i,:])\n #if not len(spike_times) == 0:\n # spiked.append(i)\n PN_times.append(spike_times)\n PN_odor.append(PN_times)\n # Load LN data\n for filename in sorted(glob.glob('{1}LN_od{0}_inj*'.format(odor,folder_prefix))):\n data = np.load(filename)\n ln_num = data.shape[0]\n time = np.arange(np.shape(data)[1])*0.02\n LN_times = []\n for i in range(np.shape(data)[0]):\n spike_times = get_spikes_LN(time,data[i,:])\n #if not len(spike_times) == 0:\n # spiked.append(i)\n LN_times.append(spike_times)\n LN_odor.append(LN_times)\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nSMALL_SIZE = 12\nMEDIUM_SIZE = 15\nBIGGER_SIZE = 20\n\nplt.rc('font', size=SMALL_SIZE) # controls default text sizes\nplt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title\nplt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\nplt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title\nplt.style.use('ggplot')\n\nfig, axs = plt.subplots(figsize=(20,16))\naxs.set_ylim(0,pn_num)\naxs.set_ylabel('PNs')\naxs.set_xlabel('Time (ms)')\naxs.eventplot(PN_odor[0],orientation='horizontal',linelengths=1.5,linewidths=3.5)\naxs.set_title('PN Raster Odor 0')\nplt.savefig('{0}PNraster.png'.format(folder_prefix))\nplt.show()\nplt.close()\n\nfig, axs = plt.subplots(figsize=(20,16))\naxs.set_ylim(0,ln_num)\naxs.set_ylabel('LNs')\naxs.set_xlabel('Time (ms)')\naxs.eventplot(LN_odor[0],orientation='horizontal',linelengths=1.5,linewidths=3.5)\naxs.set_title('LN Raster Odor 0')\nplt.savefig('{0}LNraster.png'.format(folder_prefix))\nplt.show()\nplt.close()\n\n#outF.close()\n","sub_path":"v0.1/examples/random_scripts/raster.py","file_name":"raster.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"92136718","text":"from ...os_v3_hek.defs.scen import *\r\n\r\n#import and use the open saucified obje attrs\r\nfrom .obje import *\r\n\r\n# replace the object_type enum one that uses\r\n# the correct default value for this object\r\nobje_attrs = dict(obje_attrs)\r\nobje_attrs[0] = dict(obje_attrs[0], DEFAULT=6)\r\n\r\nscen_body = dict(scen_body)\r\nscen_body[0] = obje_attrs\r\n\r\ndef get():\r\n return scen_def\r\n\r\nscen_def = TagDef(\"scen\",\r\n blam_header('scen'),\r\n scen_body,\r\n\r\n ext=\".scenery\", endian=\">\", tag_cls=ObjeTag\r\n )\r\n","sub_path":"os_v4_hek/defs/scen.py","file_name":"scen.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"206640096","text":"class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n # P[i][j] = True if the string s[i:] and pattern p[j:] matches. False otherwise. \n # if p[j] == '*', P[i][j] = P[i][j+1] or p[i+1]p[j] or p[i+1][j+1] \n # else p[i][j] = (p[j] == '?' or s[i] == p[j]) and p[i+1][j+1]\n # mem[i][j] means P[i][j]\n # edge case: if j >= len(p) and i < len(s) False. (pattern depleted)\n # if i >= len(s) and j < len(p) and p[j] != '*', False. (string depleted first. \n # if ...........................and p[j] == '*', return p[i][j+1]\n mem = {} # shit!!! use map, if present, return. I'm actually reevaluating things from ground up all the time? \n i = 0\n # remove adjacent *\n while i < len(p) - 1:\n if p[i] == p[i + 1] and p[i] == '*':\n p = p[:i] + p[i+1:]\n else:\n i += 1\n # print(p)\n def dp(i,j):\n if (i,j) in mem:\n return mem[i,j]\n # edge cases first\n if i >= len(s) and j >= len(p):\n return True \n if i >= len(s) and j == len(p) - 1 and p[j] == '*':\n return True\n if i >= len(s) and j < len(p):\n return False \n if j >= len(p) and i < len(s):\n return False\n else:\n # normal case \n if p[j] == '*':\n mem[(i,j)] = dp(i,j+1) or dp(i+1,j) or dp(i+1,j+1)\n else:\n mem[(i,j)] = (p[j] == '?' or s[i] == p[j]) and dp(i+1,j+1)\n return mem[(i,j)] \n return dp(0,0)\n\ns = \"bbbbbbbabbaabbabbbbaaabbabbabaaabbababbbabbbabaaabaab\"\np = \"b*b*ab**ba*b**b***bba\"\n\n\nprint(Solution().isMatch(s,p))\n","sub_path":"leetcode1-115/44. Wildcard Matching.py","file_name":"44. Wildcard Matching.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"268407597","text":"import json\nimport locale\nimport os\nfrom datetime import datetime\nfrom os import listdir, mkdir, path\nfrom os.path import basename, isfile, join\nfrom urllib.parse import urljoin\nfrom email.utils import parsedate_to_datetime\nimport bleach\nimport requests\nimport yaml\n\nlocale.setlocale(locale.LC_TIME, '')\n\n\ndef obtain_manifest(pkgid, url: str):\n if not path.exists('cache'):\n mkdir('cache')\n cache_file = path.join('cache', 'manifest_%s.json' % pkgid)\n try:\n resp = requests.get(url=url, allow_redirects=True)\n manifest = resp.json()\n manifest['ipkUrl'] = urljoin(url, manifest['ipkUrl'])\n with open(cache_file, 'w') as f:\n json.dump(manifest, f)\n last_modified = datetime.now()\n if 'last-modified' in resp.headers:\n last_modified = parsedate_to_datetime(\n resp.headers['last-modified'])\n os.utime(cache_file, (last_modified.timestamp(), last_modified.timestamp()))\n return manifest, last_modified\n except requests.exceptions.RequestException:\n if (path.exists(cache_file)):\n with open(cache_file) as f:\n return json.load(f), datetime.fromtimestamp(os.stat(cache_file).st_mtime)\n return None\n\n\ndef parse_package_info(path: str):\n filename = basename(path)\n with open(path) as f:\n content = yaml.safe_load(f)\n suffixidx = filename.rfind('.yml')\n if suffixidx < 0:\n return None\n pkgid = filename[:suffixidx]\n if not ('title' in content) and ('iconUri' in content) and ('manifestUrl' in content):\n return None\n pkginfo = {\n 'id': pkgid,\n 'title': content['title'],\n 'iconUri': content['iconUri'],\n 'manifestUrl': content['manifestUrl'],\n 'category': content['category'],\n 'description': bleach.clean(content.get('description', '')),\n }\n manifest, lastmodified = obtain_manifest(pkgid, content['manifestUrl'])\n pkginfo['lastmodified'] = lastmodified.strftime('%Y/%m/%d %H:%M:%S %Z')\n if manifest:\n pkginfo['manifest'] = manifest\n return pkginfo\n\n\ndef list_packages(pkgdir):\n paths = [join(pkgdir, f)\n for f in listdir(pkgdir) if isfile(join(pkgdir, f))]\n return sorted(filter(lambda x: x, map(parse_package_info, paths)), key=lambda x: x['title'])\n","sub_path":"repogen/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"542369799","text":"\"\"\"\n 8. Determine the twin prime numbers p1 and p2\n immediately larger than the given non-null natural number n.\n Two prime numbers p and q are called twin if q-p = 2.\n\n\"\"\"\n\ndef prime(a):\n \"\"\"\n Checks if a number is prime or not\n input: a - integer\n output: True or False\n \"\"\"\n if a > 1:\n for i in range(2,a//2+1):\n if a%i == 0:\n return False\n return True\n else:\n return False\n\ndef twinnumbers(a):\n \"\"\"\n Identifies the twin prime numbers immediately larger than the given one\n input: a - integer\n output: p1,p2 - integers =, twin numbers\n \"\"\"\n ok = False\n p1 = a + 1\n p2 = a + 3\n while ok == False:\n if prime(p1) and prime(p2):\n ok == True\n return p1,p2\n p1 += 1\n p2 += 1\n\nwhile True:\n try:\n n=int(input(\"Enter your number: \"))\n except ValueError:\n print(\"You habe to enter a number.\")\n continue\n if n < 0:\n print(\"You have to enter a natural number.\")\n continue\n else:\n break\n \nprint(\"The twin prime numbers immediately larger than your number are: \", twinnumbers(n))\n\n","sub_path":"Assignment_1/8..py","file_name":"8..py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"442145031","text":"import base64\nimport logging\nimport random\nimport re\nfrom urllib.parse import urlparse\nfrom uuid import UUID\n\nimport dateutil.parser\nimport rethinkdb as r\nimport w3lib.url\n\nfrom . import VERSION\nfrom .captcha import CaptchaSolver\nimport protobuf.shared_pb2\n\n\nlogger = logging.getLogger(__name__)\nACTION_ENUM = protobuf.shared_pb2.PolicyUrlRule.Action\nMATCH_ENUM = protobuf.shared_pb2.PatternMatch\nUSAGE_ENUM = protobuf.shared_pb2.PolicyRobotsTxt.Usage\n\n\nclass PolicyValidationError(Exception):\n ''' Custom error for policy validation. '''\n\n\ndef _invalid(message, location=None):\n ''' A helper for validating policies. '''\n if location is None:\n raise PolicyValidationError(f'{message}.')\n else:\n raise PolicyValidationError(f'{message} in {location}.')\n\n\nclass PolicyManager:\n ''' Manages policy objects. '''\n\n def __init__(self, db_pool):\n ''' Constructor. '''\n self._db_pool = db_pool\n\n async def delete_policy(self, policy_id):\n ''' Delete a policy. '''\n async with self._db_pool.connection() as conn:\n await r.table('policy').get(policy_id).delete().run(conn)\n\n async def get_policy(self, policy_id):\n ''' Get policy details. '''\n async with self._db_pool.connection() as conn:\n policy = await r.table('policy').get(policy_id).run(conn)\n return policy\n\n async def list_policies(self, limit, offset):\n ''' Return a list of policies. '''\n policies = list()\n query = (\n r.table('policy')\n .order_by(index='name')\n .skip(offset)\n .limit(limit)\n )\n\n async with self._db_pool.connection() as conn:\n count = await r.table('policy').count().run(conn)\n cursor = await query.run(conn)\n async for policy in cursor:\n policies.append(policy)\n await cursor.close()\n\n return count, policies\n\n async def set_policy(self, policy):\n '''\n Save policy details.\n\n If the policy has an ID, then that the corresponding document is\n updated and this method returns None. If the policy does not have an ID,\n then a new document is created and this method returns the new ID.\n '''\n # Validate policy by trying to instantiate a Policy object, which will\n # raise an exception if the policy is invalid.\n Policy(\n policy,\n version=VERSION,\n seeds=['http://test1.com', 'http://test2.org'],\n robots_txt_manager=None\n )\n\n # Save policy.\n async with self._db_pool.connection() as conn:\n if 'id' in policy:\n policy['updated_at'] = r.now()\n await (\n r.table('policy')\n .get(policy['id'])\n .update(policy)\n .run(conn)\n )\n policy_id = None\n else:\n policy['created_at'] = r.now()\n policy['updated_at'] = r.now()\n result = await r.table('policy').insert(policy).run(conn)\n policy_id = result['generated_keys'][0]\n\n return policy_id\n\n\nclass Policy:\n ''' Container for policies. '''\n\n @staticmethod\n def convert_doc_to_pb(doc, pb):\n ''' Convert policy from document to protobuf. '''\n pb.policy_id = UUID(doc['id']).bytes\n pb.name = doc['name']\n pb.created_at = doc['created_at'].isoformat()\n pb.updated_at = doc['updated_at'].isoformat()\n\n # A copy of a policy is stored with each job, so we need to be able\n # to gracefully handle old policies that are missing expected fields.\n PolicyAuthentication.convert_doc_to_pb(doc.get('authentication',\n dict()), pb.authentication)\n if doc.get('captcha_solver_id') is not None:\n pb.captcha_solver_id = UUID(doc['captcha_solver_id']).bytes\n PolicyLimits.convert_doc_to_pb(doc.get('limits', dict()), pb.limits)\n PolicyMimeTypeRules.convert_doc_to_pb(doc.get('mime_type_rules',\n list()), pb.mime_type_rules)\n PolicyProxyRules.convert_doc_to_pb(doc.get('proxy_rules', list()),\n pb.proxy_rules)\n PolicyRobotsTxt.convert_doc_to_pb(doc.get('robots_txt', dict()),\n pb.robots_txt)\n PolicyUrlNormalization.convert_doc_to_pb(doc.get('url_normalization',\n dict()), pb.url_normalization)\n PolicyUrlRules.convert_doc_to_pb(doc.get('url_rules', list()),\n pb.url_rules)\n PolicyUserAgents.convert_doc_to_pb(doc.get('user_agents', list()),\n pb.user_agents)\n\n @staticmethod\n def convert_pb_to_doc(pb):\n ''' Convert policy from protobuf to document. '''\n doc = {\n 'name': pb.name,\n 'authentication': dict(),\n 'limits': dict(),\n 'mime_type_rules': list(),\n 'proxy_rules': list(),\n 'robots_txt': dict(),\n 'url_normalization': dict(),\n 'url_rules': list(),\n 'user_agents': list(),\n }\n if pb.HasField('policy_id'):\n doc['id'] = str(UUID(bytes=pb.policy_id))\n if pb.HasField('created_at'):\n doc['created_at'] = dateutil.parser.parse(pb.created_at)\n if pb.HasField('updated_at'):\n doc['updated_at'] = dateutil.parser.parse(pb.updated_at)\n PolicyAuthentication.convert_pb_to_doc(pb.authentication,\n doc['authentication'])\n if pb.HasField('captcha_solver_id'):\n doc['captcha_solver_id'] = str(UUID(bytes=pb.captcha_solver_id))\n else:\n doc['captcha_solver_id'] = None\n PolicyLimits.convert_pb_to_doc(pb.limits, doc['limits'])\n PolicyMimeTypeRules.convert_pb_to_doc(pb.mime_type_rules,\n doc['mime_type_rules'])\n PolicyProxyRules.convert_pb_to_doc(pb.proxy_rules, doc['proxy_rules'])\n PolicyRobotsTxt.convert_pb_to_doc(pb.robots_txt, doc['robots_txt'])\n PolicyUrlNormalization.convert_pb_to_doc(pb.url_normalization,\n doc['url_normalization'])\n PolicyUrlRules.convert_pb_to_doc(pb.url_rules, doc['url_rules'])\n PolicyUserAgents.convert_pb_to_doc(pb.user_agents, doc['user_agents'])\n return doc\n\n def __init__(self, doc, version, seeds, robots_txt_manager):\n ''' Initialize from ``doc``, a dict representation of a policy. '''\n if doc['name'].strip() == '':\n _invalid('Policy name cannot be blank')\n\n self.authentication = PolicyAuthentication(doc['authentication'])\n if 'captcha_solver' in doc:\n self.captcha_solver = CaptchaSolver(doc['captcha_solver'])\n else:\n self.captcha_solver = None\n self.limits = PolicyLimits(doc['limits'])\n self.mime_type_rules = PolicyMimeTypeRules(doc['mime_type_rules'])\n self.proxy_rules = PolicyProxyRules(doc['proxy_rules'])\n self.robots_txt = PolicyRobotsTxt(doc['robots_txt'], robots_txt_manager,\n self)\n self.url_normalization = PolicyUrlNormalization(\n doc['url_normalization'])\n self.url_rules = PolicyUrlRules(doc['url_rules'], seeds)\n self.user_agents = PolicyUserAgents(doc['user_agents'], version)\n\n def replace_mime_type_rules(self, doc):\n '''\n Return a shallow copy of this policy with new MIME type rules from\n ``doc``.\n '''\n policy = Policy.__new__(Policy)\n policy.authentication = self.authentication\n policy.captcha_solver = self.captcha_solver\n policy.limits = self.limits\n policy.mime_type_rules = PolicyMimeTypeRules(doc)\n policy.proxy_rules = self.proxy_rules\n policy.robots_txt = self.robots_txt\n policy.url_normalization = self.url_normalization\n policy.url_rules = self.url_rules\n policy.user_agents = self.user_agents\n return policy\n\n\nclass PolicyAuthentication:\n ''' Policy for authenticated crawling. '''\n\n @staticmethod\n def convert_doc_to_pb(doc, pb):\n ''' Convert policy from document to protobuf. '''\n pb.enabled = doc['enabled']\n\n @staticmethod\n def convert_pb_to_doc(pb, doc):\n ''' Convert policy from protobuf to document. '''\n doc['enabled'] = pb.enabled\n\n def __init__(self, doc):\n ''' Initialize from ``doc``, a dict representation of limits. '''\n self._enabled = doc.get('enabled', False)\n\n def is_enabled(self):\n ''' Return True if authentication is enabled. '''\n return self._enabled\n\n\nclass PolicyLimits:\n ''' Limits on crawl size/duration. '''\n\n @staticmethod\n def convert_doc_to_pb(doc, pb):\n ''' Convert policy from document to protobuf. '''\n if doc.get('max_cost') is not None:\n pb.max_cost = doc['max_cost']\n if doc.get('max_duration') is not None:\n pb.max_duration = doc['max_duration']\n if doc.get('max_items') is not None:\n pb.max_items = doc['max_items']\n\n @staticmethod\n def convert_pb_to_doc(pb, doc):\n ''' Convert policy from protobuf to document. '''\n doc['max_cost'] = pb.max_cost if pb.HasField('max_cost') else None\n doc['max_duration'] = pb.max_duration if pb.HasField('max_duration') \\\n else None\n doc['max_items'] = pb.max_items if pb.HasField('max_items') else None\n\n def __init__(self, doc):\n ''' Initialize from ``doc``, a dict representation of limits. '''\n self._max_cost = doc.get('max_cost')\n self._max_duration = doc.get('max_duration')\n self._max_items = doc.get('max_items')\n if self._max_duration is not None and self._max_duration < 0:\n _invalid('Max duration must be ≥0')\n if self._max_items is not None and self._max_items < 0:\n _invalid('Max items must be ≥0')\n\n def exceeds_max_cost(self, cost):\n ''' Return true if ``cost`` is greater than the policy's max cost. '''\n return self._max_cost is not None and cost > self._max_cost\n\n def exceeds_max_duration(self, duration):\n '''\n Return true if ``duration`` is greater than or equal to the policy's max\n duration.\n '''\n return self._max_duration is not None and duration >= self._max_duration\n\n def exceeds_max_items(self, items):\n '''\n Return true if ``items`` is greater than or equal to the policy's max\n item count.\n '''\n return self._max_items is not None and items >= self._max_items\n\n\nclass PolicyMimeTypeRules:\n ''' Filter responses by MIME type. '''\n\n @staticmethod\n def convert_doc_to_pb(doc, pb):\n ''' Convert policy from document to protobuf. '''\n for doc_mime in doc:\n pb_mime = pb.add()\n if 'pattern' in doc_mime:\n pb_mime.pattern = doc_mime['pattern']\n if 'match' in doc_mime:\n pb_mime.match = MATCH_ENUM.Value(doc_mime['match'])\n if 'save' in doc_mime:\n pb_mime.save = doc_mime['save']\n\n @staticmethod\n def convert_pb_to_doc(pb, doc):\n ''' Convert policy from protobuf to document. '''\n for pb_mime in pb:\n doc_mime = dict()\n if pb_mime.HasField('pattern'):\n doc_mime['pattern'] = pb_mime.pattern\n if pb_mime.HasField('match'):\n doc_mime['match'] = MATCH_ENUM.Name(pb_mime.match)\n if pb_mime.HasField('save'):\n doc_mime['save'] = pb_mime.save\n doc.append(doc_mime)\n\n def __init__(self, docs):\n ''' Initialize from ``docs``, a dict representation of MIME rules. '''\n\n if len(docs) == 0:\n _invalid('At least one MIME type rule is required')\n\n # Rules are stored as list of tuples: (pattern, match, save)\n self._rules = list()\n max_index = len(docs) - 1\n MATCH_ENUM = protobuf.shared_pb2.PatternMatch\n\n for index, mime_type_rule in enumerate(docs):\n if index < max_index:\n location = 'MIME type rule #{}'.format(index+1)\n if mime_type_rule.get('pattern', '').strip() == '':\n _invalid('Pattern is required', location)\n if 'save' not in mime_type_rule:\n _invalid('Save selector is required', location)\n if 'match' not in mime_type_rule:\n _invalid('Match selector is required', location)\n\n try:\n pattern_re = re.compile(mime_type_rule['pattern'])\n except:\n _invalid('Invalid regular expression', location)\n\n self._rules.append((\n pattern_re,\n mime_type_rule['match'],\n mime_type_rule['save'],\n ))\n else:\n location = 'last MIME type rule'\n if 'save' not in mime_type_rule:\n _invalid('Save selector is required', location)\n if 'pattern' in mime_type_rule:\n _invalid('Pattern is not allowed', location)\n if 'match' in mime_type_rule:\n _invalid('Match selector is not allowed', location)\n self._rules.append((None, None, mime_type_rule['save']))\n\n def should_save(self, mime_type):\n '''\n Returns True if ``mime_type`` is approved by this policy.\n\n If rules are valid, this method always returns True or False.\n '''\n for pattern, match, save in self._rules:\n if pattern is None:\n return save\n else:\n result = pattern.search(mime_type) is not None\n if match == 'DOES_NOT_MATCH':\n result = not result\n if result:\n return save\n\n\nclass PolicyProxyRules:\n ''' Modify which proxies are used for each request. '''\n\n PROXY_SCHEMES = ('http', 'https', 'socks4', 'socks4a', 'socks5')\n\n @staticmethod\n def convert_doc_to_pb(doc, pb):\n ''' Convert policy from document to protobuf. '''\n for doc_proxy in doc:\n pb_proxy = pb.add()\n if 'pattern' in doc_proxy:\n pb_proxy.pattern = doc_proxy['pattern']\n if 'match' in doc_proxy:\n pb_proxy.match = MATCH_ENUM.Value(doc_proxy['match'])\n if 'proxy_url' in doc_proxy:\n pb_proxy.proxy_url = doc_proxy['proxy_url']\n\n @staticmethod\n def convert_pb_to_doc(pb, doc):\n ''' Convert policy from protobuf to document. '''\n for pb_proxy in pb:\n doc_proxy = dict()\n if pb_proxy.HasField('pattern'):\n doc_proxy['pattern'] = pb_proxy.pattern\n if pb_proxy.HasField('match'):\n doc_proxy['match'] = MATCH_ENUM.Name(pb_proxy.match)\n if pb_proxy.HasField('proxy_url'):\n doc_proxy['proxy_url'] = pb_proxy.proxy_url\n doc.append(doc_proxy)\n\n def __init__(self, docs):\n ''' Initialize from ``docs``, a dict representation of proxy rules. '''\n\n # Rules are stored as list of tuples: (pattern, match, proxy_type,\n # proxy_url)\n self._rules = list()\n max_index = len(docs) - 1\n MATCH_ENUM = protobuf.shared_pb2.PatternMatch\n\n for index, proxy_rule in enumerate(docs):\n if index < max_index:\n location = 'proxy rule #{}'.format(index+1)\n\n if proxy_rule.get('pattern', '').strip() == '':\n _invalid('Pattern is required', location)\n try:\n pattern_re = re.compile(proxy_rule['pattern'])\n except:\n _invalid('Invalid regular expression', location)\n\n try:\n match = (proxy_rule['match'] == 'MATCHES')\n except KeyError:\n _invalid('Match selector is required', location)\n\n proxy_url = proxy_rule.get('proxy_url', '')\n if proxy_url == '':\n _invalid('Proxy URL is required', location)\n else:\n location = 'last proxy rule'\n\n if 'pattern' in proxy_rule:\n _invalid('Pattern is not allowed', location)\n if 'match' in proxy_rule:\n _invalid('Pattern is not allowed', location)\n\n pattern_re = None\n match = None\n proxy_type = None\n proxy_url = proxy_rule.get('proxy_url')\n\n if proxy_url is None:\n proxy_type = None\n else:\n proxy_url = proxy_url.strip()\n try:\n parsed = urlparse(proxy_url)\n proxy_type = parsed.scheme\n if proxy_type not in self.PROXY_SCHEMES:\n raise ValueError()\n except:\n schemes = ', '.join(self.PROXY_SCHEMES)\n _invalid('Must have a valid URL with one of the '\n f'following schemes: {schemes}', location)\n\n\n self._rules.append((\n pattern_re,\n match,\n proxy_type,\n proxy_url,\n ))\n\n def get_proxy_url(self, target_url):\n '''\n Return a proxy (type, URL) tuple associated with ``target_url`` or\n (None, None) if no such proxy is defined.\n '''\n proxy = None, None\n\n for pattern, needs_match, proxy_type, proxy_url in self._rules:\n if pattern is not None:\n has_match = pattern.search(target_url) is not None\n if has_match == needs_match:\n proxy = proxy_type, proxy_url\n break\n elif proxy_url is not None:\n proxy = proxy_type, proxy_url\n break\n\n return proxy\n\n\nclass PolicyRobotsTxt:\n ''' Designate how robots.txt affects crawl behavior. '''\n\n @staticmethod\n def convert_doc_to_pb(doc, pb):\n ''' Convert policy from document to protobuf. '''\n pb.usage = USAGE_ENUM.Value(doc['usage'])\n\n @staticmethod\n def convert_pb_to_doc(pb, doc):\n ''' Convert policy from protobuf to document. '''\n if pb.HasField('usage'):\n doc['usage'] = USAGE_ENUM.Name(pb.usage)\n\n def __init__(self, doc, robots_txt_manager, parent_policy):\n ''' Initialize from ``doc``, a dict representation of robots policy. '''\n if 'usage' not in doc:\n _invalid('Robots.txt usage is required')\n self._parent_policy = parent_policy\n self._usage = doc['usage']\n self._robots_txt_manager = robots_txt_manager\n\n async def is_allowed(self, url):\n ''' Returns True if robots policy permits ``url``. '''\n if self._usage == 'IGNORE':\n return True\n\n result = await self._robots_txt_manager.is_allowed(\n url,\n self._parent_policy\n )\n\n if self._usage == 'INVERT':\n result = not result\n\n return result\n\n\nclass PolicyUrlNormalization:\n ''' Customize URL normalization. '''\n\n @staticmethod\n def convert_doc_to_pb(doc, pb):\n ''' Convert policy from document to protobuf. '''\n if 'enabled' in doc:\n pb.enabled = doc['enabled']\n if 'strip_parameters' in doc:\n pb.strip_parameters.extend(doc['strip_parameters'])\n\n def convert_pb_to_doc(pb, doc):\n ''' Convert policy from protobuf to document. '''\n if pb.HasField('enabled'):\n doc['enabled'] = pb.enabled\n doc['strip_parameters'] = list(pb.strip_parameters)\n\n def __init__(self, doc):\n ''' Instantiate from a dictionary representation ``doc``. '''\n self._enabled = doc.get('enabled', True)\n self._strip_parameters = doc.get('strip_parameters', list())\n\n def normalize(self, url):\n ''' Normalize ``url`` according to policy. '''\n if self._enabled:\n if len(self._strip_parameters) > 0:\n url = w3lib.url.url_query_cleaner(url, remove=True,\n unique=False, parameterlist=self._strip_parameters)\n\n url = w3lib.url.canonicalize_url(url)\n\n return url\n\n\nclass PolicyUrlRules:\n ''' Customize link priorities based on URL. '''\n\n @staticmethod\n def convert_doc_to_pb(doc, pb):\n ''' Convert policy from document to protobuf. '''\n for doc_url in doc:\n pb_url = pb.add()\n if 'pattern' in doc_url:\n pb_url.pattern = doc_url['pattern']\n if 'match' in doc_url:\n pb_url.match = MATCH_ENUM.Value(doc_url['match'])\n if 'action' in doc_url:\n pb_url.action = ACTION_ENUM.Value(doc_url['action'])\n if 'amount' in doc_url:\n pb_url.amount = doc_url['amount']\n\n @staticmethod\n def convert_pb_to_doc(pb, doc):\n ''' Convert policy from protobuf to document. '''\n for pb_url in pb:\n doc_url = dict()\n if pb_url.HasField('pattern'):\n doc_url['pattern'] = pb_url.pattern\n if pb_url.HasField('match'):\n doc_url['match'] = MATCH_ENUM.Name(pb_url.match)\n if pb_url.HasField('action'):\n doc_url['action'] = ACTION_ENUM.Name(pb_url.action)\n if pb_url.HasField('amount'):\n doc_url['amount'] = pb_url.amount\n doc.append(doc_url)\n\n def __init__(self, docs, seeds):\n ''' Initialize from ``docs``, a dict representation of url rules. '''\n if len(docs) == 0:\n _invalid('At least one URL rule is required')\n\n # Rules are stored as tuples: (pattern, match, action, amount)\n self._rules = list()\n max_index = len(docs) - 1\n seed_domains = {urlparse(seed).hostname for seed in seeds}\n ACTION_ENUM = protobuf.shared_pb2.PolicyUrlRule.Action\n MATCH_ENUM = protobuf.shared_pb2.PatternMatch\n\n for index, url_rule in enumerate(docs):\n if index < max_index:\n location = 'URL rule #{}'.format(index+1)\n if url_rule.get('pattern', '').strip() == '':\n _invalid('Pattern is required', location)\n if 'match' not in url_rule:\n _invalid('Match selector is required', location)\n if 'action' not in url_rule:\n _invalid('Action selector is required', location)\n if 'amount' not in url_rule:\n _invalid('Amount is required', location)\n\n try:\n pattern_re = re.compile(url_rule['pattern']\n .format(SEED_DOMAINS='|'.join(seed_domains)))\n except:\n _invalid('Invalid regular expression', location)\n\n self._rules.append((\n pattern_re,\n url_rule['match'],\n url_rule['action'],\n url_rule['amount'],\n ))\n else:\n location = 'last URL rule'\n if 'pattern' in url_rule:\n _invalid('Pattern is not allowed', location)\n if 'match' in url_rule:\n _invalid('Match is not allowed', location)\n if 'action' not in url_rule:\n _invalid('Action is required', location)\n if 'amount' not in url_rule:\n _invalid('Amount is required', location)\n self._rules.append((\n None,\n None,\n url_rule['action'],\n url_rule['amount'],\n ))\n\n def get_cost(self, parent_cost, url):\n ''' Return the cost for a URL. '''\n for pattern, match, action, amount in self._rules:\n if pattern is None:\n break\n else:\n result = pattern.search(url) is not None\n if match == 'DOES_NOT_MATCH':\n result = not result\n if result:\n break\n\n if action == 'ADD':\n return parent_cost + amount\n elif action == 'MULTIPLY':\n return parent_cost * amount\n\nclass PolicyUserAgents:\n ''' Specify user agent string to send in HTTP requests. '''\n\n @staticmethod\n def convert_doc_to_pb(doc, pb):\n ''' Convert policy from document to protobuf. '''\n for doc_user_agent in doc:\n pb_user_agent = pb.add()\n pb_user_agent.name = doc_user_agent['name']\n\n @staticmethod\n def convert_pb_to_doc(pb, doc):\n ''' Convert policy from protobuf to document. '''\n for user_agent in pb:\n doc.append({\n 'name': user_agent.name,\n })\n\n def __init__(self, docs, version):\n ''' Initialize from ``docs``, a dict representation of user agents. '''\n if len(docs) == 0:\n _invalid('At least one user agent is required')\n self._user_agents = list()\n for index, user_agent in enumerate(docs):\n location = 'User agent #{}'.format(index + 1)\n if user_agent.get('name', '').strip() == '':\n _invalid('Name is required', location)\n self._user_agents.append(user_agent['name'].format(VERSION=version))\n\n def get_user_agent(self):\n ''' Return a user agent string. '''\n return random.choice(self._user_agents)\n","sub_path":"starbelly/policy.py","file_name":"policy.py","file_ext":"py","file_size_in_byte":25590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"139768195","text":"#!/usr/bin/python3\n\"\"\" assign keywords \"\"\"\n\nfrom os import chdir, listdir\nfrom json import load, dump\n\n\ndef getKeyWord(knownKeys, department):\n key = None\n prompt = 'Give me a keyword for {}:\\n'\n while key is None:\n key = input(prompt.format(department))\n if key in knownKeys:\n print('KEY ALREADY IN USE')\n key = None\n return key\n\n\ndeptFilePath = '/home/jicruz/portfolio/github_repo/helper_files/'\ndeptFileName = deptFilePath + 'departments_by_municipality.json'\nwith open(deptFileName, 'r+') as file:\n departments = load(file)\n keywords = {}\n for department in departments:\n if department.count('-') < 3:\n keyword = department\n else:\n keyword = getKeyWord(keywords, department)\n departments[department].update({'palabra clave': keyword})\n keywords[keyword] = department\n file.seek(0)\n dump(departments, file)\n file.truncate()\n file.close()\n\nwith open(deptFilePath + 'departments_by_keyword.json', 'w') as file:\n dump(keywords, file)\n file.close()\n","sub_path":"scripts/not_needed/assign_keywords.py","file_name":"assign_keywords.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"187408759","text":"import glob\nimport os\n\n\ndef gen_txt(dirsrc):\n imglist = glob.glob(f'{dirsrc}/annotations/*.xml')\n imgnameList = [os.path.split(imgpath)[-1][: -4] for imgpath in imglist]\n imgnameList.sort()\n\n splits_dir = dirsrc\n traintest_split_f = os.path.join(splits_dir, \"img_list\" + '.txt')\n traintest_split = imgnameList\n\n with open(traintest_split_f, 'w') as fp:\n fp.write('\\n'.join(traintest_split) + '\\n')\n return \n\ndef gen_txt_shore(dirsrc, dirdest, split):\n imglist = glob.glob(f'{dirsrc}/*.jpg')\n imgnameList = [os.path.split(imgpath)[-1][: -4] for imgpath in imglist]\n imgnameList.sort()\n\n splits_dir = dirdest\n traintest_split_f = os.path.join(splits_dir, \"img_list_\" + split + '.txt')\n traintest_split = imgnameList\n\n with open(traintest_split_f, 'w') as fp:\n fp.write('\\n'.join(traintest_split) + '\\n')\n return \n\n\nif __name__ == \"__main__\":\n # generate_dir()\n\n # dirsrc_list = [\"/home/sun/projects/sar/SSDD/SSDD_train\", \"/home/sun/projects/sar/SSDD/SSDD_test\"] \n # for dirsrc in dirsrc_list:\n # gen_txt(dirsrc)\n \n dirsrc_list = {'inshore': '/home/sun/projects/sar/SSDD/SSDD_r/JPEGImages_test_inshore', 'offshore': '/home/sun/projects/sar/SSDD/SSDD_r/JPEGImages_test_offshore'}\n dirdest = '/home/sun/projects/sar/SSDD/SSDD_test'\n for k, v in dirsrc_list.items():\n spilt = k\n dirsrc = v\n gen_txt_shore(dirsrc, dirdest, spilt)\n ","sub_path":"tools/my_tools/gen_img_list.py","file_name":"gen_img_list.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"587455476","text":"##############################################################\n# Libraries\n##############################################################\nimport sys\nimport getopt\nimport serial\nimport time\n\n\n##############################################################\n# Initialization\n##############################################################\nserialHandle = serial.Serial(\"/dev/ttyAMA0\", 115200) # Initialize Port\n\n\n##############################################################\n# Function Prototype\n##############################################################\ndef print_help(): # PASS\n print(\"USAGE: python test.py -[command] (id)\")\n print(\" [-a aid] servo action with action id\")\n print(\" [-h] print this help message\")\n print(\" [-r rid] reset with reset id\")\n print(\" [-s sid] spin with spin id\")\n print(\" [-t tid] test with test id\")\n sys.exit(1)\n\n\ndef servo_write_cmd(servo_id, cmd, par1=None, par2=None): # PASS\n buf = bytearray(b'\\x55\\x55')\n try:\n length = 3 # Set Default Package Length\n buf1 = bytearray(b'')\n\n # Edit Data Package\n if par1 is not None:\n length += 2\n buf1.extend([(0xff & par1), (0xff & (par1 >> 8))])\n if par2 is not None:\n length += 2\n buf1.extend([(0xff & par2), (0xff & (par2 >> 8))])\n buf.extend([(0xff & servo_id), (0xff & length), (0xff & cmd)])\n buf.extend(buf1)\n\n # CheckSum Reference Point\n check_sum = 0x00\n for b in buf:\n check_sum += b\n check_sum = check_sum - 0x55 - 0x55\n check_sum = ~check_sum\n buf.append(0xff & check_sum)\n serialHandle.write(buf)\n except Exception as e:\n print(e)\n\n\ndef test(test_id): # PASS\n while True:\n try:\n servo_write_cmd(int(test_id), 1, 0, 1000)\n # ServoID=1 CMD=1 Position=0 Time=1000\n time.sleep(1.1)\n servo_write_cmd(int(test_id), 1, 1000, 1000)\n time.sleep(2.1)\n except Exception as e:\n print(e)\n break\n\n\ndef test_all(): # PASS\n print(\"test servos for 5 cycles\")\n run_num = 1\n while run_num <= 5:\n try:\n print(\"run #\", run_num)\n print(\"testing servo 1\")\n servo_write_cmd(1, 1, 0, 1000)\n time.sleep(1.1)\n servo_write_cmd(1, 1, 1000, 1000)\n time.sleep(2.1)\n print(\"testing servo 2\")\n servo_write_cmd(2, 1, 0, 1000)\n time.sleep(1.1)\n servo_write_cmd(2, 1, 1000, 1000)\n time.sleep(2.1)\n print(\"testing servo 3\")\n servo_write_cmd(3, 1, 0, 1000)\n time.sleep(1.1)\n servo_write_cmd(3, 1, 1000, 1000)\n time.sleep(2.1)\n print(\"testing servo 4\")\n servo_write_cmd(4, 1, 0, 1000)\n time.sleep(1.1)\n servo_write_cmd(4, 1, 1000, 1000)\n time.sleep(2.1)\n print(\"testing servo 5\")\n servo_write_cmd(5, 1, 0, 1000)\n time.sleep(1.1)\n servo_write_cmd(5, 1, 1000, 1000)\n time.sleep(2.1)\n run_num += 1\n except Exception as e:\n print(e)\n break\n\n \ndef reset(reset_id): # PASS\n try:\n servo_write_cmd(int(reset_id), 1, 500, 1000)\n time.sleep(1.1)\n print(\"reset servo\", reset_id, \"complete\")\n except Exception as e:\n print(e)\n\n\ndef reset_all(): # PASS\n print(\"resetting all servos\")\n while True:\n try:\n print(\"resetting servo 1\")\n servo_write_cmd(1, 1, 500, 1000)\n time.sleep(2.1)\n print(\"resetting servo 2\")\n servo_write_cmd(2, 1, 500, 1000)\n time.sleep(2.1)\n print(\"resetting servo 3\")\n servo_write_cmd(3, 1, 500, 1000)\n time.sleep(2.1)\n print(\"resetting servo 4\")\n servo_write_cmd(4, 1, 500, 1000)\n time.sleep(2.1)\n print(\"resetting servo 5\")\n servo_write_cmd(5, 1, 500, 1000)\n time.sleep(2.1)\n print(\"reset completed\")\n break\n except Exception as e:\n print(e)\n break\n\n\ndef spin(spin_id, spin_angle):\n arrival = spin_angle/240*1000\n while True:\n try:\n servo_write_cmd(int(spin_id), 1, int(arrival), 1000)\n time.sleep(2.1)\n print(\"servo\", spin_id, \"arrived at\", spin_angle, \"degree\")\n break\n except Exception as e:\n print(e)\n break\n\n\ndef action1():\n try:\n servo_write_cmd(1, 1, 300, 1000)\n time.sleep(2.1)\n servo_write_cmd(2, 1, 800, 1000)\n time.sleep(2.1)\n servo_write_cmd(3, 1, 600, 1000)\n time.sleep(2.1)\n servo_write_cmd(4, 1, 900, 1000)\n time.sleep(2.1)\n servo_write_cmd(5, 1, 200, 1000)\n time.sleep(2.1)\n print(\"action 1 completed\")\n except Exception as e:\n print(e)\n\n\n##############################################################\n# Main Function\n##############################################################\ndef main(argv):\n try:\n opts, args = getopt.getopt(argv, \"hr:s:a:t:\", [\"rid=\", \"sid=\", \"aid=\", \"tid=\"])\n except getopt.GetoptError as err:\n print(\"Error 2: Arguments Fault ->\", err)\n print_help()\n for opt, arg in opts:\n # Sub Command -h\n if opt == '-h':\n print_help()\n # Sub Command -r\n elif opt in (\"-r\", \"--rid\"):\n reset_id = arg\n if str(1) <= str(reset_id) <= str(5):\n print(\"reset servo\", reset_id, \"to default position\")\n reset(reset_id)\n elif str(reset_id) == 'a':\n print(\"reset all servo\")\n reset_all()\n else:\n print(\"Error 3: Unknown Argument for -r\")\n # Sub Command -s\n elif opt in (\"-s\", \"--sid\"):\n spin_id = arg\n arrival_angle = int(input(\"Enter Arriving Angle (degree) >> \"))\n if 0 < int(arrival_angle) < 240:\n print(\"spinning servo\", spin_id, \"to angle\", arrival_angle)\n spin(spin_id, arrival_angle)\n else:\n print(\"Error 4: Arriving Angle Not Valid\")\n # Sub Command -a\n elif opt in (\"-a\", \"--aid\"):\n action_id = arg\n print(\"moving servos with action\", action_id)\n action1()\n # Sub Command -t\n elif opt in (\"-t\", \"--tid\"):\n test_id = arg\n if str(1) <= str(test_id) <= str(5):\n print(\"testing servo\", test_id)\n test(test_id)\n elif str(test_id) == 'a':\n print(\"test all servos\")\n test_all()\n else:\n print(\"Error 5: Unknown Argument for -t\")\n\n\n##############################################################\n# Main Function Runner\n##############################################################\nif __name__ == \"__main__\":\n if len(sys.argv[1:]) == 0:\n print(\"Error 1: Not Enough Argument\")\n print_help()\n else:\n main(sys.argv[1:])\n","sub_path":"Arm/raspi/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":7202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"161574473","text":"from setuptools import setup, find_packages\n\nprefix = '/'\nshare_dir = 'usr/share/swiftstory/'\n\ndata_files = list()\n\nimport os\n\nfor n in os.walk('usr'):\n if len(n[2]) == 0:\n continue\n\n files = list()\n for f in n[2]:\n files.append(n[0] + '/' + f)\n\n data_files.append((prefix + n[0] + '/', files))\n\nprint(data_files)\n\nsetup(\n name = 'swiftstory',\n description = \"SwiftStory game: We're not out of the woods yet.\",\n version = '0.1',\n author = 'Olivier Gayot',\n author_email = 'olivier.gayot@sigexec.com',\n packages = find_packages(),\n data_files = data_files,\n entry_points = {\n 'console_scripts': [\n 'swiftstoryd = swiftstory.SwiftStory:main',\n ],\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"73774075","text":"import copy\n\n\ndef BubbleSort(C, n):\n flag = 1\n while flag:\n flag = 0\n for i in range(n-1, 0, -1):\n if int(C[i][1]) < int(C[i - 1][1]):\n C[i], C[i-1] = C[i-1], C[i]\n flag = 1\n return C\n\n\ndef SelectionSort(C, n):\n for i in range(n-1):\n minj = i\n for j in range(i, n):\n if int(C[j][1]) < int(C[minj][1]):\n minj = j\n if minj != i:\n C[i], C[minj] = C[minj], C[i]\n return C\n\n\nn = int(input())\nC = list(input().split())\nC2 = C.copy()\n\nprint(*BubbleSort(C, n), sep=' ')\nprint(\"Stable\")\nprint(*SelectionSort(C2, n), sep=' ')\nif C ==C2:\n print(\"Stable\")\nelse:\n print(\"Not stable\")\n\n","sub_path":"Python_codes/p02261/s487107663.py","file_name":"s487107663.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"599120765","text":"import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom collections import deque\nimport sys\n\n# site argument will be used in the title & also in the name of the chart\n# chartdata must be a list in which each item is a tuple which\n# contains 3 items: confname,num_worker_list,latencies_list\n# ex: chartdata=[\n# (conf1,num_workers_list,conf1_latencies),\n# (conf2,num_workers_list,conf2_latencies), \n# (conf3,num_workers_list,conf3_latencies)\n# ]\n# where conf1 = \"1 Server, 10 container\"\n# num_workers_list = [3,6,9,12,15,18,21]\n# conf1_latencies = [10,15,12,13,11,17,15]\n# Note: chartdata can create chart with atmost 8 configuration\n# as we have only 8 colour to distinguish between \n# different configuration\n\ndef CreateConfChart(site,chartdata):\n colours= deque(['b','g','r','c','m','y','k','w'])\n # change the size of chart using figsize parameter\n fig1 =plt.figure(figsize=(10,5))\n plt.xlabel('number of workers')\n plt.ylabel('latency(s)')\n plt.title('latencies for ' + site)\n max_x = None\n max_y = None\n max_xn = None\n max_yn = None\n line_list = []\n confname_list = []\n\n for data in chartdata:\n confname, num_workers1,latencies= data;\n if len(colours) == 0:\n print >> sys.stderr, \"not enough colour for seperation of line\"\n return False\n max_x = max(num_workers1)\n max_y = max(latencies)\n max_xn = len(num_workers1)\n max_yn = len(latencies)\n fmt = colours.popleft()+'-o'\n line, = plt.plot(num_workers1,latencies, fmt)\n line_list.append(line)\n confname_list.append(confname)\n #set properites for legend\n fp = matplotlib.font_manager.FontProperties(size='xx-small')\n plt.legend( tuple(line_list),tuple(confname_list), loc='best', prop=fp)\n #plt.legend( tuple(line_list),tuple(confname_list),bbox_to_anchor=(0., 1.02, 1., .102), ncol=2,loc=3,mode=\"expand\", borderaxespad=0.)\n #plt.legend( tuple(line_list),tuple(confname_list), prop =fp, loc=3, bbox_to_anchor=(-0.2,0),borderaxespad=0.)\n #plt.xticks((np.arange(0,max_x+10-(max_x%10)+2*((max_x+10-(max_x%10))/max_xn),(max_x+10-(max_x%10))/max_xn)))\n #plt.yticks((np.arange(0,max_y+10-(max_y%10)+2*((max_y+10-(max_y%10))/max_yn),(max_y+10-(max_y%10))/max_yn)))\n plt.savefig(site, format='png') \n plt.close()\n return True\n\n\n\n\n\n\n\n#usage of CreateChart function\nconf1_latencies = [10.53232323543,15,12,13,11,17,15]\nconf2_latencies = [8.242342354,10,6,8,10,14,17]\nconf3_latencies = [9,11,10,12,11,13,9]\nconf4_latencies = [7,6,8,9,4,12,17]\nconf5_latencies = [1,2,4,6,7,5,8]\nconf6_latencies = [3,4,8,6,9,11,10]\nconf7_latencies = [5,7,9,8,10,9,1]\nconf1 = \"1 Server, 10 container\"\nconf2 = \"2 Server, 5 container\"\nconf3 = \"3 Server, 10 container\"\nconf4 = \"4 Server, 5 container\"\nconf5 = \"5 Server, 10 container\"\nconf6 = \"6 Server, 5 container\"\nconf7 = \"7 Server, 10 container\"\nnum_workers_list = [10,30,50,70,90,110,150]\nconf_list=[]\nt1 = (conf1,num_workers_list,conf1_latencies)\nconf_list.append(t1)\nt2 = (conf2,num_workers_list,conf2_latencies)\nconf_list.append(t2)\nCreateConfChart(\"www.google.com\",conf_list)\n","sub_path":"createchart.py","file_name":"createchart.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"360188616","text":"\"\"\"user tokens v2\n\nRevision ID: cfa3888eefed\nRevises: c2a5ff589988\nCreate Date: 2020-01-07 12:55:24.244526\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cfa3888eefed'\ndown_revision = 'c2a5ff589988'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('token', sa.String(length=32), nullable=True))\n op.create_index(op.f('ix_user_token'), 'user', ['token'], unique=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_user_token'), table_name='user')\n op.drop_column('user', 'token')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/cfa3888eefed_user_tokens_v2.py","file_name":"cfa3888eefed_user_tokens_v2.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"136884187","text":"# printing all solution of N queen problem\nfrom itertools import permutations\n\nn = 4\nsol = 0\ncol = range(n)\n\nfor combo in permutations(col):\n if n == len(set(combo[i] + i for i in col)) == len(set(combo[i] - i for i in col)):\n sol += 1\n print(f'Solution {sol} : {combo}')\n print('\\n'.join(' 0 ' * i + ' 1 ' + ' 0 ' * (n-i-1) for i in combo)+ '\\n\\n\\n\\n')\n","sub_path":"Backtracking problems/N_Queen_problem.py","file_name":"N_Queen_problem.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"157780945","text":"#Houdini Wedger 2.0 \n#Author : Timucin OZGER \n#Date : 23.09.2018\n\n# Importing all needed modules\nimport multiprocessing\nfrom multiprocessing.pool import ThreadPool\nimport time, timeit, os , subprocess, resource, threading, sys\nfrom multiprocessing import Process\n\n# Starting timer for Parent measurement\nstart_time = timeit.default_timer()\n\n#Loads Variables from cmd.txt file\ncmdFile = sys.argv[1]\nlines = open(cmdFile).read().split('\\n')\n\n#Arguements Needed to run the script \n#lines[0] /home/tricecold/Work/tempHoudini/Fire.hiplc ***File To Run\n#lines[1] 10 ***Batch Size\n#lines[2] 2 ***Max SImultanious Task Limit\n#lines[3] 1 ***Is it a Sim\n#lines[4] 0 ***Make Daily (Not Implemented)\n#lines[5] /obj/pyro_import/FileCache_2.01/Wedge_Iterate ***Changes Linked Value in Hython Session\n#lines[6] /obj/pyro_import/FileCache_2.01/rop/cache ***Cache Node\n#lines[7] /obj/pyro_import/FileCache_2.01/rop/cache/f ***Cache Frames Tuple\n\n#My Variables\nhou.hipFile.load(lines[0]) # loads the file\nwedger = hou.parm(lines[5])\ncache = hou.node(lines[6])\nflipbook = hou.node(lines[10])\ntotal_tasks = int(lines[1]) # sets the task amount\nmax_number_processes = int(lines[2]) # defines the batch size\nFileRange = int(abs(hou.evalParmTuple(lines[7])[0] - hou.evalParmTuple(lines[7])[1]))\nisSim = int(lines[3]) # simulate or cache flag\nmakeDaily = int(lines[4]) # make daily from a camera\n\n#Split Frames for Wedging Non Simulation\ndef split_seq(seq, size):\n newseq = []\n splitsize = 1.0/size*len(seq)\n for i in range(size):\n newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])\n return newseq\n\ntaskList = split_seq(range(FileRange), total_tasks)\n\n#Updates the wedge Value and runs the rop as simulation\ndef simRops(wedge=total_tasks):\n wedger.set(wedge)\n time.sleep(0.1)\n cache.render(verbose=True,)\n\n#Updates the wedge Value and runs the rop in splitted frame ranges \ndef cacheRops(wedge=total_tasks):\n startFrame = taskList[wedge][0]\n endFrame = taskList[wedge][-1]\n hou.parmTuple(lines[7])[0].set(startFrame)\n hou.parmTuple(lines[7])[1].set(endFrame)\n time.sleep(0.1)\n cache.render(verbose=True,)\n\n#Makes a Flipbooks from Sequence\ndef dailyHoudini(wedge=total_tasks):\n wedger.set(wedge)\n daily = os.path.dirname(hou.evalParm(lines[8])) + \"/\"\n videos = lines[11]\n if not os.path.exists(videos):\n os.makedirs(videos)\n time.sleep(0.1)\n flipbook.render(verbose=True,)\n sframe = int(hou.evalParmTuple(lines[9])[0])\n mp4 = \"ffmpeg -start_number 0\" + str(sframe) + \" -framerate 25 -i \" + daily + \"%04d.jpg -c:v libx264 -vf \\\"pad=ceil(iw/2)*2:ceil(ih/2)*2\\\" -pix_fmt yuv420p \" + videos + str(wedge) + \".mp4\"\n p = subprocess.call(mp4,shell=True)\n\n#Prints memory Usage\ndef current_mem_usage():\n return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.\n\n#Multiprocess Functions Here \nif __name__ == '__main__':\n \n pool = multiprocessing.Pool(max_number_processes) #Defines the Batch Size\n \n if(isSim == 1):\n for wedge in range(0,total_tasks):\n pool.apply_async(simRops,args=(wedge,)) #Runs an Instance with each adjusted wedge Value\n \n if(isSim == 0):\n for wedge in range(0,total_tasks):\n pool.apply_async(cacheRops,args=(wedge,)) #Runs an Instance with each adjusted wedge Value\n\n if(makeDaily == 1):\n for wedge in range(0,total_tasks):\n pool.apply_async(dailyHoudini,args=(wedge,)) #Runs an Instance with each adjusted wedge Value\n\n \n pool.close() # After all threads started we close the pool\n pool.join() # And wait until all threads are done\n \nprint(\"Parent: this Process ran %s seconds\" % str(timeit.default_timer() - start_time))\n","sub_path":"hythonWedger.py","file_name":"hythonWedger.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"498052015","text":"#!/usr/bin/env python\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom std_msgs.msg import String\n\nback=2;\nspeed=0;\n\ndef talker():\n # Starts a new node\n velocity_publisher = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)\n vel_msg = Twist()\n global back;\n global speed;\n vel_msg.linear.z = 0\n vel_msg.angular.y = 0\n vel_msg.angular.x = 0\n vel_msg.angular.z = 0\n i=0\n rate = rospy.Rate(10)\n while not rospy.is_shutdown():\n if i<20 and back==0:\n i=i+1\n move(vel_msg,-speed)\n elif i==20 and back==0:\n back=1\n elif back==1 and i>0:\n move(vel_msg,speed)\n i=i-1\n else :\n move(vel_msg,0)\n back=2;\n\n velocity_publisher.publish(vel_msg)\n rate.sleep()\n\n\ndef reaction(data):\n global back;\n global speed;\n if back==2:\n back=0;\n speed=float(data.data);\n \n \ndef move(vel_msg,i):\n vel_msg.linear.x = i\n \n \ndef comp():\n rospy.init_node('robot_comportement', anonymous=True)\n rospy.Subscriber('claques', String, reaction)\n talker()\n \nif __name__ == '__main__':\n try:\n #Testing our function\n comp()\n except rospy.ROSInterruptException: pass\n","sub_path":"scripts/detectionprimaire.py","file_name":"detectionprimaire.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"264348273","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom denorm import denorms\n\ndef denormalized(DBField,*args,**kwargs):\n \"\"\"\n Turns a callable into model field, analogous to python's ``@property`` decorator.\n The callable will be used to compute the value of the field every time the model\n gets saved.\n If the callable has dependency information attached to it the fields value will\n also be recomputed if the dependencies require it.\n\n **Arguments:**\n\n DBField (required)\n The type of field you want to use to save the data.\n Note that you have to use the field class and not an instance\n of it.\n\n \\*args, \\*\\*kwargs:\n Those will be passed unaltered into the constructor of ``DBField``\n once it gets actually created.\n \"\"\"\n\n class DenormDBField(DBField):\n\n \"\"\"\n Special subclass of the given DBField type, with a few extra additions.\n \"\"\"\n\n def contribute_to_class(self,cls,name,*args,**kwargs):\n self.denorm.model = cls\n self.denorm.fieldname = name\n self.field_args = (args, kwargs)\n models.signals.class_prepared.connect(self.denorm.setup,sender=cls)\n DBField.contribute_to_class(self,cls,name,*args,**kwargs)\n\n def pre_save(self,model_instance,add):\n \"\"\"\n Updates the value of the denormalized field before it gets saved.\n \"\"\"\n value = self.denorm.func(model_instance)\n setattr(model_instance, self.attname, value)\n return value\n\n def south_field_definition(self):\n \"\"\"\n the old way of telling south how this field should be\n inserted into migrations, this will be removed soon\n \"\"\"\n import warnings\n warnings.warn(\"south_field_definition will be deprecated, you should really update your south version.\",DeprecationWarning)\n if DBField.__module__.startswith(\"django.db.models.fields\"):\n arglist = [repr(x) for x in args]\n kwlist = [\"%s=%r\" % (x, y) for x, y in kwargs.items()]\n return \"%s(%s)\" % (\n DBField.__name__,\n \", \".join(arglist + kwlist)\n )\n\n def south_field_triple(self):\n \"\"\"\n Because this field will be defined as a decorator, give\n South hints on how to recreate it for database use.\n \"\"\"\n if DBField.__module__.startswith(\"django.db.models.fields\"):\n return (\n '.'.join(('models',DBField.__name__)),\n [repr(x) for x in args],\n kwargs,\n )\n\n def deco(func):\n denorm = denorms.CallbackDenorm()\n denorm.func = func\n kwargs[\"blank\"] = True\n kwargs[\"null\"] = True\n dbfield = DenormDBField(*args,**kwargs)\n dbfield.denorm = denorm\n return dbfield\n return deco\n\nclass CountField(models.PositiveIntegerField):\n \"\"\"\n A ``PositiveIntegerField`` that stores the number of rows\n related to this model instance through the specified manager.\n The value will be incrementally updated when related objects\n are added and removed.\n\n **Arguments:**\n\n manager_name:\n The name of the related manager to be counted.\n\n Any additional arguments are passed on to the contructor of\n PositiveIntegerField.\n \"\"\"\n def __init__(self,manager_name,**kwargs):\n self.denorm = denorms.CountDenorm()\n self.denorm.manager_name = manager_name\n self.kwargs = kwargs\n kwargs['default'] = 0\n super(CountField,self).__init__(**kwargs)\n\n def contribute_to_class(self,cls,name,*args,**kwargs):\n self.denorm.model = cls\n self.denorm.fieldname = name\n models.signals.class_prepared.connect(self.denorm.setup)\n super(CountField,self).contribute_to_class(cls,name,*args,**kwargs)\n\n def south_field_triple(self):\n return (\n '.'.join(('models',models.PositiveIntegerField.__name__)),\n [],\n self.kwargs,\n )\n\n def pre_save(self,model_instance,add):\n \"\"\"\n Makes sure we never overwrite the count with an\n outdated value.\n This is necessary because if the count was changed by\n a trigger after this model instance was created the value\n we would write has not been updated.\n \"\"\"\n if add:\n # if this is a new instance there can't be any related objects yet\n value = 0\n else:\n # if we're updating, get the most recent value from the DB\n value = self.denorm.model.objects.filter(\n pk=model_instance.pk,\n ).values_list(\n self.attname,flat=True,\n )[0]\n\n setattr(model_instance, self.attname, value)\n return value\n","sub_path":"denorm/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":4920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"218080311","text":"class User:\n\tdef __init__(self, cardID, UCMID):\n\t\tself.cardID = cardID\n\t\tself.UCMID = UCMID\n\t\tself.name = \"\"\n\t\tself.status = 0 #user status 0 = normal user, 1 = super user\n\t\tself.lockerCount = 0\n\n\tdef changeStatus(self, input):\n\t\tself.status = input\n\nclass UserList:\n\tdef __init__(self):\n\t\tself.dataFile = \"backend/user.txt\" #cardID UCMID status lockerCount name\n\t\tself.userList = []\n\t\tself.getUserInfo(self.dataFile)\n\n\tdef getUserInfo(self, fileName):\n\t\topenFile = open(fileName, 'r')\n\t\tself.userList = []\n\t\tfor line in openFile:\n\t\t\tlineSplit = line.split()\n\t\t\tuserTemp = User(lineSplit[0], lineSplit[1])\n\t\t\tself.userList.append(userTemp)\n\t\t\tself.userList[-1].status = int(lineSplit[2])\n\t\t\tself.userList[-1].lockerCount = int(lineSplit[3])\n\t\t\tfor i in lineSplit[4:]:\n\t\t\t\tself.userList[-1].name += (i + \" \")\n\t\t\tself.userList[-1].name = self.userList[-1].name[:-1]\n\t\topenFile.close()\n\t\t\n\tdef writeData(self, fileName):\n\t\topenFile = open(fileName, 'w')\n\t\tfor element in self.userList:\n\t\t\topenFile.write(str(element.cardID) + \" \" + str(element.UCMID) + \" \" + str(element.status) + \" \" + str(element.lockerCount) + \" \" + str(element.name) + \"\\n\")\n\t\topenFile.close()\n\n\tdef display(self):\n\t\tfor element in self.userList:\n\t\t\tstring = \"name: \" + element.name\n\t\t\tstring += \", cardID: \" + element.cardID\n\t\t\tstring += \", UCMID: \" + element.UCMID\n\t\t\tstring += \", status: \" + str(element.status)\n\t\t\tstring += \", lockerCount: \" + str(element.lockerCount)\n\t\t\tprint(string)","sub_path":"backend/User2.py","file_name":"User2.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"313718497","text":"# flake8: noqa\nfrom .base import * # pylint: disable=W0401,W0614\n\nSECRET_KEY = env.str(\"SECRET_KEY\")\n\nINSTALLED_APPS.append(\"django.contrib.postgres\")\n\n# Database\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.postgresql\",\n \"NAME\": env.str(\"POSTGRES_DB\").rstrip(),\n \"USER\": env.str(\"POSTGRES_USER\").rstrip(),\n \"PASSWORD\": env.str(\"POSTGRES_PASSWORD\").rstrip(),\n \"HOST\": env.str(\"POSTGRES_HOST\"),\n \"PORT\": env.str(\"POSTGRES_PORT\"),\n \"ATOMIC_REQUESTS\": True,\n \"CONN_MAX_AGE\": None,\n }\n}\n\n# Static files\nMIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware')\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\n# Security\nSECURE_PROXY_SSL_HEADER = (\"HTTP_X_FORWARDED_PROTO\", \"https\")\nSECURE_HSTS_SECONDS = 31536000\nSECURE_FRAME_DENY = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nSECURE_BROWSER_XSS_FILTER = True\nSESSION_COOKIE_SECURE = True\nX_FRAME_OPTIONS = \"DENY\"\n","sub_path":"config/settings/docker.py","file_name":"docker.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"28192009","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy import stats\nimport scipy.stats as st\nfrom scipy.stats import norm\n# import xgboost as xgb\nfrom sklearn.model_selection import KFold\nfrom IPython.display import HTML, display\nfrom sklearn.manifold import TSNE\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\n\nclass HousePrice(object):\n def explore_data(self):\n df_train = pd.read_csv('train.csv')\n var = 'YearBuilt'\n data = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)\n # data.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\n f,ax = plt.subplots(figsize=(16,8))\n fg = sns.boxplot(x=var,y='SalePrice',data=data)\n fg.axis(ymin=0,ymax=800000)\n plt.xticks(rotation=90)\n plt.show()\n sns.distplot(df_train['SalePrice'])\n plt.show()\n corrmat = df_train.corr()\n f,ax = plt.subplots(figsize=(12,9))\n sns.heatmap(corrmat,vmax=.8,square=True)\n plt.show()\n k = 10 # number of variables for heatmap\n cols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index\n cm = np.corrcoef(df_train[cols].values.T)\n sns.set(font_scale=1.25)\n hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10},\n yticklabels=cols.values, xticklabels=cols.values)\n plt.show()\n sns.set()\n cols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt']\n sns.pairplot(df_train[cols])\n plt.show()\n\n def missing_data(self):\n df_train = pd.read_csv('/Users/hanzhao/PycharmProjects/ml-example/file/data/train.csv')\n total = df_train.isnull().sum().sort_values(ascending=True)\n percent = (df_train.isnull().sum() / df_train.isnull().count()).sort_values(ascending=True)\n missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\n df_train = df_train.drop((missing_data[missing_data['Total'] > 1]).index, 1)\n df_train = df_train.drop(df_train.loc[df_train['Electrical'].isnull()].index)\n self.out_liars(df_train)\n print(df_train.isnull().sum().max())\n\n def out_liars(self, deleted_data):\n \"\"\"TODO handle datas that out liars\"\"\"\n df_train = deleted_data\n # deleting points\n var = df_train.sort_values(by='GrLivArea', ascending=False)[:2]\n df_train = df_train.drop(df_train[df_train['Id'] == 1299].index)\n df_train = df_train.drop(df_train[df_train['Id'] == 524].index)\n self.normality_explore(df_train)\n\n def normality_explore(self, handled_data):\n \"\"\"Normality\n 1.Kurtosis and skewness.\n 2.Normal distribution\n 3.make it close to Normal distribution\n 4.transformate in log()\n \"\"\"\n df_train = handled_data\n df_train['SalePrice'] = np.log(df_train['SalePrice'])\n # sns.distplot(df_train['SalePrice'],fit=norm)\n # fig = plt.figure()\n # res = stats.probplot(df_train['SalePrice'],plot=plt)\n df_train['GrLivArea'] = np.log(df_train['GrLivArea'])\n df_train['HasBsmt'] = pd.Series(len(df_train['TotalBsmtSF']), index=df_train.index)\n df_train['HasBsmt'] = 0\n df_train.loc[df_train['TotalBsmtSF'] > 0, 'HasBsmt'] = 1\n df_train.loc[df_train['HasBsmt'] == 1, 'TotalBsmtSF'] = np.log(df_train['TotalBsmtSF'])\n df_train = pd.get_dummies(df_train)\n\n def price_eda(self):\n pd.options.display.max_rows = 1000\n pd.options.display.max_columns = 20\n\n train = pd.read_csv('/Users/hanzhao/PycharmProjects/ml-example/file/data/train.csv')\n test = pd.read_csv('/Users/hanzhao/PycharmProjects/ml-example/file/data/train.csv')\n\n quantitative = [f for f in train.columns if train.dtypes[f] != 'object']\n quantitative.remove('SalePrice')\n quantitative.remove('Id')\n qualitative = [f for f in train.columns if train.dtypes[f] == 'object']\n\n # missing = train.isnull().sum()\n # missing = missing[missing > 0]\n # missing.sort_values(inplace=True)\n # missing.plot.bar()\n # plt.show()\n\n # y = train['SalePrice']\n # plt.figure(1);plt.title('johnson su')\n # sns.distplot(y,kde=True,fit=st.johnsonsu)\n # plt.figure(2);plt.title('Normal')\n # sns.distplot(y,kde=True,fit=st.norm)\n # plt.figure(3);plt.title('Log Norm')\n # sns.distplot(y,kde=True,fit=st.lognorm)\n # plt.show()\n \"\"\" shapiro, check normality\"\"\"\n # test_normality = lambda x: stats.shapiro(x.fillna(0))[1] < 0.01\n # normal = pd.DataFrame(train[quantitative])\n # normal = normal.apply(test_normality)\n # print(not normal.any())\n # f = pd.melt(train,value_vars=quantitative)\n # g = sns.FacetGrid(f,col=\"variable\",col_wrap=2,sharex=False,sharey=False)\n # g = g.map(sns.distplot,\"value\")\n # plt.show()\n\n\nhp = HousePrice()\nhp.price_eda()","sub_path":"hourse_price/house_price.py","file_name":"house_price.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"109426689","text":"# title.py\n\nimport html\nimport re\n\nfrom bobbit.utils import strip_html\n\n# Metadata\n\nNAME = 'title'\nENABLE = True\nPATTERN = r'.*(?Phttp[^\\s]+$).*'\nUSAGE = '''Usage: \nLooks up title of URL.\nExample:\n > http://www.insidehighered.com/quicktakes/2019/06/24/uc-santa-cruz-removes-catholic-mission-bell\n Title: UC Santa Cruz Removes Catholic Mission Bell\n'''\n\n# Constants\n\nWHITELIST = []\n\n# Command\n\nasync def title(bot, message, url=None):\n if message.channel not in WHITELIST:\n return\n\n async with bot.http_client.get(url) as response:\n try:\n text = (await response.text()).replace('\\n', ' ')\n html_title = re.findall(r']*>([^<]+)', text)[0]\n response = bot.client.format_text(\n '{color}{green}Title{color}: {bold}{title}{bold}',\n title = strip_html(html.unescape(html_title))\n )\n except (IndexError, ValueError):\n return\n\n return message.with_body(response)\n\n# Register\n\ndef register(bot):\n global WHITELIST\n\n config = bot.config.load_module_config('title')\n WHITELIST = config.get('whitelist', WHITELIST)\n\n return (\n ('command', PATTERN, title),\n )\n\n# vim: set sts=4 sw=4 ts=8 expandtab ft=python:\n","sub_path":"src/bobbit/modules/title.py","file_name":"title.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"528989962","text":"from itertools import dropwhile\n\nlst = list(range(0, 10))\n\na = list(map(lambda x: x**2, lst))\nprint(\"map func for 'lst':\", a)\n\nb = list(filter(lambda x: x%2, lst))\nprint(\"filter func for 'lst':\", b)\n\nd = list(dropwhile(lambda x: x<4, lst))\nprint(\"printing 'lst' elements starting from the first one that don't meet the condition:\", d)\n\ny = 4\nz = 4\nc = [(y is z), (z is y), (y != 4), (z == 4)]\nprint(\"are all the elements of 'c' true? -\", all(c))\n\nprint(\"are any of the elements of 'c' true? -\", any(c))\n","sub_path":"homework/jenya_s/builtin_func.py","file_name":"builtin_func.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"357540901","text":"# -*- coding: utf-8 -*-\n#\n# This source file is part of the FabSim software toolkit, which is distributed under the BSD 3-Clause license.\n# Please refer to LICENSE for detailed information regarding the licensing.\n#\n\nfrom base.fab import *\nimport os\n\n# Add local script, blackbox and template path.\nadd_local_paths(\"FabUQCampaign\")\n\n@task\ndef run_UQ_sample(config,**args):\n \"\"\"Submit a UQ sample job to the remote queue.\n The job results will be stored with a name pattern as defined in the environment,\n e.g. cylinder-abcd1234-legion-256\n config : config directory to use to define input files, e.g. config=cylinder\n Keyword arguments:\n cores : number of compute cores to request\n images : number of images to take\n steering : steering session i.d.\n wall_time : wall-time job limit\n memory : memory per node\n \"\"\"\n update_environment(args)\n with_config(config)\n execute(put_configs,config)\n job(dict(script='run_UQ_sample', job_wall_time='0:15:0', memory='2G'),args)\n\n@task\ndef uq_ensemble(config=\"dummy_test\", script=\"ERROR: PARAMETER script SHOULD BE DEFINED FOR TASK UQ_ENSEMBLE\",**args):\n \"\"\"\n Submits an ensemble of EasyVVUQ jobs.\n One job is run for each file in /dummy_test/SWEEP.\n \"\"\"\n \n path_to_config = find_config_file_path(config)\n sweep_dir = path_to_config + \"/SWEEP\"\n env.script = script\n\n run_ensemble(config, sweep_dir, **args)\n\n#@task\n#def uq_ensemble_ocean(config=\"dummy_test\",**args):\n# \"\"\"\n# Submits an ocean_2D ensemble.\n# \"\"\"\n# uq_ensemble(config, 'ocean', **args)\n\n#@task\n#def uq_ensemble_ade(config=\"dummy_test\",**args):\n# \"\"\"\n# Submits an advection_diffusion ensemble.\n# \"\"\"\n# uq_ensemble(config, 'ade', **args)\n\n@task\ndef run_uq_ensemble(config, campaign_dir, script_name, **args):\n \"\"\"\n Generic subsmission of samples\n \"\"\"\n\n campaign2ensemble(config, campaign_dir=campaign_dir)\n uq_ensemble(config, script_name)\n# fetch_results()\n#\n# #loop through all result dirs to find result dir of sim_ID\n# dirs = os.listdir(env.local_results)\n# for dir_i in dirs:\n# if config in dir_i:\n# break\n#\n# print('Copying results from', env.local_results + '/' + dir_i + 'to' + campaign_dir)\n# ensemble2campaign(env.local_results + '/' + dir_i, campaign_dir, **args)\n\n@task\ndef get_uq_samples(config, campaign_dir, **args):\n \"\"\"\n Fetches sample output from host, and copies results to EasyVVUQ work directory\n \"\"\"\n \n fetch_results()\n\n #loop through all result dirs to find result dir of sim_ID\n found = False\n dirs = os.listdir(env.local_results)\n for dir_i in dirs:\n if config in dir_i:\n found = True\n break\n\n if found:\n print('Copying results from', env.local_results + '/' + dir_i + 'to' + campaign_dir)\n ensemble2campaign(env.local_results + '/' + dir_i, campaign_dir, **args)\n else:\n print('Campaign dir not found')","sub_path":"FabUQCampaign.py","file_name":"FabUQCampaign.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"77903810","text":"from __future__ import with_statement\nfrom input import main\nimport copy\nimport unittest\ndef sort_Array(a,b):\n i=0\n j=0\n mid=0\n mid1 = 0\n for i in range(0,len(a)-1):\n for j in range(i+1,len(a)):\n if a[j] < a[i]:\n mid = a[i]\n a[i] = a[j]\n a[j] = mid\n mid1 = b[i]\n b[i] = b[j]\n b[j] = mid1\ndef checkValid(a):\n for i in range(0,len(a)-1):\n if i%2:\n if a[i] > a[i+1]:\n raise Exception(\"wrong input\")\ndef getArrayFromString(s):\n xau = []\n i = 0\n for letter in s:\n if letter == '[':\n start = i+1\n elif letter == ';':\n end = i \n start1 = i + 1\n if start < end:\n xau.append(s[start:end])\n elif letter == ']':\n end1 = i\n if start1 < end1:\n xau.append(s[start1:end1])\n i=i+1\n if i == len(s):\n break\n xau = map(float,xau)\n min_list = []\n max_list = []\n for k in range(0,len(xau)):\n if not k%2:\n min_list.append(xau[k])\n else:\n max_list.append(xau[k] )\n sort_Array(min_list,max_list)\n for t in range(0,len(xau)/2):\n xau[2*t] = min_list[t]\n xau[2*t+1]= max_list[t]\n checkValid(xau)\n \n xau_get_mid = []\n length = len(xau)/2\n for j in range(0, length):\n mid_value = (xau[2*j] + xau[2*j+1]) / 2\n mid = round(mid_value,0)\n xau_get_mid.append(mid)\n return xau_get_mid\n \ndef concat(a,b):\n length = len(a)\n c = copy.deepcopy(a)\n if(length != 0):\n for i in range(0,len(b) - 1):\n c = c + copy.deepcopy(a)\n \n for j in range(0,len(b)):\n for k in range(j*length,(j+1)*length):\n c[k].append(b[j])\n return c \n \ndef process():\n with open('input.py') as file:\n data = file.readlines()\n#File is now closed\n stringList = []\n flag = 0\n for line in data:\n line = line.strip()\n if flag == 1 and line != \"'''\":\n stringList.append(line)\n \n if line == \"'''\":\n flag = flag + 1\n if flag == 2:\n break\n\n endList = [[]]\n for i in range(0,len(stringList)):\n array = getArrayFromString(stringList[i])\n if i == 0:\n endList[0].append(array[0])\n for j in range(1,len(array)):\n endList.append([])\n endList[j].append(array[j])\n \n else:\n \n endList = copy.deepcopy(concat(endList,array)) \n return endList \nclass TestSequense(unittest.TestCase):\n pass\ndef test_generator(a, b):\n def test(self):\n self.assertEqual(a,b)\n return test\nendList = process()\nif __name__ == '__main__':\n for t in endList:\n test_name = 'test_%s' % t\n test = test_generator(main(*t), \"\")\n setattr(TestSequense, test_name, test)\n unittest.main()\n \n \n \n ","sub_path":"test_generation/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"650513815","text":"# -*-coding:utf-8 -*-\r\nfrom flask import (Flask, flash,request, make_response as response, abort, redirect,url_for,render_template as render, session,escape,g,Blueprint)\r\n\r\nfrom werkzeug.security import check_password_hash,generate_password_hash\r\nfrom werkzeug.utils import secure_filename\r\n\r\nimport pymongo\r\nfrom bson.objectid import ObjectId\r\nimport functools\r\nimport secrets\r\nimport json\r\n\r\nbp = Blueprint('account', __name__, url_prefix='/account')\r\n\r\nfrom app import mezzanine_treatment\r\n\r\ndef login_guard(view):\r\n\t@functools.wraps(view)\r\n\tdef wrapped_view(**kwargs):\r\n\t\tif g.user is None:\r\n\t\t\treturn redirect(url_for('security.login'))\r\n\r\n\t\treturn view(**kwargs)\r\n\r\n\treturn wrapped_view\r\n\r\n\r\n\r\n@bp.route(\"/channels\", methods=('GET',))\r\n@login_guard\r\ndef my_channels(slug=None):\r\n\r\n\tclient = pymongo.MongoClient()\r\n\tdb = client.shortz_vod\r\n\t\r\n\r\n\tchannels = db.channel.aggregate([\r\n\t\t{\"$match\":{\r\n\t\t\t\"user_id\":g.user['_id']\r\n\t\t}},\r\n\t\t{\"$lookup\":{\r\n\t\t\t\"from\":\"movie\",\r\n\t\t\t\"let\":{\"localField\":\"$_id\"},\r\n\t\t\t\"pipeline\":[\r\n\t\t\t\t{\"$match\":{ \r\n\t\t\t\t\t\"$expr\":{ \r\n\t\t\t\t\t\t\"$and\":[\r\n \t{ \"$eq\": [ \"$channel_id\", \"$$localField\" ] },\r\n \t]\r\n }\r\n }},\r\n\t\t\t\t{ \"$project\": { \"_id\": 0, \"user_id\":0, \"channel_id\":0 } },\r\n\t\t\t\t{\"$sort\":{\"_id\":-1}},\r\n\t\t\t\t{\"$limit\":1},\r\n\t\t\t],\r\n\t\t\t\"as\":\"trailer\"\r\n\t\t}},\r\n\t\t{ \"$project\": { \"user_id\": 0 } },\r\n\t\t{ \"$addFields\": { \"trailer\": {\"$arrayElemAt\":[\"$trailer\",0]} } },\r\n\t\t{\"$sort\":{\"_id\":-1}},\r\n\t\t{\"$limit\":20}\r\n\t])\r\n\r\n\tdata:dict = {\r\n\t\t\"channels\":channels\r\n\t}\r\n\treturn render(\"account/channel.html\", data=data)\r\n\r\n\r\n@bp.route(\"/channels/create\", methods=('POST',))\r\n@login_guard\r\ndef create(slug=None):\r\n\timport hashlib\r\n\r\n\tclient = pymongo.MongoClient()\r\n\tdb = client.shortz_vod\r\n\r\n\tclient = pymongo.MongoClient()\r\n\tdb = client.shortz_vod\r\n\tmax_file_size = 100*1024*1024\r\n\r\n\tf = request.files['file']\r\n\r\n\tresult = {\"status\":False}\r\n\r\n\tif f.mimetype != \"application/x-zip-compressed\":\r\n\t\tresult['log'] = \"Veuillez utiliser un fichier zip {} n'est pas un fichier valide\".format(escape(f.filename))\r\n\telse:\r\n\t\tname = secure_filename(f.filename)\r\n\t\tfilename = 'ftp/{}-{}.zip'.format(g.user['_id'],secrets.token_urlsafe(20).lower())\r\n\r\n\t\tf.save(filename)\r\n\t\tf.seek(0,2)\r\n\t\tfile_length = f.tell()\r\n\t\tif file_length > max_file_size:\r\n\t\t\tresult['log'] = \"Taille limite pour l'upload est de {}Mo par fichier\".format((max_file_size//1024)//1024)\r\n\t\telse:\r\n\t\t\ttry:\r\n\t\t\t\tmezzanine_treatment(filename)\r\n\t\t\t\tresult['log'] = \"votre chiane a été creeé avec succès\"\r\n\t\t\t\tresult['status'] = True\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tresult[\"log\"] = str(e)\r\n\r\n\r\n\tr = response(json.dumps(result))\r\n\tr.headers[\"content-type\"] = \"application/json\"\r\n\treturn r,200\t\r\n\r\n\r\n\r\n\r\n\r\n@bp.route(\"/historic\", methods=('GET',))\r\n@login_guard\r\ndef my_historic():\r\n\treturn render(\"account/historic.html\")\r\n\r\n\r\n@login_guard\r\n@bp.route(\"/settings\", methods=('GET',))\r\n@login_guard\r\ndef my_settings():\r\n\treturn render(\"account/setting.html\")\r\n\r\n","sub_path":"account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"360474359","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。\n\n# 说明:\n# 1 ≤ m ≤ n ≤ 链表长度。\n\n# ���例:\n\n# 输入: 1->2->3->4->5->NULL, m = 2, n = 4\n# 输出: 1->4->3->2->5->NULL\n\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def reverseBetween(self, head, m, n):\n \"\"\"\n :type head: ListNode\n :type m: int\n :type n: int\n :rtype: ListNode\n \"\"\"\n left = None\n mid = head\n\n index = 1\n while index != m:\n index += 1\n left = mid\n mid = mid.next\n\n count = n - m + 1\n\n first = True\n foo = None\n\n r_node = None\n\n while count:\n if first:\n first = False\n foo = mid\n\n tmp_r = r_node\n next_node = mid.next\n\n r_node = mid\n r_node.next = tmp_r\n mid = next_node\n\n count -= 1\n\n if mid:\n right = mid\n foo.next = right\n\n if left:\n left.next = r_node\n return head\n\n else:\n return r_node\n\n\nif __name__ == '__main__':\n from utils import list_to_node, node_to_list\n s = Solution()\n\n # num_list = [1, 2, 3, 4, 5]\n # num_list = [5]\n # num_list = [3, 5]\n num_list = [1, 2, 3]\n\n head = list_to_node(num_list)\n\n # result = s.reverseBetween(head, 2, 4)\n # result = s.reverseBetween(head, 1, 1)\n # result = s.reverseBetween(head, 1, 2)\n result = s.reverseBetween(head, 3, 3)\n\n print(node_to_list(result))\n","sub_path":"leetcode/92.py","file_name":"92.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"181081712","text":"from django.shortcuts import render\nfrom .documents import ProductDocument\nfrom blog.models import Product\n\n# Create your views here.\ndef search(request):\n q = request.GET.get('q')\n if q:\n products = ProductDocument.search().query('match', title=q)\n else:\n products=''\n\n return render(request, 'search/search.html', {'products':products})","sub_path":"product_category/ElasticsearchWithDjango/project1/search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"598322887","text":"# @date 2019-01-19\n# @author Frederic SCHERMA\n# @license Copyright (c) 2019 Dream Overflow\n# Bitcoin Alpha strategy, sub-strategy A.\n\nimport numpy as np\n\nfrom terminal.terminal import Terminal\n\nfrom strategy.indicator import utils\nfrom strategy.strategysignal import StrategySignal\nfrom monitor.streamable import StreamMemberFloatSerie, StreamMemberSerie, StreamMemberFloatBarSerie, StreamMemberOhlcSerie\n\nfrom .bcasub import BitcoinAlphaStrategySub\n\nimport logging\nlogger = logging.getLogger('siis.strategy.cryptoalpha')\n\n\nclass BitcoinAlphaStrategySubA(BitcoinAlphaStrategySub):\n \"\"\"\n Bitcoin Alpha strategy, sub-strategy A.\n \"\"\"\n\n def __init__(self, strategy_trader, params):\n super().__init__(strategy_trader, params)\n\n if 'scores' in params:\n # for older method\n self.rsi_score_factor = params['scores']['rsi_factor']\n self.rsi_trend_score_factor = params['scores']['rsi_trend_factor']\n self.sma_ema_cross_score_factor = params['scores']['sma_ema_cross_factor']\n self.ema_vwma_cross_score_factor = params['scores']['ema_vwma_cross_factor']\n self.price_vwma_cross_score_factor = params['scores']['price_vwma_factor']\n self.ema_vwma_score_bonus = params['scores']['ema_vwma_cross_bonus']\n self.rsi_ema_trend_div_score_factor = params['scores']['rsi_ema_trend_div_factor']\n \n self.rsi_low = params['constants']['rsi_low']\n self.rsi_high = params['constants']['rsi_high']\n\n # triangle bottom and top trend lignes (scattered)\n self.triangle_bottom = []\n self.triangle_top = []\n\n self.supports = []\n self.resistances = []\n\n self.last_signal = None\n\n def process(self, timestamp):\n # candles = self.strategy_trader.instrument.last_candles(self.tf, self.depth)\n candles = self.strategy_trader.instrument.candles_from(self.tf, self.next_timestamp - self.depth*self.tf)\n\n if len(candles) < self.depth:\n # not enought samples\n return\n\n last_timestamp = candles[-1].timestamp\n\n prices = self.price.compute(last_timestamp, candles)\n volumes = self.volume.compute(last_timestamp, candles)\n\n signal = self.process4(timestamp, last_timestamp, candles, prices, volumes)\n\n if candles:\n # last processed candle timestamp (from last candle if non consolidated else from the next one)\n self.next_timestamp = candles[-1].timestamp if not candles[-1].ended else candles[-1].timestamp + self.tf\n\n # avoid duplicates signals\n if signal:\n # self.last_signal = signal\n if (self.last_signal and (signal.signal == self.last_signal.signal) and\n (signal.dir == self.last_signal.dir) and\n (signal.base_time() == self.last_signal.base_time())): # or (signal.ts - self.last_signal.ts) < (self.tf * 0.5):\n # same base time avoid multiple entries on the same candle\n signal = None\n else:\n # retains the last valid signal only if valid\n self.last_signal = signal\n\n if self.profiling:\n # store signal data condition when profiling\n signal.add_condition('price', self.price.trace())\n # signal.add_condition('rsi', self.rsi.trace())\n # signal.add_condition('sma', self.sma.trace())\n # signal.add_condition('ema', self.ema.trace())\n # signal.add_condition('stochrsi', self.stochrsi.trace())\n # signal.add_condition('tomdemark', self.tomdemark.trace())\n # signal.add_condition('bollinger', self.bollingerbands.trade())\n\n return signal\n\n def process1(self, timestamp, to_ts, candles, prices, volumes):\n signal = None\n\n # volume sma, increase signal strength when volume increase over its SMA\n volume_sma = utils.MM_n(self.depth-1, self.volume.volumes)\n\n rsi = 0\n rsi_30_70 = 0 # 1 <30, -1 >70\n rsi_40_60 = 0 # 1 if RSI in 40-60\n\n stochrsi = 0\n stochrsi_20_80 = 0 # 1 <20, -1 >80\n stochrsi_40_60 = 0 # 1 if stochRSI in 40-60\n \n volume_signal = 0\n \n ema_sma_cross = 0\n ema_sma_height = 0\n\n if self.rsi:\n self.rsi.compute(to_ts, prices)[-1]\n\n if self.rsi.last < self.rsi_low:\n rsi_30_70 = 1.0\n elif self.rsi.last > self.rsi_high:\n rsi_30_70 = -1.0\n\n if self.rsi.last > 0.4 and self.rsi.last < 0.6:\n rsi_40_60 = 1\n\n if self.stochrsi:\n stochrsi = self.stochrsi.compute(to_ts, prices)[0][-1]\n\n if stochrsi < 0.2:\n stochrsi_20_80 = 1.0\n elif stochrsi > 0.8:\n stochrsi_20_80 = -1.0\n\n if stochrsi > 0.4 and stochrsi < 0.6:\n stochrsi_40_60 = 1\n\n signal = StrategySignal(self.tf, timestamp)\n\n if self.volume.last > volume_sma[-1]:\n volume_signal = 1\n elif self.volume.last < volume_sma[-1]:\n volume_signal = -1\n\n if self.sma and self.ema:\n sma = self.sma.compute(to_ts, prices)[-2:]\n ema = self.ema.compute(to_ts, prices)[-2:]\n\n # ema over sma crossing\n ema_sma_cross = utils.cross((ema[-2], sma[-2]), (ema[-1], sma[-1]))\n\n if ema[-1] > sma[-1]:\n ema_sma_height = 1\n elif ema[-1] < sma[-1]:\n ema_sma_height = -1\n\n if self.tomdemark:\n td = self.tomdemark.compute(to_ts, self.price.timestamp, self.price.high, self.price.low, self.price.close)[-1]\n\n #\n # setup entry\n #\n\n # long entry on sell-setup + rsi oversell\n if (td.c == 2 or td.c == 3) and td.d < 0 and candles[-1].close > candles[-2].close:\n # if rsi < 0.6: # (ema_sma_height > 0 and rsi_40_60 > 0): # or rsi_30_70 < 0: # 1\n if stochrsi_20_80 > 0 or rsi_30_70 > 0:\n signal.signal = StrategySignal.SIGNAL_ENTRY\n signal.dir = 1\n signal.p = candles[-1].close\n signal.sl = td.tdst or candles[-1].low - candles[-1].height\n\n # 1.618 fibo\n # signal.tp = (self.price.max - self.price.min) * 1.618 + self.price.close\n #logger.info(\"> entry long %s c2-c3, c:%s p:%s sl:%s tp:%s\" % (self.tf, td.c, signal.p, signal.sl, signal.tp))\n\n # short entry on buy-setup + rsi overbuy\n elif (td.c > 1 and td.c < 4) and td.d > 0 and candles[-1].close < candles[-2].close:\n if stochrsi_20_80 < 0 or rsi_30_70 < 0:\n signal.signal = StrategySignal.SIGNAL_ENTRY\n signal.dir = -1\n signal.p = candles[-1].close\n signal.sl = td.tdst or candles[-1].high + candles[-1].height\n\n # 1.618 fibo\n # signal.tp = self.price.close - (self.price.max - self.price.min) * 1.618\n # logger.info(\"> entry short c2-c3, p:%s sl:%s tp:%s\" % (signal.p, signal.sl, signal.tp))\n\n #\n # invalidation (3-7)\n #\n\n # elif td.c >= 3 and td.c <= 7:\n # # if td.d > 0: # and candles[-1].close < candles[-2].low: \n # if td.d < 0: # and candles[-1].close < candles[-2].low:\n # # short cancelation (excess of volume and ema under sma)\n # pass\n\n # # elif td.d < 0 and candles[-1].close < candles[-2].close:\n # elif td.d > 0: # and candles[-1].close < candles[-2].close:\n # # long cancelation (excess of volume and ema under sma)\n # # if ema_sma_height < 0 or rsi_40_60 > 0:\n # # if stochrsi_20_80 < 0: # and volume_signal > 0:\n # # if ema_sma_height < 0 and volume_signal > 0:\n # # logger.info(\"> rsi_30_70 %s / rsi_40_60 %s / ema_sma_height %s / volume_signal %s\" % (rsi_30_70, rsi_40_60, ema_sma_height, volume_signal))\n # signal.signal = StrategySignal.SIGNAL_EXIT # CANCEL\n # signal.dir = 1\n # signal.p = candles[-1].close\n # logger.info(\"> canceled long entry c2-c3, p:%s\" % (signal.p,))\n\n #\n # setup completed\n #\n\n elif (td.c == 8 and td.p) or td.c == 9:\n if td.d < 0: # and candles[-1].close > candles[-2].close:\n #if stochrsi_20_80 > 1:\n signal.signal = StrategySignal.SIGNAL_EXIT\n signal.dir = 1\n signal.p = candles[-1].close\n # logger.info(\"> Exit long %s c8p-c9 (%s%s)\" % (self.tf, td.c, 'p' if signal.p else ''))\n\n elif td.d > 0: # and candles[-1].close < candles[-2].close:\n # if stochrsi_20_80 < 0:\n signal.signal = StrategySignal.SIGNAL_EXIT\n signal.dir = -1\n signal.p = candles[-1].close\n # logger.info(\"> Exit short %s c8p-c9 (%s%s)\" % (self.tf, td.c, 'p' if signal.p else ''))\n\n #\n # CD entry\n #\n\n if td.cd >= 1 and td.cd <= 3:\n # count-down sell-setup + rsi oversell\n if td.cdd < 0: # and candles[-1].close > candles[-2].high:\n # if rsi_30_70 > 0:\n signal.signal = StrategySignal.SIGNAL_ENTRY\n signal.dir = 1\n signal.p = candles[-1].close\n signal.sl = td.tdst\n\n self.score.add(1.0, 1.0, 'td9-cd')\n logger.info(\"> Entry long %s cd13, sl:%s\" % (self.tf, signal.sl,))\n\n # count-down buy-setup + rsi overbuy\n elif td.cdd > 0: # and candles[-1].close < candles[-2].low:\n signal.signal = StrategySignal.SIGNAL_ENTRY\n signal.dir = -1\n signal.p = candles[-1].close\n logger.info(\"> cancel entry long %s (sell ct13), p:%s\" % (self.tf, signal.p,))\n\n # # if rsi_30_70 < 0:\n # # signal.signal = StrategySignal.SIGNAL_ENTRY\n # # signal.dir = -1\n # # signal.p = candles[-1].close\n # # signal.sl = td.tdst\n\n # # self.score.add(-1.0, 1.0, 'td9-cd')\n # logger.info(\"> entry short cd13\")\n # pass\n\n #\n # CD13 setup\n #\n\n elif td.cd == 13:\n logger.info(td.cd)\n # count-down sell-setup completed\n if td.cdd < 0:\n signal.signal = StrategySignal.SIGNAL_EXIT\n signal.p = candles[-1].close\n signal.dir = 1\n\n logger.info(\"> Exit long cd13\")\n\n # count-down buy-setup completed\n elif td.cdd > 0:\n signal.signal = StrategySignal.SIGNAL_EXIT\n signal.p = candles[-1].close\n signal.dir = -1\n\n logger.info(\"> Exit short cd13\")\n pass\n\n return signal\n\n# def process2(self, timestamp, to_ts, candles, prices, volumes):\n# signal = None\n\n# rsi = []\n# sma = []\n# ema = []\n# vwma = []\n\n# if self.rsi:\n# rsi = self.rsi.compute(to_ts, prices)[-self.depth:]\n\n# if self.sma:\n# sma = self.sma.compute(to_ts, prices)[-self.depth:]\n\n# if self.ema:\n# ema = self.ema.compute(to_ts, prices)[-self.depth:]\n \n# if self.vwma:\n# vwma = self.vwma.compute(to_ts, prices, volumes)[-self.depth:]\n\n# mmt = [] # self.mmt.compute(to_ts, prices)[-self.depth:]\n# macd = [] # self.macd.compute(to_ts, prices)[-self.depth:]\n# stochastic = [] # self.stochastic.compute(to_ts, prices)[-self.depth:]\n\n# if self.bollingerbands:\n# self.bollingerbands.compute(to_ts, prices)\n\n# # if self.triangle and self.bollingerbands:\n# # self.triangle.compute(to_ts, self.bollingerbands.last_bottom, self.bollingerbands.last_top)\n\n# # if self.fibonacci:\n# # last_candles = self.strategy_trader.instrument.last_candles(self.tf, self.depth)\n# # self.fibonacci.compute(to_ts, candles)\n\n# if self.pivotpoint:\n# self.pivotpoint.compute(to_ts, candles)\n# # @todo check price and pivot/sn/rn\n\n# #\n# # keep last supports and resistances\n# #\n\n# if self.fibonacci:\n# # remove previous N last time\n# # @todo a ScatterWindowData(depth) .update(strategy_trader) ... or maybe store a max depth in each indicator and remove .last_xyz\n\n# while self.supports and self.supports[-1][0] >= timestamp - self.depth*self.tf:\n# self.supports.pop(-1)\n\n# while self.resistances and self.resistances[-1][0] >= timestamp - self.depth*self.tf:\n# self.resistances.pop(-1)\n\n# for s in self.fibonacci.lowers:\n# # set with timestamp and price\n# self.supports.append((timestamp+((self.depth-s[0])*self.tf), s[1]))\n\n# for r in self.fibonacci.highers:\n# # set with timestamp and price\n# self.resistances.append((timestamp+((self.depth-r[0])*self.tf), r[1]))\n\n# # remove support/resistances older than n*tf (timestamp in second)\n# while self.supports and (self.supports[0][0] + self.tf*96) < timestamp:\n# self.supports.pop(0)\n\n# while self.resistances and (self.resistances[0][0] + self.tf*96) < timestamp:\n# self.resistances.pop(0)\n\n# #\n# # find fibonacci levels and detect current pattern\n# #\n\n# # @todo\n\n# #\n# # triangle interpretations\n# #\n\n# if self.triangle:\n# # @todo have to remove previous N last time\n# bottoms, tops = self.triangle.triangles()\n\n# for bottom in bottoms:\n# # set with timestamp and price\n# self.triangle_bottom.append((timestamp-(self.depth*self.tf)+(bottom[0]*self.tf), bottom[1]))\n\n# for top in tops:\n# # set with timestamp and price\n# self.triangle_top.append((timestamp-(self.depth*self.tf)+(top[0]*self.tf), top[1]))\n\n# # remove triangle bottom/top older than 24h (timestamp in second)\n# while self.triangle_bottom and (self.triangle_bottom[0][0] + 60*60*24) < timestamp:\n# self.triangle_bottom.pop(0)\n\n# while self.triangle_top and (self.triangle_top[0][0] + 60*60*24) < timestamp:\n# self.triangle_top.pop(0)\n\n# #\n# # analysis of the results and scorify\n# #\n\n# rsi_ema_div = False\n\n# if len(rsi):\n# # trend of the rsi\n# rsi_trend = utils.trend_extremum(rsi)\n\n# # 30/70 @todo use Comparator, cross + strength by distance\n# if rsi[-1] < self.rsi_low:\n# rsi_score = (self.rsi_low-rsi[-1]) # ++\n# elif rsi[-1] > self.rsi_high:\n# rsi_score = (self.rsi_high-rsi[-1])\n# else:\n# rsi_score = 0\n\n# self.score.add(rsi_score*100, self.rsi_score_factor)\n\n# # if trend > 0.33 score it else ignore\n# #if abs(rsi_trend) > 0.33:\n# self.score.add(rsi_trend, self.rsi_trend_score_factor)\n\n# if self.bollingerbands and self.rsi:\n# self.bollingerbands.compute(to_ts, prices)\n\n# volatility = prices[-1] - ((self.bollingerbands.last_top - self.bollingerbands.last_ma) * prices[-1]) / 100.0\n# self.score.add(1.0, -volatility*rsi[-1])\n\n# if len(ema):\n# # ema trend\n# ema_trend = utils.trend_extremum(ema)\n\n# if len(rsi) and len(ema):\n# # rsi trend and ema divergence\n# if utils.divergence(rsi_trend, ema_trend):\n# rsi_ema_div = True\n\n# if len(sma) and len(ema):\n# # sma/ema distance and crossing \n# sma_ema_cross_score_factor = self.sma_ema_cross_score_factor[1] if rsi_ema_div else self.sma_ema_cross_score_factor[0]\n\n# # crossing\n# if sma_ema_cross_score_factor != 0:\n# sma_ema_score = utils.cross((sma[-2], ema[-2]), (sma[-1], ema[-1]))\n# self.score.add(sma_ema_score, sma_ema_cross_score_factor)\n\n# if len(ema) and len(vwma):\n# # ema/vwma distance and crossing \n# ema_vwma_cross_score_factor = self.ema_vwma_cross_score_factor[1] if rsi_ema_div else self.ema_vwma_cross_score_factor[0]\n\n# if ema_vwma_cross_score_factor != 0:\n# # ema-vwma normalized distance\n# ema_vwma_dst_score = (ema[-1]-vwma[-1]) / prices[-1]\n# self.score.add(ema_vwma_dst_score, ema_vwma_cross_score_factor)\n\n# # @todo ema cross vwma using Comparator\n# # ema_vwma_cross_score = utils.cross((ema[-2], vwma[-2]), (ema[-1], vwma[-1]))\n# # self.score.add(ema_vwma_cross_score, ema_vwma_cross_score_factor)\n\n# # ema-vwma + price-vwma give a bonus (@todo is it usefull ?)\n# if self.ema_vwma_score_bonus != 0:\n# if ema[-1] > vwma[-1] and prices[-1] > vwma[-1]:\n# self.score.add(1, self.ema_vwma_score_bonus)\n# elif ema[-1] < vwma[-1] and prices[-1] < vwma[-1]:\n# self.score.add(-1, self.ema_vwma_score_bonus)\n\n# if len(vwma):\n# # vwma/price distance and crossing\n# # price-vwma normalized distance\n# if self.price_vwma_cross_score_factor != 0:\n# price_vwma_score = (prices[-1]-vwma[-1]) / prices[-1]\n# self.score.add(price_vwma_score, self.price_vwma_cross_score_factor)\n\n# if rsi_ema_div:\n# rsi_ema_trend_div_score_factor = self.rsi_ema_trend_div_score_factor[1] if rsi_ema_div else self.rsi_ema_trend_div_score_factor[0]\n# # or simply neg the factor\n# # self.score.scale(0.2) # score is weaken (good result)\n\n# if rsi_ema_trend_div_score_factor != 0:\n# self.score.add(rsi_trend-ema_trend, rsi_ema_trend_div_score_factor)\n\n# # volume sma, increase signal strength when volume increase over its SMA\n# volume_sma = utils.MM_n(self.depth-1, self.volume.volumes)\n\n# if self.volume.last > volume_sma[-1]:\n# self.score.scale(2.0)\n\n def process4(self, timestamp, last_timestamp, candles, prices, volumes):\n signal = None\n\n # volume sma, increase signal strength when volume increase over its SMA\n volume_sma = utils.MM_n(self.depth-1, self.volume.volumes)\n\n rsi_30_70 = 0 # 1 <30, -1 >70\n rsi_40_60 = 0 # 1 if RSI in 40-60\n rsi_trend = 0\n\n stochrsi_20_80 = 0 # 1 <20, -1 >80\n stochrsi_40_60 = 0 # 1 if stochRSI in 40-60\n \n volume_signal = 0\n \n ema_sma_cross = 0\n ema_sma_height = 0\n\n if self.tf == 4*60*60:\n self.sma200.compute(last_timestamp, prices)\n self.sma55.compute(last_timestamp, prices)\n\n if self.rsi:\n self.rsi.compute(last_timestamp, prices)\n\n if self.rsi.last < self.rsi_low:\n rsi_30_70 = 1.0\n elif self.rsi.last > self.rsi_high:\n rsi_30_70 = -1.0\n\n if self.rsi.last > 0.4 and self.rsi.last < 0.6:\n rsi_40_60 = 1\n\n rsi_trend = utils.trend_extremum(self.rsi.rsis)\n\n # if self.stochrsi:\n # self.stochrsi.compute(last_timestamp, prices)\n\n # if self.stochrsi.last_k < 0.2:\n # stochrsi_20_80 = 1.0\n # elif self.stochrsi.last_k > 0.8:\n # stochrsi_20_80 = -1.0\n\n # if self.stochrsi.last_k > 0.4 and self.stochrsi.last_k < 0.6:\n # stochrsi_40_60 = 1\n\n # if self.volume_ema:\n # self.volume_ema.compute(last_timestamp, volumes)\n\n # if self.volume.last > self.volume_ema.last:\n # volume_signal = 1\n # elif self.volume.last < self.volume_ema.last:\n # volume_signal = -1\n\n if self.sma and self.ema:\n self.sma.compute(last_timestamp, prices)\n self.ema.compute(last_timestamp, prices)\n\n # ema over sma crossing\n ema_sma_cross = utils.cross((self.ema.prev, self.sma.prev), (self.ema.last, self.sma.last))\n\n if self.ema.last > self.sma.last:\n ema_sma_height = 1\n elif self.ema.last < self.sma.last:\n ema_sma_height = -1\n\n if self.pivotpoint:\n self.pivotpoint.compute(last_timestamp, self.price.open, self.price.high, self.price.low, self.price.close)\n\n if self.bollingerbands:\n self.bollingerbands.compute(last_timestamp, prices)\n\n bb_break = 0\n bb_ma = 0\n\n if prices[-1] > self.bollingerbands.last_top:\n bb_break = 1\n elif prices[-1] < self.bollingerbands.last_bottom:\n bb_break = -1\n\n # if prices[-1] > self.bollingerbands.last_ma:\n # bb_ma = -1\n # elif prices[-1] > self.bollingerbands.last_ma:\n # bb_ma = 1\n\n if self.atr:\n self.atr.compute(last_timestamp, self.price.high, self.price.low, self.price.close)\n\n if self.bbawe:\n bbawe = self.bbawe.compute(last_timestamp, self.price.high, self.price.low, self.price.close)\n\n if self.tomdemark:\n self.tomdemark.compute(last_timestamp, self.price.timestamp, self.price.high, self.price.low, self.price.close)\n\n level1_signal = 0\n\n # if self.ema.last < self.sma.last:\n # # bear trend\n # if self.rsi.last > 0.5: # initial: 0.5\n # level1_signal = -1\n # elif self.rsi.last < 0.2: # initial: 0.2\n # level1_signal = 1\n # else:\n # # bull trend\n # if self.rsi.last > 0.8: # initial: 0.8\n # level1_signal = -1\n # elif self.rsi.last < 0.6: # initial: 0.6\n # level1_signal = 1\n\n # if self.ema.last < self.sma.last:\n # level1_signal = -1\n # else:\n # level1_signal = 1\n\n # if level1_signal > 0 and bb_break <= 0:\n # level1_signal = 0\n\n # elif bb_break > 0 and level1_signal >= 0:\n # level1_signal = 1\n\n # if bb_break > 0:\n # level1_signal = 1\n\n if bbawe > 0:\n signal = StrategySignal(self.tf, timestamp)\n signal.signal = StrategySignal.SIGNAL_ENTRY\n signal.dir = 1\n signal.p = self.price.close[-1]\n\n if self.tomdemark.c.tdst:\n signal.sl = self.tomdemark.c.tdst\n\n if len(self.pivotpoint.resistances[2]):\n signal.tp = np.max(self.pivotpoint.resistances[2])\n\n elif bbawe < 0:\n signal = StrategySignal(self.tf, timestamp)\n signal.signal = StrategySignal.SIGNAL_ENTRY\n signal.dir = -1\n signal.p = self.price.close[-1]\n\n if self.tomdemark.c.tdst:\n signal.sl = self.tomdemark.c.tdst\n\n if len(self.pivotpoint.supports[2]):\n signal.tp = np.min(self.pivotpoint.supports[2])\n\n #\n # setup completed\n #\n\n # sell-setup\n if self.tomdemark.c.c == 9 and self.tomdemark.c.d < 0:\n signal = StrategySignal(self.tf, timestamp)\n signal.signal = StrategySignal.SIGNAL_EXIT\n signal.dir = 1\n signal.p = self.price.close[-1]\n\n # buy-setup\n elif self.tomdemark.c.c == 9 and self.tomdemark.c.d > 0:\n signal = StrategySignal(self.tf, timestamp)\n signal.signal = StrategySignal.SIGNAL_EXIT\n signal.dir = -1\n signal.p = self.price.close[-1]\n\n # if signal and signal.signal == StrategySignal.SIGNAL_ENTRY:\n # # if level1_signal > 0 and len(self.pivotpoint.supports[1]):\n # # # cancel if not below a support (long direction)\n # # if self.price.last >= np.nanmax(self.pivotpoint.supports[1]):\n # # level1_signal = 0\n\n # # if level1_signal < 0 and len(self.pivotpoint.resistances[1]):\n # # # cancel if not above a resistance (short direction)\n # # if self.price.last <= np.nanmin(self.pivotpoint.resistances[1]):\n # # level1_signal = 0\n\n # if level1_signal > 0 and len(self.pivotpoint.supports[1]):\n # # cancel if not below a support (long direction)\n # if self.price.last >= np.nanmax(self.pivotpoint.supports[1]):\n # level1_signal = 0\n # signal = None\n\n # if level1_signal < 0 and len(self.pivotpoint.resistances[1]):\n # # cancel if not below a resistance (short direction)\n # if self.price.last <= np.nanmin(self.pivotpoint.resistances[1]):\n # level1_signal = 0\n # signal = None\n\n return signal\n\n def setup_streamer(self, streamer):\n streamer.add_member(StreamMemberSerie('begin'))\n \n streamer.add_member(StreamMemberOhlcSerie('ohlc'))\n streamer.add_member(StreamMemberFloatSerie('price', 0))\n streamer.add_member(StreamMemberFloatBarSerie('volume', 1))\n\n streamer.add_member(StreamMemberFloatSerie('rsi-low', 2))\n streamer.add_member(StreamMemberFloatSerie('rsi-high', 2))\n streamer.add_member(StreamMemberFloatSerie('rsi', 2))\n\n streamer.add_member(StreamMemberFloatSerie('stochrsi-low', 3))\n streamer.add_member(StreamMemberFloatSerie('stochrsi-high', 3))\n streamer.add_member(StreamMemberFloatSerie('stochrsi-k', 3))\n streamer.add_member(StreamMemberFloatSerie('stochrsi-d', 3))\n\n streamer.add_member(StreamMemberFloatSerie('sma', 0))\n streamer.add_member(StreamMemberFloatSerie('ema', 0))\n streamer.add_member(StreamMemberFloatSerie('hma', 0))\n streamer.add_member(StreamMemberFloatSerie('vwma', 0))\n\n streamer.add_member(StreamMemberFloatSerie('perf', 3))\n\n # bollinger, triangle, pivotpoint, td9, fibonacci...\n\n streamer.add_member(StreamMemberSerie('end'))\n\n streamer.next_timestamp = self.next_timestamp\n\n def stream(self, streamer):\n delta = min(int((self.next_timestamp - streamer.next_timestamp) / self.tf) + 1, len(self.price.prices))\n\n for i in range(-delta, 0, 1):\n ts = self.price.timestamp[i]\n\n streamer.member('begin').update(ts)\n\n streamer.member('ohlc').update((self.price.open[i], self.price.high[i], self.price.low[i], self.price.close[i]), ts)\n\n streamer.member('price').update(self.price.prices[i], ts)\n streamer.member('volume').update(self.volume.volumes[i], ts)\n\n streamer.member('rsi-low').update(self.rsi_low, ts)\n streamer.member('rsi-high').update(self.rsi_high, ts)\n streamer.member('rsi').update(self.rsi.rsis[i], ts)\n\n # streamer.member('stochrsi-low').update(20, ts)\n # streamer.member('stochrsi-high').update(80, ts)\n # streamer.member('stochrsi-k').update(self.stochrsi.stochrsis[i], ts)\n # streamer.member('stochrsi-d').update(self.stochrsi.stochrsis[i], ts)\n\n streamer.member('sma').update(self.sma.smas[i], ts)\n streamer.member('ema').update(self.ema.emas[i], ts)\n # streamer.member('hma').update(self.hma.hmas[i], ts)\n # streamer.member('vwma').update(self.vwma.vwmas[i], ts)\n\n streamer.member('perf').update(self.strategy_trader._stats['perf']*100, ts)\n\n streamer.member('end').update(ts)\n\n # push per frame\n streamer.push()\n\n streamer.next_timestamp = self.next_timestamp\n","sub_path":"strategy/bitcoinalpha/bcasuba.py","file_name":"bcasuba.py","file_ext":"py","file_size_in_byte":28734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"549606221","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as models\n\nclass EncoderCNN(nn.Module):\n def __init__(self, embed_size):\n super(EncoderCNN, self).__init__()\n resnet = models.resnet50(pretrained=True)\n for param in resnet.parameters():\n param.requires_grad_(False)\n \n modules = list(resnet.children())[:-1]\n self.resnet = nn.Sequential(*modules)\n self.embed = nn.Linear(resnet.fc.in_features, embed_size)\n\n def forward(self, images):\n features = self.resnet(images)\n features = features.view(features.size(0), -1)\n features = self.embed(features)\n return features\n \n\nclass DecoderRNN(nn.Module):\n def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):\n super(DecoderRNN, self).__init__()\n self.embed_size = embed_size\n self.hidden_size = hidden_size\n self.vocab_size = vocab_size\n self.num_layers = num_layers\n self.hidden = 0\n # Add embedding layers to embed words\n self.word_embeddings = nn.Embedding(vocab_size, embed_size)\n # Add LSTM layer\n self.lstm = nn.LSTM(embed_size, hidden_size)\n # Add Linear layers to map hidden_size to vocab_size\n self.hidden2tag = nn.Linear(hidden_size, vocab_size)\n \n def forward(self, features, captions):\n # Initialize hidden state each forward step, shape: [num_layers, batch, hidden_size]\n self.hidden = (torch.zeros(self.num_layers, features.shape[0], self.hidden_size).to(\"cuda\" if torch.cuda.is_available() else \"cpu\"), torch.zeros(self.num_layers, features.shape[0], self.hidden_size).to(\"cuda\" if torch.cuda.is_available() else \"cpu\"))\n # Transpose captions shape from [batch, seq_len] to [seq_len, batch]\n captions_transposed = captions.permute(1, 0).contiguous()\n # Words embedding\n embeds = self.word_embeddings(captions_transposed)\n # Joint the features from images with the embedded captions, chape: [seq_len, batch, embed_size] \n inputs = torch.cat([features.view(1, len(features), -1), embeds], 0)\n # Remove the last element: \"\"\n inputs = inputs[:-1]\n # Pass inputs and hidden into LSTM\n lstm_out, self.hidden = self.lstm(inputs, self.hidden)\n # Pass into Linear layer\n tag_space = self.hidden2tag(lstm_out)\n # Softmax scores\n tag_scores = F.log_softmax(tag_space, dim=2)\n # Transpose tag_scores shape from [seq_len, batch, vocab_size] to [batch, seq_len, vocab_size]\n return tag_scores.permute(1, 0, 2).contiguous()\n\n def sample(self, inputs, states=None, max_len=20):\n \" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) \"\n # Initialize hidden state\n hidden = (torch.zeros(self.num_layers, 1, self.hidden_size), torch.zeros(self.num_layers, 1, self.hidden_size))\n # Initialize output list\n output = []\n # The input of each time step to pass into LSTM\n out = inputs\n for i in range(max_len):\n out, hidden = self.lstm(out.view(1, 1, -1), hidden)\n tag = self.hidden2tag(out)\n tag_score = F.log_softmax(tag.view(1, -1))\n # Add the index of max score in the output list\n output.append(torch.max(tag_score, 1)[1])\n # Quit the loop if the output of the model is the end symbol of a sentence\n if output[-1] == 1:\n break\n # Embed the word before passing into LSTM\n out = self.word_embeddings(output[-1])\n return output\n ","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"436391504","text":"\"\"\"web URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom web import *\nfrom web import views\nfrom django.conf.urls import patterns\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', views.loop),\n url(r'^index.html',views.index),\n url(r'^cl.html',views.cl),\n url(r'^hztx.html',views.hztx),\n url(r'^ecduose.html', views.ecduose),\n url(r'^ecduoseht.html', views.ecduoseht),\n url(r'^ecduo.html', views.ecduo),\n url(r'^ecduoht.html', views.ecduoht),\n url(r'^tpsite.html', views.tpsite),\n url(R'^loop.html', views.loop),\n url(r'^accounts/login/$',include(admin.site.urls)),\n]\n#urlpatterns = patterns('web.views',\n # (r'^mob/(\\d*.html)/$', 'year_mob'),\n # )\n\n","sub_path":"web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"184479246","text":"# COMMON\nfrom .base import *\n\nimport dj_database_url\n\nALLOWED_HOSTS = [\".herokuapp.com\"]\n\n\n# Database\n# https://docs.djangoproject.com/en/1.9/ref/settings/#databases\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n\n\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\n\n# Force all request to use SSL\n# ------------------------------------------------------------------------------\n#SECURE_SSL_REDIRECT = True\n#SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n\n\n\n\n\n\n","sub_path":"globalradio/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"318156181","text":"import unittest\nimport mock\nimport server\nfrom protocolObjects import Countdown\n\n\n@mock.patch('twisted.internet.reactor.callLater', lambda t, f: f())\nclass TestGameServer(unittest.TestCase):\n\n def setUp(self):\n self.srv = server.GameServer()\n self.srv.startFactory()\n self.clt = mock.Mock()\n self.clt.send = mock.Mock()\n self.srv.clients = [self.clt]\n\n def get_countdown_calls(self):\n self.srv.countdown()\n calls = self.clt.send.call_args_list\n return [call[0][0] for call in calls[:3]]\n\n def test_countdown_number(self):\n for i, arg in enumerate(self.get_countdown_calls()):\n self.assertTrue(isinstance(arg, Countdown))\n self.assertEquals(arg.number, 3 - i)\n\n def test_countdown_player_id(self):\n for arg in self.get_countdown_calls():\n self.assertEquals(arg.playerId, 0)\n\n def test_countdown_map_size(self):\n for arg in self.get_countdown_calls():\n self.assertEquals(arg.mapSize, self.srv.ms)\n","sub_path":"miners/tests/test_countdown.py","file_name":"test_countdown.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"67275041","text":"import sys\nimport copy\nfrom collections import defaultdict\n\ninputFile = open(sys.argv[2])\narray = inputFile.readlines()\ntmp1,tmp2=array[0].split()\nnumD,numP=int(tmp1),int(tmp2)\nlistP=[] #list of patients\nfor i in range(0,numP):\n\tstr1='Patient-'+str(i+1)\n\tlistP.append(str1)\nlistDS=[]\nlistFind=[]\ntable1,table2,table3,table4,table5,table6,table7,table8,table9,table10,table11={},{},{},{},{},{},{},{},{},{},{} #D-P(D)\nfor i in range(0,numD):\n\ttmp=array[4*i+1]\n\tdis,num,pos=tmp.split()\n\tlistDS.append(dis)\n\ttable1[dis]=float(pos)\n\ttable2[dis]=eval(array[4*i+2])\nfor i in range(0,numD):\n\tlistF=eval(array[4*i+2])\n\ta=eval(array[4*i+3])\n\tb=eval(array[4*i+4])\n\tfor j in range(0,len(listF)):\n\t\tlistFind.append(listF[j])\n\t\ttable3[listF[j]]=float(a[j])\n\t\ttable4[listF[j]]=float(b[j])\n\t\ttable8[listF[j]]=float(float(a[j])/float(b[j]))\n\t\ttable9[listF[j]]=float((1-float(b[j]))/(1-float(a[j])))\n\t\ttable10[listF[j]]=float((1-float(a[j]))/(1-float(b[j])))\n\t\ttable11[listF[j]]=float(float(b[j])/float(a[j]))\n\t\tif float(a[j])>float(b[j]):\n\t\t\ttable6[listF[j]]='T'\n\t\t\ttable7[listF[j]]='F'\n\t\telse:\n\t\t\ttable6[listF[j]]='F'\n\t\t\ttable7[listF[j]]='T'\nfor i in range(0,numP):\n\ttmpList=[]\n\tfor j in range(0,numD):\n\t\ttmpList.append(eval(array[4*numD+1+j+numD*i]))\n\ttable5[listP[i]]=tmpList\ndef func1(D,arr):\n\tPD=table1[D]\n\tarrFind=table2[D] #list of findings\n\tarr1=[]\n\tarr2=[]\n\tfor i in range(0,len(arr)):\n\t\tif arr[i]=='T':\n\t\t\tarr1.append(table3[arrFind[i]]) #cha ru yi ge float \n\t\t\tarr2.append(table4[arrFind[i]])\n\t\telif arr[i]=='F':\n\t\t\tarr1.append(1-table3[arrFind[i]]) \n\t\t\tarr2.append(1-table4[arrFind[i]])\n\tfenzi=PD\n\tfenmu=1-PD\n\tfor x in arr1:\n\t\tfenzi=fenzi*x\n\tfor y in arr2:\n\t\tfenmu=fenmu*y\n\tans=float(1/(1+fenmu/fenzi))\n\treturn \"{0:.4f}\".format(round(ans,4))\n\ndef func2(tmplist):\n\tans={}\n\tfor i in range(0,len(tmplist)):\n\t\tans[listDS[i]]=func1(listDS[i],tmplist[i])\n\treturn ans\n\ndef maxP(table):\n\tfor x in table.values():\n\t\tcount=0\n\t\tfor y in x:\n\t\t\tfor i in range(0,len(y)):\n\t\t\t\tif y[i]=='U':\n\t\t\t\t\ty[i]=table6[listFind[count]]\n\t\t\t\tcount=count+1\n\treturn table\n\ndef minP(table):\n\tfor x in table.values():\n\t\tcount=0\n\t\tfor y in x:\n\t\t\tfor i in range(0,len(y)):\n\t\t\t\tif y[i]=='U':\n\t\t\t\t\ty[i]=table7[listFind[count]]\n\t\t\t\tcount=count+1\n\treturn table\n\ncopy1=copy.deepcopy(table5)\ncopy2=copy.deepcopy(table5)\nmaxTable=maxP(copy1)\nminTable=minP(copy2)\n\ndef findMax(D,list1):\n\tmaxNum=0\n\tans=[]\n\ttempStr=''\n\tflag=''\n\tcheck=0\n\tcheck1=0\n\tlist2=table2[D]\n\tfor i in range(0,len(list1)):\n\t\tif list1[i]=='U':\n\t\t\tcheck=1\n\tif check==0:\n\t\tans.append(\"none\")\n\t\tans.append(\"N\")\n\telse:\n\t\tfor i in range(0,len(list1)):\n\t\t\tif list1[i]=='U':\n\t\t\t\tif table8[list2[i]]!=table10[list2[i]]:\n\t\t\t\t\tcheck1=1\t\t\t\t\t\n\t\t\t\t\tif table8[list2[i]]>table10[list2[i]]:\n\t\t\t\t\t\tcurMax=table8[list2[i]]\n\t\t\t\t\telse:\n\t\t\t\t\t\tcurMax=table10[list2[i]]\n\t\t\t\t\tif curMax>maxNum:\n\t\t\t\t\t\tmaxNum=curMax\n\t\t\t\t\t\ttempStr=list2[i]\n\t\t\t\t\t\tif table8[list2[i]]table10[list2[i]]:\n\t\t\t\t\t\tcurMax=table8[list2[i]]\n\t\t\t\t\telse:\n\t\t\t\t\t\tcurMax=table10[list2[i]]\n\t\t\t\t\tif curMax>maxNum:\n\t\t\t\t\t\tmaxNum=curMax\n\t\t\t\t\t\ttempStr=list2[i]\n\t\t\t\t\t\tif table8[list2[i]] 1:\n os.environ[\"MKL_SERVICE_FORCE_INTEL\"] = \"1\"\n\n\n_BATCH_SIZE = 32\n_WORKERS = 1\n_LR = 1e-3\n\n\nclass CustomDistributedSampler(DistributedSampler):\n def __iter__(self):\n indices = list(range(len(self.dataset))) # type: ignore\n indices = indices[self.rank : self.total_size : self.num_replicas]\n return iter(indices)\n\n\nclass CustomSampler(SequentialSampler):\n def __iter__(self):\n indices = list(range(len(self.data_source)))\n # indices = indices[self.rank:self.total_size:self.num_replicas]\n indices = indices[0 : len(self.data_source) : 2] + indices[1 : len(self.data_source) : 2]\n return iter(indices)\n\n\nclass CounterCallback(Callback):\n def __init__(self):\n super().__init__(CallbackOrder.external, CallbackNode.all, CallbackScope.stage)\n self.counter = 0\n self.counter2 = [0] * 4\n self.counter3 = 0\n\n def on_loader_start(self, runner: \"IRunner\") -> None:\n self.counter = 0\n self.counter2 = [0] * 4\n self.counter3 = 0\n\n def on_batch_end(self, runner: \"IRunner\") -> None:\n self.counter += torch.sum(runner.batch[\"targets\"]).detach().cpu().item()\n preds = torch.argmax(runner.batch[\"logits\"], dim=1).detach().cpu().numpy()\n for i_class in range(runner.batch[\"logits\"].shape[1]):\n self.counter2[i_class] += (preds == i_class).sum()\n self.counter3 += len(runner.batch[\"logits\"])\n\n def on_loader_end(self, runner: \"IRunner\") -> None:\n print(f\"{runner.engine}, {self.counter}, {self.counter2}, {self.counter3}\")\n # assert self.counter == self.required_num, f\"{runner.engine}, {self.counter}\"\n\n\nclass IRunnerMixin(IRunner):\n def __init__(self, logdir):\n super().__init__()\n self._logdir = logdir\n\n def get_loggers(self):\n return {\"console\": ConsoleLogger(), \"csv\": CSVLogger(logdir=self._logdir)}\n\n @property\n def stages(self) -> \"Iterable[str]\":\n return [\"train\"]\n\n def get_stage_len(self, stage: str) -> int:\n return 1\n\n def get_model(self, stage: str):\n # return MnistSimpleNet(out_features=10, normalize=False)\n return TwoBlobsModel()\n\n def get_criterion(self, stage: str):\n return torch.nn.CrossEntropyLoss()\n\n def get_optimizer(self, model, stage: str):\n return torch.optim.SGD(model.parameters(), lr=_LR)\n\n def get_scheduler(self, optimizer, stage: str):\n return None\n\n def get_callbacks(self, stage: str):\n return {\n \"criterion\": CriterionCallback(\n metric_key=\"loss\", input_key=\"logits\", target_key=\"targets\"\n ),\n \"accuracy\": AccuracyCallback(input_key=\"logits\", target_key=\"targets\", topk_args=(1,)),\n \"auc\": AUCCallback(input_key=\"scores\", target_key=\"targets_onehot\"),\n \"classification\": PrecisionRecallF1SupportCallback(\n input_key=\"logits\", target_key=\"targets\", num_classes=4\n ),\n # \"optimizer\": OptimizerCallback(metric_key=\"loss\"),\n # \"checkpoint\": CheckpointCallback(\n # self._logdir, loader_key=\"valid\", metric_key=\"loss\", minimize=True, save_n_best=3\n # ),\n # \"verbose\": TqdmCallback(),\n \"counter\": CounterCallback(),\n }\n\n def handle_batch(self, batch):\n x, y = batch\n logits = self.model(x)\n num_class = logits.shape[1]\n\n self.batch = {\n \"features\": x,\n \"targets\": y.view(-1),\n \"targets_onehot\": F.one_hot(y.view(-1), num_class).to(torch.float32),\n \"logits\": logits,\n \"scores\": torch.sigmoid(logits),\n }\n\n\nclass CustomDeviceRunner(IRunnerMixin, IRunner):\n def get_engine(self):\n return DeviceEngine(\"cuda:0\")\n\n def get_loaders(self, stage: str):\n dataset = TwoBlobsDataset()\n # dataset = MNIST(os.getcwd(), train=False, download=True, transform=ToTensor())\n sampler = CustomSampler(data_source=dataset)\n loader = DataLoader(dataset, batch_size=_BATCH_SIZE, num_workers=_WORKERS, sampler=sampler)\n return {\"valid\": loader}\n\n\nclass CustomDPRunner(IRunnerMixin, IRunner):\n def get_engine(self):\n return DataParallelEngine()\n\n def get_loaders(self, stage: str):\n dataset = TwoBlobsDataset()\n # dataset = MNIST(os.getcwd(), train=False, download=True, transform=ToTensor())\n sampler = CustomSampler(data_source=dataset)\n loader = DataLoader(dataset, batch_size=_BATCH_SIZE, num_workers=_WORKERS, sampler=sampler)\n return {\"valid\": loader}\n\n\nclass CustomDDPRunner(IRunnerMixin, IRunner):\n def get_engine(self):\n return DistributedDataParallelEngine(port=\"22222\")\n\n def get_loaders(self, stage: str):\n dataset = TwoBlobsDataset()\n # dataset = MNIST(os.getcwd(), train=False, download=True, transform=ToTensor())\n sampler = CustomDistributedSampler(dataset=dataset, shuffle=True)\n loader = DataLoader(dataset, batch_size=_BATCH_SIZE, num_workers=_WORKERS, sampler=sampler)\n return {\"valid\": loader}\n\n\nclass MyConfigRunner(SupervisedConfigRunner):\n _dataset = TwoBlobsDataset()\n\n def get_datasets(self, *args, **kwargs):\n return {\"valid\": self._dataset}\n\n def handle_batch(self, batch):\n x, y = batch\n logits = self.model(x)\n\n self.batch = {\"features\": x, \"targets\": y.view(-1), \"logits\": logits}\n\n\ndef train_device_custom_runner(logdir):\n runner = CustomDeviceRunner(logdir)\n runner.run()\n return runner.epoch_metrics\n\n\ndef train_dp_custom_runner(logdir):\n runner = CustomDPRunner(logdir)\n runner.run()\n return runner.epoch_metrics\n\n\ndef train_ddp_custom_runner(logdir):\n runner = CustomDDPRunner(logdir)\n runner.run()\n return runner.epoch_metrics\n\n\ndef train_device_config_runner(logdir, device):\n runner = MyConfigRunner(\n config={\n \"args\": {\"logdir\": logdir},\n \"model\": {\"_target_\": \"AllwaysSameModel\"},\n \"engine\": {\"_target_\": \"DeviceEngine\", \"device\": device},\n \"loggers\": {\"console\": {\"_target_\": \"ConsoleLogger\"}},\n \"stages\": {\n \"stage1\": {\n \"num_epochs\": 1,\n \"loaders\": {\n \"batch_size\": _BATCH_SIZE * NUM_CUDA_DEVICES,\n \"num_workers\": _WORKERS,\n },\n \"criterion\": {\"_target_\": \"CrossEntropyLoss\"},\n \"optimizer\": {\"_target_\": \"SGD\", \"lr\": _LR},\n \"callbacks\": {\n \"criterion\": {\n \"_target_\": \"CriterionCallback\",\n \"metric_key\": \"loss\",\n \"input_key\": \"logits\",\n \"target_key\": \"targets\",\n },\n \"optimizer\": {\"_target_\": \"OptimizerCallback\", \"metric_key\": \"loss\"},\n },\n },\n },\n }\n )\n runner.run()\n return runner.epoch_metrics\n\n\n@mark.skipif(\n not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES == 2), reason=\"Number of CUDA devices is not 2\"\n)\ndef test_device_and_ddp_metrics():\n # we have to keep dataset_len, num_gpu and batch size synced\n # dataset is 64 points\n # in DP setup we have 64 / (bs {32} * num_gpu {1} ) = 2 iteration on 1 gpu\n # in DDP setup we have 64 / (bs {32} * num_gpu {2}) = 1 iteration on 2 gpu\n with TemporaryDirectory() as logdir:\n # logdir = \"metrics_logs\"\n device_logdir = os.path.join(logdir, \"device_logs\")\n dp_logdir = os.path.join(logdir, \"dp_logs\")\n ddp_logdir = os.path.join(logdir, \"ddp_logs\")\n\n epoch_metrics1 = train_device_custom_runner(device_logdir)\n print(\"=\" * 80)\n epoch_metrics2 = train_dp_custom_runner(dp_logdir)\n print(\"=\" * 80)\n epoch_metrics3 = train_ddp_custom_runner(ddp_logdir)\n print(\"=\" * 80)\n\n # print(f\"epoch_metrics1: {epoch_metrics1}\")\n # print(f\"epoch_metrics2: {epoch_metrics2}\")\n # assert 0 == 1\n","sub_path":"tests/catalyst/engines/test_metrics.py","file_name":"test_metrics.py","file_ext":"py","file_size_in_byte":9256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"502669543","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nWFP food prices:\n------------\n\nCreates datasets with flattened tables of WFP food prices.\n\n\"\"\"\n\nimport logging\nfrom math import sin\nfrom os.path import join\n\nfrom hdx.data.dataset import Dataset\nfrom hdx.data.resource import Resource, ResourceView\nfrom hdx.data.showcase import Showcase\nfrom hdx.location.country import Country\nfrom slugify import slugify\nimport pandas as pd\nimport numpy as np\nimport math\nimport datetime\nimport time\n\nlogger = logging.getLogger(__name__)\ntags = [\"commodities\",\"prices\",\"markets\"]\n\n\ndef get_countriesdata(countries_url, downloader, country_correspondence):\n \"\"\"Download a list of countries and provide mapping if necessary.\n\n A list of dictionaries is returned, each containing the following keys:\n iso3 - ISO 3 country code\n name - country name\n code - WFP country code\n wfp_countries - a list of dictionaries describing WFP countries that are part of the \"ISO 3\" country.\n\n Note: The data source (WFP countries) may contain countries that do not have its own ISO 3 code.\n Such WFP countries can be mapped to ISO 3 country using the\n country_correspondence attribute in the project_configuration.yml. All WFP countries mapped to the same ISO 3 country\n will be listed in wfp_countries. Each ISO 3 country will appear at most once in the output.\n \"\"\"\n countries={}\n unknown=[]\n\n\n for row in downloader.get_tabular_rows(countries_url, dict_rows=False, headers=1, format='csv'):\n name = row[0]\n sub_name = name\n code = row[1]\n new_wfp_countries=[dict(name=sub_name,code=code)]\n iso3, fuzzy = Country.get_iso3_country_code_fuzzy(name)\n if iso3 is None:\n name = country_correspondence.get(sub_name)\n if name is None:\n unknown.append(sub_name)\n continue\n else:\n iso3, fuzzy = Country.get_iso3_country_code_fuzzy(name)\n\n countries[iso3] = countries.get(iso3,dict(name=name,iso3=iso3,wfp_countries=[]))\n countries[iso3][\"wfp_countries\"] = countries[iso3][\"wfp_countries\"] + new_wfp_countries\n countries[iso3][\"code\"] = ([x for x in countries[iso3][\"wfp_countries\"] if x[\"name\"] == name] + countries[iso3][\"wfp_countries\"])[0][\"code\"]\n\n if len(unknown):\n logger.warning(\"Some countries were not recognized and are ignored:\\n\"+\",\\n\".join(unknown))\n\n return [countries[iso3] for name, iso3 in sorted([(x[\"name\"],x[\"iso3\"]) for x in countries.values()])]\n\n\ndef months_between(fromdate,todate):\n \"\"\"Returns an iterator of iso-formatted dates between fromdate and todate (inclusive) with the step of 1 month.\"\"\"\n import datetime\n\n def to_date(d):\n if isinstance(d, datetime.date):\n return d\n if isinstance(d, str):\n d=datetime.datetime.strptime(d, \"%Y/%m/%d\")\n if isinstance(d, datetime.datetime):\n return datetime.date(year = d.year, month = d.month, day=d.day)\n logging.error(\"Unexpected date type: \"+repr(d))\n\n fromdate = to_date(fromdate)\n todate = to_date(todate)\n if fromdate is not None and todate is not None:\n d=fromdate\n while d<=todate:\n yield d.isoformat()\n year = d.year\n month=d.month+1\n if month>12:\n year+=1\n month=1\n d=datetime.date(year=year,month=month,day=d.day)\n\n\ndef read_flattened_data(wfpfood_url, downloader, countrydata):\n \"\"\"Reads the WFP food prices data from the source and flattens them to a plain table structure.\n\n WFP data structure contains monthly prices for a continuous time period, which need to be flattened in order\n to fit into a plain table structure. This function creates an iterator which both reads and flattens the data in one go.\n \"\"\"\n for wfp_countrydata in countrydata[\"wfp_countries\"]:\n logging.debug(\"Start reading %s data\"%countrydata[\"name\"])\n url = wfpfood_url + wfp_countrydata['code']\n for row in downloader.get_tabular_rows(url,file_type='json',dict_rows=True,headers=1):\n dates =list(months_between(row[\"startdate\"],row[\"enddate\"]))\n if len(dates)!=len(row[\"mp_price\"]):\n logging.warning(\"Number of prices %d does not match with number of expected dates (%d) between %s and %s\"%(\n len(dates),len(row[\"mp_price\"]),row[\"startdate\"],row[\"enddate\"]\n ))\n for date, price in zip(dates,row[\"mp_price\"]):\n if price is not None:\n yield dict(\n {key:value for key, value in row.items() if key not in (\"startdate\",\"enddate\",\"mp_price\")},\n date = date,\n price = float(price),\n country=wfp_countrydata['name']\n )\n logging.debug(\"Finished reading %s data\"%countrydata[\"name\"])\n\n\ndef flattened_data_to_dataframe(data):\n \"\"\"Converts data to a Pandas DataFrame format and adds the HXL taggs.\n \"\"\"\n column_definition=\"\"\"date #date\n cmname #item+name\n unit #item+unit\n category #item+type\n price #value\n currency #currency\n country #country+name\n admname #adm1+name\n adm1id #adm1+code\n mktname #name+market\n mktid \n cmid #item+code\n ptid\n umid\n catid #item+type+code\n sn #meta+id\n default \"\"\".split('\\n')\n\n columns = [x.split()[0] for x in column_definition]\n hxl = {x.split()[0]:\" \".join(x.split()[1:]) for x in column_definition}\n df = pd.DataFrame(data=[hxl] + list(data),columns=columns)\n return df\n\n_cache=None\n\n\ndef read_dataframe(wfpfood_url, downloader, countrydata):\n global _cache\n\n if _cache is not None:\n if countrydata[\"name\"] in _cache:\n df = _cache[countrydata[\"name\"]]\n else:\n df = flattened_data_to_dataframe(\n read_flattened_data(wfpfood_url, downloader, countrydata)\n )\n _cache[countrydata[\"name\"]] = df\n return df.copy()\n\n\n return flattened_data_to_dataframe(\n read_flattened_data(wfpfood_url, downloader, countrydata)\n )\n\n\ndef year_from_date(d):\n try:\n return datetime.datetime.strptime(d, \"%Y-%m-%d\").year\n except:\n return 0\n\n\ndef month_from_date(d):\n try:\n return datetime.datetime.strptime(d, \"%Y-%m-%d\").month\n except:\n return 0\n\n\ndef quickchart_dataframe(df, shortcuts, keep_last_years = 5, remove_nonfood=True):\n \"\"\"This function creates filtered dataframe with scaled median prices and short names suitable for quickchart.\n \"\"\"\n def sinceEpoch(d):\n try:\n return time.mktime(datetime.datetime.strptime(d, \"%Y-%m-%d\").timetuple())\n except:\n return 0\n df=df.assign(year = df.date.apply(year_from_date))\n hxl = df.loc[:0]\n df=df.loc[1:]\n df1=hxl.copy()\n df1=df1.assign(label=\"#item+label\")\n df1=df1.assign(cmnameshort = \"#item+name+short\")\n\n df.loc[:,\"price\"] = pd.to_numeric(df.price, errors='coerce')\n df.loc[:,\"cmname\"] = df.cmname.apply(str)\n df.loc[:,\"unit\"] = df.unit.apply(str)\n from_year = df[\"year\"].max() - keep_last_years\n df=df.loc[df[\"year\"] >= from_year] # keep only last keep_last_years years\n df=df.assign(x = df.date.apply(sinceEpoch))\n\n dates = sorted(df.date.unique())\n x = np.array([sinceEpoch(d) for d in dates])\n\n if remove_nonfood:\n df.loc[:, \"catid\"] = pd.to_numeric(df.catid, errors='coerce')\n df=df.loc[df.catid != 8]\n\n processed_data=[]\n for key, index in sorted(df.groupby([\"cmname\",\"unit\",\"category\",\"cmid\",\"catid\"]).groups.items()):\n commodity, unit, category, cmid, catid = key\n g=df.loc[index]\n gd = g.groupby([\"date\"])\n\n invmean = 100.0 / g.price.mean()\n quantity = math.pow(10, math.trunc(math.log10(invmean)))\n qunit = \"%d %s\"%(quantity,unit)\n if quantity < 1:\n qunit = \"1/%d %s\"%(int(1/quantity),unit)\n if quantity == 1:\n qunit = unit\n\n label=\"%(commodity)s (%(qunit)s)\"%locals()\n short_commodity = shortcuts.get(commodity,commodity)\n series = {}\n for date,median in gd.price.median().items():\n gg = g.loc[g.date==date]\n median = gg.loc[gg.price<=median].price.max()\n if median > 0:\n row = dict(gg.loc[gg.price==median].iloc[0])\n row[\"price\"]*=quantity\n row[\"unit\"]=qunit\n row[\"label\"]=label\n row[\"cmnameshort\"] = short_commodity\n row[\"scaling\"]=quantity\n row[\"interpolated\"]=0\n series[date]=row\n source_dates = sorted(series.keys())\n xp = np.array([series[d][\"x\"] for d in source_dates])\n yp = np.array([series[d][\"price\"] for d in source_dates])\n y = np.interp(x,xp,yp)\n for date,price in zip(dates,y):\n if date in series:\n processed_data.append(series[date])\n else:\n processed_data.append(dict(\n date = date,\n price = price,\n unit = qunit,\n label = label,\n cmname = commodity,\n cmnameshort = short_commodity,\n scaling = quantity,\n category = category,\n interpolated = 1,\n cmid = cmid,\n catid = catid\n ))\n df1=df1.append(pd.DataFrame(processed_data), ignore_index=True)\n return df1\n\n\ndef generate_dataset_and_showcase(wfpfood_url, downloader, folder, countrydata, shortcuts):\n \"\"\"Generate datasets and showcases for each country.\n \"\"\"\n title = '%s - Food Prices' % countrydata['name']\n logger.info('Creating dataset: %s' % title)\n name = 'WFP food prices for %s' % countrydata['name'] # Example name which should be unique so can include organisation name and country\n slugified_name = slugify(name).lower()\n\n df = read_dataframe(wfpfood_url, downloader, countrydata)\n\n if len(df)<=1:\n logger.warning('Dataset \"%s\" is empty' % title)\n return None, None\n\n\n dataset = Dataset({\n 'name': slugified_name,\n 'title': title,\n \"dataset_preview\": \"resource_id\"\n })\n dataset.set_maintainer(\"9957c0e9-cd38-40f1-900b-22c91276154b\") # Orest Dubay\n# dataset.set_maintainer(\"154de241-38d6-47d3-a77f-0a9848a61df3\")\n dataset.set_organization(\"3ecac442-7fed-448d-8f78-b385ef6f84e7\")\n\n dataset.set_dataset_date(df.loc[1:].date.min(),df.loc[1:].date.max(),\"%Y-%m-%d\")\n dataset.set_expected_update_frequency(\"weekly\")\n dataset.add_country_location(countrydata[\"name\"])\n dataset.set_subnational(True)\n dataset.add_tags(tags)\n dataset.add_tag('hxl')\n\n file_csv = join(folder, \"WFP_food_prices_%s.csv\"%countrydata[\"name\"].replace(\" \",\"-\"))\n df.to_csv(file_csv,index=False)\n resource = Resource({\n 'name': title,\n \"dataset_preview_enabled\": \"False\",\n 'description': \"Food prices data with HXL tags\"\n })\n resource.set_file_type('csv') # set the file type to eg. csv\n resource.set_file_to_upload(file_csv)\n dataset.add_update_resource(resource)\n\n df1 = quickchart_dataframe(df, shortcuts)\n file_csv = join(folder, \"WFP_food_median_prices_%s.csv\"%countrydata[\"name\"].replace(\" \",\"-\"))\n df1.to_csv(file_csv,index=False)\n resource = Resource({\n 'name': '%s - Food Median Prices' % countrydata['name'],\n \"dataset_preview_enabled\": \"True\",\n 'description':\n\"\"\"Food median prices data with HXL tags.\nMedian of all prices for a given commodity observed on different markets is shown, together with the market where\nit was observed. Data are shortened in multiple ways:\n\n- Rather that prices on all markets, only median price across all markets is shown, together with the market\n where it has been observed.\n- Only food commodities are displayed (non-food commodities like fuel and wages are not shown).\n- Only data after %s are shown. Missing data are interpolated.\n- Column with shorter commodity names \"cmnshort\" are available to be used as chart labels.\n- Units are adapted and prices are rescaled in order to yield comparable values (so that they\n can be displayed and compared in a single chart). Scaling factor is present in scaling column.\n Label with full commodity name and a unit (with scale if applicable) is in column \"label\". \n\nThis reduces the amount of data and allows to make cleaner charts.\n\"\"\"%(df1.loc[1:].date.min())\n })\n resource.set_file_type('csv') # set the file type to eg. csv\n resource.set_file_to_upload(file_csv)\n dataset.add_update_resource(resource)\n\n showcase = Showcase({\n 'name': '%s-showcase' % slugified_name,\n 'title': title+\" showcase\",\n 'notes': countrydata[\"name\"] + \" food prices data from World Food Programme displayed through VAM Economic Explorer\",\n 'url': \"http://dataviz.vam.wfp.org/economic_explorer/prices?adm0=\"+countrydata[\"code\"],\n 'image_url': \"http://dataviz.vam.wfp.org/_images/home/economic_2-4.jpg\"\n })\n showcase.add_tags(tags)\n return dataset, showcase\n\n\ndef generate_resource_view(dataset):\n resource_view = ResourceView({'resource_id': dataset.get_resource(1)['id']})\n resource_view.update_from_yaml()\n return resource_view\n\n\ndef joint_dataframe(wfpfood_url, downloader, countriesdata):\n def ptid_to_ptname(ptid):\n return {15:\"Retail\", 14:\"Wholesale\", 17:\"Producer\", 18:\"Farm Gate\"}.get(ptid,\"\")\n\n df = None\n for countrydata in countriesdata:\n logging.info(\"Loading %s into a joint dataset\"%(countrydata[\"name\"]))\n df_country = read_dataframe(wfpfood_url, downloader, countrydata)\n\n df_country = df_country.loc[1:]\n\n dff = pd.DataFrame(dict(\n adm0_id = [int(countrydata[\"code\"])]*len(df_country),\n adm0_name = [str(countrydata[\"name\"])]*len(df_country),\n adm1_id = df_country.adm1id,\n adm1_name = df_country.admname,\n mkt_id = df_country.mktid,\n mkt_name = df_country.mktname,\n cm_id = df_country.cmid,\n cm_name = df_country.cmname,\n cur_id = [0]*len(df_country),\n cur_name = df_country.currency,\n pt_id = df_country.ptid,\n pt_name = df_country.ptid.apply(ptid_to_ptname),\n um_id = df_country.umid,\n um_name = df_country.unit,\n mp_month = df_country.date.apply(month_from_date),\n mp_year = df_country.date.apply(year_from_date),\n mp_price = df_country.price,\n mp_commoditysource = [\"\"]*len(df_country),\n ), columns =\"\"\"adm0_id\n adm0_name\n adm1_id\n adm1_name\n mkt_id\n mkt_name\n cm_id\n cm_name\n cur_id\n cur_name\n pt_id\n pt_name\n um_id\n um_name\n mp_month\n mp_year\n mp_price\n mp_commoditysource\"\"\".split()\n )\n df = dff if df is None else df.append(dff,ignore_index=True)\n return df\n\n\ndef generate_joint_dataset_and_showcase(wfpfood_url, downloader, folder, countriesdata):\n \"\"\"Generate single joint datasets and showcases containing data for all countries.\n \"\"\"\n title = 'Global Food Prices Database (WFP)'\n logger.info('Creating joint dataset: %s' % title)\n slugified_name = 'wfp-food-prices'\n\n df = joint_dataframe(wfpfood_url, downloader, countriesdata)\n\n if len(df)<=1:\n logger.warning('Dataset \"%s\" is empty' % title)\n return None, None\n\n dataset = Dataset({\n 'name': slugified_name,\n 'title': title\n })\n dataset.set_maintainer(\"9957c0e9-cd38-40f1-900b-22c91276154b\") # Orest Dubay\n# dataset.set_maintainer(\"154de241-38d6-47d3-a77f-0a9848a61df3\")\n dataset.set_organization(\"3ecac442-7fed-448d-8f78-b385ef6f84e7\")\n\n maxmonth = (100*df.mp_year+df.mp_month).max()%100\n dataset.set_dataset_date(\"%04d-01-01\"%df.mp_year.min(),\"%04d-%02d-15\"%(df.mp_year.max(),maxmonth),\"%Y-%m-%d\")\n dataset.set_expected_update_frequency(\"weekly\")\n dataset.add_country_locations(sorted(df.adm0_name.unique()))\n dataset.add_tags(tags)\n\n file_csv = join(folder, \"WFPVAM_FoodPrices.csv\")\n df.to_csv(file_csv,index=False)\n resource = Resource({\n 'name': title,\n 'description': \"Word Food Programme – Food Prices Data Source: WFP Vulnerability Analysis and Mapping (VAM).\"\n })\n resource.set_file_type('csv') # set the file type to eg. csv\n resource.set_file_to_upload(file_csv)\n dataset.add_update_resource(resource)\n\n showcase = Showcase({\n 'name': '%s-showcase' % slugified_name,\n 'title': 'Global Food Prices',\n 'notes': \"Interactive data visualisation of WFP's Food Market Prices dataset\",\n 'url': \"https://data.humdata.org/organization/wfp#interactive-data\",\n 'image_url': \"https://docs.humdata.org/wp-content/uploads/wfp_food_prices_data_viz.gif\"\n })\n showcase.add_tags(tags)\n\n dataset.update_from_yaml()\n dataset['notes'] = dataset['notes'] % 'Global Food Prices data from the World Food Programme covering'\n dataset.create_in_hdx()\n showcase.create_in_hdx()\n showcase.add_dataset(dataset)\n dataset.get_resource().create_datastore_from_yaml_schema(yaml_path=\"wfp_food_prices.yml\", path=file_csv)\n logger.info('Finished joint dataset')\n\n return dataset, showcase\n","sub_path":"wfpfood.py","file_name":"wfpfood.py","file_ext":"py","file_size_in_byte":17667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"452456710","text":"#coding:utf-8\nimport re\n\nfilename='content.txt'\nfile=open(filename)\ncontent=file.read()\npat=re.compile(r'
.*?

(.*?)

.*?
(.*?)
(.*?).*?(\\d+).*?
',re.S)\nimg_pat=re.compile(r'
.*?
',re.S)\nbr_pat=re.compile(r'
')\nitems=re.findall(pat,content)\ni=0\nfor m in items:\n\titems[i]=list(tuple(items[i]))\n\ti+=1\nitems[:]=[m for m in items if not re.search(img_pat,m[2])]\nprint(items)\n# for m in items:\n# \tImg=re.search(img_pat,m[2])\n# \tif not Img:\n# \t\ts=re.sub(br_pat,'\\n',m[1])\n# \t\tm[1]=s\n# \t\tprint(m[0],m[1],m[3])\n# \telse:\n# \t\tpass\n\n\n\n\n ","sub_path":"爬虫学习/实战代码/抓取糗事百科热门段子/正则匹配.py","file_name":"正则匹配.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"58625226","text":"from django.urls import reverse, resolve\nfrom django.test import TestCase\nfrom ..views import costumes\nfrom ..models import Costume\n\nclass CostumesTests(TestCase):\n def setUp(self):\n self.costume = Costume.objects.create(\n title = 'Blue Costume',\n description = 'Its pretty',\n price = 25.00,\n image = 'uploads/2018/05/%18/blue_costume.jpg',\n color = 'Blue',\n skirt = True,\n sleeves = True,\n girth = 24,\n chest = 24,\n underchest = 24,\n waist = 24,\n hips = 24,\n side = 24,\n )\n url = reverse('costumes')\n self.response = self.client.get(url)\n\n def test_costumes_view_status_code(self):\n self.assertEquals(self.response.status_code, 200)\n\n def test_costumes_url_resolves_costumes_view(self):\n view = resolve('/costumes/')\n self.assertEquals(view.func, costumes)\n\n def test_costumes_view_contains_link_to_costume_detail_page(self):\n costume_detail_url = reverse('costume_detail', kwargs = { 'pk': self.costume.pk})\n self.assertContains(self.response, 'href=\"{0}\"'.format(costume_detail_url))\n","sub_path":"clothes/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"603292499","text":"import logging, sys\nfrom duxdekes.models import SquareSettings\nfrom duxdekes.exceptions import ChargeAdjustmentException, ChargeCaptureException\nimport squareconnect\nfrom squareconnect.rest import ApiException\nfrom squareconnect.apis.transactions_api import TransactionsApi\nfrom pprint import pprint\n\nlogger = logging.getLogger('duxdekes.util.square')\n\n\ndef get_api(token):\n \"\"\"\n Get an instance of the Square API, set up the access token\n \"\"\"\n squareconnect.configuration.access_token = token\n return TransactionsApi()\n\n\ndef capture_payment(reference):\n \"\"\"\n Capture a payment authorized previously\n \"\"\"\n square_settings = SquareSettings.get_settings()\n api_instance = get_api(square_settings.access_token)\n\n try:\n # Capture the previously authorized transaction\n api_response = api_instance.capture_transaction(\n square_settings.location_id,\n reference)\n\n # Something went wrong with the API; time to deal with it\n if api_response.errors:\n\n errors = ', '.join([err.detail for err in api_response.errors])\n\n raise ApiException(errors)\n\n # No success value, code or anything\n return\n\n except Exception as e:\n msg = \"Problem finalizing the transaction\"\n logger.error(msg, exc_info=sys.exc_info())\n raise ChargeCaptureException(msg) from e\n\n\ndef adjust_charge(order_number, reference, original_amount, new_amount):\n \"\"\"\n Refund the difference between the final capture and the actual cost\n \"\"\"\n square_settings = SquareSettings.get_settings()\n api_instance = get_api(square_settings.access_token)\n refund_amount = float(original_amount - new_amount)\n refund_in_cents = int(100*refund_amount)\n\n # Get the previous captured transactions' tender id\n try:\n api_response = api_instance.retrieve_transaction(\n square_settings.location_id,\n reference)\n\n if api_response.errors is not None:\n errors = ', '.join([err.detail for err in api_response.errors])\n raise ApiException(errors)\n\n previous_tender = api_response.transaction.tenders[0].id\n\n except ApiException as e:\n msg = \"Problem retrieving the previous auth transaction\"\n logger.error(msg, exc_info=sys.exc_info())\n raise ChargeCaptureException(msg) from e\n except IndexError as e:\n msg = 'Problem retrieving the tender id'\n logger.error(msg, exc_info=sys.exc_info())\n raise ChargeCaptureException(msg) from e\n\n amount = {\n 'amount': refund_in_cents,\n 'currency': 'USD'\n }\n\n body = {\n 'idempotency_key': \"{}_adjust\".format(order_number),\n 'tender_id': previous_tender,\n 'amount_money': amount,\n 'reason': 'Adjustment in shipping costs',\n }\n\n try:\n api_response = api_instance.create_refund(square_settings.location_id,\n reference, body)\n\n return api_response.refund.transaction_id\n\n except ApiException as e:\n msg = \"Problem adjusting the authorized cost by {}: {}\"\\\n .format(refund_amount, e)\n logger.error(msg, exc_info=sys.exc_info())\n raise ChargeAdjustmentException(msg) from e\n\n","sub_path":"duxdekes/util/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"299908464","text":"#coding:utf-8\n\nimport json\nimport statis\nfrom handler.base import BaseHandler\nfrom common.dao import BAS, APS, APStat\nfrom utils.encoder import TAPSEncoder\nfrom utils.usual import login_required, parse_argument\nfrom collections import OrderedDict\nfrom wtforms.fields import IntegerField, StringField\nfrom wtforms.validators import Required\nfrom utils.usual import FixedForm, convert_traffic\n\n\nclass ACHandler(BaseHandler):\n class PostForm(FixedForm):\n vendor = StringField(validators=[Required()])\n ip = StringField(validators=[Required()])\n pri = StringField(validators=[Required()])\n user = StringField(validators=[Required()])\n password = StringField(validators=[Required()])\n name = StringField(validators=[Required()])\n model = StringField(validators=[Required()])\n coa_port = IntegerField(default=2000, validators=[Required()])\n tz = IntegerField(),\n port = IntegerField(default=0)\n mask = IntegerField()\n secret = StringField()\n @login_required\n @parse_argument(PostForm)\n def post(self):\n ac_id = BAS.create(self, **self.arguments)\n data = dict(ac_id=ac_id)\n self.write_json(data)\n\n class DeleteForm(FixedForm):\n ac_id = IntegerField(validators=[Required()])\n @login_required\n @parse_argument(DeleteForm)\n def delete(self):\n BAS.delete(self, **self.arguments)\n self.handle_success()\n\n class PutForm(FixedForm):\n ac_id = IntegerField(validators=[Required()])\n vendor = StringField()\n ip = StringField()\n pri = IntegerField()\n pip = StringField()\n user = StringField()\n password = StringField()\n name = StringField()\n model = StringField()\n secret = StringField()\n coa_port = IntegerField()\n tz = IntegerField()\n port = IntegerField(default=0)\n mask = IntegerField()\n @login_required\n @parse_argument(PutForm)\n def put(self):\n BAS.update(self, **self.arguments)\n self.handle_success()\n\n\nclass APSHandler(BaseHandler):\n class GetForm(FixedForm):\n location = StringField(default='')\n page = IntegerField(default=1)\n page_size = IntegerField(default=10)\n sort = StringField(default='{}', filters=[json.loads])\n @login_required\n @parse_argument(GetForm)\n def get(self):\n _location = self.arguments['location']\n macs = [bind['mac'] for bind in self.mdb.aps_bind.find({'_location': {'$regex': '^{}'.format(_location)}})]\n aps = self.mdb.list.find({'mac': {'$in': macs}})\n if self.arguments['sort']:\n aps = aps.sort(self.arguments['sort'])\n aps = list(aps)\n for ap in aps:\n ap['id'] = str(self.mdb.aps_bind.find_one({'mac': ap['mac']})['_id'])\n self.write_json({'aps': aps}, encoder=TAPSEncoder)\n\n class PutForm(FixedForm):\n mac = StringField(validators=[Required()])\n location = StringField(default='')\n position = StringField()\n @login_required\n @parse_argument(PutForm)\n def put(self):\n self.arguments['_location'] = self.arguments.pop('location')\n APS.update(self, **self.arguments)\n self.handle_success()\n\n\nclass APSBatchHandler(BaseHandler):\n class PutForm(FixedForm):\n location = StringField(validators=[Required()])\n macs = StringField(validators=[Required()])\n @login_required\n @parse_argument(PutForm)\n def put(self):\n _location, macs = self.split('location', 'macs')\n APS.multi_bind(self, _location, macs)\n self.handle_success()\n\n\nclass APStatHandler(BaseHandler):\n class GetForm(FixedForm):\n start = StringField()\n end = StringField()\n date = StringField()\n @login_required\n @parse_argument(GetForm)\n def get(self):\n stat = APStat.query(self, **self.arguments)\n data = {'stat': OrderedDict(sorted(stat.items(), key=lambda x: x[0]))}\n self.write_json(data)\n\n\nclass APSListHandler(BaseHandler):\n class GetForm(FixedForm):\n page = IntegerField(default=1)\n page_size = IntegerField(default=50)\n location = StringField(default='')\n keyword = StringField(default='')\n isbind = StringField(default='')\n vendor = StringField(default='')\n online = StringField(default='')\n resource = StringField(default='')\n sort = StringField(default='{}')\n @login_required\n @parse_argument(GetForm)\n def get(self):\n aps, page_count = APS.table(self, *self.split('page', 'page_size', 'location', 'keyword', 'isbind', 'vendor',\n 'online', 'resource', 'sort'))\n self.data.update({'aps': aps, 'page_count': page_count, 'sort': json.loads(self.arguments['sort'])})\n if not self.arguments['location']:\n table = self.render_string('block_ap.html', **self.data)\n else:\n table = self.render_string('block_projectaplist.html', **self.data)\n paginate = self.render_string('block_ap_paginate.html', page_count=page_count, page=self.arguments['page'])\n self.write_json({'table': table, 'paginate': paginate})\n\n\nclass DataMapHandler(BaseHandler):\n class GetForm(FixedForm):\n location = StringField(validators=[Required()], label='_location')\n @parse_argument(GetForm)\n def get(self):\n _location = self.arguments['_location']\n rs = self.mdb.datamap_device_data.find({'_location': _location}).sort([('_id', -1)]).limit(1)\n cache = list(rs)[0]['data']\n self.write_json(json.loads(cache))\n\n\nclass OnlineHandler(BaseHandler):\n class GetForm(FixedForm):\n location = StringField(validators=[Required()], label='_location')\n @parse_argument(GetForm)\n def get(self):\n _location = self.arguments['_location']\n rs = self.mdb.datamap_online_data.find({'_location': _location}).sort([('_id', -1)]).limit(1)\n cache = list(rs)[0]['data']\n self.write_json(json.loads(cache))\n","sub_path":"core/handler/wifi.py","file_name":"wifi.py","file_ext":"py","file_size_in_byte":6011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"128052624","text":"\nfrom PIL import Image\nimport numpy as np\nimport pickle\nimport datetime\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import classification_report\nfrom feature import NPDFeature\nfrom ensemble import AdaBoostClassifier\nimport os\n# 设置当前路径\n#os.chdir('F:/DataMining') \n\n# 这里参数命名写的是matrix,个人习惯,其实是ndarray类型\ndef extract_NPD(feature_matrix, label_matrix, path):\n label = None\n if (path.split('/')[2] == 'face'):\n label = [1]\n elif (path.split('/')[2] == 'nonface'):\n label = [-1]\n else:\n print('path error!')\n exit(1)\n \n for file in os.listdir(path):\n # 得到图片路径\n file_path = os.path.join(path, file)\n if not os.path.isdir(file_path):\n image_file = Image.open(file_path)\n # 将图片转为24*24的灰度图\n image_file = image_file.convert('L').resize((24, 24))\n # 获取图片的像素值\n data_matrix = np.array(image_file.getdata())\n# data_matrix = data_matrix.reshape(24, 24)\n # 调用feature.py里的NPDFeature抽取特征\n npd_feature = NPDFeature(data_matrix).extract()\n # 将特征作为一行加到参数feature_matrix中\n feature_matrix = np.vstack((feature_matrix, [npd_feature]))\n # 将对应标签加入到label_matrix中\n label_matrix = np.vstack((label_matrix, [label]))\n \n # 返回对应路径下的特征矩阵和标签矩阵(ndarray类型) \n return feature_matrix, label_matrix\n \ndef save(data, filename):\n with open(filename, \"wb\") as f:\n pickle.dump(data, f)\n \ndef load(filename):\n with open(filename, \"rb\") as f:\n return pickle.load(f)\n\ndef pre_process():\n # 特征大小,计算方法是在feature.py中看到的\n features_size = 576 * (576-1) // 2\n \n # 保存特征用的空array\n face_matrix = np.zeros((0, features_size))\n nonface_matrix = np.zeros((0, features_size))\n \n # 保存标签用的空array\n face_labels = np.ones((0, 1))\n nonface_labels = np.ones((0, 1))\n \n # 抽取特征\n face_matrix, face_labels = extract_NPD(face_matrix, face_labels, 'datasets/original/face')\n nonface_matrix, nonface_labels = extract_NPD(nonface_matrix, nonface_labels, 'datasets/original/nonface')\n \n # 将人脸和非人脸特征存到同一个array\n mix_matrix = np.vstack((face_matrix, nonface_matrix))\n mix_labels = np.vstack((face_labels, nonface_labels))\n \n del face_matrix\n del nonface_matrix\n del face_labels\n del nonface_labels\n \n save(mix_matrix, 'datasets/features/mix_matrix')\n save(mix_labels, 'datasets/features/mix_labels') \n \n\nif __name__ == \"__main__\":\n # write your code here\n print(datetime.datetime.now())\n pre_process()\n print(datetime.datetime.now())\n \n X = load('datasets/features/mix_matrix')\n y = load('datasets/features/mix_labels')\n \n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n \n del X\n del y\n \n print(datetime.datetime.now())\n \n ada_booster = AdaBoostClassifier(DecisionTreeClassifier, 5)\n ada_booster.fit(X_train, y_train)\n \n del X_train\n del y_train\n \n y_test = y_test.reshape(y_test.shape[0])\n \n y_predict = ada_booster.predict(X_test)\n \n report = classification_report(y_test, y_predict, target_names=[\"nonface\", \"face\"])\n \n file = open('report.txt', 'w')\n file.write(report)\n file.close()\n \n print(report)\n \n print(datetime.datetime.now())\n ","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"625945660","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 1 23:34:45 2018\n\n@author: aksha\n\"\"\"\n\nimport tkinter as Tk\nr = Tk()\ndef change_label():\n label2[\"text\"] = \"nice to meet you! \"\nframe = Tk.Frame(r)\nframe.pack()\nlabel2 = Tk.Label(r,text=\"\\nCLICK ONE OF THE BUTTONS\\n\")\nlabel2.pack()\nbottomframe =Tk.Frame(r)\nbottomframe.pack(side=Tk.BOTTOM)\nstopbutton = Tk.Button(frame, text='Abort', width = 40, fg = 'green', command = r.destroy)\nstopbutton.pack(side=Tk.LEFT)\nprintbutton = Tk.Button(frame, text='Change Label', width = 40, fg = 'yellow', command=change_label)\nprintbutton.pack(side=Tk.LEFT) ","sub_path":"cc/tki/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"202616730","text":"\"\"\"\nReformat Code plugin for gedit 3\nv1.0\nCopyright (C) 2014 J.L. Rodriguez \n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\"\"\"\n\n\nfrom gi.repository import GObject, Gtk, Gedit\n\nUI_XML = \"\"\"\n\n \n \n \n \n \n\n\"\"\"\n\nclass ReformatCodePlugin(GObject.Object, Gedit.WindowActivatable):\n __gtype_name__ = \"ReformatCode\"\n window = GObject.property(type=Gedit.Window)\n \n def __init__(self):\n GObject.Object.__init__(self)\n \n def _add_ui(self):\n manager = self.window.get_ui_manager()\n self._actions = Gtk.ActionGroup(\"ReformatCodeActions\")\n self._actions.add_actions([\n ('ReformatHTMLAction', Gtk.STOCK_INFO, \"Reformat HTML\", \n None, \"Reformat HTML code to be included in HTML-code-label\", \n self.reformat_HTML),\n ])\n manager.insert_action_group(self._actions)\n self._ui_merge_id = manager.add_ui_from_string(UI_XML)\n manager.ensure_update()\n \n def do_activate(self):\n self._add_ui()\n\n def do_deactivate(self):\n self._remove_ui()\n\n def do_update_state(self):\n pass\n \n def reformat_HTML(self, action, data=None):\n view = self.window.get_active_view()\n if view:\n # the boundaries of the selection are obtained\n selection_bounds = view.get_buffer().get_selection_bounds()\n # if there is a selected text\n if selection_bounds:\n # retrieve it\n text = view.get_buffer().get_text(selection_bounds[0], selection_bounds[1], True)\n text = text.replace(\"<\", \"<\")\n text = text.replace(\">\", \">\")\n view.delete_selection()\n view.get_buffer().insert_at_cursor(text)\n \n def _remove_ui(self):\n manager = self.window.get_ui_manager()\n manager.remove_ui(self._ui_merge_id)\n manager.remove_action_group(self._actions)\n manager.ensure_update()\n","sub_path":"reformatcode.py","file_name":"reformatcode.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"321093257","text":"import numpy as np\nimport math\nimport copy\nimport data_struc\n\nclass sample_generator:\n \n \n def __init__(self, feature_amount, prototype_distance, variance = 1, distance_spread_k = 1, distance_spread_x0 = 0):\n \n self.feature_amount = feature_amount\n \n self.prototype_distance = prototype_distance\n self.variance = variance\n \n self.distance_spread_k = distance_spread_k\n self.distance_spread_x0 = distance_spread_x0\n \n self.sample_list_X = []\n self.sample_list_y = []\n self.sample_list = []\n \n self.prototypes = [] \n self.initial_prototypes = []\n self.initial_prototype_distance_table = []\n self.initial_feature_significance = []\n \n self.create_prototypes(prototype_distance)\n \n \n def create_prototypes(self, distance):\n \n self.initial_prototype_distance_table = self.create_prototype_distance_table(self.prototype_distance,\n self.distance_spread_k, \n self.distance_spread_x0)\n prototype1_coord = []\n prototype2_coord = [] \n for i in range(self.feature_amount): \n prototype1_coord.append(np.random.random())\n for i in range(self.feature_amount): \n if np.random.choice([True, False]):\n prototype2_coord.append(prototype1_coord[i]+self.initial_prototype_distance_table[i])\n else:\n prototype2_coord.append(prototype1_coord[i]-self.initial_prototype_distance_table[i])\n \n prototypebuffer = []\n prototypebuffer.append(prototype1_coord)\n prototypebuffer.append(prototype2_coord)\n \n self.prototypes = prototypebuffer\n self.initial_prototypes = copy.deepcopy(prototypebuffer)\n \n \n def create_prototype_distance_table(self, added_feature_distance, k, x_0):\n \n distance_table = [] \n for i in range(self.feature_amount): \n if self.feature_amount%2 == 0:\n distance_table.append(1/(1+math.exp(-k*((i-int(self.feature_amount/2)+0.5-x_0)))))\n else:\n distance_table.append(1/(1+math.exp(-k*((i-int(self.feature_amount/2)-x_0))))) \n \n list_sum = 0 \n for i in range(len(distance_table)): \n list_sum += distance_table[i]\n \n scale_factor = added_feature_distance/list_sum \n distance_table = scale_factor*np.array(distance_table) \n initial_significance = range(self.feature_amount)\n \n buffer = list(zip(distance_table, initial_significance)) \n np.random.shuffle(buffer)\n distance_table, initial_significance = zip(*buffer)\n \n self.initial_feature_significance = initial_significance\n return distance_table\n \n \n def change_prototype_distance_high_significance(self, n_highest_features, change_percentage):\n \n for i in range(n_highest_features): \n index_highest = self.initial_feature_significance.index(self.feature_amount-i-1) \n initial_distance = self.initial_prototype_distance_table[index_highest] \n change_amount = initial_distance/((100/change_percentage)*2)\n \n if self.initial_prototypes[0][index_highest] < self.initial_prototypes[1][index_highest]: \n self.prototypes[0][index_highest] += change_amount\n self.prototypes[1][index_highest] -= change_amount\n else:\n self.prototypes[0][index_highest] -= change_amount\n self.prototypes[1][index_highest] += change_amount\n \n \n def return_prototype_distance_by_attribute(self, attribte_by_significance):\n \n index = self.initial_feature_significance.index(attribte_by_significance)\n return self.prototypes[1][index]-self.prototypes[0][index]\n \n \n def create_samples(self, amount_samples):\n \n amount_samples = int(amount_samples/2) \n for i in range(amount_samples): \n X_buffer = []\n for j in range(self.feature_amount): \n v = np.random.normal(self.prototypes[0][j],self.variance)\n X_buffer.append(v) \n self.sample_list_X.append(X_buffer)\n self.sample_list_y.append(0)\n \n for i in range(amount_samples): \n X_buffer = []\n for j in range(self.feature_amount): \n v = np.random.normal(self.prototypes[1][j],self.variance)\n X_buffer.append(v) \n self.sample_list_X.append(X_buffer)\n self.sample_list_y.append(1)\n \n\n def return_sample_table(self, sample_amount): \n \n self.sample_list_X.clear()\n self.sample_list_y.clear() \n self.create_samples(sample_amount) \n return data_struc.sample_table(self.sample_list_X, self.sample_list_y) \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 ","sub_path":"world_generator.py","file_name":"world_generator.py","file_ext":"py","file_size_in_byte":5521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"305235931","text":"# Class to perform majority-class undersampling\n\n# Author: Lukas Snoek [lukassnoek.github.io]\n# Contact: lukassnoek@gmail.com\n# License: 3 clause BSD\n\nimport numpy as np\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n\nclass MajorityUndersampler(BaseEstimator, TransformerMixin):\n \"\"\"\n Undersamples the majority-class(es) by selecting random samples.\n\n Parameters\n ----------\n verbose : bool\n Whether to print downsamples number of samples.\n \"\"\"\n\n def __init__(self, verbose=False):\n \"\"\" Initializes MajorityUndersampler object. \"\"\"\n self.verbose = verbose\n self.idx_ = None\n\n def fit(self, X=None, y=None):\n \"\"\" Does nothing, but included for scikit-learn pipelines. \"\"\"\n return self\n\n def transform(self, X, y):\n \"\"\" Downsamples majority-class(es).\n\n Parameters\n ----------\n X : ndarray\n Numeric (float) array of shape = [n_samples, n_features]\n\n Returns\n -------\n X : ndarray\n Transformed array of shape = [n_samples, n_features] given the\n indices calculated during fit().\n \"\"\"\n\n if isinstance(y[0], (np.float64, np.float32, np.float16)):\n print('Converting y to integer')\n y = y.astype(int)\n\n bins = np.bincount(y)\n all_idx = np.zeros(y.size, dtype=bool)\n\n for i in np.unique(y):\n\n if bins[i] != np.min(bins):\n y_idx = y == i\n tmp_idx = np.zeros(y_idx.sum(), dtype=bool)\n idx_idx = np.random.choice(np.arange(y_idx.sum()),\n np.min(bins), replace=False)\n tmp_idx[idx_idx] = True\n all_idx[y_idx] = tmp_idx\n else:\n all_idx[y == i] = True\n\n X_ds, y_ds = X[all_idx, :], y[all_idx]\n\n if self.verbose:\n print('Number of samples (after resampling): %.3f' % y_ds.size)\n print('Resampled class proportion: %.3f\\n' % y_ds.mean())\n\n self.idx_ = all_idx\n\n return X[all_idx, :], y[all_idx]\n","sub_path":"skbold/transformers/majority_undersampler.py","file_name":"majority_undersampler.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"533040625","text":"data = []\r\n\r\nwhile True:\r\n count = input('Введите количество загружаемых товаров:\\n')\r\n if count.isdigit():\r\n count = int(count)\r\n break\r\n else:\r\n print('Ошибка, необходимо ввести число:')\r\n\r\ni = 1\r\nwhile True:\r\n name = input(f'Введите название {i}-го товара:\\n')\r\n while True:\r\n cost = input(f'Введите значение цены {i}-го товара:\\n')\r\n if cost.isdigit():\r\n cost = int(cost)\r\n break\r\n else:\r\n print('Ошибка, необходимо ввести число:')\r\n while True:\r\n amount = input(f'Введите значение количества {i}-го товара:\\n')\r\n if amount.isdigit():\r\n amount = int(amount)\r\n break\r\n else:\r\n print('Ошибка, необходимо ввести число:')\r\n cargo = (i, {\"название\": name, \"цена\": cost, \"количество\": amount, \"eд\": \"шт.\"})\r\n data.insert(i - 1, cargo)\r\n if i == count:\r\n break\r\n i += 1\r\n\r\n# data = [\r\n# (1, {\"название\": \"компьютер\", \"цена\": 20000, \"количество\": 5, \"eд\": \"“шт.”\"}),\r\n# (2, {\"название\": \"принтер\", \"цена\": 6000, \"количество\": 2, \"eд\": \"“шт.”\"}),\r\n# (3, {\"название\": \"сканер\", \"цена\": 2000, \"количество\": 7, \"eд\": \"“шт.”\"})\r\n# ]\r\n\r\nanalytics_data = {}\r\nfor el_list in data:\r\n for key, val in el_list[1].items():\r\n analytics_data[key] = []\r\n\r\nfor el_list in data:\r\n for key, val in el_list[1].items():\r\n analytics_data[key].append(val)\r\n\r\n# Костыль для исключения повторений в ключе единиц измерений\r\nlast = list(analytics_data.keys())[-1]\r\nanalytics_data[last] = list(set(analytics_data[last]))\r\n\r\nprint(data)\r\nprint(analytics_data)\r\n","sub_path":"practice_2.6.py","file_name":"practice_2.6.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"425292309","text":"import json\nimport os.path\nimport re\nimport ipykernel\nimport requests\n\nfrom requests.compat import urljoin\n\nfrom notebook.notebookapp import list_running_servers\n\nfrom tf.apphelpers import URL_GH, URL_NB\n\n\ndef repoLocation(cwd):\n cwdPat = re.compile(f'^.*/github/([^/]+)/([^/]+)((?:/.+)?)$', re.I)\n cwdRel = cwdPat.findall(cwd)\n if not cwdRel:\n return None\n # org, repo, path\n (org, repo, path) = cwdRel[0]\n onlineTail = (f'{org}/{repo}' f'/blob/master{path}')\n nbUrl = f'{URL_NB}/{onlineTail}'\n ghUrl = f'{URL_GH}/{onlineTail}'\n return (org, repo, path, nbUrl, ghUrl)\n\n\ndef location(cwd, name):\n repoLoc = repoLocation(cwd)\n if name is not None:\n return (('', name, '.ipynb'), repoLoc)\n\n hasKernel = False\n try:\n kernelId = re.search('kernel-(.*).json', ipykernel.connect.get_connection_file()).group(1)\n hasKernel = True\n except Exception:\n pass\n\n found = None\n\n try:\n servers = list_running_servers()\n if hasKernel:\n for ss in servers:\n response = requests.get(\n urljoin(ss['url'], 'api/sessions'), params={'token': ss.get('token', '')}\n )\n for nn in json.loads(response.text):\n if nn['kernel']['id'] == kernelId:\n relPath = nn['notebook']['path']\n absPath = os.path.join(ss['notebook_dir'], relPath)\n (dirName, filePart) = os.path.split(absPath)\n (fileName, extension) = os.path.splitext(filePart)\n found = (dirName, fileName, extension)\n break\n except Exception:\n print('Cannot determine the name of this notebook')\n pass\n\n return (found, repoLoc)\n","sub_path":"tf/notebook.py","file_name":"notebook.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"304138534","text":"# -*- coding: utf-8 -*-\n\nfrom argparse import ArgumentParser\nimport os\nimport csv\nfrom datetime import datetime\nimport time\n\nimport pytz\n\nimport nemsneak\nfrom nemsneak import util\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(\n 'enumerate all the \"infected\" accounts.' +\n '\"infected\" means the accounts which recieved XEM from the root or ' +\n ' an infected account.'\n )\n parser.add_argument('target', help='the root account')\n parser.add_argument(\n '--dt_from',\n help='search after this datetime. specify if of the form ' +\n '%%Y%%m%%d%%H%%M%%S (ex: 20180126000200). (default: 20180126000200)',\n default='20180126000200'\n )\n parser.add_argument(\n '--timezone', help='timezone (default: Asia/Tokyo)',\n default='Asia/Tokyo'\n )\n parser.add_argument(\n '--api_host', help='API Host (default: http://localhost:7890)',\n default='http://localhost:7890'\n )\n args = parser.parse_args()\n tz = pytz.timezone(args.timezone)\n conn = nemsneak.Connection(tz, args.api_host)\n\n start_time = datetime.now()\n\n target = args.target\n from_dt = datetime.strptime(args.dt_from, '%Y%m%d%H%M%S').replace(\n tzinfo=tz\n )\n\n marked_mosaics = ({\n 'namespaceId': 'ts',\n 'name': 'warning_dont_accept_stolen_funds'\n }, {\n 'namespaceId': 'mizunashi.coincheck_stolen_funds_do_not_accept_trades',\n 'name': 'owner_of_this_account_is_hacker',\n })\n\n marked_mosaic_slug = tuple(\n ':'.join((d['namespaceId'], d['name'])) for d in marked_mosaics\n )\n\n def is_marked(addr):\n tmp = conn.get('/account/mosaic/owned', {'address': addr})['data']\n time.sleep(0.1)\n mosaic_set = set(\n ':'.join((\n d['mosaicId']['namespaceId'],\n d['mosaicId']['name']\n )) for d in tmp\n )\n return tuple([\n s in mosaic_set for s in marked_mosaic_slug\n ])\n\n queue = [(target, from_dt)]\n known = {}\n\n res = []\n\n def hook_func(sender, tx):\n print((sender, tx['transaction']['timeStamp']))\n res.append(tuple(util.pp_transaction([\n 'datetime', 'amount', 'from_address', 'to_address', 'fee',\n 'message'\n ], util.tidy_transaction(\n tx, conn, sender\n ))))\n print(res[-1])\n\n ch = nemsneak.Chaser(\n target, conn,\n hook_func, from_dt, daemon=True\n )\n\n ch.start()\n\n ch.join()\n\n addrs = set(\n [d[2] for d in res if d[2] is not None] +\n [d[3] for d in res if d[3] is not None]\n )\n\n info = {}\n\n for addr in addrs:\n tmp = conn.get_account_info(addr)\n time.sleep(0.1)\n info[addr] = (\n tmp['account']['balance'],\n tmp['account']['vestedBalance']\n ) + is_marked(addr)\n\n res.sort(key=lambda x: x[0])\n\n for d in res:\n print(d)\n\n if not os.path.exists('results'):\n os.makedirs('results')\n\n with open(os.path.join(\n 'results',\n 'info_{}.csv'.format(start_time.strftime('%Y%m%d_%H%M%S'))\n ), 'w') as fout:\n wr = csv.writer(fout, lineterminator='\\n')\n wr.writerow((\n 'address', 'balance', 'vestedBalance'\n ) + marked_mosaic_slug)\n for k, v in info.items():\n wr.writerow((k, ) + v)\n\n with open(os.path.join(\n 'results',\n 'tx_{}.csv'.format(start_time.strftime('%Y%m%d_%H%M%S'))\n ), 'w') as fout:\n wr = csv.writer(fout, lineterminator='\\n')\n wr.writerow([\n 'datetime', 'amount', 'from_address', 'to_address', 'fee',\n 'message', 'is_sender_marked', 'is_recipient_marked'\n ])\n for d in res:\n wr.writerow(\n d + (\n any(t for t in info[d[2]][2:]) if d[2] is not None else '',\n any(t for t in info[d[3]][2:]) if d[3] is not None else ''\n )\n )\n","sub_path":"scripts/chase_coincheck_20180126.py","file_name":"chase_coincheck_20180126.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"562922804","text":"import logging\nimport os\nimport sys\n\nfrom math import ceil\n\nfrom sodapy import Socrata\n\nlogging.basicConfig(filename=\"./logs.log\", level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\nDATA_URL = \"data.cityofnewyork.us\"\nDATA_ID = \"nc67-uf89\"\n\n\ndef get_client(url: str, app_token: str) -> Socrata:\n return Socrata(url, app_token)\n\n\ndef parse_args() -> dict:\n opts = {}\n args = sys.argv[1:]\n\n for arg in args:\n try:\n argname, argval = arg.split('=')\n except ValueError:\n logger.warn(\"Failed to split {arg} along '=', \"\n \"assuming to be a boolean.\")\n argname = arg\n argval = True\n except Exception:\n continue\n\n if argname.startswith('--'):\n argname = argname[2:]\n\n opts[argname] = argval\n\n return opts\n\n\ndef validate_num_pages(opts: dict, page_size: int) -> int:\n try:\n return int(opts['num_pages'])\n except KeyError:\n logger.warn(\"No option called 'num_pages' found! \"\n \"Attempting to calculate from COUNT of all rows\")\n except Exception as e:\n logger.warn(\"Failed to process num_pages. Here is why: \"\n f\"{e}. Attempting to calculate from COUNT of all rows\")\n\n try:\n results = client.get(DATA_ID, select='COUNT(*)')\n total = int(results[0]['COUNT'])\n return ceil(total / page_size)\n except Exception as e:\n logger.warn(f\"Failed to count total: {e} \"\n \"Stopping script and raising exception\")\n raise\n\n\nif __name__ == '__main__':\n opts = parse_args()\n client = get_client(DATA_URL, os.environ['APP_TOKEN'])\n\n page_size = int(opts.get('page_size', 1000))\n num_pages = validate_num_pages(opts, page_size)\n\n i = 0\n logger.debug(\"Begin processing of data for \"\n f\"page_size: {page_size} and num_pages: {num_pages}\")\n while i < num_pages:\n resp = client.get(DATA_ID, limit=page_size, offset=i*page_size)\n logger.debug(f\"Processed page {i+1}, limit={page_size} and \"\n f\"offset={i*page_size}\")\n\n i += 1\n write_to_file = 'output' in opts\n if write_to_file:\n with open(opts['output'], 'a+') as fh:\n for item in resp:\n fh.write(f\"{str(item)}\\n\")\n else:\n for item in resp:\n print(str(item))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"313598111","text":"import unittest\nfrom osf import read_json\n\n\nclass CreateUser(unittest.TestCase):\n def test(self):\n value = 'jino.kor@li-st.com'\n value = value.split('@', 1)[0]\n self.assertEqual(value, 'jino.kor')\n self.assertTrue(True)\n\n def test_read_json(self):\n rj = read_json.ReadJson()\n data = rj.get_library()\n self.assertTrue(len(data) > 0)\n\n def test_view_json(self):\n rj = read_json.ReadJson()\n data = rj.read_json('./json/kci_paper_library_one.json')\n print(data)\n\n def test_get_author(self):\n rj = read_json.ReadJson()\n author_main = []\n datas = rj.get_library()\n for data in datas:\n author_main.append(data.get('AUTHOR_MAIN'))\n temp = data.get('AUTHOR_SUB')\n if temp is not None:\n ss = temp.split(';')\n for j in ss:\n author_main.append(j)\n author_main = sorted(list(set(author_main)))\n self.assertTrue(len(author_main) > 0)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"kisti/test/bulk_create_user_test.py","file_name":"bulk_create_user_test.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"459451883","text":"import os\nimport torch\nLOAD_STATE_DICT = True\nNET_DIR = './nets/MNIST/'\nDES_NET_FILE = 'netE_epoch_319'\nGEN_NET_FILE = 'netG_epoch_319'\nINF_NET_FILE = 'netI_epoch_319'\nFILE_END = '.pth'\n\n\ndef main():\n # load nets and coop explorer\n if LOAD_STATE_DICT:\n des_params = torch.load(os.path.join(NET_DIR, DES_NET_FILE + FILE_END))\n gen_params = torch.load(os.path.join(NET_DIR, GEN_NET_FILE + FILE_END))\n for key in des_params.keys():\n des_params[key] = des_params[key].to('cpu')\n for key in gen_params.keys():\n gen_params[key] = gen_params[key].to('cpu')\n torch.save(des_params, os.path.join(NET_DIR, DES_NET_FILE + '_cpu' + FILE_END))\n torch.save(gen_params, os.path.join(NET_DIR, GEN_NET_FILE + '_cpu' + FILE_END))\n if INF_NET_FILE is not None:\n inf_params = torch.load(os.path.join(NET_DIR, INF_NET_FILE + FILE_END))\n for key in inf_params.keys():\n inf_params[key] = inf_params[key].to('cpu')\n torch.save(inf_params, os.path.join(NET_DIR, INF_NET_FILE + '_cpu' + FILE_END))\n else:\n gen_net = torch.load(os.path.join(NET_DIR, GEN_NET_FILE + FILE_END))\n des_net = torch.load(os.path.join(NET_DIR, DES_NET_FILE + FILE_END))\n torch.save(des_net.to('cpu'), os.path.join(NET_DIR, DES_NET_FILE + '_cpu' + FILE_END))\n torch.save(gen_net.to('cpu'), os.path.join(NET_DIR, GEN_NET_FILE + '_cpu' + FILE_END))\n if INF_NET_FILE is not None:\n inf_net = torch.load(os.path.join(NET_DIR, INF_NET_FILE + FILE_END))\n torch.save(inf_net.to('cpu'), os.path.join(NET_DIR, INF_NET_FILE + '_cpu' + FILE_END))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main_save_net_cpu.py","file_name":"main_save_net_cpu.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"169516180","text":"# -*- coding=utf-8 -*-\n\nfrom handlers.handlers import WebNewsInfoHandler, NewsAdjacentHandler, NewsListHandler, CmsNewsEditHandler, CmsNewsDelHandler\n\nnews_routes = [{\n 'path': r\"news/\",\n 'handler': WebNewsInfoHandler\n}, {\n 'path': r\"news/list\",\n 'handler': NewsListHandler\n}, {\n 'path': r\"news/adjacent/\",\n 'handler': NewsAdjacentHandler\n}, {\n 'path': r\"news/c\",\n 'handler': CmsNewsEditHandler\n}, {\n 'path': r\"news/d/\",\n 'handler': CmsNewsDelHandler\n}]\n","sub_path":"api/routes/src/news_route.py","file_name":"news_route.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"302465550","text":"import numpy as np\nimport pytest\n\nfrom periscope.data.creator import DataCreator\nfrom periscope.data.seeker import DataSeeker\nfrom periscope.utils.constants import DATASETS\n\nproteins = np.random.choice(DATASETS.eval, 10)\n\n\n@pytest.fixture(params=proteins)\ndef target(request):\n return request.param\n\n\nclass TestDataCreator:\n\n def test_backcompat_refs(self, target):\n creator = DataCreator(target)\n parsed_msa = creator._parse_msa()\n seeker = DataSeeker(target, n_refs=10)\n\n target_msa_seq = \"\".join(parsed_msa[creator.target].seq)\n target_sequence = ''.join(creator.protein.sequence)\n target_pdb_indices = list(range(0, len(target_sequence)))\n pdb_inds_target, msa_inds_target = creator._align_pdb_msa(target_sequence, target_msa_seq, target_pdb_indices)\n\n for hom in seeker._get_closest_references()[0:1]:\n seeker_dm = seeker._get_ref_dm(hom)\n\n creator_dm = creator._find_reference(hom, parsed_msa[hom], pdb_inds_target, msa_inds_target)\n\n assert np.allclose(creator_dm[~np.isnan(creator_dm)], seeker_dm[~np.isnan(creator_dm)])\n","sub_path":"tests/data/test_creator.py","file_name":"test_creator.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"633175366","text":"from threading import Thread\nimport os, time, datetime, tracemalloc\n\ntracemalloc.start()\nchildren = 100\nmaxdelay = 6\n\n\ndef status():\n return ('Time: ' +\n str(datetime.datetime.now().time()) +\n '\\t Malloc, Peak: ' +\n str(tracemalloc.get_traced_memory()))\n\n\ndef child(num):\n delay = maxdelay\n print(f\"{status()}\\t\\tProcess \"\n f\"{num}, PID: {os.getpid()}, Delay: {delay} seconds...\")\n time.sleep(delay)\n print(f\"{status()}\\t\\tProcess {num}: Done.\")\n\n\nif __name__ == '__main__':\n start = time.time()\n print(f'Parent PID: {os.getpid()}')\n threads = []\n for i in range(children):\n thread = Thread(target=child, args=(i,))\n thread.start()\n threads.append(thread)\n\n for thread in threads:\n thread.join()\n end = time.time()\n\n print(f'Slapsed time: {end-start}')\n","sub_path":"threads.py","file_name":"threads.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"62271700","text":"def linear_search(list,target):\n for i in range(0, len(list)):\n if list[i]==target:\n return i\n return None\n# Runs in linear time o(n)\n\ndef verify(index):\n if index is not None:\n print(\"target found at \", index)\n else:\n print(\"bummer\")\n\n\nnumbers=[1,4,5,6,7,12]\nresult=linear_search(numbers,12)\nverify(result)","sub_path":"linear_search.py","file_name":"linear_search.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"249414230","text":"import pandas as pd\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n\nclass DatasetCreator(BaseEstimator, TransformerMixin):\n VALID_COLS = ['title', 'score', 'num_comments', 'created_at', 'text']\n TARGET = 'label'\n \n def __init__(self, cols_to_drop_na=None, train=True, labels=None):\n self.train = train\n self.LABELS = labels\n\n if cols_to_drop_na is not None:\n if not isinstance(cols_to_drop_na, list):\n self.cols_to_drop_na = [cols_to_drop_na]\n else:\n self.cols_to_drop_na = cols_to_drop_na\n else:\n self.cols_to_drop_na = None\n \n if self.train:\n self.VALID_COLS = self.VALID_COLS + [self.TARGET]\n \n def _drop_na(self, X):\n if self.cols_to_drop_na is not None:\n return X.dropna(subset=self.cols_to_drop_na)\n else: \n return X \n \n def _get_valid_labels_only(self, X):\n if self.train:\n return X[X[self.TARGET].str.lower().isin(self.LABELS)]\n else:\n return X\n \n def _concatenate_title_body(self, X):\n X['text'] = X['title'].fillna('') + ' ' + X['body'].fillna('')\n return X\n \n def _convert_to_datetime(self, X):\n X['created_at'] = pd.to_datetime(X['created_at'])\n return X.sort_values(by='created_at').reset_index()\n \n def fit(self, X, y=None):\n return self\n \n def transform(self, X):\n X = X.copy()\n X = self._drop_na(X)\n X = self._get_valid_labels_only(X)\n X = self._concatenate_title_body(X)\n X = self._convert_to_datetime(X)\n X = X[self.VALID_COLS]\n return X\n \n \nclass DropUnnecessaryFeatures(BaseEstimator, TransformerMixin):\n def __init__(self, variables_to_drop=None):\n self.variables = variables_to_drop\n \n def fit(self, X, y=None):\n return self\n \n def transform(self, X):\n X = X.copy()\n X = X.drop(self.variables, axis=1)\n return X","sub_path":"notebooks/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"117862246","text":"#!/usr/bin/env python\n#\n# License: BSD 2-clause\n# Last Change: Mon Dec 14, 2020 at 04:05 PM +0100\n\nimport unittest\n# from math import factorial\n\nimport sys\nsys.path.insert(0, '..')\n\nfrom pyUTM.io import csv_line\nfrom pyUTM.io import parse_cell_range\nfrom pyUTM.io import XLWriter\nfrom pyUTM.io import PcadReader\nfrom pyUTM.io import netnode_to_netlist\nfrom pyUTM.io import prepare_descr_for_xlsx_output\nfrom pyUTM.io import WirelistNaiveReader\nfrom pyUTM.datatype import ColNum\nfrom pyUTM.datatype import NetNode\nfrom pyUTM.sim import CurrentFlow\n\n\nclass GenerateCsvLineTester(unittest.TestCase):\n dummy_prop = {'NETNAME': 'NET', 'ATTR': None}\n\n def test_normal_entry(self):\n entry = NetNode(*[str(i) for i in range(1, 5)])\n self.assertEqual(csv_line(entry, self.dummy_prop), 'NET,1,2,3,4')\n\n def test_entry_with_none(self):\n entry = NetNode(*[str(i) for i in range(1, 4)], None)\n self.assertEqual(csv_line(entry, self.dummy_prop), 'NET,1,2,3,')\n\n def test_entry_with_attr(self):\n entry = NetNode('2', '3', '4', '5')\n self.assertEqual(csv_line(entry, {'NETNAME': 'A_B', 'ATTR': '_C_'}),\n 'A_C_B,2,3,4,5')\n\n\nclass ParseCellRangeTester(unittest.TestCase):\n def test_parsing(self):\n cell_range = 'A12:CC344'\n initial_col, initial_row, final_col, final_row = parse_cell_range(\n cell_range\n )\n self.assertEqual(str(initial_col), 'A')\n self.assertEqual(initial_row, 12)\n self.assertEqual(str(final_col), 'CD')\n self.assertEqual(final_row, 345)\n\n def test_parsing_make_upper(self):\n cell_range = 'a12:cC344'\n initial_col, initial_row, final_col, final_row = parse_cell_range(\n cell_range\n )\n self.assertEqual(str(initial_col), 'A')\n self.assertEqual(initial_row, 12)\n self.assertEqual(str(final_col), 'CD')\n self.assertEqual(final_row, 345)\n\n\nclass XLWriterTester(unittest.TestCase):\n def test_rearrange_table_case1(self):\n self.assertEqual(\n XLWriter.rearrange_table(\n [['Header1', 'Header2', 'Header3'], [1, 2, 3], [4, 5, 6]],\n initial_row=1, initial_col=ColNum('A'),\n ),\n ([['Header1', 'Header2', 'Header3'], [1, 2, 3], [4, 5, 6]],\n 'A1:C3')\n )\n\n def test_rearrange_table_case2(self):\n self.assertEqual(\n XLWriter.rearrange_table(\n [['Header1', 'Header2', 'Header3'], [1, 2, 3], [4, 5, 6]],\n initial_row=3, initial_col=ColNum('B'),\n ),\n ([[''], [''],\n ['', 'Header1', 'Header2', 'Header3'], ['', 1, 2, 3], ['', 4, 5, 6]\n ],\n 'B3:D5'\n )\n )\n\n\nclass PcadReaderTester(unittest.TestCase):\n def test_net_hop_with_real_netlist(self):\n reader = PcadReader('./comet_db.sample.net')\n nethopper = CurrentFlow(passable=[r'^W\\d+'])\n result = reader.read(nethopper=nethopper)\n self.assertEqual(result['NetD1_1'], result['DIFF_TERM_STV'])\n self.assertEqual(result['NetD1_1'], result['NetD2_1'])\n self.assertEqual(result['NetD1_1'], result['J1_LOC_TERM'])\n self.assertEqual(result['NetD1_1'], result['J2_LOC_TERM'])\n\n\nclass NetNodeToNetListTester(unittest.TestCase):\n def test_dcb_pt_node(self):\n nodes_dict = {\n NetNode('JD1', 'A1', 'JP1', 'A1'):\n {'NETNAME': 'JD1_JP1_unreal', 'ATTR': None}\n }\n self.assertEqual(\n dict(netnode_to_netlist(nodes_dict)),\n {'JD1_JP1_unreal': [('JD1', 'A1'), ('JP1', 'A1')]}\n )\n\n def test_dcb_none_node(self):\n nodes_dict = {\n NetNode('JD1', 'A1'):\n {'NETNAME': 'JD1_JPL1_unreal', 'ATTR': None}\n }\n self.assertEqual(\n dict(netnode_to_netlist(nodes_dict)),\n {'JD1_JPL1_unreal': [('JD1', 'A1')]}\n )\n\n def test_multiple_nodes(self):\n nodes_dict = {\n NetNode('JD1', 'A1'):\n {'NETNAME': 'JD1_JPL1_unreal', 'ATTR': None},\n NetNode('JD2', 'A2', 'JP1', 'A1'):\n {'NETNAME': 'JD2_JP1_unreal', 'ATTR': None},\n }\n self.assertEqual(\n dict(netnode_to_netlist(nodes_dict)),\n {\n 'JD1_JPL1_unreal': [('JD1', 'A1')],\n 'JD2_JP1_unreal': [('JD2', 'A2'), ('JP1', 'A1')],\n }\n )\n\n\nclass PrepareDescrForXlsxOutputTester(unittest.TestCase):\n def test_prepare_descr_for_xlsx_output_case1(self):\n descr = {\n 'connector1': [\n {'prop1': 1, 'prop2': 2},\n {'prop1': 1.5, 'prop2': 2.5},\n ],\n 'connector2': [\n {'prop1': 3, 'prop2': 4},\n {'prop1': 4.5, 'prop2': 4.5},\n {'prop1': 5, 'prop2': 5.5},\n ],\n }\n self.assertEqual(\n prepare_descr_for_xlsx_output(descr),\n {\n 'connector1': [\n ['prop1', 'prop2'],\n [1, 2],\n [1.5, 2.5]\n ],\n 'connector2': [\n ['prop1', 'prop2'],\n [3, 4],\n [4.5, 4.5],\n [5, 5.5]\n ],\n }\n )\n\n def test_prepare_descr_for_xlsx_output_case2(self):\n descr = {\n 'connector1': [\n {'prop1': 1, 'Pigtail pin': 'A1'},\n {'prop1': 1.5, 'Pigtail pin': 'B5'},\n ],\n 'connector2': [\n {'prop1': 3, 'SEAM pin': 'A11'},\n {'prop1': 4.5, 'SEAM pin': 'A10'},\n {'prop1': 5, 'SEAM pin': 'D1'},\n ],\n }\n self.assertEqual(\n prepare_descr_for_xlsx_output(descr),\n {\n 'connector1': [\n ['prop1', 'Pigtail pin'],\n [1, 'A01'],\n [1.5, 'B05']\n ],\n 'connector2': [\n ['prop1', 'SEAM pin'],\n [3, 'A11'],\n [4.5, 'A10'],\n [5, 'D01']\n ],\n }\n )\n\n\nclass WirelistNaiveReaderTester(unittest.TestCase):\n def test_wire_list_parse(self):\n reader = WirelistNaiveReader('./true_ppp.sample.wirelist')\n result = reader.read()\n self.assertEqual(\n result['JD0_JPL0_1V5_Master'],\n [('P21', '1'), ('P27', '1'), ('P33', '1')]\n )\n self.assertEqual(\n result['JP0 JPU0 P1E LV Return'],\n [('P6', '15')]\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/io.unittest.py","file_name":"io.unittest.py","file_ext":"py","file_size_in_byte":6697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"248103945","text":"import time\nimport tkinter as tk\nimport page\n\nimport config\nimport crank\nimport utilities\n\n\ndef calculate_counter_value(time_elapsed, interval_seconds, negative=False):\n counter_value = int(time_elapsed / interval_seconds) / 100\n if negative and counter_value != 0:\n counter_value *= -1\n return counter_value\n\n\ndef on_done(append_data, activate_next_page, experiment_type, progress_data):\n earnings = calculate_counter_value(progress_data['time_elapsed'], config.earnings_measure_interval_seconds)\n emotion_measure_counter = 0\n if experiment_type is 'negative' or experiment_type is 'positive':\n negative_measure = True if experiment_type is 'negative' else False\n emotion_measure_counter = calculate_counter_value(progress_data['time_elapsed'],\n config.emotion_measure_interval_seconds,\n negative_measure)\n append_data(experiment_type, earnings, emotion_measure_counter)\n activate_next_page(earnings)\n\n\ndef generate_page(root, width, activate_next_page, experiment_type, append_data):\n global progress\n global earnings_counter\n\n data = {}\n\n frame = page.generate_frame(root)\n\n page.generate_title(frame, 'Pyöritä kampea niin kauan kuin haluat')\n\n progress = tk.Label(frame,\n text='●●●●●●●',\n bg=config.background_color,\n fg=config.text_color,\n font=config.big_font)\n progress.pack(side=tk.TOP)\n\n content_text = ('HUOM: Pyöritysnopeudella ei ole väliä. Nopea pyöritys ei tuota enemmän rahaa.')\n\n page.generate_content(frame, width, content_text)\n\n iframe2 = page.generate_frame(frame)\n\n if experiment_type is 'neutral':\n earnings_counter = page.generate_label(iframe2, None, config.big_font)\n earnings_counter.pack(side=tk.TOP)\n page.generate_label(iframe2, 'Sinulle kertyvät rahat', config.tiny_font).pack()\n else:\n iframe3 = page.generate_frame(iframe2)\n earnings_counter = page.generate_label(iframe3, None, config.big_font)\n earnings_counter.pack()\n page.generate_label(iframe3, 'Sinulle kertyvät rahat', font=config.tiny_font).pack()\n iframe3.pack(side=tk.LEFT)\n\n iframe4 = page.generate_frame(iframe2)\n global emotion_measure_counter\n emotion_measure_counter = page.generate_label(iframe4, None, config.big_font)\n\n emotion_measure_counter.pack()\n page.generate_label(iframe4, 'Hyväntekeväisyyteen lahjoitettavat rahat', config.tiny_font).pack()\n iframe4.pack(side=tk.RIGHT)\n\n iframe2.pack(expand=1, fill=tk.X, padx=config.body_padding)\n\n page.generate_button(frame,\n 'Kun olet pyörittänyt tarpeeksi,\\npaina tästä',\n lambda: on_done(append_data, activate_next_page, experiment_type, data))\n\n return {'frame': frame, 'data': data}\n\n\ndef update_earnings_text(text):\n earnings_counter.configure(text=text)\n\n\ndef update_emotion_measure_counter_text(text):\n emotion_measure_counter.configure(text=text)\n\n\ndef refresh_progress(result, time_elapsed, progress_data):\n time_elapsed = int(time.time() - progress_data['time_since_last_progress'])\n time_elapsed = min(int(config.progress_indicator_time_limit / 1000), time_elapsed)\n time_remaining = int(config.progress_indicator_time_limit / 1000 - time_elapsed)\n\n if progress_data['progress_in_progress']:\n if time_remaining:\n progress_data['time_elapsed'] = (progress_data['total_time'] + time.time() -\n progress_data['initialized_time'])\n else:\n progress_data['progress_in_progress'] = False\n progress_data['total_time'] += time.time() - progress_data['initialized_time']\n\n if result:\n progress_data['time_since_last_progress'] = time.time()\n progress.configure(text='●●●●●●●●')\n if not progress_data['progress_in_progress']:\n progress_data['progress_in_progress'] = True\n progress_data['initialized_time'] = time.time()\n else:\n progress.configure(text='●' * time_remaining + '○' * time_elapsed)\n\n return progress_data\n\n\ndef counter_formatter(time_elapsed, interval_seconds, negative=False):\n counter_value = calculate_counter_value(time_elapsed, interval_seconds, negative)\n counter_value = utilities.to_euros(counter_value)\n return counter_value\n\n\ndef update_earnings(time_elapsed):\n earnings = counter_formatter(time_elapsed, config.earnings_measure_interval_seconds)\n update_earnings_text(earnings)\n\n\ndef update_emotion_measure_counter(time_elapsed, experiment_type):\n if experiment_type is 'negative' or experiment_type is 'positive':\n negative_measure = True if experiment_type is 'negative' else False\n emotion_measure_counter = counter_formatter(time_elapsed,\n config.emotion_measure_interval_seconds,\n negative_measure)\n update_emotion_measure_counter_text(emotion_measure_counter)\n\n\ndef do_refresh_page(\n root,\n activate_next_frame,\n experiment_initialized_time,\n progress_data,\n experiment_type,\n append_data):\n time_elapsed = time.time() - experiment_initialized_time\n\n if (time_elapsed < config.test_time_limit):\n result = crank.read_serial()\n refresh_progress(result, time_elapsed, progress_data)\n update_earnings(progress_data['time_elapsed'])\n update_emotion_measure_counter(progress_data['time_elapsed'], experiment_type)\n root.experiment_refresher = root.after(\n 100,\n do_refresh_page,\n root,\n activate_next_frame,\n experiment_initialized_time,\n progress_data,\n experiment_type,\n append_data)\n\n else:\n root.after_cancel(root.experiment_refresher)\n on_done(append_data, activate_next_frame, experiment_type, progress_data)\n\n\ndef refresh_page(root, activate_next_frame, experiment_initialized_time, experiment_type, progress_data, append_data):\n progress_data['time_since_last_progress'] = time.time()\n progress_data['time_elapsed'] = 0\n progress_data['total_time'] = 0\n progress_data['progress_in_progress'] = True\n progress_data['initialized_time'] = time.time()\n\n do_refresh_page(\n root,\n activate_next_frame,\n experiment_initialized_time,\n progress_data,\n experiment_type,\n append_data)\n","sub_path":"experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":6758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"131678791","text":"from influence.dataset import DataSet\nimport numpy as np\nimport io\nimport csv\nfrom tensorflow.contrib.learn.python.learn.datasets import base\n\n\ndef process_heart_disease(ex_to_leave_out=None, num_examples=None):\n \"\"\"\n Process heart_disease data\n \"\"\"\n np.random.seed(0)\n train_fraction = 0.8\n valid_fraction = 0.0\n with io.open('data/heart_disease/cleveland.csv', 'r',encoding='utf-8-sig') as f:\n reader = csv.reader(f)\n example_list = list(reader)\n for counter,example in enumerate(example_list):\n for number in example:\n number = np.float64(number)\n\n\n if num_examples is not None:\n num_examples = num_examples * 2\n example_list = example_list[:num_examples]\n else:\n num_examples = len(example_list)\n\n attributes =[]\n Y = []\n counter = 0\n for example in example_list:\n counter += 1\n example_vector = []\n for counter,value in enumerate(example):\n if counter == len(example) - 1 :\n Y.append(int(value))\n else:\n example_vector.append(value)\n attributes.append(example_vector)\n\n # print(attributes[0:10])\n # print(Y)\n\n num_train_examples = int(train_fraction * num_examples)\n num_valid_examples = int(valid_fraction * num_examples)\n num_test_examples = num_examples - num_train_examples - num_valid_examples\n\n # Apply the numbers to the location in the list of documents\n attributes_train = attributes[:num_train_examples]\n Y_train = Y[:num_train_examples]\n\n attributes_valid = attributes[num_train_examples : num_train_examples+num_valid_examples]\n Y_valid = Y[num_train_examples : num_train_examples+num_valid_examples]\n\n attributes_test = attributes[-num_test_examples:]\n Y_test = Y[-num_test_examples:]\n\n if ex_to_leave_out is not None:\n Y_train = np.delete(Y_train, ex_to_leave_out)\n attributes_train = np.delete(attributes_train, ex_to_leave_out, axis = 0)\n number_of_elements_excluded = 1\n else:\n number_of_elements_excluded = 0\n \n #print(len(attributes_train))\n #print(len(Y_train))\n assert(len(attributes_train) == len(Y_train))\n assert(len(attributes_valid) == len(Y_valid))\n assert(len(attributes_test) == len(Y_test))\n assert(len(Y_train) + len(Y_valid) + len(Y_test) == num_examples - number_of_elements_excluded)\n\n return attributes_train, Y_train, attributes_valid, Y_valid, attributes_test, Y_test\n\n\n \n\ndef load_heart_disease(ex_to_leave_out=None,num_examples=None):\n X_train, Y_train, X_valid, Y_valid, X_test, Y_test = process_heart_disease(ex_to_leave_out, num_examples)\n # Convert them to dense matrices\n Y_train = np.array(Y_train)\n Y_valid = np.array(Y_valid)\n Y_test = np.array(Y_test)\n X_train = np.array(X_train)\n if X_valid is not None:\n X_valid = np.array(X_valid)\n X_test = np.array(X_test)\n\n train = DataSet(X_train, Y_train)\n if X_valid is not None:\n validation = DataSet(X_valid, Y_valid)\n else:\n validation = None\n test = DataSet(X_test, Y_test)\n #print(X_train[1])\n return base.Datasets(train=train, validation=validation, test=test)\n\n\n ","sub_path":"load_heart_disease.py","file_name":"load_heart_disease.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"388780718","text":"from django.conf.urls import patterns, include, url\nimport settings\n\nimport ext.django_cron\next.django_cron.autodiscover()\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', 'websocket_django_server.views.home', name='home'),\n url(r'^slides$', 'websocket_django_server.views.slides', name='slides'),\n url(r'^controller$', 'websocket_django_server.views.controller', name='controller'),\n url(r'^zapette$', 'websocket_django_server.views.zapette', name='zapette'),\n url(r'^statics/(.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),\n # url(r'^push/', include('push.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":"websocket_django_server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"107697699","text":"\nfrom datetime import datetime\n\n# Determine the most likely year for a datetime object with only month/day set. Choose the year of the next time that \n# month will occur. Eg.: in Nov '16, Dec likely refers to '16 and Jan likely refers to '17.\ndef determine_year(new_datetime):\n curr_datetime = datetime.now()\n curr_val = curr_datetime.month*100 + curr_datetime.day\n new_val = new_datetime.month*100 + new_datetime.day\n\n if new_val >= curr_val:\n return curr_datetime.year\n else:\n return curr_datetime.year + 1\n\n\ndef output_html(all_events, filename):\n with open(filename, 'w') as f:\n f.write('
\\n'\n '\\n'\n ''\n ''\n '\\n'\n ' \\n'\n ' \\n'\n ' \\n'\n '\\n')\n for event in sorted(all_events):\n f.write('\\n'\n ' \\n'.format(event.datetime.strftime('%a, %-m/%d %-I:%M%p'), event.venue, event.details_page, event.title))\n f.write('
DateVenueShow
{0}\\n'\n ' {1}\\n'\n ' {3}\\n'\n '
\\n'\n '
\\n')\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"402825386","text":"from __future__ import absolute_import\n\n\nclass DBUtil:\n @staticmethod\n def get_selects(table, column_names: list):\n \"\"\"\n 根据字段名获取 table 查询 column 列表。\n\n :param table: 数据库表(sqlalchemy.Table类型)。\n :param column_names: 查询字段名称列表(list)。\n :retruns: 查询字段列表(list)。\n \"\"\"\n cols = []\n for c in table.c:\n if c.name in column_names:\n cols.append(c)\n return cols\n\n @staticmethod\n def get_column_names(mapping, indexs, key):\n \"\"\"\n 根据序号获取查询字段名称列表,处理过程:\\n\n 1)根据展示字段生成一个二进制字符串,如果第n个字段在表格\\n\n 中展示将二进制字符串第n位字符设置为1,否则设置为0.\\n\n 2)将二进制字符串转换为整数传到后台。\\n\n 3)将整数解析为二进制字符串。\\n\n 4)根据二进制字符串和mappgin字段进行匹配,遍历mapping,如\\n\n 果字段对应序号在二进制字符串中的字符为1,将字段添加到查\\n\n 询字段名称列表,否则不添加。\\n\n 5)返回查询字段名称列表。\\n\n 举例:get_column_names(mapping, indexs)。\n\n :param mapping: 数据库表字段名称映射(dict)。\n :param indexs: 字段序号(str)。\n :param key: 主键字段(str)。\n :retruns: 查询字段名称列表(list)。\n \"\"\"\n column_names = [key]\n if indexs is not None:\n count = len(indexs)\n if count > 0:\n end = count - 1\n if count > len(mapping):\n end = len(mapping) - 1\n indexs_dict = {}\n for i in range(0, end):\n if indexs[i] == '1':\n indexs_dict[i] = indexs[i]\n n = 0\n for k, v in mapping.items():\n if indexs_dict.get(n) is not None:\n column_names.append(v)\n n += 1\n else:\n for k, v in mapping.items():\n column_names.append(v)\n return column_names\n\n @staticmethod\n def exchange_key_value(mapping):\n new_dict = {}\n for k, v in mapping.items():\n new_dict[v] = k\n return new_dict\n","sub_path":"api/ext/dbutil.py","file_name":"dbutil.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"266493247","text":"from random import shuffle\r\nprint (\"***************WELCOME TO THE GENERAL SPORTS QUIZ Developed by Guransh******************\")\r\n\r\n\r\n \r\n\r\n#Asking for user details, name\r\ndef greet():\r\n global name\r\n while True:\r\n name = input(\"Please enter your name : \")\r\n if name.replace(' ','').isalpha():\r\n break\r\n print(\"Please enter your name using alphabets only \")\r\n \r\n \r\ngreet()\r\n\r\n#Asking for user details, age\r\ndef age():\r\n while True:\r\n age = input(\"Please enter your age : \")\r\n if age.replace(' ','').isnumeric():\r\n if 4< int(age)<100: \r\n break\r\n print(\"Please enter your age using numbers only : \")\r\n \r\n else:\r\n print('You need to be 5 to 99 to play the quiz')\r\n exit()\r\n \r\n \r\n\r\nage()\r\n\r\n\r\n\r\n\r\n\r\n\r\n#Ask if they are ready to take the quiz\r\nstatus = input(\"Are you ready to take the quiz {} ? If you enter anything other than Y the quiz will end: \\na. Yes \\nb. No \\n=>\".format( name)).lower()\r\n\r\n# what is they are not ready\r\nif status == 'yes' or status == 'y' or status == 'b':\r\n pass\r\nelse:\r\n print(\"Thank you for coming please come back later\")\r\n exit()\r\n\r\n\r\n\r\n\r\n\r\n#What if the user is ready\r\ndef inst():\r\n inst = input (\"Would you like instructions for the quiz? : \\na. Yes \\nb. No \\n=>\")\r\n if inst == 'yes' or inst == 'Yes' or inst == 'y' or inst == 'Y' or inst == 'a' or inst == 'A':\r\n print(\"*********************\")\r\n print(\"Welcome to the quiz.\")\r\n print(\"*********************\")\r\n print(\"Here are the instructions to the quiz\")\r\n print(\"You will be given 5 questions which will have three options\")\r\n print(\"Only one of the options will be correct \")\r\n print(\"Lets see how many you get correct.\")\r\n# what if the user in not ready \r\n elif inst == 'No' or inst == 'no' or inst == 'N' or inst == 'n':\r\n print(\"Thats fine here are the questions \")\r\n\r\n \r\ninst()\r\n\r\n\r\n#asking how many questions they would like to answer\r\ndef questions():\r\n global r ,total\r\n while True:\r\n try:\r\n r = int(input(\"\\nPlease enter how many questions you want to answer : \"))\r\n if 00:\r\n data = questions[0]\r\n q = data[0]\r\n data =data[1]\r\n answer = data['answer']\r\n option = data['option']\r\n\r\n print(q)\r\n print(option)\r\n while True:\r\n user_answers = input(\"Please enter your answer here : \").lower().replace(' ','')\r\n if user_answers =='a' or user_answers == 'b' or user_answers == 'c': \r\n if user_answers == answer:\r\n print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\r\n print(\"Well done thats correct keep going \")\r\n print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\r\n score +=1\r\n print(\"^^^^^^^^^^^^^\")\r\n print(\"your score is\",score)\r\n print(\"^^^^^^^^^^^^^\")\r\n else:\r\n print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\r\n print(\"Sorry your answer is incorrect, The correct answer is \",answer) \r\n print(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\r\n print(\"^^^^^^^^^^^^^\")\r\n print(\"your score is\",score)\r\n print(\"^^^^^^^^^^^^^\")\r\n\r\n del questions[0]\r\n r-=1\r\n break\r\n else:\r\n print(\"please enter the alphabet for the chosen option\")\r\n \r\n#end of quiz summary\r\nprint(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\r\nprint(\"End of quiz summary\")\r\nprint(\"Your final score is\", score,\"out of\",total)\r\nprint(\"That means you answered\", (round(score/total*100,2)),\"% of the questions correctly!\")\r\nprint(\"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\")\r\nexit()\r\n\r\n\r\n","sub_path":"PYTHON ASSESSMENT/Assembled quiz.py","file_name":"Assembled quiz.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"70261520","text":"# Extract_AGDC_for_study_sites_monthly_raijin.py\n\n'''\nThis code extracts all available measurement data for each of a list of case study sites, then saves the time averaged output to a netcdf file for later use. This code was designed \nto minimise the amount of time required to perform analyses with datacube data over known areas. By creating the netcdf files of each measurement, these can be called in by another \nprogram and quickly analysed to look for patterns.\nThis code saves a single netcdf file with monthly time averaged data.\n\nNote that the netcdf files should eventually be deleted once the further analyses have been conducted to avoid duplication of data, and to save memory on /g/data.\n\nCreated by Claire Krause January 2017 Datacube version 1.1.13\n\nDependancies in this code:\n- csv file with the lat/lon coordinates of the case study bounding box/es\n\nAccompanying code\n- Extract_AGDC_for_study_sites.ipynb - steps through this code with explanations of how this code is compiled. See the acompanying code for more detailed explanations and\nexamples\n- Run_AGDC_extraction - PBS submission code to generate single CPU jobs for each study site\n'''\n\n# Import the libraries we need in the code and tell matplotlib to display the plots here\nimport fiona\nimport shapely.geometry\nimport rasterio\nimport rasterio.features\nimport datacube\ndatacube.set_options(reproject_threads=1)\nimport numpy as np\nfrom datacube.storage import masking\nimport matplotlib.pyplot as plt\nimport xarray as xr\nimport scipy.stats\nimport pandas\nimport os \nimport sys\nfrom affine import Affine\n\n# Set up some functions to use later in the code\ndef warp_geometry(geom, src_crs, dst_crs):\n \"\"\"\n warp geometry from src_crs to dst_crs\n \"\"\"\n return shapely.geometry.shape(rasterio.warp.transform_geom(src_crs, dst_crs, shapely.geometry.mapping(geom)))\n\ndef geometry_mask(geom, geobox, all_touched=False, invert=False):\n \"\"\"\n rasterize geometry into a binary mask where pixels that overlap geometry are False\n \"\"\"\n return rasterio.features.geometry_mask([geom],\n out_shape=geobox.shape,\n transform=geobox.affine,\n all_touched=all_touched,\n invert=invert)\n\ndef pq_fuser(dest, src):\n valid_bit = 8\n valid_val = (1 << valid_bit)\n\n no_data_dest_mask = ~(dest & valid_val).astype(bool)\n np.copyto(dest, src, where=no_data_dest_mask)\n\n both_data_mask = (valid_val & dest & src).astype(bool)\n np.copyto(dest, src & dest, where=both_data_mask)\n\ndef return_good_pixels(nbar, pq):\n \"\"\"\n This function uses pixel quality information to mask out and remove pixel quality artifacts from extracted data.\n \"\"\"\n mask_components = {'cloud_acca':'no_cloud',\n 'cloud_shadow_acca' :'no_cloud_shadow',\n 'cloud_shadow_fmask' : 'no_cloud_shadow',\n 'cloud_fmask' :'no_cloud',\n 'blue_saturated' : False,\n 'green_saturated' : False,\n 'red_saturated' : False,\n 'nir_saturated' : False,\n 'swir1_saturated' : False,\n 'swir2_saturated' : False,\n 'contiguous':True}\n pqmask = masking.make_mask(pq.pixelquality, **mask_components)\n return nbar.where(pqmask)\n\n##############################################################################################\n\nnames = pandas.read_csv('/g/data/p25/cek156/case_study_sites_small.csv', delimiter = ',')\n\nprint(sys.argv)\nnum = int(sys.argv[1])\nStudysite = names.ix[num]\nprint('Working on ' + Studysite.Name)\n\n# Pull in some data from the datacube to apply our mask to\ndc = datacube.Datacube(app='poly-drill-recipe')\n\n#Define wavelengths/bands of interest, remove this kwarg to retrieve all bands\nbands_of_interest = ['blue',\n 'green',\n 'red', \n 'nir',\n 'swir1', \n 'swir2',\n ]\n\n#Define sensors of interest\nsensors = ['ls8', 'ls7', 'ls5'] \n\nOUTPUT_dir = '/g/data/p25/cek156/' + Studysite.Name\n\n# Set up AGDC extraction query\nquery = {'lat': (names.maxlat[num], names.minlat[num]), \n 'lon': (names.minlon[num], names.maxlon[num]),\n 'resolution': (-250, 250)}\n\n# Loop through the bands of interest\nfor band in enumerate(bands_of_interest):\n print('Working on ' + band[1])\n\n OUTPUT_file = '/g/data/p25/cek156/' + Studysite.Name + '/' + Studysite.Name + '_' + band[1] + 'monthly_time_mean.nc'\n\n # Check if this file already exists, and if so, skip this iteration\n file_check = file_check1 = os.path.isfile(OUTPUT_file)\n if file_check == True:\n print(band[1] + ' file aready created. Moving onto the next one...')\n elif file_check == False:\n # Grab data from all three sensors (ls5, ls7 and ls8). We will loop through the three sensors, then calculate an average.\n for idx, sensor in enumerate(sensors):\n #Retrieve the data and pixel quality (PQ) data for sensor n\n sens = 1\n nbar = dc.load(product = sensor +'_nbar_albers', group_by='solar_day', measurements = [band[1]], **query)\n if nbar : \n pq = dc.load(product = sensor +'_pq_albers', group_by='solar_day', fuse_func=pq_fuser, **query)\n crs = nbar.crs.wkt\n affine = nbar.affine\n geobox = nbar.geobox\n # Filter the data to remove bad pixels\n nbar = return_good_pixels(nbar, pq)\n print('Finished grabbing data for ' + sensor)\n if sens == 1:\n allsens = nbar\n sens = sens + 1\n elif sens == 2:\n allsens = xr.concat([allsens, nbar], dim = 'new_dim')\n sens = sens + 1\n else:\n nbar = xr.concat([nbar], dim = 'new_dim')\n allsens = xr.concat([allsens, nbar], dim = 'new_dim')\n sens = sens + 1 \n if sens >= 3:\n datamean = allsens.mean(dim = 'new_dim') \n datamean = datamean.groupby('time.month').mean()\n else:\n #datamean = allsens.mean(dim = 'time')\n datamean = allsens.groupby('time.month').mean()\n\n ## Save the time-mean, all sensor mean data into a netcdf file for later use.\n # Check whether the Study site directory has been created, and if not, create it.\n dir_check = os.path.isdir(OUTPUT_dir)\n if dir_check == False:\n os.makedirs(OUTPUT_dir)\n\n # Save the outputs so that we don't need to keep running this script\n datamean.attrs['affine'] = affine\n datamean.attrs['crs'] = crs\n #ds.attrs['geobox'] = geobox\n datamean.to_netcdf(path = OUTPUT_file, mode = 'w')\n print('Saved ' + band[1] + ' averages for ' + Studysite.Name)\nprint('Finished with ' + Studysite.Name)\n","sub_path":"Extract_AGDC_for_study_sites_monthly_raijin.py","file_name":"Extract_AGDC_for_study_sites_monthly_raijin.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"577149999","text":"from util import get_resource_path\nfrom mapcreator import gdal_util\nimport mock\nPRECISION = 0.0001\n\n@mock.patch('subprocess.Popen')\ndef test_gdal_coordinates(mock_popen):\n f = open(get_resource_path('test_satelliteimg_gdalinfo.txt'), 'rb')\n mock_popen.return_value.__enter__.return_value.communicate.return_value = (f.read(), b'')\n gdal_info = gdal_util.Gdalinfo.for_file(get_resource_path('test_satelliteimage.tif'))\n assert abs(gdal_info.minX - (-112.5047533)) < PRECISION\n assert abs(gdal_info.maxY - (36.0036116)) < PRECISION\n\n assert abs(gdal_info.maxX - (-112.4328512)) < PRECISION\n assert abs(gdal_info.minY - (35.9338875)) < PRECISION","sub_path":"tests/test_gdal_util.py","file_name":"test_gdal_util.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"599918097","text":"import tempfile\nimport time\nimport threading\nimport subprocess\n\nclass Komander(object):\n \"\"\" Launch commands and returns the output \"\"\"\n\n @staticmethod\n def run(cmd, timeout=0):\n \"\"\"\n Executes a command in the shell,\n Returns a ShellCommand object with the results\n \"\"\"\n tmp_stdout = tempfile.SpooledTemporaryFile()\n tmp_stderr = tempfile.SpooledTemporaryFile()\n\n command = ShellCommand(cmd)\n p = subprocess.Popen(command.cmd, stdout=tmp_stdout,\n stderr=tmp_stderr, shell=True)\n\n # Wait for subprocess to complete.\n\n if timeout > 0:\n while p.poll() is None and timeout > 0:\n time.sleep(0.25)\n timeout -= 0.25\n p.kill()\n\n p.communicate()\n tmp_stdout.seek(0)\n tmp_stderr.seek(0)\n\n command.stdout = tmp_stdout.read()\n command.stderr = tmp_stderr.read()\n command.retcode = p.returncode\n\n tmp_stdout.close()\n tmp_stderr.close()\n\n return command\n\nclass ShellCommand(object):\n \"\"\" Represents a shell command \"\"\"\n\n def __init__(self, cmd=\"\"):\n self.cmd = cmd\n self.stdout = \"\"\n self.stderr = \"\"\n self.retcode = \"\"\n\n def __str__(self):\n msg = \"Command : {0}\\nstdout = {1}\\nstderr = {2}\\nretcode = {3}\"\n return msg.format(self.cmd,\n self.stdout,\n self.stderr,\n self.retcode)\n","sub_path":"diff_demo/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"368091917","text":"def train(batch_size, epochs):\n '''\n this takes batch size and epochs as args, and train CNN on fminst dataset\n '''\n ## tutorial by adesphande3 on github\n \n import tensorflow as tf\n import random\n import numpy as np\n import matplotlib.pyplot as plt\n import datetime\n import fashion_data_import as fin\n #%matplotlib inline # what's this do?\n \n # loading MNIST dataset from TF library\n from tensorflow.examples.tutorials.mnist import input_data\n from sklearn import preprocessing\n #mnist = input_data.read_data_sets('MNIST_data/', one_hot=True) # alraedy onehotted\n # but this should be the fMNIST dataset loading and data preprocessing \n Xo, yo = fin.data_in('train')\n Xt, yt = fin.data_in('test')\n # oneHot\n enc = preprocessing.OneHotEncoder()\n enc.fit(yo)\n y_data = enc.transform(yo).toarray() # oneHot as ndarray\n #y_data = tf.one_hot(yo, depth=10) # oneHot as Tensor\n #yt_data = tf.one_hot(yt, depth=10)\n #enc = preprocessing.OneHotEncoder()\n enc.fit(yt)\n yt_data = enc.transform(yt).toarray() # oneHot as ndarray\n ## batch creating function\n def next_batch(num, data, labels):\n \"\"\"\n Returns a total of 'num' random samples and labels\n \"\"\"\n idx = np.arange(0, len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n labels_shuffle = [labels[i] for i in idx]\n \n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n \n \n ## Human readable labels, corresponding to the number labels\n human_label = {0:'T-shirt/top', 1:'Trouser', 2:'Pullover', 3:'Dress', 4:'Coat', 5:'Sandal', 6:'Shirt', 7:'Sneaker', 8:'Bag', 9:'Ankle boot'}\n \n ##### INPUTS AND OUTPUTS\n \n \"\"\"\n So, in this next step, we're just going to create a session. \n Your x and y_ are just going to place placeholders that basically just indicate\n the type of input you want in your CNN and the type of output. \n For each of these placeholders, you have to specify the type and the shape.\n \"\"\"\n \n tf.reset_default_graph()\n sess = tf.InteractiveSession()\n x = tf.placeholder(\"float\", shape = [None, 28, 28, 1]) # shape in CNNs is always None x height x w\n y_ = tf.placeholder(\"float\", shape=[None, 10]) # shape is always None x number of classes\n \n ##### NETWORK ARCHITECTURE #####\n \"\"\"\n With placeholders, we can now specify the network architecture.\n All of the weights and filters are TF variable. \n \"\"\"\n # Filters and biases for the first layer\n W_conv1 = tf.Variable(tf.truncated_normal([5, 5, 1, 32], stddev=0.1)) # shape is fileter x filter x input channels x output channels\n b_conv1 = tf.Variable(tf.constant(.1, shape=[32])) # shape of the bias just has to match output channels of the filter\n \n ## Call first conv layer, with 4 vars. \n # input(placeholder), the filter, the stride, the padding\n \n print('x', x)\n print('1st layer weight: ', W_conv1)\n \n h_conv1 = tf.nn.conv2d(input=x, filter=W_conv1, strides=[1, 1, 1, 1], padding='SAME') + b_conv1\n #h_conv1 = tf.nn.relu(h_conv1)\n h_conv1 = tf.nn.sigmoid(h_conv1)\n h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n \n ## organizing method calling functions\n def conv2d(x, W):\n return tf.nn.conv2d(input=x, filter=W, strides=[1, 1, 1, 1], padding='SAME')\n \n def max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n \n ## completing the network\n \n # Second Conv and Pool Layers\n W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1))\n b_conv2 = tf.Variable(tf.constant(.1, shape=[64]))\n #h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n h_conv2 = tf.nn.sigmoid(conv2d(h_pool1, W_conv2) + b_conv2)\n h_pool2 = max_pool_2x2(h_conv2)\n \n #First Fully Connected Layer\n W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1))\n b_fc1 = tf.Variable(tf.constant(.1, shape=[1024]))\n h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n #h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n h_fc1 = tf.nn.sigmoid(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n \n # Dropout Layer\n keep_prob = tf.placeholder('float')\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n \n # Second Fully Connected Layer\n W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1))\n b_fc2 = tf.Variable(tf.constant(.1, shape=[10]))\n \n # Final Layer\n y = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n \n ## formulating loss function\n crossEntropyLoss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits = y))\n \n # optimizer to minimize the function\n trainStep = tf.train.AdamOptimizer().minimize(crossEntropyLoss)\n \n ## Calculating the accuracy\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) #y_, ?? \n accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))\n \n ## initializing everything\n sess.run(tf.global_variables_initializer())\n \n ## Visualization\n tf.summary.scalar('Cross_Entropy_Loss', crossEntropyLoss)\n tf.summary.scalar('Accuracy', accuracy)\n merged = tf.summary.merge_all()\n logdir = 'tensorboard/' + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\") + \"/\"\n writer = tf.summary.FileWriter(logdir, sess.graph)\n \n b, v = next_batch(1, Xo, y_data)\n print(b[0].shape) #b[0] contains the image\n image = tf.reshape(b[0], [-1, 28, 28, 1])\n print(image)\n my_img = image.eval() # here is your image Tensor\n my_i = my_img.squeeze()\n v_label = int(v.argmax(axis=1))\n xlabel = 'Label: ' + str(v_label) + ', ' + str(human_label[v_label])\n plt.xlabel(xlabel)\n plt.imshow(my_i, cmap='gray_r')\n plt.show()\n \n ##### TRAINING #####\n \n i = 0\n batchSize = batch_size \n trainAccuracy = 0\n for i in range(epochs):\n #while trainAccuracy < 0.95 and i < 6000:\n #batch = mnist.train.next_batch(batchSize)\n X_batch, y_batch = next_batch(batchSize, Xo, y_data)\n trainingInputs = X_batch.reshape([batchSize, 28, 28, 1]) # 50x28x28x1\n trainingLabels = y_batch \n #trainingInputs = batch[0].reshape([batchSize, 28, 28, 1]) # 50x28x28x1\n #trainingLabels = batch[1] # 50x10\n if i%10 == 0:\n summary = sess.run(merged, {x: trainingInputs, y_: trainingLabels, keep_prob:1.0})\n writer.add_summary(summary, i)\n if i%100 == 0:\n trainAccuracy = accuracy.eval(session=sess, feed_dict={x:trainingInputs, y_:trainingLabels, keep_prob:1.0})\n print(\"step %d, training accuracy %g\"%(i, trainAccuracy))\n trainStep.run(session = sess, feed_dict={x: trainingInputs, y_:trainingLabels,keep_prob:0.5})\n #i += 1 # increment the counter\n \n \n ##### TESTING #####\n \n #testInputs = mnist.test.images.reshape([-1, 28, 28, 1])\n #testLabels = mnist.test.labels\n testInputs = Xt.reshape([-1, 28, 28, 1]) # =1 becasue of placeholder setup for batch\n testLabels = yt_data\n acc = accuracy.eval(feed_dict = {x:testInputs, y_:testLabels, keep_prob:1.0})\n print(\"testing accuracy: {}\".format(acc))\n\n","sub_path":"cnn_fmnist/cnn_fminf.py","file_name":"cnn_fminf.py","file_ext":"py","file_size_in_byte":7286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"521396040","text":"import numpy as np\nimport cv2\nimport lmdb\nimport ImageLoader as il\nimport os\nimport caffe\nimport caffe.proto\nimport matplotlib.pyplot as plt\nfrom Cython.Compiler.ExprNodes import constant_value_not_set\nfrom numpy import int\n\n\n\n#Preperation of Dataset\ndef database(pathtoTest,pathtoNTest):\n N = 2 * 11 * 11\n X = np.zeros(N,1,572,572, dtype=np.uint8)\n Y = np.zeros(N,1,388,388,dtype=np.uint8)\n map_size = X.nbytes() * N\n env = lmdb.open(\"train_lmdb\", map_size=map_size)\n with env.begin(write=True) as txn:\n for i in range(N):\n datum = caffe.proto.caffe_pb2.Datum()\n datum.channels = X.shape[1]\n datum.height = X.shape[2]\n datum.width = X.shape[3]\n datum.data = X[i].tobytes()\n datum.label = int(Y[i])\n str_id = '{:08}'.format(i)\n txn.put(str_id.encode('ascii'),datum.SerializeToString())\n return env\n#Fill data directory\ndef makeFillTestDirectory(n):\n os.chdir(\"../\")\n path = \"Data/\"\n pathT = \"Test_Data/\"\n pathTN = \"Test_NData/\"\n pathTestData = path + pathT + \"Set00\" + str(n) + \"/Split/\"\n pathTestNData = path + pathTN + \"Set00\" + str(n) + \"/Split/\"\n path3388 = path + pathT + \"Set00\"+ str(n) + \"/3388.png\"\n path5584 = path + pathT + \"Set00\"+ str(n) + \"/5584.png\"\n pathNormal = path + pathT + \"Set00\"+ str(n) + \"/Normal.png\"\n img = il.loadImg(path+pathT + \"Set00\" + str(n) +\"/Normal.png\")\n img_resize3388 = il.resizeImage(img,(3492,3492))\n il.saveImg(path3388,img_resize3388)\n img_resize5584 = il.mirrorBorder(img,3296)\n il.saveImg(path5584,img_resize5584)\n il.saveImg(pathNormal,img)\n il.makeSplit(img_resize3388,9,pathTestNData)\n il.makeSplit(img_resize5584,9,pathTestData)\n\nif __name__ == \"__main__\":\n makeFillTestDirectory(1)\n\n","sub_path":"Tools/DataPrep.py","file_name":"DataPrep.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"307800882","text":"#\n# @lc app=leetcode.cn id=86 lang=python\n#\n# [86] 分隔链表\n#\n# https://leetcode-cn.com/problems/partition-list/description/\n#\n# algorithms\n# Medium (52.90%)\n# Likes: 155\n# Dislikes: 0\n# Total Accepted: 24.8K\n# Total Submissions: 44.7K\n# Testcase Example: '[1,4,3,2,5,2]\\n3'\n#\n# 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。\n# \n# 你应当保留两个分区中每个节点的初始相对位置。\n# \n# 示例:\n# \n# 输入: head = 1->4->3->2->5->2, x = 3\n# 输出: 1->2->2->4->3->5\n# \n# \n#\n\n# @lc code=start\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def partition(self, head, x):\n \"\"\"\n :type head: ListNode\n :type x: int\n :rtype: ListNode\n \"\"\"\n min_chain = ListNode(-1)\n max_chain = ListNode(-1)\n pt1 = min_chain\n pt2 = max_chain\n # 遍历链表形成两条子链\n while not head == None:\n if head.val < x:\n pt1.next = head\n pt1 = pt1.next\n else:\n pt2.next = head\n pt2 = pt2.next\n head = head.next\n pt1.next = None\n pt2.next = None\n # 掐头\n min_chain = min_chain.next\n max_chain = max_chain.next\n if min_chain == None:\n return max_chain\n else:\n # 衔接\n pt1.next = max_chain\n return min_chain\n \n# @lc code=end\n\n\nhead = ListNode(1)\n# head.next = ListNode(4)\n# head.next.next = ListNode(3)\n# head.next.next.next = ListNode(2)\n# head.next.next.next.next = ListNode(5)\n# head.next.next.next.next.next = ListNode(2)\nx = 0\nsolu = Solution()\nans = solu.partition(head,x)\nwhile not ans == None:\n print(ans.val)\n ans = ans.next\n\n","sub_path":"86.分隔链表.py","file_name":"86.分隔链表.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"499613297","text":"import re\n\nimport _pickle as cPickle\nimport nltk\nfrom config import config\nfrom util import coreNlp as nlp\nwith open(config.get('spellcheck_dic'), 'rb') as handle:\n dic_search_pickle = cPickle.load(handle)\n\nproperties = {\n 'annotators': 'tokenize,ssplit,ner',\n 'outputFormat': 'json'\n}\n\n\ndef loadDicts(word):\n lookup_flags = []\n if word.lower() in dic_search_pickle:\n lookup_flags.append(\"Y\")\n else:\n lookup_flags.append(\"N\")\n return lookup_flags\n\n\ndef getvalidwords(file_content):\n file_content = re.sub(\n r'((https?|ftp|smtp)://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+|(www)(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+|(?:[\\d]{1,3})\\.(?:[\\d]{1,3})\\.(?:[\\d]{1,3})\\.(?:[\\d]{1,3})|[a-zA-Z0-9+_\\-\\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+)',\n ' ', str(file_content), flags=re.M | re.I | re.S)\n return (re.findall(r'\\b[a-z|A-Z]{3,45}\\b', file_content, flags=re.M | re.I | re.S))\n\n\ndef removeStopWords(words):\n stopwords = nltk.corpus.stopwords.words('english')\n newStopWords = ['The', 'among', 'I', 'ME', 'MY', 'MYSELF', 'WE', 'OUR', 'OURS', 'OURSELVES', 'YOU', \"YOU'RE\",\n \"YOU'VE\", \"YOU'LL\", \"YOU'D\", 'YOUR', 'YOURS', 'YOURSELF', 'YOURSELVES', 'HE', 'HIM', 'HIS',\n 'HIMSELF', 'SHE', \"SHE'S\", 'HER', 'HERS', 'HERSELF', 'IT', \"IT'S\", 'ITS', 'ITSELF', 'THEY', 'THEM',\n 'THEIR', 'THEIRS', 'THEMSELVES', 'WHAT', 'WHICH', 'WHO', 'WHOM', 'THIS', 'THAT', \"THAT'LL\", 'THESE',\n 'THOSE', 'AM', 'IS', 'ARE', 'WAS', 'WERE', 'BE', 'BEEN', 'BEING', 'HAVE', 'HAS', 'HAD', 'HAVING',\n 'DO', 'DOES', 'DID', 'DOING', 'A', 'AN', 'THE', 'AND', 'BUT', 'IF', 'OR', 'BECAUSE', 'AS', 'UNTIL',\n 'WHILE', 'OF', 'AT', 'BY', 'FOR', 'WITH', 'ABOUT', 'AGAINST', 'BETWEEN', 'INTO', 'THROUGH',\n 'DURING', 'BEFORE', 'AFTER', 'ABOVE', 'BELOW', 'TO', 'FROM', 'UP', 'DOWN', 'IN', 'OUT', 'ON', 'OFF',\n 'OVER', 'UNDER', 'AGAIN', 'FURTHER', 'THEN', 'ONCE', 'HERE', 'THERE', 'WHEN', 'WHERE', 'WHY', 'HOW',\n 'ALL', 'ANY', 'BOTH', 'EACH', 'FEW', 'MORE', 'MOST', 'OTHER', 'SOME', 'SUCH', 'NO', 'NOR', 'NOT',\n 'ONLY', 'OWN', 'SAME', 'SO', 'THAN', 'TOO', 'VERY', 'S', 'T', 'CAN', 'WILL', 'JUST', 'DON', \"DON'T\",\n 'SHOULD', \"SHOULD'VE\", 'NOW', 'D', 'LL', 'M', 'O', 'RE', 'VE', 'Y', 'AIN', 'AREN', \"AREN'T\",\n 'COULDN', \"COULDN'T\", 'DIDN', \"DIDN'T\", 'DOESN', \"DOESN'T\", 'HADN', \"HADN'T\", 'HASN', \"HASN'T\",\n 'HAVEN', \"HAVEN'T\", 'ISN', \"ISN'T\", 'MA', 'MIGHTN', \"MIGHTN'T\", 'MUSTN', \"MUSTN'T\", 'NEEDN',\n \"NEEDN'T\", 'SHAN', \"SHAN'T\", 'SHOULDN', \"SHOULDN'T\", 'WASN', \"WASN'T\", 'WEREN', \"WEREN'T\", 'WON',\n \"WON'T\", 'WOULDN', \"WOULDN'T\", 'THE', \"I\", \"Me\", \"My\", \"Myself\", \"We\", \"Our\", \"Ours\", \"Ourselves\",\n \"You\", \"You're\", \"You've\", \"You'll\", \"You'd\", \"Your\", \"Yours\", \"Yourself\", \"Yourselves\", \"He\",\n \"Him\", \"His\", \"Himself\", \"She\", \"She's\", \"Her\", \"Hers\", \"Herself\", \"It\", \"It's\", \"Its\", \"Itself\",\n \"They\", \"Them\", \"Their\", \"Theirs\", \"Themselves\", \"What\", \"Which\", \"Who\", \"Whom\", \"This\", \"That\",\n \"That'll\", \"These\", \"Those\", \"Am\", \"Is\", \"Are\", \"Was\", \"Were\", \"Be\", \"Been\", \"Being\", \"Have\", \"Has\",\n \"Had\", \"Having\", \"Do\", \"Does\", \"Did\", \"Doing\", \"A\", \"An\", \"The\", \"And\", \"But\", \"If\", \"Or\",\n \"Because\", \"As\", \"Until\", \"While\", \"Of\", \"At\", \"By\", \"For\", \"With\", \"About\", \"Against\", \"Between\",\n \"Into\", \"Through\", \"During\", \"Before\", \"After\", \"Above\", \"Below\", \"To\", \"From\", \"Up\", \"Down\", \"In\",\n \"Out\", \"On\", \"Off\", \"Over\", \"Under\", \"Again\", \"Further\", \"Then\", \"Once\", \"Here\", \"There\", \"When\",\n \"Where\", \"Why\", \"How\", \"All\", \"Any\", \"Both\", \"Each\", \"Few\", \"More\", \"Most\", \"Other\", \"Some\", \"Such\",\n \"No\", \"Nor\", \"Not\", \"Only\", \"Own\", \"Same\", \"So\", \"Than\", \"Too\", \"Very\", \"S\", \"T\", \"Can\", \"Will\",\n \"Just\", \"Don\", \"Don't\", \"Should\", \"Should've\", \"Now\", \"D\", \"Ll\", \"M\", \"O\", \"Re\", \"Ve\", \"Y\", \"Ain\",\n \"Aren\", \"Aren't\", \"Couldn\", \"Couldn't\", \"Didn\", \"Didn't\", \"Doesn\", \"Doesn't\", \"Hadn\", \"Hadn't\",\n \"Hasn\", \"Hasn't\", \"Haven\", \"Haven't\", \"Isn\", \"Isn't\", \"Ma\", \"Mightn\", \"Mightn't\", \"Mustn\",\n \"Mustn't\", \"Needn\", \"Needn't\", \"Shan\", \"Shan't\", \"Shouldn\", \"Shouldn't\", \"Wasn\", \"Wasn't\", \"Weren\",\n \"Weren't\", \"Won\", \"Won't\", \"Wouldn\", \"Wouldn't\", ]\n stopwords.extend(newStopWords)\n important_words = []\n for word in words:\n if word not in stopwords:\n word = word.strip('\\-\\–\\--\\---\\—\\–\\| ')\n important_words.append(word)\n Final_vocab_per_paper = set(important_words)\n return Final_vocab_per_paper\n\n\ndef identifyNER(Final_vocab_per_paper):\n #print(Final_vocab_per_paper)\n Final_vocab_per_paper = list(Final_vocab_per_paper)\n important_words = []\n for i in range(0, len(Final_vocab_per_paper)):\n output = nlp.annotate(Final_vocab_per_paper[i], properties=properties)\n for sentence in output['sentences']:\n #print(output)\n for t in sentence['tokens']:\n if t['ner'] == 'O':\n important_words.append(t['word'])\n else:\n pass\n Final_vocab_per_paper = set(important_words)\n return Final_vocab_per_paper\n\n\ndef identifySpellingMistake(Final_vocab_per_paper):\n final_spell_error = []\n #print(Final_vocab_per_paper)\n for word in Final_vocab_per_paper:\n if not (word.isupper()):\n flag_list = loadDicts(word)\n if 'Y' in flag_list:\n pass\n else:\n final_spell_error.append(word)\n return len(final_spell_error)\n\n\ndef detectSpellErrorSingleFile(text_data):\n words = getvalidwords(text_data)\n Final_vocab_per_paper_after_removing_stopword = removeStopWords(words)\n Final_vocab_per_paper = identifyNER(Final_vocab_per_paper_after_removing_stopword)\n result = identifySpellingMistake(Final_vocab_per_paper)\n return result\n","sub_path":"spellerrordetect.py","file_name":"spellerrordetect.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"319657014","text":"'''\r\nGiven a non negative integer number num.\r\nFor every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.\r\n\r\nExample:\r\nFor num = 5 you should return [0,1,1,2,1,2].\r\n\r\nFollow up:\r\nIt is very easy to come up with a solution with run time O(n*sizeof(integer)).\r\nBut can you do it in linear time O(n) /possibly in a single pass?\r\nSpace complexity should be O(n).\r\nCan you do it like a boss?\r\nDo it without using any builtin function like __builtin_popcount in c++ or in any other language.\r\n\r\nCredits:\r\nSpecial thanks to @ syedee for adding this problem and creating all test cases.\r\n'''\r\n\r\nclass Solution(object):\r\n def countBits(self, num):\r\n \"\"\"\r\n :type num: int\r\n :rtype: List[int]\r\n \"\"\"\r\n \r\n result = [0]\r\n print (result)\r\n while len(result) <= num :\r\n \tex_list = list(map(lambda x : x + 1, result))\r\n \tresult.extend(ex_list)\r\n \tprint (\"ex :\" , ex_list, \"result :\" , result)\r\n return result[:num + 1]\r\n \r\nif __name__ == \"__main__\":\r\n\t\r\n\tnum = 5\r\n\r\n\tresult = Solution().countBits(num)\r\n\tprint (result)","sub_path":"python/Dynamic Programming/338_Counting_Bits.py","file_name":"338_Counting_Bits.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"274551659","text":"import os\n\nmax_events = 100000\ntotal_jobs = 10\n\nos.system(\"mkdir -p JobFiles\")\n\n# Starts from 1 to match the SLURM array index\nfor i in range(1, total_jobs+1):\n template_file = open(\"oneStep_wideRange_template.py\", \"r\")\n output_file = open(\"JobFiles/oneStep_wideRange_\"+str(i)+\".py\", \"w\")\n for line in template_file:\n line = line.replace(\"GENERATORSEED\", str(i))\n line = line.replace(\"VTXSMEAREDSEED\", str(i+1))\n line = line.replace(\"G4SIMHITSSEED\", str(i+2))\n line = line.replace(\"MIXSEED\", str(i+3))\n line = line.replace(\"MAXEVENTS\", str(max_events))\n line = line.replace(\"INDEX\", str(i))\n output_file.write(line)\n\n output_file.close()\n\nslurm_template_file = open(\"jobFile_template.slrm\", \"r\")\nslurm_output_file = open(\"JobFiles/jobFile.slrm\", \"w\")\nfor line in slurm_template_file:\n line = line.replace(\"ARRAYMAX\", str(total_jobs))\n slurm_output_file.write(line)\nslurm_output_file.close()\n","sub_path":"LinearizedTrackFit/test/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"447169139","text":"import os\n\nenvDic = {}\nHOME = os.environ.get(\"HOME\")\ndicPath = \"%s/.myPythonEnv\" % HOME\ninitFlag = False\n\ndef setMyPythonEnv(key, value):\n global initFlag\n global dicPath\n if not initFlag:\n loadDic(dicPath)\n envDic[key] = value\n saveDic(dicPath)\ndef getMyPythonEnv(key):\n global initFlag\n global dicPath\n if not initFlag:\n loadDic(dicPath)\n return envDic.get(key)\n\ndef loadDic(dicPath):\n global envDic\n fp = open(dicPath, \"a+\")\n envList = fp.readlines()\n '''\n repeatCount 2\n '''\n for line in envList:\n element = line.split(\":\")\n envDic[element[0]] = element[1].strip()\n\n fp.close()\n\ndef saveDic(dicPath):\n global envDic\n fp = open(dicPath, \"w+\")\n for key, value in envDic.items():\n fp.write(key)\n fp.write(\":\")\n fp.write(value)\n fp.write(\"\\n\")\n fp.flush()\n fp.close()\n\ndef getArg(key, returnType):\n lastArg = getMyPythonEnv(key)\n arg = raw_input((\"%s(%s): \" % (key, lastArg)))\n if arg == \"\":\n arg = lastArg\n else:\n setMyPythonEnv(key, arg)\n if returnType == \"int\":\n return int(arg)\n elif returnType == \"str\":\n return arg\n","sub_path":"MyEnv.py","file_name":"MyEnv.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"264016549","text":"#!/usr/bin/env python\n\n'''\n@file ion/services/mi/drivers/satlantic_par/test/test_satlantic_par.py\n@author Steve Foley\n@test ion.services.mi.drivers.satlantic_par\nUnit test suite to test Satlantic PAR sensor\n@todo Find a way to test timeouts?\n'''\n\nfrom gevent import monkey; monkey.patch_all()\nimport gevent\n\nimport unittest\nimport time\nimport json\nfrom mock import Mock, call, DEFAULT\nfrom pyon.util.unit_test import PyonTestCase\nfrom nose.plugins.attrib import attr\nfrom unittest import TestCase\n\nfrom mi.core.log import get_logger ; log = get_logger()\n\nfrom mi.core.common import InstErrorCode\nfrom mi.core.instrument.instrument_driver import DriverState\nfrom mi.core.instrument.instrument_driver import DriverConnectionState\nfrom mi.core.instrument.instrument_driver import DriverProtocolState\nfrom mi.core.instrument.instrument_protocol import InterfaceType\nfrom mi.core.instrument.data_particle import DataParticleKey\nfrom mi.core.instrument.data_particle import DataParticleValue\n\nfrom mi.core.exceptions import InstrumentProtocolException\nfrom mi.core.exceptions import InstrumentDataException\nfrom mi.core.exceptions import InstrumentCommandException\nfrom mi.core.exceptions import InstrumentStateException\nfrom mi.core.exceptions import InstrumentParameterException\n\nfrom mi.idk.unit_test import InstrumentDriverTestCase\nfrom mi.idk.unit_test import InstrumentDriverUnitTestCase\nfrom mi.idk.unit_test import InstrumentDriverIntegrationTestCase\nfrom mi.idk.unit_test import InstrumentDriverQualificationTestCase\n\nfrom mi.instrument.satlantic.par_ser_600m.driver import SatlanticPARInstrumentProtocol\nfrom mi.instrument.satlantic.par_ser_600m.driver import PARProtocolState\nfrom mi.instrument.satlantic.par_ser_600m.driver import PARProtocolEvent\nfrom mi.instrument.satlantic.par_ser_600m.driver import Parameter\nfrom mi.instrument.satlantic.par_ser_600m.driver import Command\nfrom mi.instrument.satlantic.par_ser_600m.driver import SatlanticChecksumDecorator\nfrom mi.instrument.satlantic.par_ser_600m.driver import SatlanticPARDataParticle\nfrom mi.instrument.satlantic.par_ser_600m.driver import SatlanticPARDataParticleKey\n\nfrom interface.objects import AgentCommand\nfrom ion.agents.instrument.direct_access.direct_access_server import DirectAccessTypes\n\nfrom pyon.agent.agent import ResourceAgentState\nfrom pyon.agent.agent import ResourceAgentEvent\nfrom pyon.core.exception import Conflict\n\nVALID_SAMPLE = \"SATPAR0229,10.01,2206748544,234\"\n# Make tests verbose and provide stdout\n# bin/nosetests -s -v ion/services/mi/drivers/test/test_satlantic_par.py\n# All unit tests: add \"-a UNIT\" to end, integration add \"-a INT\"\n# Test device is at 10.180.80.173, port 2001\n\n\n@attr('UNIT', group='mi')\nclass SatlanticParProtocolUnitTest(InstrumentDriverUnitTestCase):\n \"\"\"\n @todo test timeout exceptions while transitioning states and handling commands\n \"\"\"\n \n #def setUp(self):\n \"\"\"\n Mocked up stuff\n \n def response_side_effect(*args, **kwargs):\n if args[0] == Command.SAMPLE:\n mi_logger.debug(\"Side effecting!\")\n return \"SATPAR0229,10.01,2206748544,234\"\n else:\n return DEFAULT\n \n self.mock_callback = Mock(name='callback')\n self.mock_logger = Mock(name='logger')\n self.mock_logger_client = Mock(name='logger_client')\n self.mock_fsm = Mock(name='fsm')\n# self.mock_logger_client.send = Mock()\n self.par_proto = SatlanticPARInstrumentProtocol(self.mock_callback)\n self.config_params = {'device_addr':'1.1.1.1',\n 'device_port':1,\n 'server_addr':'2.2.2.2',\n 'server_port':2}\n self.par_proto._fsm = self.mock_fsm\n self.par_proto.configure(self.config_params)\n self.par_proto.initialize()\n self.par_proto._logger = self.mock_logger \n self.par_proto._logger_client = self.mock_logger_client\n self.par_proto._get_response = Mock(return_value=('$', None))\n # Quick sanity check to make sure the logger got mocked properly\n self.assertEquals(self.par_proto._logger, self.mock_logger)\n self.assertEquals(self.par_proto._logger_client, self.mock_logger_client)\n self.assertEquals(self.par_proto._fsm, self.mock_fsm)\n self.mock_logger_client.reset_mock()\n \"\"\"\n \n\n @unittest.skip(\"Need better mocking of FSM or smaller testing chunks\")\n def test_get_param(self):\n # try single\n result = self.par_proto.get([Parameter.MAXRATE])\n self.mock_logger_client.send.assert_called_with(\"show %s\\n\" %\n Parameter.MAXRATE)\n \n # try group\n result = self.par_proto.get(Parameter.list())\n \n # try empty set\n self.mock_logger_client.reset_mock()\n result = self.par_proto.get([])\n self.assertEquals(result, {})\n self.assertEquals(self.mock_logger_client.send.call_count, 0)\n \n # try bad param\n self.assertRaises(InstrumentProtocolException, self.par_proto.get, None)\n self.assertRaises(InstrumentProtocolException,\n self.par_proto.get,['bad_param'])\n\n @unittest.skip(\"Need better mocking of FSM or smaller testing chunks\") \n def test_set_param(self):\n #@todo deal with success/fail flag or catch everywhere?\n #@todo add save checks?\n self.par_proto.set({Parameter.TELBAUD:9600})\n self.mock_logger_client.send.assert_called_with(\"set %s 9600\\n\" %\n Parameter.TELBAUD)\n self.mock_logger_client.send.assert_called_with(\"save\")\n \n self.par_proto.set({Parameter.MAXRATE:10})\n self.mock_logger_client.send.assert_called_with(\"set %s 10\\n\" %\n Parameter.MAXRATE)\n self.mock_logger_client.send.assert_called_with(\"save\")\n \n # try group\n self.mock_logger_client.reset_mock()\n self.par_proto.set({Parameter.TELBAUD:4800,Parameter.MAXRATE:9})\n self.assertEquals(self.mock_logger_client.send.call_count, 3)\n\n # try empty set\n self.mock_logger_client.reset_mock()\n result = self.par_proto.set({})\n self.assertEquals(self.mock_logger_client.send.call_count, 0)\n self.assertEquals(result, {})\n \n # some error cases\n self.assertRaises(InstrumentProtocolException, self.par_proto.set, [])\n self.assertRaises(InstrumentProtocolException, self.par_proto.set, None)\n self.assertRaises(InstrumentProtocolException, self.par_proto.set, ['foo'])\n \n # try bad param\n self.assertRaises(InstrumentProtocolException,\n self.par_proto.set,{'bad_param':0})\n \n @unittest.skip(\"Need better mocking of FSM or smaller testing chunks\")\n def test_get_config(self):\n fetched_config = {}\n fetched_config = self.par_proto.get_config()\n self.assert_(isinstance(fetched_config, dict))\n calls = [call(\"show %s\\n\" % Parameter.TELBAUD),\n call(\"show %s\\n\" % Parameter.MAXRATE)]\n self.mock_logger_client.send.assert_has_calls(calls, any_order=True)\n \n self.assertEquals(len(fetched_config), 2)\n self.assertTrue(fetched_config.has_key(Parameter.TELBAUD))\n self.assertTrue(fetched_config.has_key(Parameter.MAXRATE))\n \n @unittest.skip(\"Need better mocking of FSM or smaller testing chunks\")\n def test_restore_config(self):\n self.assertRaises(InstrumentProtocolException,\n self.par_proto.restore_config, None) \n \n self.assertRaises(InstrumentProtocolException,\n self.par_proto.restore_config, {})\n \n self.assertRaises(InstrumentProtocolException,\n self.par_proto.restore_config, {'bad_param':0})\n\n test_config = {Parameter.TELBAUD:19200, Parameter.MAXRATE:2}\n restore_result = self.par_proto.restore_config(test_config)\n calls = [call(\"set %s %s\\n\" % (Parameter.TELBAUD, 19200)),\n call(\"set %s %s\\n\" % (Parameter.MAXRATE, 2))]\n self.mock_logger_client.send.assert_has_calls(calls, any_order=True)\n \n @unittest.skip(\"Need better mocking of FSM or smaller testing chunks\")\n def test_get_single_value(self):\n result = self.par_proto.execute_poll()\n calls = [call(\"%s\\n\" % Command.EXIT),\n call(Command.STOP),\n call(Command.SAMPLE),\n call(Command.AUTOSAMPLE),\n call(Command.BREAK)]\n self.mock_logger_client.send.assert_has_calls(calls, any_order=False)\n \n @unittest.skip(\"Need better mocking of FSM or smaller testing chunks\")\n def test_breaks(self):\n # test kick to autosample, then back\n result = self.par_proto.execute_exit() \n self.mock_callback.reset_mock()\n result = self.par_proto.execute_break()\n self.mock_logger_client.send.assert_called_with(Command.BREAK) \n self.assertEqual(self.mock_callback.call_count, 1)\n\n # test autosample to poll change\n result = self.par_proto.execute_exit()\n self.mock_callback.reset_mock()\n result = self.par_proto.execute_stop()\n self.mock_logger_client.send.assert_called_with(Command.STOP)\n self.assertEqual(self.mock_callback.call_count, 1)\n\n result = self.par_proto.execute_autosample()\n self.mock_callback.reset_mock()\n result = self.par_proto.execute_reset()\n self.mock_logger_client.send.assert_called_with(Command.RESET)\n self.assertEqual(self.mock_callback.call_count, 1)\n\n self.mock_callback.reset_mock()\n result = self.par_proto.execute_break()\n self.mock_logger_client.send.assert_called_with(Command.BREAK)\n self.assertEqual(self.mock_callback.call_count, 1)\n \n @unittest.skip(\"Need better mocking of FSM or smaller testing chunks\")\n def test_got_data(self):\n # Cant trigger easily since the async command/response, so short circut\n # the test early.\n self.mock_callback.reset_mock()\n result = self.par_proto.execute_exit()\n self.assertEqual(self.mock_callback.call_count, 1)\n self.assert_(result)\n self.mock_callback.reset_mock()\n result = self.par_proto._got_data(\"SATPAR0229,10.01,2206748544,234\\n\")\n # check for publish\n self.assertEqual(self.mock_callback.call_count, 2)\n\n # check for correct parse\n \n @unittest.skip(\"Need better mocking of FSM or smaller testing chunks\")\n def test_connect_disconnect(self):\n pass\n \n @unittest.skip(\"Need better mocking of FSM or smaller testing chunks\")\n def test_get_status(self):\n pass\n \n def test_sample_format(self):\n \"\"\"\n Test to make sure we can get sample data out in a reasonable format.\n Parsed is all we care about...raw is tested in the base DataParticle tests\n VALID_SAMPLE = \"SATPAR0229,10.01,2206748544,234\"\n \"\"\"\n \n port_timestamp = 3555423720.711772\n internal_timestamp = 3555423721.711772\n driver_timestamp = 3555423722.711772\n particle = SatlanticPARDataParticle(VALID_SAMPLE,\n port_timestamp=port_timestamp,\n internal_timestamp=internal_timestamp)\n # perform the extraction into a structure for parsed\n sample_parsed_particle = {\n DataParticleKey.PKT_FORMAT_ID: DataParticleValue.JSON_DATA,\n DataParticleKey.PKT_VERSION: 1,\n DataParticleKey.STREAM_NAME: DataParticleValue.PARSED,\n DataParticleKey.PORT_TIMESTAMP: port_timestamp,\n DataParticleKey.DRIVER_TIMESTAMP: driver_timestamp,\n DataParticleKey.PREFERRED_TIMESTAMP: DataParticleKey.PORT_TIMESTAMP,\n DataParticleKey.QUALITY_FLAG: DataParticleValue.OK,\n DataParticleKey.VALUES: [\n {DataParticleKey.VALUE_ID:SatlanticPARDataParticleKey.SERIAL_NUM,\n DataParticleKey.VALUE:\"0229\"},\n {DataParticleKey.VALUE_ID:SatlanticPARDataParticleKey.TIMER,\n DataParticleKey.VALUE:10.01},\n {DataParticleKey.VALUE_ID:SatlanticPARDataParticleKey.COUNTS,\n DataParticleKey.VALUE: 2206748544},\n {DataParticleKey.VALUE_ID:SatlanticPARDataParticleKey.CHECKSUM,\n DataParticleKey.VALUE: 234}\n ]\n }\n \n self.compare_parsed_data_particle(SatlanticPARDataParticle,\n VALID_SAMPLE,\n sample_parsed_particle) \n\n#@unittest.skip(\"Need a VPN setup to test against RSN installation\")\n@attr('INT', group='mi')\nclass SatlanticParProtocolIntegrationTest(InstrumentDriverIntegrationTestCase):\n \n def check_state(self, expected_state):\n state = self.driver_client.cmd_dvr('get_resource_state')\n self.assertEqual(state, expected_state)\n \n\n def put_instrument_in_command_mode(self):\n \"\"\"Wrap the steps and asserts for going into command mode.\n May be used in multiple test cases.\n \"\"\"\n # Test that the driver is in state unconfigured.\n self.check_state(DriverConnectionState.UNCONFIGURED)\n\n # Configure driver and transition to disconnected.\n self.driver_client.cmd_dvr('configure', self.port_agent_comm_config())\n\n # Test that the driver is in state disconnected.\n self.check_state(DriverConnectionState.DISCONNECTED)\n\n # Setup the protocol state machine and the connection to port agent.\n self.driver_client.cmd_dvr('connect')\n\n # Test that the driver protocol is in state unknown.\n self.check_state(PARProtocolState.UNKNOWN)\n\n # Discover what state the instrument is in and set the protocol state accordingly.\n self.driver_client.cmd_dvr('discover_state')\n\n # Test that the driver protocol is in state command.\n self.check_state(PARProtocolState.COMMAND)\n\n\n def _start_stop_autosample(self):\n \"\"\"Wrap the steps and asserts for going into and out of auto sample.\n May be used in multiple test cases.\n \"\"\"\n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.START_AUTOSAMPLE)\n\n self.check_state(PARProtocolState.AUTOSAMPLE)\n \n # @todo check samples arriving here\n # @todo check publishing samples from here\n \n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.STOP_AUTOSAMPLE)\n \n self.check_state(PARProtocolState.COMMAND)\n \n\n def test_configuration(self):\n \"\"\"\n Test to configure the driver process for device comms and transition\n to disconnected state.\n \"\"\"\n\n # Test that the driver is in state unconfigured.\n self.check_state(DriverConnectionState.UNCONFIGURED)\n\n # Configure driver and transition to disconnected.\n self.driver_client.cmd_dvr('configure', self.port_agent_comm_config())\n\n # Test that the driver is in state disconnected.\n self.check_state(DriverConnectionState.DISCONNECTED)\n\n # Re-Initialize the driver and transition to unconfigured.\n self.driver_client.cmd_dvr('initialize')\n\n # Test that the driver returned to state unconfigured.\n self.check_state(DriverConnectionState.UNCONFIGURED)\n \n\n def test_connect_disconnect(self):\n \"\"\"\n Test configuring and connecting to the device through the port\n agent. Discover device state. Then disconnect and re-initialize\n \"\"\"\n self.put_instrument_in_command_mode()\n \n # Stop comms and transition to disconnected.\n self.driver_client.cmd_dvr('disconnect')\n\n # Test that the driver is in state disconnected.\n self.check_state(DriverConnectionState.DISCONNECTED)\n\n # Re-Initialize the driver and transition to unconfigured.\n self.driver_client.cmd_dvr('initialize')\n \n # Test that the driver returned to state unconfigured.\n self.check_state(DriverConnectionState.UNCONFIGURED)\n \n\n def test_get(self):\n \n self.put_instrument_in_command_mode()\n \n reply = self.driver_client.cmd_dvr('get_resource',\n [Parameter.TELBAUD,\n Parameter.MAXRATE],\n timeout=20)\n \n self.assertEquals(reply, {Parameter.TELBAUD:19200,\n Parameter.MAXRATE:1})\n \n self.assertRaises(InstrumentCommandException,\n self.driver_client.cmd_dvr,\n 'bogus', [Parameter.TELBAUD])\n\n # Assert get fails without a parameter.\n self.assertRaises(InstrumentParameterException,\n self.driver_client.cmd_dvr, 'get_resource')\n \n # Assert get fails with a bad parameter (not ALL or a list).\n with self.assertRaises(InstrumentParameterException):\n bogus_params = 'I am a bogus param list.'\n self.driver_client.cmd_dvr('get_resource', bogus_params)\n \n # Assert get fails with a bad parameter in a list).\n with self.assertRaises(InstrumentParameterException):\n bogus_params = [\n 'a bogus parameter name',\n Parameter.TELBAUD,\n Parameter.MAXRATE\n ]\n self.driver_client.cmd_dvr('get_resource', bogus_params) \n \n\n def test_set(self):\n config_key = Parameter.MAXRATE\n value_A = 12\n value_B = 1\n config_A = {config_key:value_A}\n config_B = {config_key:value_B}\n \n self.put_instrument_in_command_mode()\n \n reply = self.driver_client.cmd_dvr('set_resource', config_A, timeout=20)\n self.assertEquals(reply[config_key], value_A)\n \n reply = self.driver_client.cmd_dvr('get_resource', [config_key], timeout=20)\n self.assertEquals(reply, config_A)\n \n reply = self.driver_client.cmd_dvr('set_resource', config_B, timeout=20)\n self.assertEquals(reply[config_key], value_B)\n \n reply = self.driver_client.cmd_dvr('get_resource', [config_key], timeout=20)\n self.assertEquals(reply, config_B)\n\n # Assert we cannot set a bogus parameter.\n with self.assertRaises(InstrumentParameterException):\n bogus_params = {\n 'a bogus parameter name' : 'bogus value'\n }\n self.driver_client.cmd_dvr('set_resource', bogus_params)\n \n # Assert we cannot set a real parameter to a bogus value.\n with self.assertRaises(InstrumentParameterException):\n bogus_params = {\n Parameter.MAXRATE : 'bogus value'\n }\n self.driver_client.cmd_dvr('set_resource', bogus_params)\n \n \n #@unittest.skip('temp for debugging')\n def test_error_conditions(self):\n # Test that the driver is in state unconfigured.\n self.check_state(DriverConnectionState.UNCONFIGURED)\n\n # Assert we forgot the comms parameter.\n self.assertRaises(InstrumentParameterException,\n self.driver_client.cmd_dvr, 'configure')\n\n # Assert we send a bad config object (not a dict).\n with self.assertRaises(InstrumentParameterException):\n BOGUS_CONFIG = 'not a config dict' \n self.driver_client.cmd_dvr('configure', BOGUS_CONFIG)\n \n # Assert we send a bad config object (missing addr value).\n with self.assertRaises(InstrumentParameterException):\n BOGUS_CONFIG = self.port_agent_comm_config().copy()\n BOGUS_CONFIG.pop('addr')\n self.driver_client.cmd_dvr('configure', BOGUS_CONFIG)\n\n # Assert we send a bad config object (bad addr value).\n with self.assertRaises(InstrumentParameterException):\n BOGUS_CONFIG = self.port_agent_comm_config().copy()\n BOGUS_CONFIG['addr'] = ''\n self.driver_client.cmd_dvr('configure', BOGUS_CONFIG)\n \n # Configure driver and transition to disconnected.\n self.driver_client.cmd_dvr('configure', self.port_agent_comm_config())\n\n # Test that the driver is in state disconnected.\n self.check_state(DriverConnectionState.DISCONNECTED)\n\n # Assert for a known command, invalid state.\n self.assertRaises(InstrumentStateException,\n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.ACQUIRE_SAMPLE)\n\n # Setup the protocol state machine and the connection to port agent.\n self.driver_client.cmd_dvr('connect')\n\n # Test that the driver protocol is in state unknown.\n self.check_state(PARProtocolState.UNKNOWN)\n\n # Assert for a known command, invalid state.\n self.assertRaises(InstrumentStateException,\n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.ACQUIRE_SAMPLE)\n\n # Discover what state the instrument is in and set the protocol state accordingly.\n self.driver_client.cmd_dvr('discover_state')\n\n # Test that the driver protocol is in state command.\n self.check_state(PARProtocolState.COMMAND)\n\n # tests when driver is in command mode\n # Test a bad driver command \n self.assertRaises(InstrumentCommandException, \n self.driver_client.cmd_dvr, 'bogus_command')\n \n self.assertRaises(InstrumentStateException,\n self.driver_client.cmd_dvr, 'connect')\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.ACQUIRE_SAMPLE)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.RESET)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.STOP_AUTOSAMPLE)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.STOP_DIRECT)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.STOP_POLL)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.EXECUTE_DIRECT)\n\n # tests when driver is in auto-sample mode\n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.START_AUTOSAMPLE)\n self.check_state(PARProtocolState.AUTOSAMPLE)\n\n # Test a bad driver command \n self.assertRaises(InstrumentCommandException, \n self.driver_client.cmd_dvr, 'bogus_command')\n \n # Test get from wrong state\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'get_resource', [Parameter.MAXRATE])\n\n # Test set from wrong state\n self.assertRaises(InstrumentStateException,\n self.driver_client.cmd_dvr, 'set_resource', {Parameter.MAXRATE:10})\n\n # test commands for invalid state\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.ACQUIRE_SAMPLE)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.START_DIRECT)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.STOP_DIRECT)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.EXECUTE_DIRECT)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.STOP_POLL)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.START_AUTOSAMPLE)\n\n # tests when driver is in poll mode\n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.START_POLL)\n self.check_state(PARProtocolState.POLL)\n\n # Test a bad driver command \n self.assertRaises(InstrumentCommandException, \n self.driver_client.cmd_dvr, 'bogus_command')\n \n # Test get from wrong state\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'get_resource', [Parameter.MAXRATE])\n\n # Test set from wrong state\n self.assertRaises(InstrumentStateException,\n self.driver_client.cmd_dvr, 'set_resource', {Parameter.MAXRATE:10})\n\n # test commands for invalid state\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.START_DIRECT)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.STOP_DIRECT)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.EXECUTE_DIRECT)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.STOP_AUTOSAMPLE)\n\n self.assertRaises(InstrumentStateException, \n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.START_POLL)\n\n\n def test_stop_from_slow_autosample(self):\n # test break from autosample at low data rates\n self.put_instrument_in_command_mode()\n \n self.driver_client.cmd_dvr('set_resource', {Parameter.MAXRATE:1}, timeout=20)\n\n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.START_AUTOSAMPLE)\n #time.sleep(5)\n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.STOP_AUTOSAMPLE)\n self.check_state(PARProtocolState.COMMAND)\n\n\n def test_stop_from_fast_autosample(self):\n # test break from autosample at high data rates\n self.put_instrument_in_command_mode()\n \n self.driver_client.cmd_dvr('set_resource', {Parameter.MAXRATE:12}, timeout=20)\n\n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.START_AUTOSAMPLE)\n #time.sleep(5)\n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.STOP_AUTOSAMPLE)\n self.check_state(PARProtocolState.COMMAND)\n self.driver_client.cmd_dvr('set_resource', {Parameter.MAXRATE:1}, timeout=20)\n\n\n\n def test_start_stop_autosample(self):\n \"\"\"\n Test moving into and out of autosample, gathering some data, and\n seeing it published\n @todo check the publishing, integrate this with changes in march 2012\n \"\"\"\n\n self.put_instrument_in_command_mode()\n self._start_stop_autosample()\n \n\n def test_start_stop_poll(self):\n self.put_instrument_in_command_mode()\n \n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.START_POLL)\n self.check_state(PARProtocolState.POLL)\n time.sleep(2)\n\n # Already in poll mode, so this shouldn't give us anything\n self.assertRaises(InstrumentStateException,\n self.driver_client.cmd_dvr, 'execute_resource', PARProtocolEvent.START_POLL)\n \n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.ACQUIRE_SAMPLE)\n\n # @todo check samples arriving here\n # @todo check publishing samples from here\n \n self.driver_client.cmd_dvr('execute_resource', PARProtocolEvent.STOP_POLL) \n self.check_state(PARProtocolState.COMMAND)\n \n\n @unittest.skip('Need to write this test')\n def test_reset(self):\n pass\n\n \n@attr('UNIT', group='mi')\nclass SatlanticParDecoratorTest(PyonTestCase):\n \n def setUp(self):\n self.checksum_decorator = SatlanticChecksumDecorator()\n \n def test_checksum(self):\n self.assertEquals((\"SATPAR0229,10.01,2206748544,234\",\"SATPAR0229,10.01,2206748544,234\"),\n self.checksum_decorator.handle_incoming_data(\"SATPAR0229,10.01,2206748544,234\",\"SATPAR0229,10.01,2206748544,234\"))\n self.assertRaises(InstrumentDataException,\n self.checksum_decorator.handle_incoming_data,\n \"SATPAR0229,10.01,2206748544,235\",\n \"SATPAR0229,10.01,2206748544,235\")\n\n\n###############################################################################\n# QUALIFICATION TESTS #\n# Device specific qualification tests are for #\n# testing device specific capabilities #\n###############################################################################\n\n@attr('QUAL', group='mi')\nclass SatlanticParProtocolQualificationTest(InstrumentDriverQualificationTestCase):\n \"\"\"Qualification Test Container\"\"\"\n \n # Qualification tests live in the base class. This class is extended\n # here so that when running this test from 'nosetests' all tests\n # (UNIT, INT, and QUAL) are run. \n\n\n @unittest.skip(\"skip for automatic tests\")\n def test_direct_access_telnet_mode_manually(self):\n \"\"\"\n @brief This test manually tests that the Instrument Driver properly supports direct access to the physical instrument. (telnet mode)\n \"\"\"\n\n state = self.instrument_agent_client.get_agent_state()\n self.assertEqual(state, ResourceAgentState.UNINITIALIZED)\n \n with self.assertRaises(Conflict):\n res_state = self.instrument_agent_client.get_resource_state()\n \n cmd = AgentCommand(command=ResourceAgentEvent.INITIALIZE)\n retval = self.instrument_agent_client.execute_agent(cmd)\n state = self.instrument_agent_client.get_agent_state()\n print(\"sent initialize; IA state = %s\" %str(state))\n self.assertEqual(state, ResourceAgentState.INACTIVE)\n\n res_state = self.instrument_agent_client.get_resource_state()\n self.assertEqual(res_state, DriverConnectionState.UNCONFIGURED)\n\n cmd = AgentCommand(command=ResourceAgentEvent.GO_ACTIVE)\n retval = self.instrument_agent_client.execute_agent(cmd)\n state = self.instrument_agent_client.get_agent_state()\n print(\"sent go_active; IA state = %s\" %str(state))\n self.assertEqual(state, ResourceAgentState.IDLE)\n\n res_state = self.instrument_agent_client.get_resource_state()\n self.assertEqual(res_state, DriverProtocolState.COMMAND)\n\n cmd = AgentCommand(command=ResourceAgentEvent.RUN)\n retval = self.instrument_agent_client.execute_agent(cmd)\n state = self.instrument_agent_client.get_agent_state()\n print(\"sent run; IA state = %s\" %str(state))\n self.assertEqual(state, ResourceAgentState.COMMAND)\n\n res_state = self.instrument_agent_client.get_resource_state()\n self.assertEqual(res_state, DriverProtocolState.COMMAND)\n\n # go direct access\n cmd = AgentCommand(command=ResourceAgentEvent.GO_DIRECT_ACCESS,\n kwargs={'session_type': DirectAccessTypes.telnet,\n #kwargs={'session_type':DirectAccessTypes.vsp,\n 'session_timeout':600,\n 'inactivity_timeout':600})\n retval = self.instrument_agent_client.execute_agent(cmd)\n log.warn(\"go_direct_access retval=\" + str(retval.result))\n \n gevent.sleep(600) # wait for manual telnet session to be run\n","sub_path":"mi/instrument/satlantic/par_ser_600m/test/test_driver.py","file_name":"test_driver.py","file_ext":"py","file_size_in_byte":32334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"24881286","text":"from KratosMultiphysics import *\nfrom KratosMultiphysics.DEMApplication import *\nfrom KratosMultiphysics.SwimmingDEMApplication import *\nimport pre_calculated_fluid_algorithm\nBaseAlgorithm = pre_calculated_fluid_algorithm.Algorithm\nimport h5py\n\nclass Algorithm(BaseAlgorithm):\n def __init__(self, varying_parameters = Parameters(\"{}\")):\n BaseAlgorithm.__init__(self, varying_parameters)\n final_time = self.pp.CFD_DEM.AddEmptyValue(\"FinalTime\").GetDouble()\n L = 0.0048 # the channel width\n center_x = 0.0044\n self.bbox_watcher = BoundingBoxRule(0.0, 2 * final_time,\n center_x - L, center_x + L,\n -0.007, -0.002,\n -0.005, 0.001)\n\n def PerformFinalOperations(self, time = None):\n BaseAlgorithm.PerformFinalOperations(self, time)\n self.particles_loader.RecordParticlesInBox(self.bbox_watcher)\n\n def PerformZeroStepInitializations(self):\n BaseAlgorithm.PerformZeroStepInitializations(self)\n import hdf5_io_tools\n self.particles_loader = hdf5_io_tools.ParticleHistoryLoader(self.all_model_parts.Get('SpheresPart'), self.disperse_phase_algorithm.watcher, self.pp, self.main_path)\n\n def FluidSolve(self, time = 'None', solve_system = True):\n BaseAlgorithm.FluidSolve(self, time, solve_system)\n self.particles_loader.UpdateListOfAllParticles()\n","sub_path":"applications/swimming_DEM_application/python_scripts/t_junction/t_junction_algorithm.py","file_name":"t_junction_algorithm.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"644952531","text":"import re\nimport time\nimport unittest\n\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.support.select import Select\n\n# script to choose district , block ,cluster and mouse over on last\nfrom Data.Paramters import Data\n\n\nclass Choose13(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Chrome(Data.Path)\n self.driver.maximize_window()\n self.driver.implicitly_wait(10)\n self.driver.get(Data.URL)\n\n print(self.driver.title)\n self.driver.find_element_by_xpath(Data.email).send_keys(Data.username)\n self.driver.find_element_by_xpath(Data.pwd).send_keys(Data.password)\n self.driver.find_element_by_xpath(Data.loginbtn).click()\n time.sleep(10)\n\n def test_District(self):\n dist = self.driver.find_element_by_xpath(Data.dist5).click()\n blk = self.driver.find_element_by_xpath(Data.blk2).click()\n clus = self.driver.find_element_by_xpath(Data.clu3).click()\n\n print(self.driver.find_element_by_xpath(Data.dist5).text)\n print(self.driver.find_element_by_xpath(Data.blk2).text)\n print(self.driver.find_element_by_xpath(Data.clu3).text)\n time.sleep(15)\n data = self.driver.find_elements_by_xpath(Data.details)\n for i in range(len(data)):\n print(data[i].text)\n\n lists = self.driver.find_elements_by_class_name(Data.dots)\n def mouseover(i):\n\n action = ActionChains(self.driver)\n action.move_to_element(lists[i]).perform()\n time.sleep(5)\n del action\n\n i = 0\n while i < len(lists):\n mouseover(i)\n i = i + 1\n count = len(lists) - 1\n school = self.driver.find_element_by_xpath(Data.schoolcount).text\n res = re.sub(\"\\D\", \"\", school)\n self.assertEqual(res, str(count), \"both are not having matching records\")\n\n def tearDown(self):\n time.sleep(5)\n # print(self.driver.get_screenshot_as_file(\"\"))\n self.driver.close()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Testscripts/District_details.py","file_name":"District_details.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"485605032","text":"import numpy as np\nfrom tqdm import tqdm\n\nfrom datasets import DataManager\nfrom datasets import get_class_names\nfrom preprocessing import get_image_size\nfrom models import SSD300\nfrom metrics import compute_average_precision\nfrom metrics import compute_precision_and_recall\n\nfrom utils.boxes import create_prior_boxes\nfrom utils.boxes import calculate_intersection_over_union\nfrom utils.boxes import denormalize_boxes\nfrom utils.inference import infer_from_path\n\n\ndataset_name = 'VOC2007'\nimage_prefix = '../datasets/VOCdevkit/VOC2007/JPEGImages/'\nweights_path = '../trained_models/SSD300_weights.hdf5'\nmodel = SSD300(weights_path=weights_path)\n\nprior_boxes = create_prior_boxes()\ninput_shape = model.input_shape[1:3]\nclass_threshold = .1\niou_nms_threshold = .45\niou_threshold = .5\nnum_classes = 21\n\nimage_prefix = '../datasets/VOCdevkit/VOC2007/JPEGImages/'\nwith_difficult_objects = False\nsplit = 'test'\n\nclass_names = get_class_names(dataset_name)\nclass_names = class_names[1:]\naverage_precisions = []\nfor class_name in class_names:\n selected_classes = ['background'] + [class_name]\n data_manager = DataManager(dataset_name, split, selected_classes,\n with_difficult_objects)\n ground_truth_data = data_manager.load_data()\n difficult_data_flags = data_manager.parser.difficult_objects\n scores = []\n labels = []\n num_gt_boxes = 0\n for image_name, gt_sample in tqdm(ground_truth_data.items()):\n image_path = image_prefix + image_name\n reference_size = get_image_size(image_path)\n detections = infer_from_path(image_path, model, prior_boxes)\n gt_sample = denormalize_boxes(gt_sample, reference_size)\n num_gt_boxes = num_gt_boxes + len(gt_sample)\n already_detected = np.zeros(shape=len(gt_sample), dtype=bool)\n for detection in detections:\n ious = calculate_intersection_over_union(detection, gt_sample)\n score = np.max(detection[4:])\n best_iou = np.max(ious)\n best_iou_arg = np.argmax(ious)\n if best_iou > iou_threshold:\n if not already_detected[best_iou_arg]:\n labels.append(True)\n scores.append(best_iou)\n already_detected[best_iou_arg] = True\n else:\n labels.append(False)\n scores.append(best_iou)\n else:\n labels.append(False)\n scores.append(best_iou)\n results = compute_precision_and_recall(scores, labels, num_gt_boxes)\n precision, recall = results\n average_precision = compute_average_precision(precision, recall)\n average_precisions.append(average_precision)\n print('Class:', class_name)\n print('Number of ground_truth_boxes:', num_gt_boxes)\n print('AP:', average_precision)\n\nmean_average_precision = np.mean(average_precisions)\nprint('mAP:', mean_average_precision)\n","sub_path":"src/old/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"204985030","text":"from flask_wtf import FlaskForm\r\nfrom wtforms import StringField, FloatField, IntegerField, BooleanField\r\nfrom wtforms.validators import InputRequired, URL, ValidationError, Optional\r\n\r\ndef age_check(form, field):\r\n if not field.data:\r\n return\r\n elif field.data < 0 or field.data >30:\r\n raise ValidationError('Age must be between 0-30 years')\r\n\r\ndef species_check(form,field):\r\n types = ['cat','dog','porcupine']\r\n if field.data not in types:\r\n raise ValidationError('Species must be cat, dog, or porcupine')\r\n\r\n\r\nclass AddPetForm(FlaskForm):\r\n \"\"\"Form to add new pet\"\"\"\r\n name = StringField('Pet Name', validators=[InputRequired()])\r\n\r\n species = StringField('Species',validators=[InputRequired(),species_check])\r\n\r\n photo_url = StringField('Photo url', validators=[URL(require_tld=True,message='Must be valid URL'), Optional()])\r\n\r\n age = IntegerField('Age', validators=[age_check, Optional()])\r\n\r\n notes = StringField('Notes', validators=[Optional()])\r\n\r\n available = BooleanField('Available',validators=[Optional()],default='checked')\r\n\r\nclass EditPetForm(FlaskForm):\r\n \"\"\"Edit existing pet\"\"\"\r\n photo_url = StringField('Photo url', validators=[URL(require_tld=True,message='Must be valid URL'), Optional()])\r\n\r\n notes = StringField('Notes', validators=[Optional()])\r\n\r\n available = BooleanField('Available',validators=[Optional()],default='checked')\r\n\r\n\r\n ","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"350005409","text":"#set up environment\nimport testretrieveDataSRA\nimport testreformatDataSRA\nimport testmapReads\nimport testclusteringAnalysis\n\n#GEO Accession -- CCS Component -- SRA run (raw data)\n#GSM3885058 -- Zone I: SAN region -- SRR9290711/2\n#GSM3885059\t-- Zone II: AVN/His region -- SRR9290713/4\n#GSM3885060\t-- Zone III (Left): BB/PF region (Left Ventricle) -- SRR9290715/6\n#GSM3885061\t-- Zone III (Right): BB/PF region (Right Ventricle) -- SRR9290717/8\n\n#list of SRA sample runs (one of each)\ntestSRRs = ['SRR9290711', 'SRR9290712', 'SRR9290713', 'SRR9290714', 'SRR9290715', 'SRR9290716', 'SRR9290717', 'SRR9290718']\n\n#retrieve mouse heart data from NCBI's SRA + retrieve mouse reference genome\ntestretrieveDataSRA.getSRAdata(testSRRs)\n\n#rename fastq files to Cell Ranger compatabile format\ntestreformatDataSRA.renameFastqs(testSRRs)\n\n#map sample reads using Cell Ranger and create Cell Ranger output folder\ntestmapReads.run_CellRanger_test_ALLRuns()\ntestmapReads.runCellRanger_test_SAN()\ntestmapReads.runCellRanger_test_AVN()\ntestmapReads.runCellRanger_test_LPF()\ntestmapReads.runCellRanger_test_RPF()\n\n#perform clustering and other statistical analyses using Seurat\ntestclusteringAnalysis.performClusteringFiltered()\ntestclusteringAnalysis.performClusteringUnfiltered()\n","sub_path":"testpipeline.py","file_name":"testpipeline.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"581236637","text":"class Solution:\r\n def lengthOfLongestSubstring(self, s):\r\n basket = []\r\n len_seq = 0\r\n for i in s:\r\n if i not in basket:\r\n basket.append(i)\r\n if len(basket) > len_seq: len_seq = len(basket)\r\n else:\r\n basket = basket[basket.index(i)+1:]\r\n basket.append(i)\r\n return len_seq\r\n","sub_path":"lengthOfLongestSubstring.py","file_name":"lengthOfLongestSubstring.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"473667792","text":"\"\"\"empty message\n\nRevision ID: 9452402e522b\nRevises: c04f5e3c4ea0\nCreate Date: 2018-04-01 23:54:41.109546\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '9452402e522b'\ndown_revision = 'c04f5e3c4ea0'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('student', sa.Column('branch_id', sa.Integer(), nullable=True))\n op.add_column('student', sa.Column('category_id', sa.Integer(), nullable=True))\n op.drop_column('student', 'category')\n op.drop_column('student', 'branch')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('student', sa.Column('branch', mysql.VARCHAR(length=50), nullable=True))\n op.add_column('student', sa.Column('category', mysql.VARCHAR(length=50), nullable=False))\n op.drop_column('student', 'category_id')\n op.drop_column('student', 'branch_id')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/9452402e522b_.py","file_name":"9452402e522b_.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"193984864","text":"import numpy as np\nimport sys\n\n# parsing input data #################################################################\ndef parsingTrainingData(file_name) :\n # read data\n # please note that the first element in each line have label\n # The reason why I use str type is that the first element of each row is str type\n data_in = np.genfromtxt(fname=file_name,skip_header=1,dtype=str,delimiter=' ')\n # number of train data\n num_train = len(data_in)\n \n # initialize label\n label = np.zeros(num_train)\n #print(num_train)\n for i in range(num_train) :\n label[i] = data_in[i,0].split(',')[0]\n data_in[i,0] = data_in[i,0].split(',')[1]\n \n # This step is copy reference, so memory won't double\n feature = data_in\n \n \n # reshaping for convolution\n feature = np.reshape(feature,(num_train,48,48,1))\n \n # np.save('train_X.npy', feature)\n # sys.exit(0)\n \n feature = feature.astype(float)\n feature = feature/255\n \n # split data\n valid_feature = feature[:2000]\n valid_label = label[:2000]\n train_feature = feature[2000:]\n train_label = label[2000:]\n\n np.save('feature_valid',valid_feature)\n np.save('label_valid',valid_label)\n \n\nparsingTrainingData(sys.argv[1])\n\nprint('done')\n","sub_path":"hw3/generate_confusion_data.py","file_name":"generate_confusion_data.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"75866092","text":"import os\nimport cv2\nimport numpy as np\nimport torch\n\n# 功能介绍博客\n# https://blog.csdn.net/rush9838465/article/details/114291144\n\ndef show_CAM(save_img_path, image, feature_maps, class_id, all_ids=10, image_size=(320, 640), normalization=True):\n \"\"\"\n\n save_img_path: save heatmap images path\n feature_maps: this is a list [tensor,tensor,tensor], tensor shape is [1, 3, N, N, all_ids]\n normalization: Normalize score and class to 0 to 1\n image_size: w, h\n \"\"\"\n SHOW_NAME = [\"score\", \"class\", \"class*score\"]\n img_ori = image\n layers0 = feature_maps[0].reshape([-1, all_ids])\n layers1 = feature_maps[1].reshape([-1, all_ids])\n layers2 = feature_maps[2].reshape([-1, all_ids])\n layers = torch.cat([layers0, layers1, layers2], 0)\n if normalization:\n score_max_v = 1.\n score_min_v = 0.\n class_max_v = 1.\n class_min_v = 0.\n else:\n score_max_v = layers[:, 4].max() # compute max of score from all anchor\n score_min_v = layers[:, 4].min() # compute min of score from all anchor\n class_max_v = layers[:, 5 + class_id].max() # compute max of class from all anchor\n class_min_v = layers[:, 5 + class_id].min() # compute min of class from all anchor\n for j in range(3): # layers\n layer_one = feature_maps[j]\n # compute max of score from three anchor of the layer\n if normalization:\n anchors_score_max = layer_one[0, :, :, :, 4].max(0)[0].sigmoid()\n # compute max of class from three anchor of the layer\n anchors_class_max = layer_one[0, :, :, :, 5 + class_id].max(0)[0].sigmoid()\n else:\n anchors_score_max = layer_one[0, :, :, :, 4].max(0)[0]\n # compute max of class from three anchor of the layer\n anchors_class_max = layer_one[0, :, :, :, 5 + class_id].max(0)[0]\n\n scores = ((anchors_score_max - score_min_v) / (\n score_max_v - score_min_v))\n classes = ((anchors_class_max - class_min_v) / (\n class_max_v - class_min_v))\n\n layer_one_list = []\n layer_one_list.append(scores)\n layer_one_list.append(classes)\n layer_one_list.append(scores * classes)\n for idx, one in enumerate(layer_one_list):\n layer_one = one.cpu().numpy()\n if normalization:\n ret = ((layer_one - layer_one.min()) / (layer_one.max() - layer_one.min())) * 255\n else:\n ret = ((layer_one - 0.) / (1. - 0.)) * 255\n ret = ret.astype(np.uint8)\n gray = ret[:, :, None]\n ret = cv2.applyColorMap(gray, cv2.COLORMAP_JET)\n\n ret = cv2.resize(ret, image_size)\n img_ori = cv2.resize(img_ori, image_size)\n\n show = ret * 0.50 + img_ori * 0.50\n show = show.astype(np.uint8)\n cv2.imwrite(os.path.join(save_img_path, f\"{j}_{SHOW_NAME[idx]}.jpg\"), show)\n\n\n# show_CAM(path, ret[1], 21)","sub_path":"acv/training/feature_map_visualization.py","file_name":"feature_map_visualization.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"358749227","text":"from selenium.webdriver.common.by import By\nfrom page_objects.BasePage import BasePage\nfrom page_objects.old.elements.ProductFilterForm import ProductFilterForm\n\n\nclass AdminPage(BasePage):\n CATEGORY_SELECTOR = (By.CSS_SELECTOR, \"li#menu-catalog\")\n PRODUCT_PAGE_SELECTOR = (By.CSS_SELECTOR, \"#collapse1 > li:nth-child(2) > a\")\n ADD_NEW_PRODUCT_SELECTOR = (By.CSS_SELECTOR, \".btn.btn-primary[data-original-title='Add New']\")\n FILTERED_PRODUCTS_SELECTOR = (By.CSS_SELECTOR, \"tbody > tr > td.text-left\")\n FILTERED_PRODUCT_CHECKBOX_SELECTOR = (By.CSS_SELECTOR, \"tbody > tr > td.text-center > input[type='checkbox']\")\n DELETE_PRODUCT_SELECTOR = (By.CSS_SELECTOR, \"i.fa.fa-trash-o\")\n\n def open_products_page(self):\n element = self._verify_element_presence(self.CATEGORY_SELECTOR)\n self._click_element(element)\n element = self._verify_element_presence(self.PRODUCT_PAGE_SELECTOR)\n self._click_element(element)\n\n def add_new_product_click(self):\n element = self._verify_element_presence(self.ADD_NEW_PRODUCT_SELECTOR)\n self._click_element(element)\n\n def check_test_product_present(self, product_name, product_desc, product_meta, product_model):\n ProductFilterForm(self.browser).filter_product_by_test_params(product_name, product_model)\n self._verify_element_presence(self.FILTERED_PRODUCTS_SELECTOR)\n\n def delete_test_product(self):\n element = self._verify_element_presence(self.FILTERED_PRODUCT_CHECKBOX_SELECTOR)\n self._click_element(element)\n element = self._verify_element_presence(self.DELETE_PRODUCT_SELECTOR)\n self._click_element(element)\n self.logger.info(f'Admin page clicking alert')\n alert = self.browser.switch_to.alert\n alert.accept()\n","sub_path":"page_objects/old/AdminPage.py","file_name":"AdminPage.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"161721690","text":"import os, datetime, time, json\nfrom db_local import DB_Manager\n\nclass Cookie_struct():\n\tdef __init__(self, HTTPOnly=True, _lifetime=2):\n\t\tself.cookies = {}\t\t#Cookie: UUID, ip address, date\n\t\tself.lifetime = _lifetime\n\t\t\n\tdef _validate(self, ip, cookie):\n\t\t#ensure the IP is the same for the two cookie usage requests.\n\t\tprint(\"MY COOKIE: \", cookie)\n\t\tall_cookies = self.getAllCookies()\n\t\tprint(\"COOKIE STRUCT: \", all_cookies)\n\t\t#if cookie not in self.cookies:\n\t\t#\t return False\n\t\t#if ip != self.cookies[cookie][\"ip\"]:\n\t\t#\t return False\n\t\t\n\t\tfetched_cookies = DB_Manager.execute(\"AUTH\", '''SELECT * FROM Sessions WHERE (cookie='%s')''', cookie)\n\t\tif fetched_cookies == None: return False\n\t\telif len(fetched_cookies) == 0: return False\n\t\telse: return True\n\t\t\n\t\t#ensure the cookie is still within lifetime\n\t\t#dateDiff = datetime.datetime.now() - self.cookies[cookie][\"datetime\"]\n\t\t#if (dateDiff.total_seconds()/3600) > self.lifetime:\n\t\t#\t return False\n\t\t\n\t\treturn True\n\t\t\n\tdef validateCSRF(self, S_ID, token):\n\t\ttry:\n\t\t\tcookie = self.getCookieByToken(S_ID)\n\t\t\tif cookie == None: return False\n\t\t\telse: return cookie[0][3] == token\n\t\texcept Exception as e:\n\t\t\tprint(\"ERROR in validateCSRF: \", str(e))\n\t\t\treturn False\n\t\t\t\n\tdef getCSRF(self, S_ID):\n\t\tcookie = self.getCookieByToken(S_ID)\n\t\tif cookie == None: return ''\n\t\treturn cookie[0][3]\n\t\n\t\n\tdef getUUID(self, cookie, ip):\n\t\tif not self._validate(ip, cookie):\n\t\t\treturn None\n\t\telse:\n\t\t\tcookie = self.getCookieByToken(cookie)\n\t\t\tif cookie == None: return None\n\t\t\telse:\n\t\t\t\treturn cookie[0][0]\n\t\t\t\n\tdef deleteCookie(self, cookie, ip):\n\t\tif not self._validate(ip, cookie):\n\t\t\tprint(\"Cookie not valid!\")\n\t\t\treturn False\n\t\telse:\n\t\t\tDB_Manager.execute(\"AUTH\", '''DELETE FROM Sessions WHERE (cookie='%s');''', cookie)\n\t\t\treturn True\n\t\t\t\n\tdef createBlankCookie(self):\n\t\treturn \"\"\n\t\t\n\t\t\n\t\t\n\t\t\n\tdef createCookie(self, UUID, ip):\n\t\t#https://owasp.org/www-project-cheat-sheets/cheatsheets/Session_Management_Cheat_Sheet.html\n\t\t#cookie length - at least 16 bytes\n\t\t#must be meaningless - to prevent information dislosure attacks\n\t\tcurrCookie = self.getCookieByUUID(UUID)\n\t\t\n\t\tif currCookie == None: currCookie = []\n\t\tfor c in currCookie:\n\t\t\tself.deleteCookie(c[1], c[2])\n\t\t\n\t\t\n\t\tcookie = Token_generator.new_crypto_bytes(20).hex()\n\t\tcsrf_token = Token_generator.new_crypto_bytes(20).hex()\n\t\tcreation_datetime = datetime.datetime.now()\n\t\tDB_Manager.execute(\"AUTH\", '''INSERT INTO Sessions VALUES ('%s', '%s', '%s', '%s')''', UUID, cookie, ip, csrf_token)\n\n\t\t\n\t\treturn cookie\n\t\t\n\tdef _toString(self):\n\t\tfor cookie in self.cookies:\n\t\t\tprint(cookie)\n\t\n\tdef clearCookies(self):\n\t\tDB_Manager.execute(\"AUTH\", '''DELETE FROM Sessions;''')\n\t\t\n\tdef getAllCookies(self):\n\t\ttotal_cookies = DB_Manager.execute(\"AUTH\", '''SELECT * FROM Sessions''')\n\t\tif total_cookies == None: return []\n\t\telse:return total_cookies\n\t\n\tdef getCookieByUUID(self, UUID):\n\t\tcookies = DB_Manager.execute(\"AUTH\", '''SELECT * FROM Sessions WHERE (UUID='%s')''', UUID)\n\t\tif cookies == None: return None\n\t\telif len(cookies) == 0: return None\n\t\telse: return cookies\n\t\n\tdef getCookieByToken(self, token):\n\t\tcookies = DB_Manager.execute(\"AUTH\", '''SELECT * FROM Sessions WHERE (cookie='%s')''', token)\n\t\tif cookies == None: return None\n\t\telif len(cookies) == 0: return None\n\t\telse: return cookies\n\t\t\n\t\t\n\t\t\n\t\t\n\tdef saveSessions(self):\n\t\twith open('sessions.json', 'w') as outfile:\n\t\t\tjson.dump(self.cookies, outfile)\n\tdef getSessions(self):\n\t\tdata = open('config/HEADERS_local.conf', 'r')\n\t\treturn json.load(data)\n\nclass CSRF_tokens_struct():\n\tdef __init__(self):\n\t\tself.CSRF_tokens = {}\t#\n\tdef generate_token(self, user_UUID):\n\t\tpass\n\t\t\n\t\n\n\n\n\t\t\nclass Token_generator():\n\t@staticmethod\n\tdef new_crypto_bytes(size):\n\t\t#this is cryptographically secure. See https://docs.python.org/3/library/os.html\n\t\treturn os.urandom(size) \n\t\t\n\t\t\n\t\t\nif __name__ == \"__main__\":\n\tc = Cookie_struct(True, 6)\n\tcookie = c.createCookie(\"14henderson\", \"127.0.0.1\")\n\ttime.sleep(5)\n\tprint(\"Got user?\", c.getUser(cookie, \"127.0.0.1\"))\n\tc._toString()","sub_path":"lib/Session_structs.py","file_name":"Session_structs.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"281761844","text":"class Solution:\n def rotateString(self, A: str, B: str) -> bool:\n if len(A) != len(B):\n return False\n if A == B and A == \"\":\n return True\n for i in range(len(A)):\n A = self.reverseLeftWords(A, 1)\n if A == B:\n return True\n return False\n\n def reverseLeftWords(self, s: str, n: int) -> str:\n # write your code here\n offset = n % len(s)\n\n x1 = s[:offset]\n x2 = s[offset:]\n\n return x2 + x1\n","sub_path":"796. 旋转字符串.py","file_name":"796. 旋转字符串.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"343941326","text":"import telebot\ntelebot.apihelper.proxy = {'https': 'socks5://geek:socks@t.geekclass.ru:7777'}\nbot = telebot.TeleBot(token=\"982351184:AAFdbXkPxQTN8Y3Ebs_2osqOEQASK1W27mA\")\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n chat_id = message.chat.id\n answer = bot.send_message(chat_id, \"Добро пожаловать в квест. Хочешь получить 10000000$? Тогда тебе нужно победить 3 монстров, а в конце сможешь забрать свой приз. Боссы будут нелегкие и тебе придется подбирать оружие для каждого из них. \")\n bot.send_message(chat_id, \"Первый босс. Босса нужно побеждать в ближнем бою. Какое оружие ты выберешь?\")\n t = \"\"\"Вот твой арсенал: \n 1) Меч\n 2) Лук\n 3) Копьё\n \"\"\"\n m = bot.send_message(chat_id, t)\n bot.register_next_step_handler(m, first_answer)\n\n\ndef first_answer(message):\n text = message.text\n chat_id = message.chat.id\n if text == \"1\":\n answer = bot.send_message(chat_id, \"Правильно, ты выбрал правильное оружие. Проходи дальше\")\n answer = bot.send_message(chat_id,\n \"Второй босс. Босса нужно побеждать на расстояние, но и не из лука. Какое оружие ты выберешь?\")\n t = \"\"\"Вот твой арсенал: \n 1) Меч\n 2) Лук\n 3) Копьё\n \"\"\"\n answer = bot.send_message(chat_id,t)\n bot.register_next_step_handler(answer, secondb)\n else:\n bot.send_message(chat_id, \"ты умер\")\n start(message)\n\ndef secondb(message):\n chat_id = message.chat.id\n text = message.text\n if text == \"3\":\n bot.send_message(chat_id, \"Правильно, ты выбрал правильное оружие. Проходи дальше\")\n answer = bot.send_message(chat_id, \"Третий босс. Босса нужно побеждать на расстоянии, но не их лука. Какое оружие ты выберешь?\")\n t = \"\"\"Вот твой арсенал: \n 1) Меч\n 2) Лук\n 3) Копьё\n \"\"\"\n\n bot.send_message(chat_id, t)\n\n bot.register_next_step_handler(answer, thirdb)\n else:\n bot.send_message(chat_id, \"ты умер\")\n start(message)\n\ndef thirdb(message):\n chat_id = message.chat.id\n text = message.text\n if text == \"2\":\n answer = bot.send_message(chat_id, \"ты победил\")\n else:\n answer = bot.send_message(chat_id, \"ты умер. Начинай заново\")\n bot.register_next_step_handler(answer, start)\n\n\nbot.polling(none_stop=True)\n","sub_path":"last_bot.py","file_name":"last_bot.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"183648136","text":"from django.conf.urls 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\nimport events\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', 'events.views.home', name='home'),\n # url(r'^joinlite/', include('joinlite.foo.urls')),\n\n url(r'^about/$', 'main.views.about', name='about'),\n url(r'^team/$', 'main.views.team', name='team'),\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 url(r'^events/', include('events.urls')),\n)\n","sub_path":"joinlite/joinlite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"191356172","text":"from threading import Condition\n\n\nclass BroadcastEvent:\n condition: Condition\n\n def __init__(self, message, peers=None):\n self.condition = Condition()\n self.message = message\n self.peers = peers\n self.responses = {}\n\n def add_response(self, peer: str, response):\n self.responses[peer] = response\n","sub_path":"client/broadcast_event.py","file_name":"broadcast_event.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"520587578","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 1 10:58:50 2018\n\n@author: root\n\"\"\"\nimport sys\nimport ctypes\nfrom ctypes import *\nimport time\n\nimport redis\n\nimport RFIDSYSSqliteClass\n\nimport socket\nimport json\n\nimport threading\n# import psycopg2\nimport datetime\n#import Com4GModularClass\nfrom redisqueue import RedisQueue\n\nfrom bluetooth import *\nimport threading\n\n\nclass SendDataToDestinationBLC(object):\n def __init__(self, bluetuuid=\"94f39d29-7d6d-437d-973b-fba39e49d4ee\"):\n \n self.usedtosendEPCQueue = RedisQueue(name='UsedEPCSendQueue',host='127.0.0.1',psw='123456',db=1)\n\n self.devID = b''\n self.uuid=bluetuuid\n\n self.thread_read_flg=False\n self.thread_read=None\n\n self.runallflg=False\n\n self.allthread=None\n\n\n\n def GetRfidDevID(self):\n if self.devID == b'':\n try:\n conn = redis.Redis(host='127.0.0.1', password='123456', port=6379, db=1)\n if conn.ping():\n print('conn ok')\n else:\n print('shawanyi')\n except: #\n return self.devID\n #conn.set('RFIDDevID', devID)\n if conn.exists('RFIDDevID'):\n pass\n else:\n print(self.devID)\n return self.devID\n ret=conn.get('RFIDDevID')\n if ret!=self.devID:\n self.devID=ret\n print('devID',self.devID)\n return self.devID\n\n def GetSysBluetoothCMD(self):\n cmd=0\n try:\n conn = redis.Redis(host='127.0.0.1', password='123456', port=6379, db=1)\n except:\n print('GetSysBluetoothCMD ERR')\n return 0\n \n ret=conn.get('RFIDSysBluetoothCMD')\n if ret==None:\n return 0\n \n if ret==b'START':\n cmd=1\n elif ret==b'STOP':\n cmd=2\n elif ret==b'POWERUP':\n cmd=3\n elif ret==b'POWERDOWN':\n cmd=4\n elif b'POWER:' in ret:\n p,var = ret.split(b':')\n cmd=int(var)\n else:\n cmd=0\n return cmd\n\n def SetSysBluetoothCMD(self,cmd=0):\n try:\n conn = redis.Redis(host='127.0.0.1', password='123456', port=6379, db=1)\n except:\n print('GetSysBluetoothCMD ERR')\n return False\n strcmd=''\n #ret=conn.get('RFIDSysBluetoothCMD')\n if cmd==1:#b'START':\n strcmd='START'\n elif cmd==2:#b'STOP':\n strcmd='STOP'\n elif cmd==3:#b'POWERUP':\n strcmd='POWERUP'\n elif cmd==4:#b'POWERDOWN':\n strcmd='POWERDOWN'\n elif cmd==5:\n strcmd='RUN'\n elif cmd>=10 and cmd<=30:\n strcmd='POWER:'+str(cmd)\n else:\n strcmd='START'\n\n conn.set('RFIDSysBluetoothCMD',strcmd)\n return True\n\n def RecvThreading(self,s):\n #global thread_read_flg\n while self.thread_read_flg:\n data = s.recv(1024)\n if len(data) == 0:\n continue#break\n print(\"received [%s]\" % data)\n if b'START' in data:\n self.SetSysBluetoothCMD(cmd=1)\n elif b'STOP'in data:\n self.SetSysBluetoothCMD(cmd=2)\n elif b'POWERUP' in data:\n self.SetSysBluetoothCMD(cmd=3)\n elif b'POWERDOWN' in data:\n self.SetSysBluetoothCMD(cmd=4)\n elif b'POWER:' in data:\n p,var = data.split(b':')\n self.SetSysBluetoothCMD(cmd=int(var))\n else:\n pass\n\n def StopRecvThread(self):\n self.thread_read_flg=False\n self.thread_read.join()\n self.thread_read=None\n \n self.SetSysBluetoothCMD(cmd=2)\n\n def StopAll(self):\n self.runallflg=False\n self.StopRecvThread()\n self.allthread=None\n \n def EPCSendRoServerForBluetooth(self):\n #global devID\n #global usedtosendEPCQueue\n #global thread_read_flg\n #global thread_read\n print('EPCSendRoServerForBluetooth')\n\n #uuid = \"94f39d29-7d6d-437d-973b-fba39e49d4ee\"\n uuid = self.uuid\n\n try:\n service_matches = find_service( uuid = uuid, address = None )\n\n if len(service_matches) == 0:\n print(\"couldn't find the SampleServer service =(\")\n return\n\n first_match = service_matches[0]\n port = first_match[\"port\"]\n name = first_match[\"name\"]\n host = first_match[\"host\"]\n\n print(\"connecting to \\\"%s\\\" on %s\" % (name, host))\n\n # Create the client socket\n sock=BluetoothSocket( RFCOMM )\n sock.connect((host, port))\n\n self.thread_read_flg=True\n self.thread_read=threading.Thread(target=self.RecvThreading,args=(sock,))\n self.thread_read.setDaemon(True)\n self.thread_read.start()\n\n print(\"connected. type stuff\")\n except:\n print(\"Bluetooth connect err\")\n return\n \n try:\n s_conn = redis.Redis(host='127.0.0.1', password='123456', port=6379, db=1)\n if s_conn.ping():\n print('EPCSendRoServerForBluetooth ok')\n else:\n print('shawanyi')\n except: #\n print('EPCSendRoServerForBluetooth err')\n s_conn = None\n return False\n\n s_conn.set('RFIDSysIsStart','isok')\n self.SetSysBluetoothCMD(cmd=1)\n while self.devID==b'':\n retdevid=self.GetRfidDevID()\n time.sleep(2)\n\n try: \n while True:\n msg = self.usedtosendEPCQueue.get_nowait()\n #print('msg:',msg)\n if msg==None:\n continue\n \n varepc = msg.split(b':')\n sdevs = b'DEVID:' + self.devID + b';' + varepc[1] + b'+'\n print('queueSend:',sdevs)\n sock.send(sdevs)\n\n except:\n print('Bluetooth sock err')\n\n self.StopRecvThread()\n #self.thread_read_flg=False\n #self.thread_read.join()\n #self.thread_read=None\n \n #self.SetSysBluetoothCMD(cmd=2)\n sock.close()\n\n def EPCSendRoServerForBluetoothRUN(self):\n if self.runallflg==True:\n self.StopAll()\n self.runallflg=True\n while self.runallflg:\n self.EPCSendRoServerForBluetooth()\n\n def RunAll_Bluetooth(self):\n if self.allthread!=None:\n return False\n self.allthread=threading.Thread(target=self.EPCSendRoServerForBluetoothRUN)\n self.allthread.setDaemon(True)\n self.allthread.start()\n return True\n\n\n\n\n\ndef RunMain():\n test=SendDataToDestinationBLC()\n test.EPCSendRoServerForBluetoothRUN()\n\n\nif __name__ == '__main__':\n RunMain()\n","sub_path":"Firefly交/firefly-3288c-rfid-bluetoolth/RFIDBluetooth/SendDataToDestinationBLC - 1.py","file_name":"SendDataToDestinationBLC - 1.py","file_ext":"py","file_size_in_byte":6911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"218042594","text":"import cv2\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions\nimport numpy as np\n\n\nmodel = ResNet50(weights='imagenet')\n# cap = cv2.VideoCapture(0)\ncap = cv2.VideoCapture('./SAMPLE.mp4')\n\nif not cap.isOpened():\n\traise IOError(\"Cannot Open Webcam\")\n\nwhile True:\n\tret, frame = cap.read()\n\tx = cv2.resize(frame, (224, 224))\n\tx = image.img_to_array(x)\n\tx = np.expand_dims(x, axis=0)\n\tx = preprocess_input(x)\n\tprediction = model.predict(x)\n\toutput = decode_predictions(prediction, top=1)[0]\n\tframe = cv2.resize(frame, (1366, 768))\n\tcv2.putText(frame, str(output), (100, 50), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255))\n\tcv2.imshow(\"Webcam\", frame)\n\tc = cv2.waitKey(1)\n\tif c == 27:\n\t\tbreak\n\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"yolov4-tf/webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"219582972","text":"import pynini\nimport string\n\n##Vocabulary\nlm_char = pynini.Fst.read(\"t9.char.lm\")\nlm_word = pynini.Fst.read(\"t9.word.lm\")\nt9 = pynini.transducer(\"0\",\"[32]\") \nt9_relations = [\"0\", \"1\", \"2abc\", \"3def\", \"4ghi\", \"5jkl\", \"6mno\", \"7pqrs\", \"8tuv\", \"9wxyz\"]\n\n##Reading vocabulary into alphabet.\nfor i in range(10):\n for k in t9_relations[i]:\n t9 = pynini.union(pynini.transducer(str(i),str(k)), t9)\n##Adding punctuation to vocabulary \nfor i in string.punctuation:\n t9 = t9 | pynini.transducer(\"1\", \"[\" + str(ord(i)) + \"]\")\n##Closure and optimization\nt9.closure().optimize()\n##Inverstion for decoding\nencoder = pynini.invert(t9).optimize()\n\ndef encode(message):\n return (message.lower() * encoder).stringify()\n\n\ndef decode(message):\n###performs encoding on message, projects pathways to intersect with character ngram\n###Then returns most likely path\n lattice = (message * t9).project(True) * lm_char \n return pynini.shortestpath(lattice).stringify()","sub_path":"t9/m1_t9.py","file_name":"m1_t9.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"167936118","text":"import os\nfrom jhub.mount import SSHFSMounter\n\nc = get_config()\n\nc.JupyterHub.spawner_class = 'jhub.SwarmSpawner'\n\nc.JupyterHub.ip = '0.0.0.0'\nc.JupyterHub.hub_ip = '0.0.0.0'\n\nc.JupyterHub.base_url = '/base_url'\n\n# First pulls can be really slow, so let's give it a big timeout\nc.SwarmSpawner.start_timeout = 60 * 15\n\nc.SwarmSpawner.jupyterhub_service_name = 'jupyter-service_jupyterhub'\n\nc.SwarmSpawner.networks = [\"jupyter-service_default\"]\n\nnotebook_dir = os.environ.get('NOTEBOOK_DIR') or '/home/jovyan/work/'\nc.SwarmSpawner.notebook_dir = notebook_dir\n\nmounts = [SSHFSMounter({\n 'type': 'volume',\n 'driver_config': 'rasmunk/sshfs:latest',\n 'driver_options': {'sshcmd': '{sshcmd}', 'id_rsa': '{id_rsa}',\n 'one_time': 'True',\n 'big_writes': '', 'allow_other': ''},\n 'source': '',\n 'target': notebook_dir})]\n\n\n# 'args' is the command to run inside the service\nc.SwarmSpawner.container_spec = {\n 'args': ['/usr/local/bin/start-singleuser.sh',\n '--NotebookApp.ip=0.0.0.0',\n '--NotebookApp.port=8888'],\n 'env': {'JUPYTER_ENABLE_LAB': '1',\n 'TZ': 'Europe/Copenhagen'}\n}\n\n# Before the user can select which image to spawn,\n# user_options has to be enabled\nc.SwarmSpawner.use_user_options = True\n\n# Available docker images the user can spawn\nc.SwarmSpawner.dockerimages = [\n {'image': 'nielsbohr/base-notebook:latest',\n 'name': 'Image with automatic {replace_me} mount, supports Py2/3 and R',\n 'mounts': mounts}\n]\n\n# Authenticator -> remote user header\nc.JupyterHub.authenticator_class = 'jhubauthenticators.DummyAuthenticator'\nc.DummyAuthenticator.password = 'password'\nc.Authenticator.enable_auth_state = True\n\n# Service that checks for inactive notebooks\n# Defaults to kill services that hasen't been used for 1 hour\nc.JupyterHub.services = [\n {\n 'name': 'cull-idle',\n 'admin': True,\n 'command': 'python3 cull_idle_servers.py --timeout=3600'.split(),\n }\n]\n\n# Limit cpu/mem to 4 cores/8 GB mem\n# During conjestion, kill random internal processes to limit\n# available load to 1 core/ 2GB mem\nc.SwarmSpawner.resource_spec = {\n 'cpu_limit': int(8 * 1e9),\n 'mem_limit': int(8192 * 1e6),\n 'cpu_reservation': int(1 * 1e9),\n 'mem_reservation': int(1024 * 1e6),\n}\n","sub_path":"hub/jupyterhub_config.py","file_name":"jupyterhub_config.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"570131215","text":"from urls import urls\n\nfrom http.server import BaseHTTPRequestHandler\nimport json\n# https://docs.python.org/3/library/re.html\nimport re\n\ndef not_found():\n return '404'\n\nclass RequestHandler(BaseHTTPRequestHandler):\n \n def do_HEAD(self):\n self.respond(method='head')\n\n def do_OPTIONS(self):\n self.respond(method='options')\n\n def do_POST(self):\n method = 'post'\n\n content_length = int(self.headers.get('content-length'))\n # rfile is an io.BufferedIOBase input stream\n # BufferedIOBase is a base class for binary streams\n post_body = self.rfile.read(content_length)\n # encoded bytes array: b'{\\n\\t\"name\":\"braden\"\\n}'\n post_body = post_body.decode(encoding=\"utf-8\")\n # json loads converts json to python dictionary\n post_body = json.loads(post_body)\n self.arh_data = {'method': method, 'post_body': post_body}\n\n self.respond()\n\n def do_GET(self):\n method = 'get'\n self.arh_data = {'method': method}\n self.respond()\n\n def do_PUT(self):\n method = 'put'\n self.arh_data = {'method': method}\n self.respond()\n\n def do_DELETE(self):\n method = 'delete'\n self.arh_data = {'method': method}\n self.respond()\n\n def handle_http(self, status, content_type):\n #print(str(dir(self)))\n self.send_response(status)\n self.send_header('Content-type', content_type)\n self.end_headers()\n \n path = self.path.lstrip('/')\n params = None\n if '?' in path:\n path, params = path.split('?',1)\n\n self.arh_data['params'] = params\n\n #print('path: ' + path)\n #print('params: ' + str(params))\n\n response = self.get_url_from_path(path)\n\n return bytes(response, 'UTF-8')\n\n def respond(self):\n content = self.handle_http(200, 'text/html')\n # Contains the output stream for writing a response back to the client. Proper adherence to the HTTP protocol must be used when writing to this\n # stream in order to achieve successful interoperation with HTTP clients\n self.wfile.write(content)\n\n def get_url_from_path(self, path):\n for regex, callback in urls:\n match = re.search(regex, path)\n if match is not None:\n #print('groups: ' + str(match))\n #print('groups: ' + str(dir(match)))\n #environ['myapp.url_args'] = match.groups()\n return callback(self.arh_data)\n return not_found()\n ","sub_path":"ipa/request_handler.py","file_name":"request_handler.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"279391141","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 22 16:27:12 2019\r\n\r\n@author: Salim\r\n\"\"\"\r\n\"\"\" CLASSLAR \"\"\"\r\nclass araba():\r\n model=\"REDO\"\r\n renk=\"kırmızı\"\r\n beygir_gücü=110\r\n silindir=4\r\n\r\n\r\nprint(araba.silindir) \r\n#%%\r\nclass araba2():\r\n def __init__(self,model3,renk1,beygir,tekerler):\r\n self.model1=model3\r\n self.renk1=renk1\r\n self.beygir=beygir\r\n self.tekerler=tekerler\r\n \r\n \r\naraba3=araba2(\"RENALUT\",\"YEŞİL\",100,5) \r\naraba4=araba2(\"Pöçü\",\"sarı\",90,7)\r\nprint(araba3.model1)\r\nprint(araba4.renk1) \r\n ","sub_path":"sınıflar.py","file_name":"sınıflar.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"576541522","text":"\"\"\"\nDjango settings for lkd_site project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n# BASE_ABS_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))\n# BASE_ABS_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'w&m8d)nma*m^a_bs&g5df3s*4tb4!+ct9ot2og91f446_gx^j1'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'jurnal',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'lkd_site.urls'\n\nWSGI_APPLICATION = 'lkd_site.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n # Postgress\n # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n # 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n # 'NAME': 'vkudak_db', # Or path to database file if using sqlite3.\n # 'USER': 'vkudak_dbuser',\n # 'PASSWORD': 'post_pass',\n # 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.\n # 'PORT': '', # Set to empty string for default.\n # Sqlite\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'Europe/Kiev'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = False\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_URL = '/static/'\n\n# PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n# PROJECT_ROOT = PROJECT_ROOT.rsplit('/', 1)[0]\n# STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, \"static\"),\n)\n\nTEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'Observations')\n#'/home/vkudak/python/Django/lkd_site/Observations'\n#os.path.join(BASE_DIR, 'Observations')\n\nMEDIA_URL = '/Observations/'\n# '/Files/'\nLOGIN_URL = '/auth.html'","sub_path":"lkd_site/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"394422899","text":"\"\"\"hrpanel URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\nfrom django.urls import path\n\nfrom home import views\nfrom hrpanel import settings\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n url(r'^$', views.login_view, name=\"login\"),\n url(r'^logout/$', views.logout_view, name=\"logout\"),\n url(r'^company-details/add$', views.add_company_details,\n name=\"add_company_details\"),\n url(r'^dashboard$', views.dashboard, name=\"dashboard\"),\n url(r'^users$', views.users, name=\"users\"),\n url(r'^users/add-hr$', views.users_add_hr, name=\"add-hr\"),\n url(r'^users/add-employee$', views.users_add_employee, name=\"add-employee\"),\n url(r'^departments$', views.departments_func, name=\"departments\"),\n url(r'^edit-department/(?P[0-9A-Za-z_\\-]+)$', views.edit_departments, name=\"edit-departments\"),\n url(r'^delete-department/(?P[0-9A-Za-z_\\-]+)$', views.delete_departments, name=\"delete-departments\"),\n url(r'^designations$', views.designations_func, name=\"designations\"),\n url(r'^edit-designation/(?P[0-9A-Za-z_\\-]+)$', views.edit_designations, name=\"edit-designation\"),\n url(r'^delete-designation/(?P[0-9A-Za-z_\\-]+)$', views.delete_designations, name=\"delete-designation\"),\n url(r'^designationdetails$', views.designationdetails, name=\"designationdetails\"),\n url(r'^punching-details$', views.punching_details, name=\"punching-details\"),\n url(r'^attendance$', views.attendance, name=\"attendance\"),\n url(r'^holidays$', views.holiday_func, name=\"designations\"),\n url(r'^edit-holiday/(?P[0-9A-Za-z_\\-]+)$', views.edit_holiday, name=\"edit-designation\"),\n url(r'^delete-holiday/(?P[0-9A-Za-z_\\-]+)$', views.delete_holiday, name=\"delete-designation\"),\n url(r'^all-employees$', views.all_employee, name=\"all_employee\"),\n url(r'^settings$', views.settings, name=\"settings\"),\n url(r'^change-password$', views.change_password, name=\"change_password\"),\n url(r'^company-settings$', views.company_settings, name=\"company-settings\"),\n url(r'^termination$', views.terminations_func, name=\"termination\"),\n url(r'^total-attendance$', views.total_attendance, name=\"total_attendance\"),\n url(r'^leave-admin$', views.leave_admin, name=\"leave_admin\"),\n url(r'^leave-employee$', views.leave_employee, name=\"leave_employee\"),\n url(r'^leave-setting$', views.leave_setting, name=\"leave_setting\"),\n url(r'^leave-type$', views.leave_type, name=\"leave_type\"),\n url(r'^timesheet$', views.timesheet, name=\"timesheet\"),\n url(r'^payroll-item', views.payroll_item, name=\"payroll_item\"),\n url(r'^payslip', views.payslip, name=\"payslip\"),\n\n]\n","sub_path":"hrpanel/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"176889421","text":"from Molecule import Molecule\nfrom Polarizability import Polarizability\nfrom Position import Position\n\nclass CarbonMonoxide(Molecule):\n\t\"\"\" an example molecule\n\t\n\t\n\n\t\"\"\"\t\n\tdef __init__(self, **kwargs):\n\t\tMolecule.__init__(self)\n\t\tself._type = \"CarbonMonoxide\" # when you make your own molecules, make sure that you change the \"_type\" string \n\t\t\t\t\t# this will overwrite the \"BaseClass\" type of Molecule!\n\t\t\n\t\t#now I want to allow for hydrogen to have user entered polarizability\n\t\t# in principle I could also have the charges entered by the user\n\t\tpolC = kwargs.get('polC', Polarizability(iso=0.) ) \n\t\tpolO = kwargs.get('polO', Polarizability(iso=0.) ) \n\t\tself.add_atom(pos=Position([-0.75, 0.,0.]), pol=polC, crg=.2, elname='C')\n\t\tself.add_atom(pos=Position([ 0.75, 0.,0.]), pol=polO, crg=-.2, elname='O')\n\n","sub_path":"BasicElements/tests/CarbonMonoxide.py","file_name":"CarbonMonoxide.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"73386193","text":"\"\"\"Find all word pair palingrams in a dictionary file.\"\"\"\nimport time\n\nimport load_diction\n\nword_list = load_diction.load('2of4brif.txt')\n\n#find word pair palingrams\ndef find_palingrams():\n \"\"\"Find dictionary palingrams\"\"\"\n pali_list = []\n for word in word_list:\n end = len(word)\n rev_word = word[::-1]#word.join(reversed(word)) produces different result, not sure why\n if end > 1:\n for i in range(end):\n if word[i:] == rev_word[:end-1]and rev_word[end-1:] in word_list:\n pali_list.append((word, rev_word[end-1:]))\n if word[:i] == rev_word[end-1:]and rev_word[:end-i] in word_list:\n pali_list.append((rev_word[:end-1], word))\n return pali_list\nstart_time = time.time()\npalingrams = find_palingrams()\nend_time = time.time()\n#sort palingrams alphabetically\npalingrams_sorted = sorted(palingrams)\n\n#display list of palingrams\nprint(\"\\nNumber of palingrams = {}\\n\".format(len(palingrams_sorted)))\nfor first, second in palingrams_sorted:\n print(\"{} {}\".format(first, second))\n\nprint(\"Runtime for this program was {} seconds.\".format(end_time - start_time))\n","sub_path":"palin_dromes/palingrams_timed.py","file_name":"palingrams_timed.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"3965883","text":"from rest_framework import serializers\n\nfrom .models import *\nfrom .tdmos.tdmos import SERVED\n\n\nclass AccountCreationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = '__all__'\n\nclass StoreSerializer(serializers.ModelSerializer):\n class Meta:\n model = Store\n fields = '__all__'\n\nclass ItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = Item\n fields = '__all__'\n\n\n \nclass CityCodeSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = CityCode\n fields= '__all__'\n\nclass OrderSerialzer(serializers.ModelSerializer):\n\n class Meta:\n model = Order\n fields= '__all__'\n\nclass PilotSerializer(serializers.ModelSerializer):\n class Meta:\n model= Pilot\n fields= '__all__'\n\n\nclass FetchedItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = Item\n fields = ('item_id', 'name', 'allowed', 'price', 'measure', 'ratings')\n\nclass StoreTeamSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Servei\n fields = ('first_name','last_name','phone_number','servei_id')\n\nclass CategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = '__all__'\n\nclass DefaultItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = DefaultItems\n fields = '__all__'\n\nclass DefaultItemsSelection(serializers.ModelSerializer):\n\n class Meta:\n model = DefaultItems\n fields = ('item_id', 'name')\n\nclass HeadCategorySerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Category\n fields = ('name','cat_id','image')\n\nclass CategoryModel(object):\n\n def __init__(self, category):\n self.name = category.name\n self.cat_type = category.cat_type\n self.cat_id = category.cat_id\n self.prev_cat = category.prev_cat\n self.next_cat = category.next_cat [::1] if category.next_cat else []\n self.image = category.image\n self.required_desc = category.required_desc\n self.delivery_type = category.delivery_type\n self.radiod = category.radiod\n self.returnable = category.returnable\n self.default_items = category.default_items [::1] if category.default_items else []\n\n\nclass DefaultItemModel(object):\n\n def __init__(self,item):\n self.item_id = item.item_id\n self.name = item.name\n self.cat_id = item.cat_id\n self.unit = item.unit\n self.measure_param = item.measure_param\n self.pick_type = item.pick_type\n self.image = item.image\n self.delivery_type = item.delivery_type\n self.inspection = item.inspection\n self.description = item.description\n\n\n\n\nclass CategorySelectionSerializer:\n\n def __init__(self,query_set):\n self.query_set = query_set\n self.returnable = []\n\n\n \n def data(self):\n for category in self.query_set:\n if isinstance(category,Category):\n self.returnable.append(self.category_serialize(category))\n return self.returnable\n\n def category_serialize(self,category:Category):\n data = {}\n data[\"name\"] = category.name\n data[\"cat_type\"] = category.cat_type\n data[\"cat_id\"] = category.cat_id\n if data[\"cat_type\"] == \"FC\":\n data[\"next_cat\"] = [self.category_serialize(nextcateg) for nextcateg in category.next_cat] if category.next_cat else []\n data[\"radiod\"] = 1 if category.radiod else 0\n data[\"default_items\"] = [self.default_item_serialize(defaultitem) for defaultitem in category.default_items] if category.default_items else []\n return data\n\n\n def default_item_serialize(self,defaultitem):\n return {\n \"item_id\":defaultitem.item_id,\n \"name\":defaultitem.name,\n \"cat_id\":defaultitem.cat_id,\n \"unit\":defaultitem.unit,\n \"measure\":defaultitem.measure_param,\n \"image\":defaultitem.image,\n \"description\":defaultitem.description\n }\n\n\nclass MeasureParamSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = MeasureParam\n fields = '__all__'\n\n\nclass RateSerializer(serializers.ModelSerializer):\n \n class Meta:\n model = Rate\n fields = '__all__'\n\n\nclass CustomerReviewSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = CustomerReviewModel\n fields = '__all__'\n\nclass OrderServeiSerializer:\n\n def __init__(self,orders,servei_id,final=False):\n self.orders = orders\n self.final = final\n self.servei_id = servei_id\n\n def serialize(self,order):\n returnable_dict ={}\n returnable_dict['order_id'] = f\"{order.order_id}\"\n if order.otp:\n returnable_dict['otp'] = f\"{order.otp}\"\n cluster = None\n if self.final:\n cluster = order.final_servei_cluster[self.servei_id]\n else:\n cluster = order.servei_cluster[self.servei_id]\n print(cluster)\n returnable_dict['items'] = cluster['items']\n returnable_dict['quantity'] = cluster['quantity']\n returnable_dict['net_price'] = cluster['net_price']\n returnable_dict['price'] = cluster['price']\n returnable_dict['platform_charge'] = cluster['platform_charge']\n #extra charge to be added\n returnable_dict['status'] = cluster['status']\n returnable_dict['delivery_required'] = 1 if order.delivery_required else 0\n returnable_dict['payment_COD'] = 1 if order.payment_COD else 0\n returnable_dict['payment_complete'] = 1 if order.payment_complete else 0\n return returnable_dict\n\n def data(self):\n retdata =[]\n for order in self.orders:\n retdata.append(self.serialize(order))\n return retdata\n\n\n","sub_path":"locie/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"285348706","text":"\"\"\"Globally available external client services.\"\"\"\nfrom requests.adapters import HTTPAdapter\nfrom requests.exceptions import ConnectionError\nfrom requests.packages.urllib3.util.retry import Retry\nfrom requests.sessions import Session\nimport logging\n\nfrom boto3 import client\nfrom django.conf import settings\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nclass ClamAVClient:\n \"\"\"An HTTP client that can be used to send files to a ClamAV REST server.\"\"\"\n\n class ServiceUnavailable(Exception):\n \"\"\"Raised when the target ClamAV REST server is unavailable.\"\"\"\n\n pass\n\n # https://github.com/raft-tech/clamav-rest#status-codes\n SCAN_CODES = {\n 'CLEAN': [200],\n 'INFECTED': [406],\n 'ERROR': [400, 412, 429, 500, 501]\n }\n\n def __init__(self, endpoint_url=None):\n if not endpoint_url:\n endpoint_url = settings.AV_SCAN_URL\n\n self.endpoint_url = endpoint_url\n self.session = self.init_session()\n\n def init_session(self):\n \"\"\"Create a new request session that can retry failed connections.\"\"\"\n session = Session()\n retries = Retry(\n backoff_factor=settings.AV_SCAN_BACKOFF_FACTOR,\n status_forcelist=self.SCAN_CODES['ERROR'],\n total=settings.AV_SCAN_MAX_RETRIES\n )\n session.mount(self.endpoint_url, HTTPAdapter(max_retries=retries))\n return session\n\n def scan_file(self, file, file_name) -> bool:\n \"\"\"Scan a file for virus infections.\n\n :param file:\n The file or file-like object that should be scanned\n :param file_name:\n The name of the target file (str).\n :returns is_file_clean:\n A boolean indicating whether or not the file passed the ClamAV scan\n \"\"\"\n logger.debug(f'Initiating virus scan for file: {file_name}')\n try:\n scan_response = self.session.post(\n self.endpoint_url,\n data={'name': file_name},\n files={'file': file},\n timeout=settings.AV_SCAN_TIMEOUT\n )\n except ConnectionError as err:\n logger.debug(f'Encountered error scanning file: {err}')\n raise self.ServiceUnavailable()\n\n if scan_response.status_code in self.SCAN_CODES['CLEAN']:\n logger.debug(\n f'File scan marked as CLEAN for file: {file_name}'\n )\n return True\n\n if scan_response.status_code in self.SCAN_CODES['INFECTED']:\n logger.debug(\n f'File scan marked as INFECTED for file: {file_name}'\n )\n return False\n\n logger.debug(f'Unable to scan file with name: {file_name}')\n return False\n\n\ndef get_s3_client():\n \"\"\"Return an S3 client that points to localstack or AWS based on settings.\n\n Intended to be used in place of a direct boto3 client.\n \"\"\"\n region_name = settings.AWS_REGION_NAME\n\n # If localstack support is turned on we will return a client that redirects\n # all S3 requests to the localstack container\n if settings.USE_LOCALSTACK:\n # To get s3 signed URLs to work with localstack we must pass in\n # dummy credentials of `test` per the docs\n # https://github.com/localstack/localstack#setting-up-local-region-and-credentials-to-run-localstack # noqa\n localstack_creds_placeholder = 'test'\n\n # If localstack is in use then we must supply the endpoint URL\n # explicitly to prevent boto3 from auto-generating a live S3 URL\n localstack_endpoint_url = 'http://localhost:4566'\n\n return client(\n service_name='s3',\n aws_access_key_id=localstack_creds_placeholder,\n aws_secret_access_key=localstack_creds_placeholder,\n endpoint_url=localstack_endpoint_url,\n region_name=region_name\n )\n\n # Otherwise, use a live S3 with the credentials configured via env vars\n return client(\n service_name='s3',\n aws_access_key_id=settings.AWS_S3_ACCESS_KEY_ID,\n aws_secret_access_key=settings.AWS_S3_SECRET_ACCESS_KEY,\n region_name=region_name\n )\n","sub_path":"tdrs-backend/tdpservice/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"78265962","text":"# project 2D mask and 3D bounding box, NOTE run within DATASET folder\nimport numpy as np\nimport json\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom pycocotools import mask\nfrom matplotlib.patches import Polygon\nfrom skimage import measure\n\n\ndef project(xyz, K, RT):\n # xyz: [N, 3], K: [3, 3], RT: [3, 4]\n xyz = np.dot(xyz, RT[:, :3].T) + RT[:, 3:].T\n xyz = np.dot(xyz, K.T)\n z = xyz[:, 2:]\n xy = xyz[:, :2] / z\n return xy, z\n\n\nclass CocoKeypoints:\n def __init__(self, keypoint_paths, category_ids, coco_path, output_path):\n self.coco_ds = json.load(open(coco_path))\n self.coco_path = Path(coco_path)\n self.out_filename = Path(output_path)\n self.image_id_2_idx = {x[\"id\"]: idx for idx, x in enumerate(self.coco_ds['images'])}\n self.scene_id_to_frames = {}\n self.keypoint_names = [\"glass bottom right\", \"glass bottom left\", \"glass top left\", \"glass top right\",\n \"box front bottom right\", \"box front bottom left\", \"#box front top left\",\n \"box front top right\", \"box back bottom right\", \"box back bottom left\",\n \"box back top left\", \"box back top right\", \"bossard label bottom right\",\n \"bossard label bottom left\", \"bossard label top left\", \"bossard label top right\",\n \"bossard sidepanel top\", \"bossard sidepanel bottom\", \"bossard weight front bottom right\",\n \"bossard weight front bottom left\", \"bossard weight back bottom left\",\n \"bossard weight back bottom right\"]\n for im_data in self.coco_ds[\"images\"]:\n sid = im_data[\"scene_id\"]\n sid_frames = self.scene_id_to_frames.get(sid, {})\n channel = im_data.get(\"channel\", \"rgb\")\n if channel == \"depth\":\n sid_frames[channel] = im_data\n else:\n sid_frames[\"rgb\"] = im_data\n self.scene_id_to_frames[sid] = sid_frames\n self.category_id_to_keypoints = {}\n for keypoint_path, category_id in zip(keypoint_paths, category_ids):\n keypoint_dict = json.load(open(keypoint_path))\n keypoint_list = []\n for keypoint_name in self.keypoint_names:\n keypoint_list.append(np.array(keypoint_dict[\"keypoints\"][keypoint_name]))\n self.category_id_to_keypoints[int(category_id)] = keypoint_list\n\n def get_keypoints(self, ann_id=0):\n annot_data = self.coco_ds['annotations'][ann_id]\n im_idx = self.image_id_2_idx[annot_data['image_id']]\n scene_id = self.coco_ds['images'][im_idx][\"scene_id\"]\n # read in depth frame and scale to (m)\n depth_factor = 1000.0 #self.scene_id_to_frames[scene_id][\"depth\"][\"depth_factor\"]\n depth_path = self.coco_path.parents[0] / self.scene_id_to_frames[scene_id][\"depth\"][\"file_name\"]\n raw_depth = Image.open(str(depth_path))\n depth_frame = np.array(raw_depth) / depth_factor\n width = self.coco_ds['images'][im_idx][\"width\"]\n height = self.coco_ds['images'][im_idx][\"height\"]\n K = np.array(self.coco_ds['images'][im_idx]['K'])\n RT = np.array(annot_data['RT'])[:3, :4]\n keypoints_3D = np.array(self.category_id_to_keypoints[annot_data['category_id']])\n keypoints_xy, projected_depth = project(keypoints_3D, K, RT)\n keypoints = []\n for xy2, z in zip(keypoints_xy, projected_depth):\n x = int(xy2[0])\n keypoints.append(x)\n y = int(xy2[1])\n keypoints.append(y)\n visible = 2 #keypoint labeled and visible\n if not (0 < x < width):\n visible = 0 #keypoint not labeled and not visible\n elif not (0 < y < height):\n visible = 0 #keypoint not labeled and not visible\n elif depth_frame[y, x] + 0.01 < z:\n visible = 1 #keypoint labeled but not visible\n # print(\"keypoint not visible\", depth_frame[y, x])\n #else:\n # print(\"keypoint is visible\", depth_frame[y, x])\n keypoints.append(visible)\n return keypoints\n\n def add_keypoints_to_coco_annotations(self):\n ann_count = len(self.coco_ds[\"annotations\"])\n print(\"adding keypoints to \" + str(ann_count) + \" annotations\")\n for i in range(ann_count):\n ann = self.coco_ds[\"annotations\"][i]\n ann[\"keypoints\"] = self.get_keypoints(i)\n self.coco_ds[\"annotations\"][i] = ann\n if i % 500 == 0:\n print(\"progress \" + str(i) + \"/\" + str(ann_count))\n print(\"setting category keypoint-names to \", self.keypoint_names)\n for i in range(len(self.coco_ds[\"categories\"])):\n cat = self.coco_ds[\"categories\"][i]\n cat[\"keypoints\"] = self.keypoint_names\n self.coco_ds[\"categories\"][i] = cat\n print(\"saving file as \" + str(self.out_filename))\n f_out = open(str(self.out_filename), \"w\")\n json.dump(self.coco_ds, f_out)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Parse arguments from command line\n \"\"\"\n import argparse\n from pathlib import Path\n import json\n parser = argparse.ArgumentParser(description='Interactive 6DoF pose annotator')\n parser.add_argument('--root-path', type=Path,\n default=\"/media/mikkel/data/datasets/data_grabber_sequences/black_box\",\n help='path to the folder containing annotation file.')\n parser.add_argument('--sequence', type=str, default=None, help='sequence name.')\n parser.add_argument('--keypoint-paths',\n default=[\"/home/mikkel/data/meshes/Meshes/SchaferBoxes/Medium/schafer_box_medium.ply\",\n \"/home/mikkel/data/meshes/Meshes/SchaferBoxes/Small/schafer_box_small.ply\"],\n nargs=\"*\",\n help='file name of the object model (.pcd or .ply).')\n parser.add_argument('--category-ids', default=[0, 2], nargs=\"*\",\n help=\"desired category id's for corresponding object models. (default: [0, 1, ..., 9])\")\n args = parser.parse_args()\n data_root_path = Path(args.root_path)\n seq = \"\"\n if args.sequence is not None:\n seq = \"_\" + args.sequence\n coco_path = data_root_path / str(\"coco_annotations\" + seq + \".json\")\n output_path = data_root_path / str(\"coco_annotations_with_keypoints\" + seq + \".json\")\n coco_keypoints = CocoKeypoints(keypoint_paths=args.keypoint_paths, category_ids=args.category_ids,\n coco_path=coco_path, output_path=output_path)\n coco_keypoints.add_keypoints_to_coco_annotations()\n","sub_path":"examples/python/6d_pose_annotation/add_keypoints_to_annotation_file.py","file_name":"add_keypoints_to_annotation_file.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"340017950","text":"from sistema import Sistema\r\nfrom tkinter import *\r\n\r\nsistema=Sistema()\r\n\r\nprincipal = Tk()\r\n\r\n#tamanho na tela\r\nprincipal.geometry(\"800x600\")\r\n\r\n#titulo\r\nprincipal.title(\"Retirar Chaves\")\r\n#icone\r\nprincipal.wm_iconbitmap('icon.ico')\r\n\r\ntexto=Label(principal, text=\"Retirar Chaves\", font=(\"Verdana\",\"15\"))\r\ntexto.pack(side=\"top\")\r\n\r\nprincipal.mainloop()","sub_path":"TCC_PegarChaves/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"607741479","text":"from pydub import AudioSegment\nfrom pydub.playback import play\n# Download an audio file\n#urllib.request.urlretrieve(\"https://tinyurl.com/wx9amev\", \"metallic-drums.wav\")\n# Load into PyDub\nloop1 = AudioSegment.from_wav(\"/home/pi/Final/loop1.wav\")\n\nloop2 = AudioSegment.from_wav(\"/home/pi/Final/loop2.wav\")\n\nlength = len(loop1)\n\nmixed = loop2[:length].overlay(loop1)\n# Play the result\nwhile(1):\n\tplay(mixed)\n\t\n","sub_path":"whileplay.py","file_name":"whileplay.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"458102766","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\n\n\nclass rnd_graph:\n def __init__(self, size, p):\n self.adj_matrix = [] #creating the adjacency matrix of all zeros\n self.size = size\n self.adj_list = []\n for i in range(size):\n self.adj_matrix.append([0 for i in range(size)])\n C = np.random.random((size,size)) #making the matrix random\n for j in range(size):\n for i in range(j+1,size):\n if C[i][j] <= p:\n self.adj_matrix[i][j] = 1\n \n def vertex_degree(self, vertex): #getting the degree of a vertex (i.e counting the number of its edges)\n count = 0\n for i in range(self.size): #the matrix is lower triangular\n if i <= vertex:\n if self.adj_matrix[vertex][i] == 1:\n count = count + 1\n else:\n if self.adj_matrix[i][vertex] == 1:\n count = count + 1\n return count\n def max_degree(self): #gets the maximum degree among the vertex of the graph\n degrees = []\n for i in range(self.size):\n degree = self.vertex_degree(i)\n degrees.append(degree)\n return max(degrees)\n\n\ninfection = np.power(1 - l, np.arange(max_neigh+1)) #l is the probability of being infected, max_neigh = graph_name.max_degree()\n\n\ndef simulation_epidemy(adj_matrix, graph_size, state, infection, mu, infected_neighbour, end):\n for t in range(end):\n prob_inf = np.ones(graph_size) \n prob_rec = np.ones(graph_size)\n infect = np.zeros(graph_size)\n prob_inf[state == 0] = np.random.random(len(state[state == 0])) #creating random uniform values in prob_inf in correspondance to the vertices in susceptible state (i.e state 0)\n prob_rec[state == 1] = np.random.random(len(state[state == 1])) #creating random uniform values in prob_rec in correspondance to the vertices in infected state (i.e state 1)\n infect[state == 0] = 1 - infection[infected_neighbour[state == 0]] #in this way we select the index of the vector infection that corresponds to the correct probability of being infected of a certain susceptible node\n for i in range(graph_size): #updating vector state\n new_infected = []\n new_recovered = []\n if prob_inf[i] <= infect[i]:\n state[i] = state[i] + 1\n new_infected.append(i)\n if prob_rec[i] <= mu:\n state[i] = state[i] + 1\n new_recovered.append(i)\n for i in range(len(new_infected)): #updating infected_neighbour adding the neighbours of the new infected vertices\n for j in range(graph_size): #the adjacency matrix is lower triangular\n if j <= new_infected[i]:\n if adj_matrix[new_infected[i]][j] == 1:\n infected_neighbour[j] = infected_neighbour[j] + 1\n else:\n if adj_matrix[j][new_infected[i]] == 1:\n infected_neighbour[j] = infected_neighbour[j] + 1\n for i in range(len(new_recovered)): #updating infected_neighbour removing the neighbours of the new recovered vertices\n for j in range(graph_size):\n if j <= new_recovered[i]:\n if adj_matrix[new_recovered[i]][j] == 1:\n infected_neighbour[j] = infected_neighbour[j] - 1\n else:\n if adj_matrix[j][new_infected[i]] == 1:\n infected_neighbour[j] = infected_neighbour[j] - 1\n return state\n\ndef naive_bayes(adj_matrix, graph_size, state_T, infection, mu, end, iterations):\n freq = np.zeros((graph_size,graph_size)) #this matrix will collect the number of times in which a vertex is equal to its state_T correspondant during the iterations given a certain patient zero\n already_infected = []\n for i in range(graph_size): #we only select those in state_T who are infected or recovered (being susceptible after being the patient zero is a zero probability event)\n if state_T[i] != 0:\n already_infected.append(i)\n for pos in already_infected:\n for k in range(iterations): #we simulate many times from the initial situation in which one element of already_infected is patient zero\n state = np.zeros(graph_size)\n state[pos] = 1\n infected_neighbour = np.zeros(graph_size).astype(int)\n for i in range(graph_size): #adj_matrix is lower triangular\n if i <= pos:\n if adj_matrix[pos][i] == 1:\n infected_neighbour[i] = infected_neighbour[i] + 1\n else:\n if adj_matrix[i][pos] ==1:\n infected_neighbour[i] = infected_neighbour[i] + 1\n state = simulation_epidemy(adj_matrix, graph_size, state, infection, mu, infected_neighbour, end)\n for i in range(graph_size): #here we update matrix freq counting how many times patient i is equal to state_T[i] given pos as patient zero\n if state_T[i] == state[i]:\n freq[pos][i] = freq[pos][i] + 1\n new_freq = freq + 1 #this translation is done in order to avoid log(0)\n log_freq = np.log(new_freq)\n v = np.zeros(graph_size)\n for i in range(graph_size): #we compute v_i according to Naive Bayes theory\n v[i] = sum(log_freq[i,:])\n ordered_v = sorted(v, reverse = True)\n v_ranking = [] #we rank the v_i's\n for k in range(graph_size):\n for j in range(graph_size):\n if ordered_v[k] == v[j]:\n v_ranking.append(j)\n break\n return v_ranking\n\n#the algorithm ends here\n\n#from now on there is the code for checking the performance of the algorithm (section 4)\n\n#checking Naive Bayes performance\ndef Naive_Bayes_performance_check(graph_size, p, l, mu, end, iterations):\n initial = np.zeros(graph_size)\n init = np.random.randint(graph_size)\n initial[init] = 1\n infected_neighbour = np.zeros(graph_size).astype(int)\n G = rnd_graph(graph_size, p)\n max_neigh = G.max_degree()\n infection = np.power(1 - l, np.arange(max_neigh +1))\n for i in range(graph_size):\n if i <= init:\n if G.adj_matrix[init][i] == 1:\n infected_neighbour[i] = infected_neighbour[i] + 1\n else:\n if G.adj_matrix[i][init] == 1:\n infected_neighbour[i] = infected_neighbour[i] + 1\n state_T = simulation_epidemy(G.adj_matrix, graph_size, initial, infection, mu, infected_neighbour, end)\n naive_bayes_result = naive_bayes(G.adj_matrix, graph_size, state_T, infection, mu, end, iterations)\n for j in range(graph_size):\n if naive_bayes_result[j] == init:\n patient_zero_ranking = j\n return [patient_zero_ranking, init] \n\ndef mean_ranking_true_patientzero(graph_size, p, l, mu, end, iterations, tries): #this function returns the avarage of the rankings(computed with Naive Bayes criterion) of the true patient zero\n rankings = np.zeros(tries) #Naive Bayes criterion is computed tries times and then we make an average of the rankings\n for j in range(tries):\n rankings[j] = Naive_Bayes_performance_check(graph_size, p, l, mu, end, iterations)[0]\n return np.sum(rankings)/tries\n\ndef lambda_varying_performance(graph_size, p, lambda_interval, mu, end, iterations, tries): #in this way we get the average performances of the Naive Bayes making lambda vary one step at a time\n results = np.zeros(len(lambda_interval))\n for i in range(len(results)):\n print('lambda =', lambda_interval[i])\n results[i] = mean_ranking_true_patientzero(graph_size, p, lambda_interval[i], mu, end, iterations, tries)\n print('mean ranking =', results[i])\n return results \ndef k_varying_performance(graph_size, K, l, mu, end, iterations, tries): #in this way we get the average performances of the Naive Bayes making k vary one step at a time\n for i in range(len(K)):\n if K[i] > graph_size:\n return str('probabilities must be lesser or equal than one')\n results = np.zeros(len(K))\n for i in range(len(results)):\n print('K =', K[i])\n results[i] = mean_ranking_true_patientzero(graph_size, K[i]/graph_size, l, mu, end, iterations, tries)\n print('mean ranking =', results[i])\n return results\ndef iterations_varying_performance(graph_size, p, l, mu, end, iterations, tries):\n\tresults = np.zeros(len(iterations))\n\tfor i in range(len(results)):\n\t\tprint('iterations =', iterations[i])\n\t\tresults[i] = mean_ranking_true_patientzero(graph_size, p, l, mu, end, iterations[i], tries)\n\t\tprint('mean ranking =', results[i])\n\treturn results\n\n\n\n#we should analyze the performance of the algorithm while changing the probability lambda\n\nT = 5\ngraph_size = 100\np = 0.9\nlambda_interval = np.arange(0.1,1,0.1)\nmu = 0.4\niterations = 200\ntries = 25\nlamba_result = lambda_varying_performance(graph_size, p, lambda_interval, mu, T, iterations, tries)\n\nplt.plot(lambda_interval,lamba_result, '-o')\nplt.title(\"Performance varying Lambda (t=5)\")\nplt.xlabel(\"Lambda\")\nplt.ylabel(\"Mean position\")\n#plt.show()\nplt.savefig('Varyinglambda_5t.pdf')\n\n\nT = 10\ngraph_size = 100\np = 0.9\nlambda_interval = np.arange(0.1,1,0.1)\nmu = 0.4\niterations = 200\ntries = 25\nlamba_result = lambda_varying_performance(graph_size, p, lambda_interval, mu, T, iterations, tries)\n\nplt.plot(lambda_interval,lamba_result, '-o')\nplt.title(\"Performance varying Lambda (t=10)\")\nplt.xlabel(\"Lambda\")\nplt.ylabel(\"Mean position\")\n#plt.show()\nplt.savefig('Varyinglambda_10t.pdf')\n\n#let us analyze the performance by changing K = p*n (expected degree of interconnection (distributed as a binomial))\n\nT = 5\ngraph_size = 100\nK = [10,25,50,75,90]\nl = 0.5\nmu = 0.4\niterations = 200\ntries = 25\nk_results = k_varying_performance(graph_size, K, l, mu, T, iterations, tries)\n\nplt.plot(K, k_results, '-o')\nplt.title(\"Performance varying K (t=5)\")\nplt.xlabel(\"Expected degree of interconnection\")\nplt.ylabel(\"Mean position\")\n#plt.show()\nplt.savefig('Varyingk_5t.pdf')\n\nT = 10\ngraph_size = 100\nK = [10,25,50,75,90]\nl = 0.5\nmu = 0.4\niterations = 200\ntries = 25\nk_results = k_varying_performance(graph_size, K, l, mu, T, iterations, tries)\n\nplt.plot(K, k_results, '-o')\nplt.title(\"Performance varying K (t=10)\")\nplt.xlabel(\"Expected degree of interconnection\")\nplt.ylabel(\"Mean position\")\n#plt.show()\nplt.savefig('Varyingk_10t.pdf')\n\n#now we vary the number of iterations\nT = 5\ngraph_size = 100\np = 0.9\nl = 0.5\nmu = 0.4\niterations = np.arange(100, 500, 100)\ntries = 25\niterations_result = iterations_varying_performance(graph_size, p, l, mu, T, iterations, tries)\n\nplt.plot(iterations,iterations_result, '-o')\nplt.title(\"Performance varying iterations (t = 5)\")\nplt.xlabel(\"Number of iterations\")\nplt.ylabel(\"Mean Ranking\")\nplt.ylim((0,5))\n\n#plt.show()\nplt.savefig('Varyingiterations_5t.pdf')\n\nT = 10\ngraph_size = 100\np = 0.9\nl = 0.5\nmu = 0.4\niterations = np.arange(100, 500, 100)\ntries = 25\niterations_result = iterations_varying_performance(graph_size, p, l, mu, T, iterations, tries)\n\nplt.plot(iterations,iterations_result, '-o')\nplt.title(\"Performance varying iterations (t = 10)\")\nplt.xlabel(\"Number of iterations\")\nplt.ylabel(\"Mean Ranking\")\nplt.ylim((0,5))\n#plt.show()\nplt.savefig('Varyingiterations_10t.pdf')","sub_path":"Naive_Bayes.py","file_name":"Naive_Bayes.py","file_ext":"py","file_size_in_byte":11739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"440032528","text":"# Copyright 2017 Intel Corporation.\n# The source code, information and material (\"Material\") contained herein is\n# owned by Intel Corporation or its suppliers or licensors, and title to such\n# Material remains with Intel Corporation or its suppliers or licensors.\n# The Material contains proprietary information of Intel or its suppliers and\n# licensors. The Material is protected by worldwide copyright laws and treaty\n# provisions.\n# No part of the Material may be used, copied, reproduced, modified, published,\n# uploaded, posted, transmitted, distributed or disclosed in any way without\n# Intel's prior express written permission. No license under any patent,\n# copyright or other intellectual property rights in the Material is granted to\n# or conferred upon you, either expressly, by implication, inducement, estoppel\n# or otherwise.\n# Any license under such intellectual property rights must be express and\n# approved by Intel in writing.\n\nimport numpy as np\nfrom ctypes import *\nfrom Controllers.MiscIO import *\nfrom Controllers.DataTransforms import *\nfrom Controllers.EnumController import *\nfrom Models.EnumDeclarations import *\nfrom Views.Graphs import *\n\nfrom linecache import getline\n\nclass NetworkStage:\n\n def __init__(\n self,\n name,\n top,\n s_order,\n pad_y,\n pad_x,\n pad_type,\n dtype,\n precision,\n op_type,\n op_y,\n op_x,\n sy,\n sx,\n x,\n y,\n c,\n fh,\n fw,\n k,\n taps,\n taps_order,\n bias,\n pre_op_type,\n post_op_type,\n post_1,\n post_sx,\n post_sy,\n slicing=None,\n myriad_config=None,\n args=None,\n opParams=None,\n new_x=0,\n new_y=0,\n new_c=0):\n self.changeName(name)\n\n # Historically cocat layer was working only for axis1 i.e channels.\n # Concat on axis 2 is available only for CaffeParser and concat_axis \n # needs to default to 1 in order not to break the TensorFlowParser.\n self.concat_axis = 1\n\n # mvTensor cannot deal with such convolution, which is equivalent to fc\n if (op_type == StageType.convolution and op_x == 1 and op_y == 1\n and x == 1 and y == 1):\n op_type = StageType.fully_connected_layer\n\n self.network = args.network\n self.top = top\n self.tail = []\n self.op = op_type\n self.radixX = op_x\n self.radixY = op_y\n self.padX = pad_x\n self.padY = pad_y\n self.alias = [name]\n\n if self.radixX == -1 and self.radixY == -1:\n # Global Operation\n self.radixX = x\n self.radixY = y\n\n self.strideX = sx\n self.strideY = sy\n\n self.optMask = readOptimisationMask(name, self, myriad_config, args)\n\n self.inputStrideX = 2 * c # Concat Stride\n self.inputStrideY = 2 * c * x\n self.inputStrideZ = 2\n self.inputOffset = 0\n if slicing:\n if top is None:\n for slice in slicing:\n if slice[0] is None:\n c = slice[2] - slice[1]\n self.inputOffset = slice[1] * 2\n break\n else:\n for input in top:\n for slice in slicing:\n if slice[0] == input:\n c = slice[2] - slice[1]\n self.inputOffset = slice[1] * 2\n break\n if (op_type == StageType.eltwise_sum or op_type ==\n StageType.eltwise_prod or op_type == StageType.eltwise_max):\n # Ignore given k, which could be wrong if it ignored slicing\n k = c\n self.inputDimX = x\n self.inputDimY = y\n self.inputDimZ = c\n\n self.tapDimX = fw * fh\n self.tapDimY = c\n self.tapDimZ = k # Will be replaced when attached to another stage..\n\n self.outputDimZ = k\n if self.op in [StageType.fully_connected_layer]:\n if self.inputDimX == 0:\n #Flag that we don't want to flatten the input 2D matrix\n self.inputDimX = 1\n self.outputDimX = 1\n self.outputDimY = self.inputDimY\n else:\n self.inputDimX = 1\n self.inputDimY = 1\n self.inputDimZ = x * y * c\n\n self.tapDimX = 1\n self.tapDimY = x * y * c\n\n self.outputDimX = 1\n self.outputDimY = 1\n\n elif self.op in [StageType.convolution, StageType.depthwise_convolution, StageType.max_pooling, StageType.average_pooling]:\n if pad_type == PadStyle.tfsame:\n self.outputDimX = math.ceil(x / self.strideX)\n self.outputDimY = math.ceil(y / self.strideY)\n elif pad_type == PadStyle.tfvalid:\n self.outputDimX = math.ceil((x - self.radixX + 1) / self.strideX)\n self.outputDimY = math.ceil((y - self.radixY + 1) / self.strideY)\n # Caffe, convolution uses floor\n elif self.op in [StageType.convolution, StageType.depthwise_convolution]:\n if self.radixX == 1 and self.radixY == 1 and self.padX == 1 and self.padY == 1:\n throw_error(\n ErrorTable.StageDetailsNotSupported,\n 'Padding 1 not supported for 1x1 convolution in ' + name)\n # This code should be executed only for caffe layers.\n radix_x_extent = self.radixX\n radix_y_extent = self.radixY\n dilation = 1\n if opParams is not None:\n dilation = opParams[0]\n radix_x_extent = dilation * (self.radixX - 1) + 1\n radix_y_extent = dilation * (self.radixY - 1) + 1\n\n self.outputDimX = (x + 2 * self.padX - radix_x_extent) // self.strideX + 1\n self.outputDimY = (y + 2 * self.padY - radix_y_extent) // self.strideY + 1\n\n else: # Caffe, pooling uses ceil\n self.outputDimX = math.ceil((x + 2 * self.padX - self.radixX) / self.strideX) + 1\n self.outputDimY = math.ceil((y + 2 * self.padY - self.radixY) / self.strideY) + 1\n self.outputDimX = min(self.outputDimX, math.ceil((x + self.padX) / self.strideX))\n self.outputDimY = min(self.outputDimY, math.ceil((y + self.padY) / self.strideY))\n\n elif self.op in [StageType.deconvolution]:\n if pad_type == PadStyle.tfsame:\n pad_X = math.floor(self.radixX / 2)\n pad_Y = math.floor(self.radixY / 2)\n elif pad_type == PadStyle.tfvalid:\n pad_X = self.radixX - 1\n pad_Y = self.radixY - 1\n elif pad_type == PadStyle.caffe:\n pad_X = self.padX\n pad_Y = self.padY\n else:\n pad_X = 0\n pad_Y = 0\n\n self.outputDimX = self.strideX * (x - 1) + self.radixX - 2 * pad_X\n self.outputDimY = self.strideY * (y - 1) + self.radixY - 2 * pad_Y\n\n elif self.op == StageType.toplanemajor:\n self.outputDimX = 1\n self.outputDimY = 1\n self.outputDimZ = x * y * c\n\n elif self.op in [StageType.reshape]:\n self.outputDimX = new_x\n self.outputDimY = new_y\n self.outputDimZ = new_c\n\n if (new_x == 0):\n self.outputDimX = x\n elif (new_x > 0):\n self.outputDimX = new_x\n\n if (new_y == 0):\n self.outputDimY = y\n elif (new_y > 0):\n self.outputDimY = new_y\n\n if (new_c == 0):\n self.outputDimZ = c\n elif (new_c > 0):\n self.outputDimZ = new_c\n\n if (new_x == -1):\n self.outputDimX = x * y * \\\n c // (self.outputDimY * self.outputDimZ)\n if (new_y == -1):\n self.outputDimY = x * y * \\\n c // (self.outputDimX * self.outputDimZ)\n if (new_c == -1):\n self.outputDimZ = x * y * \\\n c // (self.outputDimX * self.outputDimY)\n\n elif self.op in [StageType.reorg]:\n stride = opParams[0]\n self.outputDimX = int(self.inputDimX / stride)\n self.outputDimY = int(self.inputDimY / stride)\n self.outputDimZ = int(self.inputDimZ * stride * stride)\n\n elif self.op in [StageType.crop, StageType.permute]:\n self.outputDimX = new_x\n self.outputDimY = new_y\n self.outputDimZ = new_c\n elif self.op in [StageType.prior_box] :\n self.tapDimX = int(opParams[1])\n self.tapDimY = int(opParams[0])\n\n opParams = opParams[2:]\n min_size_size = opParams[0]\n max_size_size = opParams[1]\n flip = int(opParams[4])\n aspect_ratio_size = opParams[2]\n aspect_ratio_size = aspect_ratio_size*2 if (flip) else aspect_ratio_size\n\n num_priors = (1 + aspect_ratio_size) * min_size_size + max_size_size\n\n self.outputDimX = 1\n self.outputDimY = int(x * y * num_priors * 4)\n self.outputDimZ = 2\n elif self.op in [StageType.detection_output]:\n self.outputDimX = 7\n # output[0,0,0] = contains the number of detections.\n # The rest of the elements on the first line are grabage.\n # The detections start at the second line and span maximum new_y lines\n # i.e. top_k lines at max.\n self.outputDimY = new_y + 1\n self.outputDimZ = 1\n else:\n self.outputDimX = x\n self.outputDimY = y\n\n self.output = np.zeros(\n (int(\n self.outputDimZ), int(\n self.outputDimY), int(\n self.outputDimX))).astype(\n enum_as_dtype(dtype))\n\n self.tapStrideX = 2 * self.tapDimZ # Concat Stride\n self.tapStrideY = 2 * self.tapDimZ\n self.tapStrideZ = 2\n\n self.outputStrideX = 2 * self.outputDimZ # Concat Stride\n self.outputStrideY = 2 * self.outputDimZ * self.outputDimX\n self.outputStrideZ = 2\n\n # Provide accessible backups in case concat or similar stages\n # overwrites them.\n self.unprocessed_w = x\n self.unprocessed_h = y\n self.unprocessed_c = c\n self.unprocessed_k = k\n self.unprocessed_output = self.output # Used for theoretical graph sizes\n\n self.datatype = dtype\n self.precision = precision\n\n self.data = np.zeros((int(self.inputDimZ),\n int(self.inputDimY),\n int(self.inputDimX)\n )).astype(enum_as_dtype(dtype))\n\n self.taps = taps\n self.tapsPointer = 0 # We will fill them in generate\n self.tapsIndex = 0\n self.tapsOrder = taps_order\n self.bias = bias\n self.biasPointer = 0 # We will fill them in generate\n self.biasIndex = 0\n self.opParams = opParams\n self.opParamsPointer = 0 # We will fill them in generate\n self.opParamsIndex = 0\n\n self.concatResult = False\n self.storageOrder = s_order\n self.padStyle = pad_type\n\n self.dataPointer = self.inputOffset\n self.dataIndex = 0\n\n self.outputPointer = 0\n self.outputIndex = 0\n\n if pre_op_type:\n self.preOp = pre_op_type\n else:\n self.preOp = StageType.none\n\n if post_op_type and post_op_type != StageType.none:\n self.postOp = post_op_type\n if post_1:\n self.post_param1 = post_1\n else:\n self.post_param1 = int(0)\n self.post_strideX = post_sx\n self.post_strideY = post_sy\n else:\n if (self.op in [StageType.convolution,\n StageType.depthwise_convolution,\n StageType.fully_connected_layer,\n StageType.scale]) and bias is not None:\n self.postOp = StageType.bias\n else:\n self.postOp = StageType.none\n self.post_param1 = 0\n self.post_strideX = 0\n self.post_strideY = 0\n\n # in the case of Reshape, the outputDims are used as parameters for reshape;\n # make sure that the parameter values are written to myriad\n if self.op in [StageType.reshape]:\n self.outputDimX = new_x\n self.outputDimY = new_y\n self.outputDimZ = new_c\n\n # Only to be used after myriad execution\n self.flops = None\n self.ms = None\n self.BWs = None\n self.isoutput = False\n self.isconcat = False\n\n def addBias(self, bias):\n if bias is not None:\n if self.bias is None:\n self.bias = bias\n self.postOp = StageType.bias\n else:\n self.bias = self.bias + bias\n\n\n def putBias(self):\n if self.bias is not None:\n self.biasPointer, self.biasBufferIndex = get_buffer(\n self.bias.astype(np.float16), self.datatype)\n self.biasIndex = MemoryIndex.blob.value\n\n def putTaps(self):\n if self.taps is not None:\n self.tapsPointer, self.tapsBufferIndex = get_buffer(\n self.taps.astype(np.float16), self.datatype)\n self.tapsIndex = MemoryIndex.blob.value\n if self.op == StageType.copy: #In copy we are using taps as input\n self.dataPointer = self.tapsPointer\n self.dataIndex = self.tapsIndex\n\n def putOpParams(self):\n \"\"\" Puts the operation parameters in the blob buffer \"\"\"\n if self.opParams is not None:\n self.opParamsPointer, self.opParamsBufferIndex = \\\n get_buffer(self.opParams, dtype_as_enum(self.opParams.dtype))\n self.opParamsIndex = MemoryIndex.blob.value\n\n def changeName(self, new_name):\n self.unprocessed_name = new_name\n self.name = set_string_range(new_name, 100).encode('ascii')\n\n def close(self):\n self.outputPointer = 0\n self.outputIndex = MemoryIndex.output\n\n def attach(self, stage):\n \"\"\"\n Attaches a node to this one.\n :param stage:\n :return:\n \"\"\"\n if (stage.op == StageType.convolution and self.op == StageType.depthwise_convolution and\n stage.radixX == 1 and stage.radixY == 1 and self.postOp == StageType.none):\n print('Fusing depthconv and conv in',self.unprocessed_name,'and',stage.unprocessed_name)\n #Create the weights for a convolution that does deptwhise convolution (inCH, outCH, kH, kW)\n taps = np.zeros([self.inputDimZ, self.tapDimZ, self.radixY, self.radixX], np.float32)\n multiplier = int(self.tapDimZ/self.tapDimY)\n for y in range(self.radixY):\n for x in range(self.radixX):\n for c in range(self.tapDimY):\n for i in range(multiplier):\n taps[c,c*multiplier+i,y,x] = self.taps[y,x,c,i]\n #Turn them to [kH, kW, inCH, outCH) in order to be able to use matmul\n taps = taps.transpose(2,3,0,1)\n #Fuse the weights of the following 1x1 convolution into the just created weights\n stage.taps = np.matmul(taps,stage.taps[0,0])\n #Bring some data from the previous stage (self) to this one (stage) as we are saving this one\n #Saving the previous node would be simpler, but unfortunately the parser keeps track\n #of what's the latest created node (stage), so we must keep it\n stage.inputDimX = self.inputDimX\n stage.inputDimY = self.inputDimY\n stage.inputDimZ = self.inputDimZ\n stage.inputStrideX = self.inputStrideX\n stage.inputStrideY = self.inputStrideY\n stage.inputStrideZ = self.inputStrideZ\n stage.tapDimX = self.tapDimX\n stage.tapDimY = self.tapDimY\n stage.radixX = self.radixX\n stage.radixY = self.radixY\n stage.strideX = self.strideX\n stage.strideY = self.strideY\n stage.padStyle = self.padStyle\n stage.top = self.top\n stage.data = self.data\n stage.dataIndex = self.dataIndex\n stage.dataPointer = self.dataPointer\n #Remove self from network and change references\n self.network.count = self.network.count - 1\n self.network.stageslist.remove(self)\n stage.top = self.top\n if self in self.network.head:\n stage.network.storageOrder = stage.storageOrder\n self.network.head.remove(self)\n self.network.head.append(stage)\n else:\n for parents in self.network.search_several(self.top):\n newtail = []\n for p in parents.tail:\n if p == self:\n newtail.append(stage)\n parents.tail = newtail\n return\n\n # This line is to build a correct graph after renaming due to absorption\n # When scale or batchnorm is absorbed into convolution, its name is appended\n # to the name of the convolution layer, so bottoms (here they are called tops,\n # wrong choice) of attached layers have to be renamed too\n # All the cases (attach, attach_several, attach_eltwise) are present in\n # test t19_UnitTest/NetworkConfig/AbsorptionRenaming.prototxt\n # What needs to be verified is the correct generation of the report\n # diagram\n stage.top = [self.unprocessed_name]\n self.tail.append(stage)\n if self.outputPointer == 0 and self.outputIndex == MemoryIndex.none.value:\n self.outputPointer, self.outputIndex = get_zero_buffer(\n self.output, self.datatype)\n\n stage.dataPointer = stage.inputOffset + self.outputPointer # Input Pointer\n stage.dataIndex = self.outputIndex\n\n if (stage.op != StageType.fully_connected_layer and not self.isconcat\n and self.op != StageType.reshape):\n stage.inputDimX, stage.inputDimY, stage.inputDimZ = self.outputDimX, self.outputDimY, self.outputDimZ\n stage.tapDimY = self.outputDimZ\n if stage.op in [StageType.max_pooling]:\n stage.output = np.zeros(\n (stage.outputDimZ, stage.outputDimY, stage.outputDimX))\n\n def setoutput(self, outputStride, outputPointer=None, outputIndex=None):\n if self.outputPointer == 0 and self.outputIndex == MemoryIndex.none.value:\n self.output = np.zeros(\n (int(\n outputStride / 2), int(\n self.outputDimY), int(\n self.outputDimX))).astype(\n enum_as_dtype(\n self.datatype))\n if outputPointer is not None and outputIndex is not None:\n self.outputPointer = outputPointer\n self.outputIndex = outputIndex\n else:\n self.outputPointer, self.outputIndex = get_zero_buffer(\n self.output, self.datatype)\n self.outputStrideX = outputStride\n self.isconcat = True\n return self.outputPointer, self.outputIndex\n\n def concat(stages, lastlayer=True):\n \"\"\"\n Set the output pointers and fix the output strides to\n concatenate the outputs into the same buffer\n \"\"\"\n\n # This check is almost irrelevant since there are other cases when the code\n # fails and this is a hack not propper code.\n for stage_i, stage in enumerate(stages):\n if stage.concat_axis != stages[0].concat_axis:\n raise Exception(\"A layer cannot be part of multiple concats\")\n\n if(stages[0].concat_axis == 1):\n z = sum([int(stage.unprocessed_k) for stage in stages])\n x = int(stages[0].outputDimX)\n y = int(stages[0].outputDimY)\n\n concat_size = (y, x, z)\n\n dtype = stages[0].datatype\n if lastlayer:\n for stage in stages:\n stage.isoutput = True\n buffer = 0\n buffer_index = MemoryIndex.output.value\n elif stages[0].outputPointer == 0 and stages[0].outputIndex == MemoryIndex.none.value:\n buffer, buffer_index = get_zero_buffer(np.zeros(concat_size).astype(enum_as_dtype(dtype)), dtype)\n else:\n buffer = stages[0].outputPointer\n buffer_index = stages[0].outputIndex\n\n concat_offset = 0\n\n for s_num, stage in enumerate(stages):\n offset_pointer = buffer\n\n if(stage.outputPointer == 0):\n stage.outputPointer = offset_pointer + concat_offset*2 # TODO: REMOVE HARDCODED 2 For FP16 Size\n\n stage.outputIndex = buffer_index\n\n stage.concatResult = True\n concat_offset += int(stage.outputDimZ)\n\n stage.outputStrideX = z*2\n stage.outputStrideY = z*2*stage.outputDimX\n stage.tapStrideY = stage.outputDimZ * 2\n elif stages[0].concat_axis == 2:\n\n z = int(stages[0].outputDimZ)\n y = sum([int(stage.outputDimY) for stage in stages])\n x = int(stages[0].outputDimX)\n\n concat_size = (y, x, z)\n\n dtype = stages[0].datatype\n if lastlayer:\n for stage in stages:\n stage.isoutput = True\n buffer = 0\n buffer_index = MemoryIndex.output.value\n elif stages[0].outputPointer == 0 and stages[0].outputIndex == MemoryIndex.none.value:\n buffer, buffer_index = get_zero_buffer(np.zeros(concat_size).astype(enum_as_dtype(dtype)), dtype)\n else:\n buffer = stages[0].outputPointer\n buffer_index = stages[0].outputIndex\n\n concat_offset = 0\n\n for s_num, stage in enumerate(stages):\n offset_pointer = buffer\n\n if(stage.outputPointer == 0):\n stage.outputPointer = offset_pointer + concat_offset*2 # TODO: REMOVE HARDCODED 2 For FP16 Size\n\n stage.outputIndex = buffer_index\n\n stage.concatResult = True\n concat_offset += int(stage.outputDimY * stage.outputDimX * stage.outputDimZ)\n\n else:\n # This check is almost irrelevant since there are other cases when the code\n # fails and this is a hack not propper code.\n raise Exception(\"Concat on axis {0} not implemented\".format(stages[0].concat_axis))\n\n def attach_eltwise(self, parents):\n # Attach two parents to this elementwise operations layer\n # The second layer will be put in the weights pointer\n\n\n if hasattr(parents[0], '__iter__'):\n NetworkStage.concat(parents[0], False)\n parents[0] = parents[0][0]\n # This line is to build a correct graph after renaming due to\n # absorption, see attach\n self.top[0] = parents[0].unprocessed_name\n # We have only two cases: intermediate, input or intermediate,\n # intermediate\n if parents[1] == 0:\n parents[0].outputPointer, parents[0].outputIndex = get_zero_buffer(\n parents[0].output, self.datatype)\n self.dataPointer = self.inputOffset + parents[0].outputPointer\n self.dataIndex = parents[0].outputIndex\n self.tapsPointer = 0\n self.tapsIndex = MemoryIndex.input.value\n parents[0].tail.append(self)\n else:\n if hasattr(parents[1], '__iter__'):\n NetworkStage.concat(parents[1], False)\n parents[1] = parents[1][0]\n # This line is to build a correct graph after renaming due to\n # absorption, see attach\n self.top[1] = parents[1].unprocessed_name\n if parents[0].outputIndex == 0:\n parents[0].outputPointer, parents[0].outputIndex = get_zero_buffer(\n parents[0].output, self.datatype)\n if parents[1].outputIndex == 0:\n parents[1].outputPointer, parents[1].outputIndex = get_zero_buffer(\n parents[1].output, self.datatype)\n self.dataPointer = self.inputOffset + parents[0].outputPointer\n self.dataIndex = parents[0].outputIndex\n self.tapsPointer = parents[1].outputPointer\n self.tapsIndex = parents[1].outputIndex\n parents[1].tail.append(self)\n return\n\n def attach_multiple_bottoms(self, parents):\n # Attach a layer with at most 3 bottoms.\n # 1st bottom -> to input data pointer.\n # 2nd bottom -> to weights data pointer.\n # 3rd bottom -> to biases data pointer.\n\n if(len(parents) > 3):\n raise Exception(\"Layer with {0} inputs not supported\".format(len(parents)))\n\n for bottom_idx, bottom in enumerate(parents):\n if hasattr(bottom, '__iter__'):\n NetworkStage.concat(parents[bottom_idx], False)\n parents[bottom_idx] = parents[bottom_idx][0]\n\n if bottom == 0:\n # This bottom is the input (ussualy named \"data\") to the network.\n if bottom_idx == 0:\n self.dataPointer = 0\n self.dataIndex = MemoryIndex.input.value\n elif bottom_idx == 1:\n self.tapsPointer = 0\n self.tapsIndex = MemoryIndex.input.value\n else:\n self.biasPointer = 0\n self.biasIndex = MemoryIndex.input.value\n else:\n # This bottom is the output of a layer.\n if(parents[bottom_idx].outputIndex == 0):\n out_ptr, out_idx = get_zero_buffer(parents[bottom_idx].output, self.datatype)\n parents[bottom_idx].outputPointer = out_ptr\n parents[bottom_idx].outputIndex = out_idx\n\n if bottom_idx == 0:\n self.dataPointer = self.inputOffset + parents[bottom_idx].outputPointer\n self.dataIndex = parents[bottom_idx].outputIndex\n elif bottom_idx == 1:\n self.tapsPointer = parents[bottom_idx].outputPointer\n self.tapsIndex = parents[bottom_idx].outputIndex\n else:\n self.biasPointer = parents[bottom_idx].outputPointer\n self.biasIndex = parents[bottom_idx].outputIndex\n\n #parents[1].tail.append(self)\n #return\n for bottom_idx, bottom in reversed(list(enumerate(parents))):\n if bottom != 0:\n parents[bottom_idx].tail.append(self)\n return\n\n def attach_several(self, parents):\n \"\"\"\n Attach a node to several parents. Under 'concat' rules, the parents will be combined at the channel level.\n Under yxz this means that we need a writeback offset.\n\n TODO: This is coded for YXZ only.\n The default mode should be ZYX and we should transform it during the optimize() phase of network setup.\n\n :param parents:\n :return:\n \"\"\"\n\n # attach_several works with both one and more parents, which must be\n # concat inputs\n\n if not hasattr(parents, '__iter__'):\n parents.attach(self)\n return\n\n # Next three lines are to build a correct graph after renaming due to\n # absorption, see attach\n self.top = []\n for l in parents:\n self.top.append(l.unprocessed_name)\n\n NetworkStage.concat(parents, False)\n z = sum([int(p.unprocessed_k) for p in parents])\n parents[len(parents) - 1].tail.append(self)\n self.inputDimZ = z\n self.inputStrideX = z * 2\n\n self.dataPointer = self.inputOffset + \\\n parents[0].outputPointer # Input Pointer\n self.dataIndex = parents[0].outputIndex\n\n self.tapDimY = z\n\n if self.op in [StageType.max_pooling]:\n self.outputDimZ = self.inputDimZ\n self.outputStrideX = self.inputStrideX\n\n def search(self, seek_name):\n \"\"\"\n return: 0 if not found. The searched node if found.\n :param seek_name: name of node we're looking for\n \"\"\"\n if self.name == seek_name or self.unprocessed_name == seek_name or seek_name in self.alias:\n return self\n\n for t in self.tail:\n if t.name == seek_name or t.unprocessed_name == seek_name or seek_name in t.alias:\n return t # Search item == current item\n else:\n # Not found, traverse deeper\n recursive_result = t.search(seek_name)\n if (recursive_result != 0 and recursive_result.name == seek_name) or \\\n (recursive_result != 0 and recursive_result.unprocessed_name == seek_name) or \\\n (recursive_result != 0 and seek_name in recursive_result.alias):\n # Found in one of the tree nodes, bubble up.\n return recursive_result\n return 0 # Not found, backtrack\n\n def set_blob_vars(self):\n \"\"\"\n Builds the layout of the network stage for use in the blobfile.\n Currently undergoing refactoring so that ctypes are only applied here.\n :return:\n \"\"\"\n self.write_items = [\n self.name,\n c_char(self.op.value),\n c_uint32(self.optMask),\n c_int8(self.radixX),\n c_int8(self.radixY),\n c_uint8(self.strideX),\n c_uint8(self.strideY),\n c_uint8(self.padX),\n c_uint8(self.padY),\n c_uint8(self.padStyle.value),\n c_uint32(self.inputDimX),\n c_uint32(self.inputDimY),\n c_uint32(self.inputDimZ),\n c_uint32(self.tapDimX),\n c_uint32(self.tapDimY),\n c_uint32(self.tapDimZ),\n c_uint32(self.outputDimX),\n c_uint32(self.outputDimY),\n c_uint32(self.outputDimZ),\n c_uint32(self.inputStrideX),\n c_uint32(self.inputStrideY),\n c_uint32(self.inputStrideZ),\n c_uint32(self.tapStrideX),\n c_uint32(self.tapStrideY),\n c_uint32(self.tapStrideZ),\n c_uint32(self.outputStrideX),\n c_uint32(self.outputStrideY),\n c_uint32(self.outputStrideZ),\n c_uint8(self.datatype.value),\n c_uint8(self.precision.value),\n c_uint8(self.storageOrder.value),\n c_uint32(self.dataPointer),\n c_uint16(self.dataIndex),\n c_uint32(self.tapsPointer),\n c_uint16(self.tapsIndex),\n c_uint32(self.biasPointer),\n c_uint16(self.biasIndex),\n c_uint32(self.opParamsPointer),\n c_uint16(self.opParamsIndex),\n c_uint32(self.outputPointer),\n c_uint16(self.outputIndex),\n c_uint8(self.preOp.value),\n c_uint8(self.postOp.value),\n c_float(self.post_param1) if isinstance(self.post_param1, float) else c_int32(self.post_param1),\n c_ushort(self.post_strideX),\n c_ushort(self.post_strideY)\n ]\n\n for t in self.tail:\n t.set_blob_vars()\n\n def generate(self, f):\n \"\"\"\n Writes this object (Layer description) to provided file.\n\n :param f: open file handler\n :return: byte_size # TODO: Unverified. Compare with binary_size output.\n \"\"\"\n\n # We can probably make this smarter with this:\n # http://stackoverflow.com/questions/11296010/iterate-through-class-members-in-order-of-their-declaration\n\n sz = 0\n for item in self.write_items:\n f.write(item)\n sz += byte_size(item)\n\n # Don't recurse, we have a list of all the stages\n # for t in self.tail:\n # sz += t.generate(f)\n\n return sz\n\n def binary_size(self):\n \"\"\"\n Get byte size of structure when written to blob file\n Doesn't count our data arrays (we only want the pointers to that data on Myriad)\n :return: total size that will be written to blob file for this stage.\n \"\"\"\n\n file_sizes = [\n byte_size(t) for t in self.write_items if isinstance(\n t, ctypes._SimpleCData) or isinstance(\n t, bytes)]\n return sum(file_sizes)\n\n def debug(self, to_file=False, f=None):\n \"\"\"\n Developers can use this function to print values recursively through every layer.\n :param to_file: A field that could be used to write debug info to a file optionally.\n :param f: The corresponding filename if to_file is True\n :return: Nothing\n \"\"\"\n if to_file:\n pass\n else:\n pass\n\n for t in self.tail:\n t.debug(to_file, f)\n\n def finalize(self):\n # Taps (and maybe bias) can be modified by batch normalization layer\n # that follows, so add them at the end\n self.putTaps()\n self.putBias()\n self.putOpParams()\n\n for t in self.tail:\n t.finalize()\n\n def check_algo(self, network):\n # Check if two layers write to the same output and one of them is convolution\n # Force im2col_v2 in this case, where it's normally never used\n if self.op == StageType.convolution and self.inputDimZ >= 200:\n if network.writes_output(self, self.outputIndex):\n if self.optMask & 0x80000000 == 0x80000000:\n self.optMask = (self.optMask & 0x7fffffff) | 4\n print(\n 'Layer ',\n self.unprocessed_name,\n ' forced to im2col_v2, because its output is used in concat')\n for t in self.tail:\n t.check_algo(network)\n\n def writes_output(self, exclude_layer, index):\n # Return True if this or a tail layer uses index as input\n for t in self.tail:\n if t.writes_output(exclude_layer, index):\n return True\n if self != exclude_layer and self.outputIndex == index:\n return True\n return False\n\n def assign_remnant_buffers(self, net):\n sizes = []\n offsets = []\n names = []\n\n if self.top is not None and isinstance(self.top[0], str):\n # This should ensure that the input strides are correct after\n # applying all concat rules.\n parent = net.search(self.top[0])\n\n self.inputStrideX = parent.outputStrideX\n if self.isoutput:\n sizes.append(self.output.shape)\n offsets.append(self.outputPointer)\n names.append(self.name)\n elif self.outputPointer == 0 and self.outputIndex == MemoryIndex.none.value and (self.top is None or len(self.top) <= 1 or get_class_of_op(self.op) != \"Pooling\"):\n self.outputIndex = MemoryIndex.output.value\n sizes.append(self.output.shape)\n offsets.append(self.outputPointer)\n names.append(self.name)\n self.isoutput = True\n elif self.outputPointer == 0 and self.outputIndex == MemoryIndex.none.value and len(self.top) > 1 and get_class_of_op(self.op) == \"Pooling\":\n node = net.head[0].search(self.top[0])\n self.output = np.zeros(\n (node.outputDimZ,\n node.outputDimY,\n node.outputDimX)).astype(np.float16)\n self.outputIndex = MemoryIndex.output.value\n sizes.append(self.output.shape)\n offsets.append(self.outputPointer)\n names.append(self.name)\n self.isoutput = True\n\n for t in self.tail:\n t_res = t.assign_remnant_buffers(net)\n sizes.extend(t_res[0])\n offsets.extend(t_res[1])\n names.extend(t_res[2])\n return sizes, offsets, names\n\n def convert_inputs_outputs_to_yxz(self, recurse, debug=False):\n \"\"\"\n It is necessary to convert the first input because it contains data, but the other inputs\n and outputs are buffers for myriads use only. But, we will need to have the final outputs shaped correctly, so\n we will transform them too.\n :param recurse: Set to false to apply to a single element, true to traverse.\n :param debug: Set to true to enable debug print messages\n :return: Nothing. Side effect of transformed buffers.\n \"\"\"\n if self.storageOrder == StorageOrder.orderYXZ:\n if debug:\n print(\"Already in this form\")\n elif self.storageOrder == StorageOrder.orderZYX:\n if len(self.data.shape) == 4:\n self.data = np.reshape(\n self.data, (self.data.shape[1], self.data.shape[2], self.data.shape[3]))\n self.data = zyx_to_yxz(\n self.data, self.datatype).astype(\n dtype=np.float16)\n self.storageOrder = StorageOrder.orderYXZ\n else:\n if not self.concatResult:\n self.output = zyx_to_yxz(\n self.output, self.datatype).astype(\n dtype=np.float16)\n self.storageOrder = StorageOrder.orderYXZ\n\n elif self.storageOrder == StorageOrder.orderXYZ:\n if len(self.data.shape) == 4:\n self.data = np.reshape(\n self.data, (self.data.shape[1], self.data.shape[2], self.data.shape[3]))\n self.data = xyz_to_yxz(\n self.data, self.datatype).astype(\n dtype=np.float16)\n self.storageOrder = StorageOrder.orderYXZ\n else:\n throw_error(\n ErrorTable.ConversionNotSupported,\n self.storageOrder.name)\n\n else:\n throw_error(\n ErrorTable.ConversionNotSupported,\n self.storageOrder.name)\n\n if 0:\n self.data.tofile('InputTensor.bin')\n\n if recurse:\n for node in self.tail:\n node.convert_inputs_outputs_to_yxz(recurse)\n\n def convert_taps_to_hwck(self, recurse):\n if self.tapsOrder != TapsOrder.orderHWCK:\n if get_class_of_op(\n self.op) in [\n \"Convolution\",\n \"FCL\",\n \"Deconvolution\"]:\n if self.op in [StageType.fully_connected_layer]:\n if self.unprocessed_h > 1 or self.unprocessed_w > 1:\n self.taps = self.taps.reshape(\n self.unprocessed_k,\n self.unprocessed_c,\n self.unprocessed_h,\n self.unprocessed_w)\n else:\n self.taps = self.taps.reshape(\n self.taps.shape[0], self.taps.shape[1], 1, 1)\n self.taps = kchw_to_hwck(self.taps)\n replace_buffer(self.taps, self.tapsBufferIndex, self.datatype)\n else:\n if (self.taps is None or\n get_class_of_op(self.op) == \"FCL\" or\n self.op == StageType.scale or\n self.op == StageType.normalize):\n pass\n else:\n throw_error(\n ErrorTable.ConversionNotSupported,\n self.op.name)\n\n self.storageOrder = StorageOrder.orderYXZ.value\n if recurse:\n for node in self.tail:\n node.convert_taps_to_hwck(recurse)\n\n def getBWs(self):\n in_dim = self.data.flatten().shape[0]\n if self.taps is not None:\n tap_dim = self.taps.flatten().shape[0]\n else:\n tap_dim = 0\n out_dim = self.output.shape[0]\n\n KB = 1024\n MB = KB * KB\n\n MS = self.ms\n S = MS / 1000\n\n if self.op == StageType.convolution:\n arrays = in_dim * self.radixX * self.radixY # Read Data NxN Times\n arrays += tap_dim # Taps once (already NxN)\n arrays += out_dim * self.radixX * self.radixY # Accumulate NxN\n else:\n arrays = in_dim + tap_dim + out_dim\n self.BWs = ((arrays * 2) / MB) / S\n return self.BWs\n\n def getBW(self):\n in_dim = self.data.flatten().shape[0]\n if self.taps is not None:\n tap_dim = self.taps.flatten().shape[0]\n else:\n tap_dim = 0\n out_dim = self.output.shape[0]\n\n if self.op == StageType.convolution:\n arrays = in_dim * self.radixX * self.radixY # Read Data NxN Times\n arrays += tap_dim # Taps once (already NxN)\n arrays += out_dim * self.radixX * self.radixY # Accumulate NxN\n else:\n arrays = in_dim + tap_dim + out_dim\n\n return (arrays * 2)\n\n def minmax(self, attr, min, max):\n if min > getattr(self, attr):\n min = getattr(self, attr)\n if max < getattr(self, attr):\n max = getattr(self, attr)\n\n for t in self.tail:\n min, max = t.minmax(attr, min, max)\n\n return min, max\n\n def calculate_metrics(self, timings):\n self.flops = self.getFlops()\n self.ms = timings[0]\n self.BWs = self.getBWs()\n\n def getFlops(self):\n \"\"\"\n\n :return:\n\n \"\"\"\n flops = 0\n if self.op == StageType.convolution:\n # Output channels too.\n flops = self.unprocessed_k * self.outputDimX * self.outputDimY * \\\n self.inputDimZ * self.radixX * self.radixY * 2\n\n elif self.op == StageType.max_pooling:\n flops = self.unprocessed_k * self.outputDimX * \\\n self.outputDimY * self.radixX * self.radixY\n\n elif self.op == StageType.average_pooling:\n flops = self.unprocessed_k * self.outputDimX * \\\n self.outputDimY * self.radixX * self.radixY * 2\n\n elif self.op == StageType.fully_connected_layer:\n in_dim = self.data.flatten().shape[0]\n out_channels = self.output.flatten().shape[0]\n flops = in_dim * out_channels * 2\n\n elif self.op == StageType.depthwise_convolution:\n flops = self.radixX * self.radixY * self.unprocessed_k * \\\n self.outputDimX * self.outputDimY * 2\n\n elif self.op == StageType.soft_max:\n in_dim = self.data.flatten().shape[0]\n flops = in_dim * 3\n\n return flops / 1000000\n\n def summaryStats(self):\n totalTime = self.ms\n totalBW = self.getBW()\n\n for t in self.tail:\n a, b = t.summaryStats()\n totalTime += a\n totalBW += b\n\n return totalTime, totalBW\n\n def newick(self, head=False):\n \"\"\"\n output a file containing a description of the node in Newick format.\n To be called from Network.head and traversed.\n :param head:\n :return:\n \"\"\"\n nw = str(self.unprocessed_name) + \":\" + str(len(self.tail))\n\n if len(self.tail) != 0:\n nw += \",(\"\n for idx, t in enumerate(self.tail):\n nw += t.newick()\n if idx + 1 != len(self.tail):\n nw += \",\"\n nw += \")\"\n else:\n pass\n return nw\n\n def graphviz(\n self,\n dot,\n ms_min,\n ms_max,\n bws_min,\n bws_max,\n flop_min,\n flop_max):\n\n table = '''<\n\n\n \n\n\n \n\n\n \n \n \n\n
{0}
{7}
{2}
(MFLOPs)
{4}
(MB/s)
{6}
(ms)
>\n'''.format(\n self.unprocessed_name, get_normalized_color(\n \"#B1F1EF\", \"#2ED1C6\", flop_min, flop_max, self.flops), self.flops, get_normalized_color(\n \"#FFE5FC\", \"#B2189E\", bws_min, bws_max, format(\n self.BWs, \".2f\")), format(\n self.BWs, \".2f\"), get_normalized_color(\n \"#FFFFCC\", \"#FFFF00\", ms_min, ms_max, format(\n self.ms, \".2f\")), format(\n self.ms, \".2f\"), str(\n self.unprocessed_output.shape))\n\n dot.node(self.unprocessed_name, table, shape=\"plaintext\")\n if self.top is not None:\n for t in self.top:\n if t is None:\n print(self.unprocessed_name, 'has no top')\n continue\n if not isinstance(t, str):\n for tt in t:\n dot.edge(tt, self.unprocessed_name)\n else:\n dot.edge(t, self.unprocessed_name)\n\n else:\n dot.edge(\"Input\", self.unprocessed_name)\n\n last_nodes = []\n for t in self.tail:\n dot, last = t.graphviz(\n dot, ms_min, ms_max, bws_min, bws_max, flop_min, flop_max)\n last_nodes.extend(last)\n if len(self.tail) == 0:\n last_nodes = [self.unprocessed_name]\n\n return dot, last_nodes\n","sub_path":"tool/Models/NetworkStage.py","file_name":"NetworkStage.py","file_ext":"py","file_size_in_byte":46169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"405533072","text":"# -*- coding: utf-8 -*-\n\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport yaml\nimport os\n\n\ndef plot_heatmap(factor, dirpath, outputpath):\n df = pd.read_csv('%s/%sPeriod_Summary.csv'%(dirpath, factor[0]), usecols=['Period'])\n\n for factor_name in factor:\n df_summary = pd.read_csv('%s/%sPeriod_Summary.csv'%(dirpath, factor_name), usecols=['Period','Active Return'])\n df_summary.columns = ['Period',factor_name]\n df = df.merge(df_summary,on = 'Period')\n df_corr = df.corr()\n\n f, ax1 = plt.subplots(figsize=(12,8))\n sns.heatmap(df_corr, annot=True, cmap='coolwarm', ax=ax1, vmax=1, vmin = -1)\n f.savefig('%s/sns_heatmap_annot.jpg'%outputpath)\n plt.close()\n # f.savefig('sns_heatmap_annot.jpg')\n\nif __name__ == '__main__':\n with open('E:/QUANT/R_code/config.yaml') as f:\n temp = yaml.load(f.read())\n lag = int(temp['lag'])\n\n dirpath = temp['dirpath']\n outputpath = temp['outputpath']\n market_path = temp['market_path']\n\n if not os.path.exists(outputpath):\n os.makedirs(outputpath)\n if not os.path.exists('%s/summary_excel' % dirpath):\n os.makedirs('%s/summary_excel' % dirpath)\n\n factor = temp['factor_name']\n factor = factor.split(',')\n\n plot_heatmap(factor, dirpath, outputpath)\n","sub_path":"Axioma_backtest/corr_heatmap.py","file_name":"corr_heatmap.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"498779301","text":"#!/usr/bin/env python\n# coding=utf-8\n\"\"\"\n\"\"\"\n\n__author__ = 'Brian Matilla, Brian Mapes'\n__version__= '1.0.0'\n__maintainer__= 'Brian Matilla'\n__email__= 'bmatilla@rsmas.miami.edu'\n\n\nimport argparse\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport xarray as xr\nimport matplotlib.gridspec as gridspec\nimport matplotlib as mpl\nimport cartopy.crs as ccrs\nfrom cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter\nimport cartopy.feature as cfeature\nfrom datetime import datetime\n\n#First, build the parser for the dates, times, and lat-lon, as well as the case name, output directory and RAMADDA publish\n\ndef get_args():\n '''This function is the one that obtains and parses the arguments passed through the command\n line'''\n \n if __name__ == '__main__':\n \n parser = argparse.ArgumentParser(description='Script to create a 16-panel plot of precipitation estimates from several observational and reanalysis data products as well as the ensemble mean and RMS. A user can \"teleport\" a multipanel plot to a specific time and location based on date, time, and lat-lon bounds.',\n epilog= \"Example use case on the command line: python NASANEWS_teleport.py \"\n \"-ds date_start \" \n \"-de date_end \"\n \"-bbox S,N,W,E \"\n \"-case foo \")\n \n parser.add_argument('-ds' , '--date_start', type=str,\n help= 'Starting date for case study, expressed as YYYY-mm-dd.',\n required= True)\n \n parser.add_argument('-de', '--date_end', type=str,\n help= 'Ending date for case study, expressed as YYYY-mm-dd.',\n required= True) #Not required for reason of interests in single-day cases.\n \n parser.add_argument('-bbox', '--boundingbox', nargs=4, type=int,\n help='Set the bounding box of the plot with boundaries: '\n 'south, north, west, east.',\n metavar=(\"south\", \"north\", \"west\", \"east\"), required=True)\n \n parser.add_argument('-case', '--nameofcase', type=str, nargs='+',\n help='Case name to prefix the plot.',\n required=True)\n \n parser.add_argument('-outdir', '--output_directory', type=os.path.isdir,\n help='Set the output path to place the output;'\n 'default is current directory from where the script is run',\n required=False) #Doesn't quite work yet...\n \n args= parser.parse_args()\n \n date_start= args.date_start\n date_end= args.date_end\n bbox= args.boundingbox\n nameofcase= args.nameofcase\n outdir= args.output_directory\n \n if args.boundingbox:\n south= bbox[0]\n north= bbox[1]\n west= bbox[2]\n east= bbox[3]\n \n if args.output_directory:\n output_directory= args.output_directory\n \n if args.nameofcase:\n nameofcase= os.path.join(args.nameofcase[0]) #Will add output_directory soon.\n \n return date_start, date_end, bbox, nameofcase, outdir\n \ndate_start, date_end, bbox, nameofcase, outdir= get_args()\n\n#Below are the calls to load all of the datasets, create lists of the names and links,\n#and convert them to a callable, iterable 2D array.\n\ngldas ='http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuZ2xkYXMuZGFpbHlfYWdnLm5jbWw=/entry.das'\ncpcu = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuY3BjdS5kYWlseV9hZ2cubmNtbA==/entry.das'\nchirps = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuY2hpcnBzLmRhaWx5X2FnZy5uY21s/entry.das'\ntrmm3b42 = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAudHJtbTNiNDIuZGFpbHlfYWdnLm5jbWw=/entry.das'\npersiann = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAucGVyc2lhbm4uZGFpbHlfYWdnLm5jbWw=/entry.das'\nmswep = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAubXN3ZXAuZGFpbHlfYWdnLm5jbWw=/entry.das'\nmerra = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAubWVycmEuZGFpbHlfYWdnLm5jbWw=/entry.das'\nmerrav2 = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAubWVycmEyLmRhaWx5X2FnZy5uY21s/entry.das'\njra55 = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuanJhNTUuZGFpbHlfYWdnLm5jbWw=/entry.das'\ngsmaprnl = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuZ3NtYXBybmwuZGFpbHlfYWdnLm5jbWw=/entry.das'\ngpcp1dd = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuZ3BjcDFkZC5kYWlseV9hZ2cubmNtbA==/entry.das'\necint = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuZWNpbnQuZGFpbHlfYWdnLm5jbWw=/entry.das'\ncmorph = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuY21vcnBoLmRhaWx5X2FnZy5uY21s/entry.das'\ncfsr = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuY2Zzci5kYWlseV9hZ2cubmNtbA==/entry.das'\nens_mean = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuZW5zbWVhbi5kYWlseV9hZ2cubmNtbA==/entry.das'\nens_rms = 'http://weather.rsmas.miami.edu/repository/opendap/synth:d68cf65c-8cdd-4886-a61f-d03e877fea67:L2FnZ3JlZ2F0aW9ucy9kYWlseS9wcmVjaXAuZW5zcm1zLmRhaWx5X2FnZy5uY21s/entry.das'\n\n#Group the names. \ndset_names= ['gldas', 'cpcu', 'chirps', 'trmm3b42', 'persiann', 'mswep', \n 'merra', 'merrav2', 'jra55', 'gsmaprnl', 'gpcp1dd', 'ecint',\n 'cmorph', 'cfsr', 'ens_mean', 'ens_rms']\n\n#and then group the links\ndset_links=[gldas, cpcu, chirps, trmm3b42, persiann, mswep, merra, merrav2, \n jra55, gsmaprnl, gpcp1dd, ecint, cmorph, cfsr, ens_mean, ens_rms]\n\ndata_map= []\nfor names in dset_names:\n for links in dset_links:\n data_map= np.column_stack(tuple([dset_names, dset_links])) \n \n#Plot error prechecks:\n#--------\n#Check for date mismatch by computing difference between date_start and date_end:\nfrom datetime import datetime\ndef days_between(d1, d2):\n d1 = datetime.strptime(d1, \"%Y-%m-%d\")\n d2 = datetime.strptime(d2, \"%Y-%m-%d\")\n return abs((d2 - d1).days)\n\n#Date check\ndays_between(date_start, date_end)\nif date_start > date_end:\n raise ValueError('Your end date is before your start date. Check your dates and try again.')\n \nif days_between(date_start, date_end) >= 10:\n print('Be patient... this is quite a large time period so the data retrieval may take some time.')\n\n#Longitudes\nif bbox[3] < bbox[2]:\n raise ValueError('Your east longitude is less than your west longitude. Check your longitudes and try again.')\n\n#Latitudes\nif bbox[1] < bbox[0]:\n raise ValueError('Your north latitude is less than your south latitude. Check your latitudes and try again.')\n\n#Check complete with no errors\nelse:\n print('No initial errors. Starting plot sequence...')\n\n#--------START PLOT SEQUENCE---------#\n\nprint('Plot sequence running... Please wait...')\n\n# Create the figure instance\n\nfig = plt.figure(figsize=(25, 25)) #Need a size large enough to avoid cramping of figure quality. \ngs = gridspec.GridSpec(5, 5, height_ratios=[1, 1, 1, 1, 0.05], width_ratios=[1,1,1,1,0.05], bottom=.05, top=.95, wspace=0.2, hspace=0.2)\n\ncols= 4 #Since we have 16 datasets, 4 columns will make plot evenly distributed.\nrows = int(len(data_map) / cols) # 16 datasets/ 4 datasets/column= 4 rows\n\n#Define the plot background here. It speeds up the plotting process to not embed it in the forthcoming loop.\ndef plot_background(ax):\n ax.set_extent([datalon.min(), datalon.max(), datalat.min(), datalat.max()], crs= ccrs.PlateCarree())\n ax.coastlines('10m', edgecolor='black', linewidth=0.5)\n ax.set_xticks(np.linspace(datalon.min(), datalon.max(), num= 3, endpoint= True), crs=ccrs.PlateCarree())\n ax.set_yticks(np.linspace(datalat.min(), datalat.max(), num= 3, endpoint= True), crs=ccrs.PlateCarree())\n ax.tick_params(labelsize=11)\n lon_formatter = LongitudeFormatter(zero_direction_label=True)\n lat_formatter = LatitudeFormatter()\n ax.xaxis.set_major_formatter(lon_formatter)\n ax.yaxis.set_major_formatter(lat_formatter)\n ax.add_feature(cfeature.BORDERS)\n ax.add_feature(cfeature.RIVERS)\n states_provinces = cfeature.NaturalEarthFeature(\n category='cultural',\n name='admin_1_states_provinces_lines',\n scale='10m',\n facecolor='none')\n ax.add_feature(states_provinces, edgecolor='gray')\n return ax\n\n#Retrieve the data from the data sources and perform calculations.\n\n# 1st loop obtains global data max.\npcp_global_max = 0\nfor i in range(cols):\n for j in range(rows):\n try:\n idx = (cols*i)+j #Obtain each individual data URL as index.\n dnum= data_map[idx][0] #Retrieve datanumber\n \n data = xr.open_dataset(data_map[idx][1], decode_times=True)\n datatitle= data.product_id\n \n datalat= data.lat[(bbox[0])+90:(bbox[1])+90] #Because the latitude units are strictly in degrees north, we must add 90 to account for southern hemisphere. Otherwise, we will end up with index values which would yield incorrect latitudes.\n datalon= data.lon[bbox[2]:bbox[3]]\n event = data.precip.sel(time=slice(date_start, date_end),lat=slice(datalat.min(), datalat.max()),lon=slice(datalon.min(), datalon.max()))\n pcp = np.sum(event, axis=0)*86400\n \n if pcp.max() > pcp_global_max:\n pcp_global_max = pcp.max()\n except IndexError:\n pcp= pcp * 0\n\n# plots data for all datasets TODO: reduce to single loop and store all values:\nfor i in range(cols):\n for j in range(rows):\n \n idx = (cols*i)+j \n dnum= data_map[idx][0] \n \n data = xr.open_dataset(data_map[idx][1], decode_times=True)\n datatitle= data.product_id\n if idx == 14:\n datatitle= 'ens mean'\n elif idx == 15:\n datatitle= 'ens rms'\n try:\n datalat= data.lat[(bbox[0])+90:(bbox[1])+90]\n datalon= data.lon[bbox[2]:bbox[3]]\n event = data.precip.sel(time=slice(date_start, date_end),lat=slice(datalat.min(), datalat.max()),lon=slice(datalon.min(), datalon.max()))\n pcp = np.sum(event, axis=0)*86400\n except IndexError:\n pcp= pcp * 0\n \n #Define cartopy grid:\n crs = ccrs.PlateCarree(central_longitude=((datalon.max()+datalon.min())/2))\n\n #Assign the 2D lon and lat variables to construct plot.\n \n lon_2d= np.linspace(datalon.min(), datalon.max(), num= ((datalon.max()- datalon.min())+1), endpoint= True)\n lat_2d= np.linspace(datalat.min(), datalat.max(), num= ((datalat.max()- datalat.min())+1), endpoint= True)\n \n extent= ([datalon.min(), datalon.max(), datalat.min(), datalat.max()])\n\n #Now for the evenly-spaced contours, separated into 4 categories of precip accumulation:\n if pcp.max() or pcp_global_max <= 500:\n levels= np.arange(0, pcp_global_max, 50)\n elif 500 < pcp.max() <= 1000:\n levels= np.arange(0, pcp_global_max, 75)\n elif pcp.max() > 1000:\n levels= np.arange(0, pcp_global_max, 100)\n \n if idx < 15:\n bounds_pcp_global= np.linspace(0,np.around(pcp_global_max, decimals=-1), num= 11, endpoint=True) \n norm_global = mpl.colors.BoundaryNorm(boundaries=bounds_pcp_global, ncolors=256)\n elif idx == 15:\n bounds_pcp= np.linspace(0,np.around(pcp.max(), decimals=-1), num= 11, endpoint=True) \n norm = mpl.colors.BoundaryNorm(boundaries=bounds_pcp, ncolors=256)\n \n # plot the data accordingly\n ax1 = plt.subplot(gs[i, j], projection=crs)\n plot_background(ax1)\n \n cf1= plt.pcolormesh((lon_2d-0.5), (lat_2d-0.5), pcp, cmap='Greens', norm=norm_global, transform=ccrs.PlateCarree())\n\n if idx == 15: #Ensemble RMS plot\n cf1= plt.pcolormesh((lon_2d-0.5), (lat_2d-0.5), pcp, cmap='Blues', transform=ccrs.PlateCarree())\n c1 = plt.contour(pcp, colors='red', levels=levels, linewidths=2, norm=norm_global, extent=extent)\n \n ax1.clabel(c1, fontsize=15, inline=1, inline_spacing=1, fmt='%i', rightside_up=True)\n \n ax1.set_title('({}) {} '.format(chr(97+idx), datatitle), fontsize=22)\n\nside_bar_ax = plt.subplot(gs[4, :-1])\npcp_global_bounds = np.linspace(0,np.around(pcp_global_max, decimals=-1), num= 11, endpoint=True)\npcp_bounds= np.linspace(0,np.around(pcp.max(), decimals=-1), num=11, endpoint=True)\ncb = mpl.colorbar.ColorbarBase(\n side_bar_ax, \n cmap='Greens',\n norm=norm_global,\n extend='max',\n ticks=pcp_global_bounds,\n spacing='uniform',\n orientation='horizontal')\ncb.set_label('Precipitation (mm/day)', fontsize=22)\ncb.ax.tick_params(labelsize=18)\n\nside_bar_ax = plt.subplot(gs[3, 4])\ncb = mpl.colorbar.ColorbarBase(side_bar_ax, cmap='Blues',norm=norm, extend='max',\n ticks=bounds_pcp, spacing='uniform', orientation='vertical')\n\ncb.ax.tick_params(labelsize=18)\ncb.set_label('Precipitation (mm/day)', fontsize=22)\n\nif date_start == date_end: \n fig.suptitle('rainfall accumulation for case on: ' + date_start, fontsize=28)\nelif date_start != date_end:\n fig.suptitle('rainfall accumulation for case from: ' + date_start + ' to ' +date_end, fontsize=28)\n\nprint('Plot sequence complete. Rendering...')\nplt.savefig(nameofcase + '.png', bbox_inches='tight')\n\nprint('SUCCESS! Your plot is complete...')\nprint('Plot saved as ' + nameofcase + '.png')\n\nplt.show()\n","sub_path":"jupyter_notebooks/NASANEWS_teleport.py","file_name":"NASANEWS_teleport.py","file_ext":"py","file_size_in_byte":14883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"606762009","text":"# Given an array of integers, return indices of the two numbers\n# such that they add up to a specific target\n# Each input have exactly one solution, and you may not use the same\n# element twice.\n# nums = [2, 7, 11, 15], target = 9\n# return [0, 1].\n\n#{}\n#{8: 0}\n#{8: 0, 6: 1}\n#{8: 0, 6: 1, -2: 2}\n#{8: 0, 6: 1, -2: 2, 7: 3}\n\ndef twoSum(nums, target):\n if len(nums) < 2:\n return False\n wanted_nums = {}\n for i in range(len(nums)):\n #print(wanted_nums)\n if nums[i] in wanted_nums:\n return [wanted_nums[nums[i]]+1, i+1]\n else:\n wanted_nums[target - nums[i]] = i\n#nums = [2,7,11,15]\n#target = 9\n#print(twoSum(nums,target))\n","sub_path":"arrays/two_sum_1.py","file_name":"two_sum_1.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"222894458","text":"import re\nimport os.path\nimport sys\nfrom os import strerror\n\npatron_horas = re.compile(\"\\d{2}h\\d{2}\")\npatron_logins = re.compile(\"^LOGIN.*\")\n\n\ntelconet_file = \"D:\\\\Scripts_PY\\\\NOC_Py\\\\programados\\\\telconet.txt\"\nlumen_file = \"D:\\\\Scripts_PY\\\\NOC_Py\\\\programados\\\\lumen.txt\"\ncnt_file = \"D:\\\\Scripts_PY\\\\NOC_Py\\\\programados\\\\cnt.txt\"\n\nline_cnt = 0\n\nif os.path.isfile(telconet_file):\n print(\"\\n* Telconet :)\\n\")\nelif os.path.isfile(lumen_file):\n print(\"\\n* Lumen :)\\n\")\nelif os.path.isfile(cnt_file):\n print(\"\\n* CNT :)\\n\")\nelse:\n print(\"\\n* File does not exist :( Please check and try again.\\n\")\n sys.exit()\n\n\ntry:\n #Abre el archivo en modo lectura\n stream_telconet = open(telconet_file, \"rt\")\n\n # #Coloca el cursor al inicio del archivo\n stream_telconet.seek(0)\n\n #procesar el contenido\n contenido_telconet = stream_telconet.readlines()\n\n stream_telconet.close()\nexcept Exception as exc:\n print(\"No se puede abrir el archivo:\", exc)\n\n\nfor linea in contenido_telconet:\n print (linea)\n\n# horas_trabajo = list(filter(re_numtrabajo, contenido_telconet))\n# print(list(filter(re_numtrabajo, contenido_telconet)))\n\nstr_contenido_telconet = str(contenido_telconet)\nx = patron_horas.findall(str_contenido_telconet)\n\nprint(x)\nif x:\n print(\"YES! We have a match!\")\nelse:\n print(\"No match\")","sub_path":"static/scripts/lee_correo.py","file_name":"lee_correo.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"511641136","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nProgram takes a directory as input and then takes the two text files found in\nthe directory and sends them to a function that iterates over both of them,\nline by line, at the same time. Each of the lines from both files are printed\nto the screen in succession.\n\nEdited by Alicia Reigel. 15 March 2016.\nCopyright Alicia Reigel. Louisiana State University. 15 March 2016. All\nrights reserved.\n\n\"\"\"\n\n\nimport itertools\nimport glob\nimport os\nimport argparse\n\n\ndef parser_directorypath():\n \"\"\"Collects the path of the directory where your files are\"\"\"\n parser = argparse.ArgumentParser(\n description=\"\"\"Input the full path to the directory of interest\"\"\"\n )\n parser.add_argument(\n '--directorypath',\n required=True,\n type=str,\n help='Enter the path to the directory of interest.'\n )\n return parser.parse_args()\n\n\ndef opening_files_making_list(file1, file2):\n \"\"\"opens both files and reads them line by line simultaneously. Prints to screen\"\"\"\n for file1_line, file2_line in itertools.zip_longest(open(file1), open(file2)):\n print(file1_line, file2_line)\n\n\ndef main():\n args = parser_directorypath()\n path_name = os.path.join(args.directorypath, \"*.txt\")\n # finds the pathnames for any files that have *c-darwin* in the directory\n file_path_list = glob.glob(path_name)\n # creates a list of the path names associated with the c-darwin files found\n file1 = os.path.basename(file_path_list[0])\n # finds the basename for the first file path in the list created by glob\n file2 = os.path.basename(file_path_list[1])\n # finds the basename of the second file path in the list created by glob\n os.chdir(args.directorypath)\n # changes the directory to the one input by argparse\n opening_files_making_list(file1, file2)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"answers/reige012/reigeltask1_15.py","file_name":"reigeltask1_15.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"595497470","text":"import pandas as pd\nfrom nltk.stem import SnowballStemmer\nfrom sklearn.decomposition import PCA\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\nclass ExtractFeaturesData:\n def __init__(self, dataset):\n self.dataset = dataset\n self.features_info = pd.DataFrame(index=dataset.index)\n \n self._extract_number_of_features()\n \n self._features_preprocessed = self._features_preprocessed()\n self._encode_features()\n \n def _features_preprocessed(self):\n def _preprocess(features):\n # Initialize a stemmer.\n stemmer = SnowballStemmer('english')\n \n features_cleaned = []\n for feature in features:\n features = feature.lower()\n feature = feature.replace('-', '')\n feature = feature.replace('/', '')\n feature = feature.replace('(', '')\n feature = feature.replace(')', '')\n feature = feature.replace('!', '')\n feature = feature.strip()\n # Stem word.\n feature = stemmer.stem(feature)\n features_cleaned.append(feature.strip())\n \n return ' '.join(features_cleaned)\n return self.dataset.features.apply(_preprocess)\n \n def _extract_number_of_features(self):\n # Get description length.\n self.features_info['n_features'] = self.dataset['features'].apply(len)\n\n def _encode_features(self):\n # Fit the vectorizer with both datasets.\n vectorizer = TfidfVectorizer(token_pattern='[a-zA-Z]+', stop_words='english')\n # Vectorize the train description.\n features_matrix = vectorizer.fit_transform(self._features_preprocessed.values)\n \n pca = PCA(n_components=2)\n features_pca = pca.fit_transform(features_matrix.toarray())\n \n self.features_info['features_pca1'] = features_pca[:, 0]\n self.features_info['features_pca2'] = features_pca[:, 1]","sub_path":"src/extract_data/extract_features_data.py","file_name":"extract_features_data.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"259289814","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, render_template,request,url_for,redirect,session\nfrom configobj import ConfigObj\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\n\n#Anasayfayı açtığımızda karşımıza çıkacak kısımla ilgili olan kısımdır.\n@app.route('/', methods=[\"GET\"])\n@app.route(\"/dashboard\", methods=[\"GET\"])\ndef dashboard():\n\t#host_names_list = data_hosts.keys()\n\t#host_names_list = data_hosts\n\t#host_info = data_hosts['ek_omurga']['host_grubu']\n\treturn render_template('dashboard.html')\n\n\n\n######### host\n@app.route('/hosts', methods=[\"GET\"])\ndef hosts():\n\tdata_hosts = ConfigObj('./data/hosts-data-file')\n\treturn render_template('hosts.html', data_hosts=data_hosts)\n\n@app.route('/add_host', methods=[\"GET\"])\ndef add_host():\n\tdata_hostgroups = ConfigObj('./data/hostgroups-data-file')\n\tdata_hosts = ConfigObj('./data/hosts-data-file')\n\treturn render_template('add_host.html', data_hostgroups=data_hostgroups, data_hosts=data_hosts)\n\n@app.route('/add_host_submit', methods=[\"POST\"])\ndef add_host_submit():\n\thostname = request.form['hostname']\n\thostdescription = request.form['hostdescription']\n\tip = request.form['ip']\n\tgrouplist = request.form.getlist('group_list') # checkbox\n\t# groups not list\n\tgroups = \"All\" \n\tfor i in grouplist:\n\t\tgroups = groups + \",\" + i\n\tparent_host = request.form.get('parent_host') # select\n\t\n\tf = open(\"./data/hosts-data-file\", \"a\")\n\tf.write(\"\\n[%s]\\n\" % (hostname))\n\tf.write(\"description = %s\\n\" % (hostdescription))\n\tf.write(\"ip_address = %s\\n\" % (ip))\n\tf.write(\"host_group = %s\\n\" % (groups))\n\tf.write(\"parent = %s\\n\" % (parent_host))\n\tf.close()\n\treturn redirect(url_for('hosts'))\n\n@app.route('/change_host_submit', methods=[\"POST\"])\ndef change_host_submit():\n\t# hostname = request.form['hostname']\n\t# hostdescription = request.form['hostdescription']\n\t# ip = request.form['ip']\n\t# grouplist = request.form.getlist('group_list') # checkbox\n\t# # groups not list\n\t# groups = \"All\" \n\t# for i in grouplist:\n\t# \tgroups = groups + \",\" + i\n\t# parent_host = request.form.get('parent_host') # select\n\t\n\t# f = open(\"./data/hosts-data-file\", \"a\")\n\t# f.write(\"\\n[%s]\\n\" % (hostname))\n\t# f.write(\"description = %s\\n\" % (hostdescription))\n\t# f.write(\"ip_address = %s\\n\" % (ip))\n\t# f.write(\"host_group = %s\\n\" % (groups))\n\t# f.write(\"parent = %s\\n\" % (parent_host))\n\t# f.close()\n\treturn redirect(url_for('hosts'))\n\n@app.route('/delete_host', methods=[\"POST\"])\ndef delete_host():\n\thostname=request.form['hostdelete']\n\tdata_hosts = ConfigObj('./data/hosts-data-file')\n\tdata_hosts.pop(hostname, None) # delete hostname\n\n\tf = open(\"./data/hosts-data-file\", \"w\")\n\t# Dictinary items\n\tfor host, hostvalue in data_host.items():\n\t\tf.write(\"[\"+host+\"]\\n\")\n\t\tfor key, value in hostvalue.items():\n\t\t\tif isinstance(value, list): # if value is list...\n\t\t\t\tvalue = ','.join(value)\n\t\t\tf.write(key+\" = \"+value+\"\\n\")\n\n\tf.close()\n\treturn redirect(url_for('hosts'))\n\n@app.route('/edit_host', methods=[\"POST\"])\ndef edit_host():\n\tdata_hostgroups = ConfigObj('./data/hostgroups-data-file')\n\thostname=request.form['hostedit']\n\tdata_hosts = ConfigObj('./data/hosts-data-file')\n\tdescription = data_hosts[hostname][\"description\"]\n\tip_address = data_hosts[hostname][\"ip_address\"]\n\thost_group = data_hosts[hostname][\"host_group\"]\n\tparent = data_hosts[hostname][\"parent\"]\n\treturn render_template('edit_host.html', data_hosts=data_hosts, data_hostgroups=data_hostgroups, hostname=hostname, description=description, ip_address=ip_address, host_group=host_group, parent=parent)\n### /host\n\n\n\n########### host group\n@app.route('/hostgroups', methods=[\"GET\"])\ndef hostgroups():\n\tdata_hostgroups = ConfigObj('./data/hostgroups-data-file')\n\treturn render_template('hostgroups.html', data_hostgroups=data_hostgroups)\n\n@app.route('/add_group', methods=[\"GET\"])\ndef add_group():\n\treturn render_template('add_group.html')\n\n@app.route('/add_group_submit', methods=[\"POST\"])\ndef add_group_submit():\n\tgroupname=request.form['groupname']\n\tgroupdescription=request.form['groupdescription']\n\n\tf = open(\"./data/hostgroups-data-file\", \"a\")\n\tf.write(\"\\n[\" + groupname + \"]\\n\")\n\tf.write(\"description = \" + groupdescription +\"\\n\")\n\tf.close()\n\n\treturn redirect(url_for('hostgroups'))\n\n@app.route('/delete_hostgroup', methods=[\"POST\"])\ndef delete_hostgroup():\n\tgroupname=request.form['hostgroupdelete']\n\tdata_hostgroups = ConfigObj('./data/hostgroups-data-file')\n\tdata_hostgroups.pop(groupname, None)\n\tf = open(\"./data/hostgroups-data-file\", \"w\")\n\n\t# Dictinary items\n\tfor i, x in data_hostgroups.items():\n\t\tf.write (\"[\"+i+\"]\\n\")\n\t\tfor y,z in x.items():\n\t\t\tf.write (\"description = \"+z+\"\\n\")\n\n\tf.close()\t\n\treturn redirect(url_for('hostgroups'))\n### \\hostgroup\n\n\n\n\n# @app.route('/services', methods=[\"GET\", \"POST\"])\n# def services():\n# \tIP_ADDRESS = request.remote_addr\n# \treturn render_template('services.html')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"213264571","text":"# PROPRIETARY AND CONFIDENTIAL\r\n# Property of Blackbird Logical Applications, LLC\r\n# Copyright Blackbird Logical Applications, LLC 2016\r\n# NOT TO BE CIRCULATED OR REPRODUCED WITHOUT PRIOR WRITTEN APPROVAL\r\n# Blackbird Environment\r\n# Module: data_structures.modelling.time_line\r\n\"\"\"\r\n\r\nModule defines TimeLine class. TimeLines are dictionaries of time periods with\r\ncustom search methods.\r\n==================== ==========================================================\r\nAttribute Description\r\n==================== ==========================================================\r\n\r\nDATA:\r\nn/a\r\n\r\nFUNCTIONS:\r\nn/a\r\n\r\nCLASSES:\r\nTimeLine collection of TimePeriod objects indexed by end date\r\n==================== ==========================================================\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n# imports\r\nimport logging\r\nimport copy\r\n\r\nfrom datetime import date, datetime, timedelta\r\n\r\nimport bb_settings\r\nimport tools.for_printing as views\r\n\r\nfrom data_structures.system.bbid import ID\r\nfrom data_structures.system.summary_maker import SummaryMaker\r\nfrom tools.parsing import date_from_iso\r\nfrom .parameters import Parameters\r\nfrom .time_period import TimePeriod\r\n\r\n\r\n\r\n\r\n# globals\r\nlogger = logging.getLogger(bb_settings.LOGNAME_MAIN)\r\n\r\n\r\n# classes\r\nclass TimeLine(dict):\r\n \"\"\"\r\n\r\n A TimeLine is a dictionary of TimePeriod objects keyed by ending date.\r\n The TimeLine helps manage, configure, and search TimePeriods.\r\n\r\n Unless otherwise specified, class expects all dates as datetime.date objects\r\n and all periods as datetime.timedelta objects.\r\n\r\n ==================== ======================================================\r\n Attribute Description\r\n ==================== ======================================================\r\n\r\n DATA:\r\n current_period P; pointer to the period that represents the present\r\n id instance of PlatformComponents.ID class, for interface\r\n master TimePeriod; unit templates that fall outside of time\r\n name str; corresponds with Model.time_line key\r\n parameters Parameters object, specifies shared parameters\r\n ref_date datetime.date; reference date for the model\r\n resolution string; 'monthly', 'annual'..etc. Model.time_line key\r\n\r\n FUNCTIONS:\r\n build() populates instance with adjacent time periods\r\n clear() delete content from past and future periods\r\n clear_future() delete content from future periods\r\n extrapolate() use seed to fill out all future periods in instance\r\n extrapolate_dates() use seed to fill out a range of dates\r\n find_period() returns period that contains queried time point\r\n get_segments() split time line into past, present, and future\r\n get_ordered() returns list of periods ordered by end point\r\n link() connect adjacent periods\r\n revert_current() go back to the prior current period\r\n update_current() updates current_period for reference or actual date\r\n ==================== ======================================================\r\n \"\"\"\r\n DEFAULT_PERIODS_FORWARD = 60\r\n DEFAULT_PERIODS_BACK = 1\r\n\r\n def __init__(self, model, resolution='monthly', name='default', interval=1):\r\n dict.__init__(self)\r\n self.id = ID()\r\n # Timeline objects support the id interface and pass the model's id\r\n # down to time periods. The Timeline instance itself does not get\r\n # its own bbid.\r\n\r\n self.model = model\r\n self.resolution = resolution\r\n self.name = name\r\n self.interval = interval\r\n self.master = None\r\n self.parameters = Parameters()\r\n self.has_been_extrapolated = False\r\n self.ref_date = None\r\n\r\n self.id.set_namespace(model.id.bbid)\r\n\r\n @property\r\n def current_period(self):\r\n \"\"\"\r\n\r\n\r\n **property**\r\n\r\n\r\n Getter returns instance._current_period. Setter stores old value for\r\n reversion, then sets new value. Deleter sets value to None.\r\n \"\"\"\r\n if len(self):\r\n cp = self.find_period(self.model.ref_date)\r\n return cp\r\n\r\n @property\r\n def first_period(self):\r\n if not self.keys():\r\n per = None\r\n else:\r\n min_date = min(self.keys())\r\n per = self[min_date]\r\n\r\n return per\r\n\r\n def __str__(self, lines=None):\r\n \"\"\"\r\n\r\n\r\n Components.__str__(lines = None) -> str\r\n\r\n\r\n Method concatenates each line in ``lines``, adds a new-line character at\r\n the end, and returns a string ready for printing. If ``lines`` is None,\r\n method calls pretty_print() on instance.\r\n \"\"\"\r\n if not lines:\r\n lines = views.view_as_time_line(self)\r\n line_end = \"\\n\"\r\n result = line_end.join(lines)\r\n return result\r\n\r\n @classmethod\r\n def from_database(cls, portal_data, model, **kargs):\r\n \"\"\"\r\n\r\n TimeLine.from_database(portal_data) -> TimeLine\r\n\r\n **CLASS METHOD**\r\n\r\n Method extracts a TimeLine from portal_data.\r\n \"\"\"\r\n key = tuple(portal_data[k] for k in ('resolution', 'name'))\r\n new = cls(\r\n model,\r\n resolution=portal_data['resolution'],\r\n name=portal_data['name'],\r\n )\r\n new.master = model.taxo_dir\r\n\r\n if portal_data['interval'] is not None:\r\n new.interval = portal_data['interval']\r\n if portal_data['ref_date']:\r\n new.ref_date = portal_data['ref_date']\r\n if isinstance(new.ref_date, str):\r\n new.ref_date = date_from_iso(new.ref_date)\r\n if portal_data['has_been_extrapolated'] is not None:\r\n new.has_been_extrapolated = portal_data['has_been_extrapolated']\r\n if portal_data['parameters'] is not None:\r\n new.parameters = Parameters.from_database(portal_data['parameters'])\r\n\r\n for data in portal_data['periods']:\r\n period = TimePeriod.from_database(\r\n data,\r\n model=model,\r\n time_line=new,\r\n )\r\n\r\n return new\r\n\r\n def to_database(self):\r\n \"\"\"\r\n\r\n TimeLine.to_database() -> dict\r\n\r\n Method yields a serialized representation of self.\r\n \"\"\"\r\n periods = [\r\n period.to_database() for period in self.values()\r\n ]\r\n result = {\r\n 'periods': periods,\r\n 'interval': self.interval,\r\n 'ref_date': format(self.ref_date) if self.ref_date else None,\r\n 'has_been_extrapolated': self.has_been_extrapolated,\r\n 'parameters': list(self.parameters.to_database()),\r\n }\r\n return result\r\n\r\n def copy_structure(self):\r\n \"\"\"\r\n\r\n\r\n TimeLine.copy_structure() -> TimeLine\r\n\r\n Method returns a copy of self linked to parent model and with the same\r\n layout.\r\n \"\"\"\r\n result = type(self)(self.model)\r\n result.ref_date = copy.copy(self.ref_date)\r\n result.parameters = self.parameters.copy()\r\n for old_period in self.iter_ordered():\r\n new_period = old_period.copy(clean=True)\r\n result.add_period(new_period)\r\n\r\n if self.master:\r\n result.master = result[self.master.end]\r\n\r\n return result\r\n\r\n def build(\r\n self, ref_date=None,\r\n fwd=DEFAULT_PERIODS_FORWARD, back=DEFAULT_PERIODS_BACK, year_end=True,\r\n ):\r\n \"\"\"\r\n\r\n\r\n TimeLine.build() -> None\r\n\r\n --``ref_date`` is datetime.date to use as the reference date for the\r\n timeline\r\n --``fwd`` is int number of periods to build forward of the ref_date\r\n --``back`` is int number of period to build before the ref_date\r\n --``year_end`` is bool for whether to build through the end of the year\r\n\r\n Method creates a chain of TimePeriods with adjacent start and end\r\n points. The chain is at least ``fwd`` periods long into the future\r\n and ``back`` periods long into the past. Forward chain ends on a Dec.\r\n\r\n Method expects ``ref_date`` to be a datetime.date object.\r\n\r\n Method sets instance.current_period to the period covering the reference\r\n date. Method also sets master to a copy of the current period.\r\n \"\"\"\r\n if not ref_date:\r\n ref_date = self.model.ref_date\r\n self.ref_date = ref_date\r\n\r\n ref_month = ref_date.month\r\n ref_year = ref_date.year\r\n\r\n current_start_date = date(ref_year, ref_month, 1)\r\n\r\n # Make reference period\r\n fwd_start_date = self._get_fwd_start_date(ref_date)\r\n current_end_date = fwd_start_date - timedelta(1)\r\n current_period = TimePeriod(\r\n current_start_date, current_end_date, model=self.model\r\n )\r\n self.add_period(current_period)\r\n\r\n # Add master period\r\n self.master = self.model.taxo_dir\r\n\r\n # Now make the chain\r\n back_end_date = current_start_date - timedelta(1)\r\n # Save known starting point for back chain build before fwd changes it.\r\n\r\n # Make fwd chain\r\n i = 0\r\n while fwd or year_end:\r\n # pick up where ref period analysis leaves off\r\n curr_start_date = fwd_start_date\r\n fwd_start_date = self._get_fwd_start_date(curr_start_date)\r\n curr_end_date = fwd_start_date - timedelta(1)\r\n fwd_period = TimePeriod(\r\n curr_start_date, curr_end_date, model=self.model\r\n )\r\n self.add_period(fwd_period)\r\n i += 1\r\n if i >= fwd and (not year_end or fwd_period.end.month == 12):\r\n break\r\n # first line picks up last value in function scope, so loop\r\n # should be closed.\r\n\r\n # Make back chain\r\n for i in range(back):\r\n curr_end_date = back_end_date\r\n curr_start_date = date(\r\n curr_end_date.year, curr_end_date.month, 1\r\n )\r\n back_period = TimePeriod(\r\n curr_start_date, curr_end_date, model=self.model\r\n )\r\n self.add_period(back_period)\r\n # close loop:\r\n back_end_date = curr_start_date - timedelta(1)\r\n\r\n def clear(self):\r\n \"\"\"\r\n\r\n\r\n TimeLine.clear() -> None\r\n\r\n\r\n Clear content from past and future, preserve current_period.\r\n \"\"\"\r\n for period in self.iter_ordered():\r\n if period.end != self.current_period.end:\r\n period.clear()\r\n # have to dereference history\r\n # have to do so recursively, to make sure that none of the objects\r\n # retain their external pointers.\r\n\r\n def clear_future(self, seed=None):\r\n \"\"\"\r\n\r\n\r\n TimeLine.clear_future() -> None\r\n\r\n\r\n Clear content from all periods after seed. Method expects a period as\r\n ``seed``, will use instance.current_period if seed is None.\r\n \"\"\"\r\n if seed is None:\r\n seed = self.current_period\r\n for period in self.iter_ordered():\r\n if period.end > seed.end:\r\n period.clear()\r\n\r\n def copy(self):\r\n \"\"\"\r\n\r\n\r\n TimeLine.copy() -> TimeLine\r\n\r\n\r\n Method returns a copy of the instance.\r\n \"\"\"\r\n result = copy.copy(self)\r\n for key, value in self.items():\r\n result[key] = value.copy()\r\n result[key].relationships.set_parent(result)\r\n result.has_been_extrapolated = self.has_been_extrapolated\r\n return result\r\n\r\n def add_period(self, period):\r\n \"\"\"\r\n\r\n\r\n Timeline.add_period() -> None\r\n\r\n --``period`` is a TimePeriod object\r\n\r\n Method configures period and records it in the instance under the\r\n period's end_date.\r\n \"\"\"\r\n period = self._configure_period(period)\r\n self[period.end] = period\r\n\r\n def iter_ordered(self, open=None, exit=None, shut=None):\r\n \"\"\"\r\n\r\n\r\n Timeline.iter_ordered() -> iter\r\n\r\n --``open`` date, soft start, if falls in period, iteration starts\r\n --``exit`` date, soft stop, if falls in period, last shown\r\n --``shut`` date, hard stop, if not exact period end, iteration stops\r\n\r\n Method iterates over periods in order, starting with the one in which\r\n ``open`` falls, and ending with the one including ``exit`` and\r\n not following ``shut``.\r\n \"\"\"\r\n for end_date, period in sorted(self.items()):\r\n if open and open > period.end:\r\n continue\r\n if exit and exit < period.start:\r\n break\r\n if shut and shut < period.end:\r\n break\r\n yield period\r\n\r\n def get_ordered(self):\r\n \"\"\"\r\n\r\n\r\n Timeline.get_ordered() -> list\r\n\r\n\r\n Method returns list of periods in instance, ordered from earliest to\r\n latest endpoint.\r\n \"\"\"\r\n return list(self.iter_ordered())\r\n\r\n def extrapolate(self, seed=None, calc_summaries=True):\r\n \"\"\"\r\n\r\n\r\n TimeLine.extrapolate() -> None\r\n\r\n\r\n Extrapolate current period to future dates. Make quarterly and annual\r\n financial summaries. Updates all summaries contained in\r\n instance.summaries.\r\n \"\"\"\r\n print('--------EXTRAPOLATE----------')\r\n if seed is None:\r\n seed = self.current_period\r\n\r\n company = self.model.get_company()\r\n\r\n company.consolidate_fins_structure()\r\n\r\n if seed.past:\r\n company.recalculate(period=seed.past, adjust_future=False)\r\n company.recalculate(period=seed, adjust_future=False)\r\n\r\n summary_maker = SummaryMaker(self.model)\r\n\r\n for period in self.iter_ordered(open=seed.end):\r\n if period.end > seed.end:\r\n logger.info(period.end)\r\n\r\n # reset content and directories\r\n period.clear()\r\n\r\n # combine tags\r\n period.tags = seed.tags.extrapolate_to(period.tags)\r\n\r\n # propagate parameters from past to current\r\n period.combine_parameters()\r\n\r\n # copy and fill out content\r\n company.fill_out(period=period)\r\n\r\n if bb_settings.MAKE_ANNUAL_SUMMARIES and calc_summaries:\r\n if period.end >= self.current_period.end:\r\n summary_maker.parse_period(period)\r\n\r\n # drop future periods that have been used up to keep size low\r\n if bb_settings.DYNAMIC_EXTRAPOLATION:\r\n if period.past and period.past.past:\r\n if period.past.past.end > self.current_period.end:\r\n period.past.past.financials.clear()\r\n\r\n if bb_settings.MAKE_ANNUAL_SUMMARIES and calc_summaries:\r\n summary_maker.wrap()\r\n\r\n # import devhooks\r\n # devhooks.picksize(self)\r\n self.has_been_extrapolated = True\r\n\r\n def extrapolate_dates(self, seed, dates, backward=False):\r\n \"\"\"\r\n\r\n\r\n TimeLine.extrapolate_dates() -> None\r\n\r\n\r\n Method extrapolates seed to the first date in dates, then sequentially\r\n extrapolates remaining dates from each other.\r\n\r\n Method expects ``seed`` to be an instance of TimePeriod. Seed can be\r\n external to the caller TimeLine.\r\n\r\n Method expects ``dates`` to be a series of endpoints for the periods in\r\n instance the caller is targeting. In other words, instance must contain\r\n a period corresponding to each date in ``dates``.\r\n\r\n Dates can contain gaps. Method will always extrapolate from one date to\r\n its neighbor. Extrapolation works by requesting that each object in a\r\n content structure extrapolate itself and any of its subordinates.\r\n For time-sensitive objects like BusinessUnits, that process should\r\n automatically adjust to the target date regardless of how far away that\r\n date is from the instance's reference date.\r\n\r\n If ``work_backward`` is True, method will go through dates\r\n last-one-first.\r\n \"\"\"\r\n #\r\n if backward:\r\n dates = dates[::-1]\r\n # Reverse order, so go from newest to oldest\r\n\r\n for i in range(len(dates)):\r\n\r\n date = dates[i]\r\n # With default arguments, start work at the period immediately\r\n # prior to the current period\r\n\r\n target_period = self[date]\r\n updated_period = seed.extrapolate_to(target_period)\r\n # extrapolate_to() always does work on an external object and leaves\r\n # the target untouched. Manually swap the old period for the new\r\n # period.\r\n\r\n if i == 0:\r\n updated_period = self._configure_period(updated_period)\r\n\r\n # On i == 0, extrapolating from the original seed. seed can be\r\n # external (come from a different model), in which case it would\r\n # use a different model namespace id for unit tracking.\r\n #\r\n # Accordingly, when extrapolating from the may-be-external seed,\r\n # use configure_period() to conform output to current model.\r\n #\r\n # Subsequent iterations of the loop will start w periods that are\r\n # already in the model, so method can leave their namespace id\r\n # configuration as is.\r\n\r\n self[date] = updated_period\r\n seed = updated_period\r\n\r\n def extrapolate_statement(self, statement_name, seed=None):\r\n \"\"\"\r\n\r\n\r\n TimeLine.extrapolate_statement() -> None\r\n\r\n\r\n Extrapolates a single statement forward in time. DOES NOT MAKE\r\n SUMMARIES.\r\n \"\"\"\r\n if seed is None:\r\n seed = self.current_period\r\n\r\n company = self.model.get_company()\r\n orig_fins = company.get_financials(period=seed)\r\n orig_statement = getattr(orig_fins, statement_name)\r\n orig_statement.reset()\r\n company.compute(statement_name, period=seed)\r\n\r\n for period in self.iter_ordered(open=seed.end):\r\n if period.end > seed.end:\r\n new_fins = company.get_financials(period=period)\r\n new_stat = new_fins.get_statement(statement_name)\r\n if new_stat is None:\r\n # need to add statement\r\n new_stat = orig_statement.copy(clean=True)\r\n new_fins.add_statement(statement_name, statement=new_stat)\r\n company.compute(statement_name, period=period)\r\n else:\r\n # compute what is already there\r\n company.compute(statement_name, period=period)\r\n\r\n def find_period(self, query):\r\n \"\"\"\r\n\r\n\r\n TimeLine.find_period() -> TimePeriod\r\n\r\n\r\n Method returns a time period that includes query. ``query`` can be a\r\n POSIX timestamp (int or float), datetime.date object, or string in\r\n \"YYYY-MM-DD\" format.\r\n \"\"\"\r\n if isinstance(query, date):\r\n q_date = query\r\n else:\r\n try:\r\n q_date = date.fromtimestamp(query)\r\n except TypeError:\r\n num_query = [int(x) for x in query.split(\"-\")]\r\n # query is a string, split it\r\n q_date = date(*num_query)\r\n end_date = self._get_ref_end_date(q_date)\r\n result = self.get(end_date)\r\n return result\r\n\r\n def get_segments(self, ref_date=None):\r\n \"\"\"\r\n\r\n\r\n TimeLine.get_segments() -> list\r\n\r\n\r\n Method returns a list of the past, present, and future segments of the\r\n instance, with respect to the ref_date. If ``ref_date`` is None, method\r\n counts current period as the present.\r\n\r\n output[0] = list of keys for periods before ref_date\r\n output[1] = list of ref period (len output[1] == 1)\r\n output[2] = list of keys for periods after ref_date\r\n \"\"\"\r\n if not ref_date:\r\n ref_date = self.current_period.end\r\n ref_end = self._get_ref_end_date(ref_date)\r\n #\r\n dates = sorted(self.keys())\r\n ref_spot = dates.index(ref_end)\r\n future_dates = dates[(ref_spot + 1):]\r\n past_dates = dates[:ref_spot]\r\n result = [past_dates, [ref_end], future_dates]\r\n return result\r\n\r\n # *************************************************************************#\r\n # NON-PUBLIC METHODS #\r\n # *************************************************************************#\r\n\r\n def _get_fwd_start_date(self, ref_date):\r\n \"\"\"\r\n\r\n\r\n TimeLine.get_fwd_start_date() -> datetime.date\r\n\r\n\r\n Method returns the starting date of the next month.\r\n \"\"\"\r\n ref_month = ref_date.month\r\n ref_year = ref_date.year\r\n if ref_month == 12:\r\n result = date(ref_year + 1, 1, 1)\r\n else:\r\n result = date(ref_year, ref_month + 1, 1)\r\n return result\r\n\r\n def _get_ref_end_date(self, ref_date):\r\n \"\"\"\r\n\r\n\r\n TimeLine._get_ref_end_date() -> datetime.date\r\n\r\n\r\n Method returns the last date of the month that contains ref_date.\r\n \"\"\"\r\n result = None\r\n fwd_start_date = self._get_fwd_start_date(ref_date)\r\n ref_end_date = fwd_start_date - timedelta(1)\r\n result = ref_end_date\r\n return result\r\n\r\n def _configure_period(self, period):\r\n \"\"\"\r\n\r\n\r\n Timeline._configure_period() -> period\r\n\r\n\r\n Method sets period's namespace id to that of the TimeLine, then returns\r\n period.\r\n \"\"\"\r\n model_namespace = self.id.namespace\r\n period.id.set_namespace(model_namespace)\r\n # Period has only a pointer to the Model.namespace_id; periods don't\r\n # have their own bbids.\r\n period.relationships.set_parent(self)\r\n\r\n # end dates of the past and future periods\r\n try:\r\n period.past_end = max(\r\n (day for day in self.keys() if day < period.end)\r\n )\r\n except:\r\n period.past_end = None\r\n try:\r\n period.next_end = min(\r\n (day for day in self.keys() if day > period.end)\r\n )\r\n except:\r\n period.next_end = None\r\n # link adjacent periods\r\n if period.past_end:\r\n past_period = self[period.past_end]\r\n past_period.next_end = period.end\r\n if period.next_end:\r\n next_period = self[period.next_end]\r\n next_period.past_end = period.end\r\n\r\n return period\r\n","sub_path":"data_structures/modelling/time_line.py","file_name":"time_line.py","file_ext":"py","file_size_in_byte":22823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"81868256","text":"\nfrom scipy import ndimage\nfrom scipy import misc\nimport matplotlib.pyplot as plt\n\nfigure = plt.figure()\nlena = misc.lena()\naxis1 = figure.add_subplot(2, 2, 1)\naxis2 = figure.add_subplot(2, 2, 2)\naxis3 = figure.add_subplot(2, 2, 3)\naxis4 = figure.add_subplot(2, 2, 4)\naxis1.imshow(ndimage.shift(lena, (50, 50)), cmap=plt.pink())\naxis2.imshow(ndimage.shift(lena, (50, 50), mode='nearest'))\naxis3.imshow(ndimage.rotate(lena, 50))\naxis4.imshow(lena[100:-100, 100:-100])\naxis2.autoscale(False)\naxis1.autoscale(False)\naxis1.axis('off')\naxis2.axis('off')\naxis3.axis('off')\naxis4.axis('off')\nplt.show()\n","sub_path":"SciPy+NumPy+MatplotLib/scipy_image_processing.py","file_name":"scipy_image_processing.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"188339456","text":"# -*- coding: utf-8 -*-\n\nfrom . import NNGraph\nfrom ...features import patch_features\n\n\nclass ImgPatches(NNGraph):\n r\"\"\"\n Create a nearest neighbors graph from patches of an image.\n\n Parameters\n ----------\n img : array\n Input image.\n patch_shape : tuple, optional\n Dimensions of the patch window. Syntax: (height, width), or (height,),\n in which case width = height.\n n_nbrs : int, optional\n Number of neighbors to consider\n dist_type : string, optional\n Type of distance between patches to compute. See\n :func:`pyflann.index.set_distance_type` for possible options.\n\n Examples\n --------\n >>> from pygsp.graphs import nngraphs\n >>> from skimage import data, img_as_float\n >>> img = img_as_float(data.camera()[::2, ::2])\n >>> G = nngraphs.ImgPatches(img)\n\n \"\"\"\n\n def __init__(self, img, patch_shape=(3, 3), n_nbrs=8, use_flann=True,\n dist_type='euclidean', symmetrize_type='full', **kwargs):\n\n X = patch_features(img, patch_shape=patch_shape)\n\n super(ImgPatches, self).__init__(X,\n use_flann=use_flann,\n symmetrize_type=symmetrize_type,\n dist_type=dist_type,\n gtype='patch-graph',\n perform_all_checks=False,\n **kwargs)\n self.img = img\n","sub_path":"pygsp/graphs/nngraphs/imgpatches.py","file_name":"imgpatches.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"18861307","text":"from django.shortcuts import render\nfrom .forms import PostCreateForm\nfrom .models import Post\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\n\n\n@login_required\ndef post_create(request):\n\tform = None\n\tif request.method == 'POST':\n\t\tform = PostCreateForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tnew_post = form.save(commit=False)\n\t\t\tnew_post.author = request.user\n\t\t\tnew_post.save()\n\t\t\tmessages.success(request, \"You created a post\")\n\t\telse:\n\t\t\tmessages.error(request, \"Something went wrong , Please try again\")\n\telse:\n\t\tform = PostCreateForm()\n\treturn render(request, 'posts/create.html', {'form': form})\t","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"80595610","text":"#!/home/lr/kobayasi/.pyenv/shims/python\nimport argparse\nimport random\nimport MeCab\nfrom nltk.tokenize.nist import NISTTokenizer #nltk3.3\n##from nltk.tokenize.moses import MosesTokenizer #nltk3.2.5\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--corpus', type=str)\n parser.add_argument('--train', type=str)\n parser.add_argument('--valid', type=str)\n parser.add_argument('--test', type=str)\n args = parser.parse_args()\n\n # Load corpus\n corpus = load_Tanaka(args.corpus)\n random.seed(0)\n random.shuffle(corpus)\n # Train\n train = corpus[:100000]\n write(args.train, train)\n # Valid\n valid = corpus[100000:110000]\n write(args.valid, valid)\n # Test\n test = corpus[110000:120000]\n write(args.test, test)\n\ndef load_Tanaka(file_path):\n mecab = MeCab.Tagger('-Owakati')\n nist = NISTTokenizer()\n corpus = []\n with open(file_path) as f:\n for line in f:\n if not line.startswith('A: '): continue\n line = line.split('A:')[1].split('# ID')[0]\n ja_sentence, en_sentence = line.strip().split('\\t')\n # Tokenize\n en_sentence = nist.tokenize(en_sentence, return_str=True).strip()\n ja_sentence = mecab.parse(ja_sentence).strip()\n corpus.append('\\t'.join([ja_sentence, en_sentence]))\n return corpus\n\ndef write(file_path, dataset):\n with open(file_path, 'w') as f:\n print('\\n'.join(dataset), file=f)\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/divide_and_tokenize.py","file_name":"divide_and_tokenize.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"103613194","text":"\"\"\" Misc utility functions \"\"\"\n\nimport sys\nimport os\nimport re\nimport subprocess\n\n\ndef func_once(func):\n \"A decorator that runs a function only once.\"\n def decorated(*args, **kwargs):\n try:\n return decorated._once_result\n except AttributeError:\n decorated.__doc__ = func.__doc__\n decorated.__name__ = func.__name__\n decorated.__dict__ = func.__dict__\n decorated.__module__ = func.__module__\n decorated._once_result = func(*args, **kwargs)\n return decorated._once_result\n return decorated\n\n\ndef method_once(method):\n \"A decorator that runs a method only once.\"\n attrname = \"_%s_once_result\" % id(method)\n\n def decorated(self, *args, **kwargs):\n try:\n return getattr(self, attrname)\n except AttributeError:\n decorated.__doc__ = method.__doc__\n decorated.__name__ = method.__name__\n decorated.__dict__ = method.__dict__\n decorated.__module__ = method.__module__\n setattr(self, attrname, method(self, *args, **kwargs))\n return getattr(self, attrname)\n return decorated\n\n\ndef ExceptionToStr(exc_info=None):\n \"\"\"Utility function to represent an exception stack trace into a string\"\"\"\n if not exc_info:\n exc_info = sys.exc_info()\n etype, value, tb = exc_info\n import traceback\n res = \"Traceback (most recent call last):\\n\"\n\n l = traceback.format_tb(tb, None) + \\\n traceback.format_exception_only(etype, value)\n res += \"\".join(l[:-1])\n res += str(l[-1])\n\n return res\n\n\ndef clean_twisted_reactor(reactor):\n # stolen from twisted unit tests, will forcefully reset the reactor,\n # so we can run it multiple times in unit tests\n reactor._uninstallHandler()\n if getattr(reactor, '_internalReaders', None) is not None:\n for reader in reactor._internalReaders:\n reactor.removeReader(reader)\n reader.connectionLost(None)\n reactor._internalReaders.clear()\n\n # Here's an extra thing unrelated to wakers but necessary for\n # cleaning up after the reactors we make. -exarkun\n reactor.disconnectAll()\n\n # It would also be bad if any timed calls left over were allowed to\n # run.\n calls = reactor.getDelayedCalls()\n for c in calls:\n c.cancel()\n\n try:\n reactor._stopThreadPool()\n except AttributeError:\n pass\n\n\ndef launch_browser(filepath, shell=True):\n if sys.platform == 'darwin':\n subprocess.call(('open', filepath))\n elif os.name == 'nt':\n CREATE_NEW_CONSOLE = 0x00000010\n cwd = os.path.dirname(filepath) if os.path.exists(filepath) else None\n subprocess.call(('start', filepath),\n shell=shell,\n close_fds=True,\n creationflags=CREATE_NEW_CONSOLE,\n cwd=cwd)\n elif os.name == 'posix':\n subprocess.call(('xdg-open', filepath))\n\n\ndef prompt_user(title, default=None, options=()):\n if default:\n sys.stdout.write(title + \" [default '%s']: \" % default)\n else:\n sys.stdout.write(title + \": \")\n invalid = True\n while invalid:\n if options:\n valid_options = map(lambda x: x[0] + \" [%s]\" % x[1], options)\n sys.stdout.write(\" \" + \", \".join(valid_options) + \": \")\n\n r = raw_input(\"\")\n\n if not r or r.isspace():\n if default:\n r = default\n break\n\n if not options or r in map(lambda x: x[1], options):\n break\n\n return r\n\n\n_KNOWN_LOCATIONS = [\n (\"/opt/sun/\", re.compile(r\"j2sdk(.+)/jre/lib/i386/client/libjvm.so\")),\n (\"/usr/java/\", re.compile(r\"j2sdk(.+)/jre/lib/i386/client/libjvm.so\")),\n (\"/usr/java/\", re.compile(r\"jdk(.+)/jre/lib/i386/client/libjvm.so\")),\n]\n\nJRE_ARCHS = [\n \"amd64/server/libjvm.so\",\n \"i386/client/libjvm.so\",\n \"i386/server/libjvm.so\",\n ]\n\n\ndef _getJVMFromJavaHome():\n java_home = os.getenv(\"JAVA_HOME\")\n if not java_home:\n return None\n rootJre = None\n if os.path.exists(java_home + \"/bin/javac\"):\n # this is a JDK home\n rootJre = java_home + '/jre/lib'\n elif os.path.exists(java_home + \"/bin/java\"):\n # this is a JRE home\n rootJre = java_home + '/lib'\n else:\n return None\n\n for i in JRE_ARCHS:\n if os.path.exists(rootJre + \"/\" + i):\n return rootJre + \"/\" + i\n return None\n\n\ndef _getJVMFromLibPath():\n if 'LD_LIBRARY_PATH' in os.environ:\n libpath = os.environ['LD_LIBRARY_PATH']\n if libpath is None:\n return None\n\n paths = libpath.split(os.pathsep)\n for i in paths:\n if i.find('jre') != -1:\n # this could be it!\n # TODO\n pass\n\n return None\n\n\ndef getDefaultJVMPath():\n if sys.platform == \"win32\":\n import _winreg\n\n try:\n jreKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,\n r\"SOFTWARE\\JavaSoft\\Java Runtime Environment\")\n cv = _winreg.QueryValueEx(jreKey, \"CurrentVersion\")\n versionKey = _winreg.OpenKey(jreKey, cv[0])\n _winreg.CloseKey(jreKey)\n\n cv = _winreg.QueryValueEx(versionKey, \"RuntimeLib\")\n _winreg.CloseKey(versionKey)\n\n return cv[0]\n except WindowsError:\n pass\n\n return None\n elif sys.platform == \"darwin\":\n return '/System/Library/Frameworks/JavaVM.framework/JavaVM'\n else:\n jvm = _getJVMFromJavaHome()\n if jvm is not None:\n return jvm\n\n # on linux, the JVM has to be in the LD_LIBRARY_PATH anyway,\n # so might as well inspect it first\n jvm = _getJVMFromLibPath()\n if jvm is not None:\n return jvm\n\n # failing that, lets look in the \"known\" locations\n #for i in _KNOWN_LOCATIONS:\n # TODO\n # pass\n\n return \"/usr/java/jre1.5.0_05/lib/i386/client/libjvm.so\"\n\n\ndef zappa2veloxID(zappa_jobID):\n # Zappa id has this format:\n # [priority]_[time stamp]_[unique id]_[seq]\n priority, time_stamp, unique_id, seq = zappa_jobID.split(\"_\")\n oid = \"%s_%s_transcode\" % (time_stamp, unique_id + seq)\n return oid, priority\n\n\ndef velox2zappaID(velox_jobID):\n # Kind of a hack, since we can't return the original zappa ID (some parts\n # were dropped). But it does return a valid ID as close as possible to the\n # original.\n velox_jobID = velox_jobID.replace(\"_transcode\", \"\")\n priority = \"00000000000\"\n timestamp, unique_id = velox_jobID.split(\"_\")\n if len(unique_id) < 14:\n # Job didn't originate in Zappa, need to invent a sequence #\n seq = \"0000\"\n else:\n seq = unique_id[-4:]\n unique_id = velox_jobID[0:-4]\n zappaID = \"%s_%s_%s_%s_transcoding\" % (priority, timestamp, unique_id, seq)\n return zappaID\n","sub_path":"pythonlib/adobe/miscutils.py","file_name":"miscutils.py","file_ext":"py","file_size_in_byte":6957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"344732299","text":"import numpy as np\nimport importlib\nimport os\nimport yaml\nimport time\nimport torch\nfrom torch.nn.utils import clip_grad_norm_\nfrom tts.utils.base_trainer import BaseTrainer\nfrom tts.models.cbhg_net import CBHGNet\nfrom tts.models.modules.cbhg_net.cbhg_net_loss import CBHGNetLoss\nfrom tts.utils.train_helpers import get_optimizer\nfrom tts.dataloaders.dataloader_cbhg import get_dataloader\nfrom tts.utils.plot import plot_spectrogram_double\nfrom tts.utils.generic import get_text_processor\n\n\nclass Trainer(BaseTrainer):\n def __init__(self, **params):\n super(Trainer, self).__init__(**params) \n # Init dataloaders\n self._init_dataloaders()\n\n # Set model\n self.model = CBHGNet(params[\"audio_params\"][\"n_mels\"], \n params[\"audio_params\"][\"n_fft\"]//2+1)\n self.model.to(self.device)\n\n # Initi criterion, optimizer\n self._init_criterion_optimizer()\n\n def _init_criterion_optimizer(self):\n # Criterion\n if self.params[\"criterion\"][\"criterion_type\"] == \"CBHGNetLoss\":\n self.criterion = CBHGNetLoss(reduction=self.params[\"criterion\"][\"reduction\"],\n device=self.device)\n else:\n raise RuntimeError(f\"Criterion {self.params['criterion']} not defined.\")\n\n # Optimizer\n self.optimizer = get_optimizer(self.model, **self.params[\"optim\"])\n\n # LR scheduler\n self.lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(self.optimizer, milestones=self.params[\"lrsched_milestone\"], gamma=self.params[\"lrsched_gamma\"])\n\n def _init_dataloaders(self):\n # Load train loader\n self.train_loader, speaker_to_id = get_dataloader(eval=False, \n **self.params)\n \n # Load eval loader\n self.eval_loader, speaker_to_id_eval = get_dataloader(eval=True, \n **self.params)\n\n def train(self):\n self.step_global = 0\n for epoch in range(self.params[\"epochs\"]):\n self._train_epoch(epoch)\n self._eval_epoch(epoch)\n \n def get_model_part_params_flattened(self, model):\n named_params = list(model.named_parameters())\n param_names = [n for (n, p) in named_params]\n model_parts = list(set([name.split(\".\")[0] for name in param_names]))\n\n model_part_params ={}\n for model_part in model_parts:\n part_params = [p.grad.flatten() for (n, p) in named_params if n.startswith(model_part) if p.grad != None]\n if len(part_params) > 0:\n part_params = torch.cat(part_params, dim=0)\n model_part_params[model_part] = part_params\n return model_part_params\n\n def _unpack_batch(self, batch_items):\n item_ids, melspecs, specs, len_specs, speaker_ids = batch_items\n # Transfer batch items to compute_device\n melspecs, specs = melspecs.to(self.device), specs.to(self.device)\n len_specs, speaker_ids = len_specs.to(self.device), speaker_ids.to(self.device)\n return item_ids, melspecs, specs, len_specs, speaker_ids\n\n def _train_epoch(self, epoch):\n self.model.train()\n\n running_loss = 0\n total_iters = len(self.train_loader)\n\n # Train for one epoch\n for itr, (batch_items) in enumerate(self.train_loader, 1):\n start = time.time()\n item_ids, melspecs, specs, len_specs, speaker_ids = self._unpack_batch(batch_items)\n\n # Feed inputs to the model\n outputs = self.model(melspecs)\n \n loss = self.criterion(outputs, specs, len_specs)\n \n # grad_norm = clip_grad_norm_(self.model.parameters(), \n # self.params[\"grad_clip_thresh\"])\n \n # Backprop\n self.optimizer.zero_grad()\n loss.backward()\n \n # Optimizer step\n self.optimizer.step()\n \n # Calculate speed\n duration = (time.time() - start)\n\n # Compute loss average and step duration for logger\n running_loss += loss.item()\n avg_loss = running_loss / itr\n step = self.step_global\n\n # Write logs to Tensorboard\n if step % self.params[\"tensorboard_log_steps\"] == 0:\n self.writer.add_scalar(\"train/loss\", loss.item(), step)\n self.writer.add_scalar(\"train/lr\", self.lr_scheduler.get_last_lr()[-1], step)\n # self.writer.add_scalar(\"train/grad_norm\", grad_norm.item(), step)\n \n # Write gradient histograms to Tensorboard\n if step % self.params[\"tensorboard_log_steps_hist\"] == 0:\n model_part_params = self.get_model_part_params_flattened(self.model)\n for part_name in model_part_params.keys():\n self.writer.add_histogram(f\"grad_hist/{part_name}\", model_part_params[part_name], step) \n \n # LR scheduler step\n self.lr_scheduler.step()\n \n # Save checkpoints\n if step % self.params[\"checkpoint_save_steps\"] == 0:\n self._save_checkpoint()\n\n # Save mel-spec and attention plots for the generated example\n if itr == len(self.train_loader):\n idx = -1\n example_spec = outputs[idx].detach().cpu().numpy()\n example_spec_gt = specs[idx].detach().cpu().numpy()\n plot_spectrogram_double(example_spec, \n example_spec_gt, \n os.path.join(self.path_manager.examples_path, f'{step}_spec_gt'),\n length_spec=len_specs[idx].item())\n \n # Print log\n if itr % self.params[\"print_steps\"] == 0:\n step_k = step // 1000\n msg = f'| Epoch: {epoch}: ({itr}/{total_iters}) | avg. loss: {avg_loss:#.4} | step loss: {loss.item():#.4} | ' + \\\n f'lr: {self.lr_scheduler.get_last_lr()[-1]:#.3} | step: {step_k}k | duration: {duration:#.2}'\n print(msg)\n\n self.step_global += 1\n\n # Save checkpoint after each epoch \n self._save_checkpoint()\n\n def _eval_epoch(self, epoch):\n self.model.eval()\n print(f\"\\nEvaluating epoch {epoch}:\")\n with torch.no_grad():\n loss_sum = 0.0\n\n # Train for one epoch\n for itr, (batch_items) in enumerate(self.eval_loader, 1):\n item_ids, melspecs, specs, len_specs, speaker_ids = self._unpack_batch(batch_items)\n\n # Feed inputs to the model\n outputs = self.model(melspecs)\n \n loss = self.criterion(outputs, specs, len_specs)\n\n # Compute loss sum\n loss_sum += loss.item()\n \n # Compute loss avg\n avg_loss = loss_sum / len(self.eval_loader)\n\n # Print and write loss log\n print(f\"Avg. loss: {avg_loss}\\n\\n\")\n self.writer.add_scalar(\"eval/avg_loss\", avg_loss, self.step_global)\n\n\n self.model.train()\n\n def _save_checkpoint(self):\n k = self.step_global // 1000\n checkpoint_path = os.path.join(self.path_manager.checkpoints_path, f\"checkpoint_{k}K.pt\")\n torch.save(self.model.state_dict(), checkpoint_path)\n","sub_path":"tts/methods/cbhg_net/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":7518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"602359434","text":"#https://projecteuler.net/problem=12\n\nimport Eulerlib\n\n#This function takes in a number and will return a total of how many divisors\n#the input number has\ndef findDivisors(n):\n total = 0\n for i in range(1, int(n**.5)+1):\n if n % i == 0:\n total += 2\n\n return total\n\n#Start timer to time algorithm\nstart = Eulerlib.getTime()\n\n#We can generate triangle numbers by just incrementing y and adding it to the\n#previous triangle number used\nx, y = 1, 2\n\n#Keep generating triangle numbers until one is found that has more than 500 divisors\nwhile findDivisors(x) <= 500:\n x += y\n y += 1\n\nEulerlib.answer = x\n\n#Stop timer to time algorithm\nend = Eulerlib.getTime()\n\n#The answer should be 76576500\nprint (\"The answer was found in %f seconds\" % (end - start))\nprint (\"And the answer is: %d\" % Eulerlib.answer)\n","sub_path":"Python/p012.py","file_name":"p012.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"465328278","text":"import pandas as pd\nimport numpy as np\nimport tqdm\nfrom collections import Counter\n\nentbase = pd.read_csv('../../data/1entbase.csv').fillna(0);\ntrain = pd.read_csv('../../data/train.csv')\ntrain_idx = list(train['EID'])\ntest_idx = list(pd.read_csv('../../data/evaluation_public.csv')['EID'])\n\n# max EID is less than 600000\nrow = [0 for i in range(600000)]\nfor (idx, eid) in enumerate(entbase['EID']):\n row[eid] = idx\n\nalter = pd.read_csv('../../data/2alter.csv')\nbranch = pd.read_csv('../../data/3branch.csv')\ninvest = pd.read_csv('../../data/4invest.csv')\nright = pd.read_csv('../../data/5right.csv')\nproject = pd.read_csv('../../data/6project.csv')\nlawsuit = pd.read_csv('../../data/7lawsuit.csv')\nbreakfaith = pd.read_csv('../../data/8breakfaith.csv')\nrecruit = pd.read_csv('../../data/9recruit.csv')\nrecruit['RECRNUM'] = recruit['RECRNUM'].fillna(recruit['RECRNUM'].median())\n\ndef count_alter():\n length = len(entbase['EID'])\n alter_count = np.zeros(length, dtype=np.int32)\n for i, x in Counter(list(alter['EID'])).items():\n alter_count[row[i]] += x\n entbase['ALTER_COUNT'] = pd.Series(alter_count, index=entbase.index)\n\ndef count_branch():\n length = len(entbase['EID'])\n branch_count = np.zeros(length, dtype=np.int32)\n home_count = np.zeros(length, dtype=np.int32)\n non_home_count = np.zeros(length, dtype=np.int32)\n ended_count = np.zeros(length, dtype=np.int32)\n ended_rate = np.zeros(length, dtype=np.float32)\n home_rate = np.zeros(length, dtype=np.float32)\n non_home_rate = np.zeros(length, dtype=np.float32)\n for i in range(len(branch['EID'])):\n r = row[branch['EID'][i]]\n branch_count[r] += 1\n if branch['IFHOME'][i] == 1:\n home_count[r] += 1\n else:\n non_home_count[r] += 1\n if not np.isnan(branch['B_ENDYEAR'][i]):\n ended_count[r] += 1\n entbase['BRANCH_COUNT'] = pd.Series(branch_count, index=entbase.index)\n entbase['HOME_BRANCH_COUNT'] = pd.Series(home_count, index=entbase.index)\n entbase['NON_HOME_BRANCH_COUNT'] = pd.Series(non_home_count, index=entbase.index)\n entbase['ENDED_BRANCH_COUNT'] = pd.Series(ended_count, index=entbase.index)\n for i in range(length):\n if branch_count[i] != 0:\n ended_rate[i] = ended_count[i] / branch_count[i]\n home_rate[i] = home_count[i] / branch_count[i]\n non_home_rate[i] = home_count[i] / branch_count[i]\n entbase['ENDED_BRANCH_RATE'] = pd.Series(ended_rate, index=entbase.index)\n entbase['HOME_BRANCH_RATE'] = pd.Series(home_rate, index=entbase.index)\n entbase['NON_HOME_BRANCH_RATE'] = pd.Series(non_home_rate, index=entbase.index)\n\ndef count_invest():\n length = len(entbase['EID'])\n invest_count = np.zeros(length, dtype=np.int32)\n home_count = np.zeros(length, dtype=np.int32)\n non_home_count = np.zeros(length, dtype=np.int32)\n ended_count = np.zeros(length, dtype=np.int32)\n ended_rate = np.zeros(length, dtype=np.float32)\n home_rate = np.zeros(length, dtype=np.float32)\n non_home_rate = np.zeros(length, dtype=np.float32)\n bt_max = np.zeros(length, dtype=np.float32)\n bt_min = np.zeros(length, dtype=np.float32)\n bt_sum = np.zeros(length, dtype=np.float32)\n bt_mean = np.zeros(length, dtype=np.float32)\n for i in range(len(invest['EID'])):\n r = row[invest['EID'][i]]\n invest_count[r] += 1\n if invest['IFHOME'][i] == 1:\n home_count[r] += 1\n else:\n non_home_count[r] += 1\n if not np.isnan(invest['BTENDYEAR'][i]):\n ended_count[r] += 1\n btbl = invest['BTBL'][i]\n bt_max[r] = max(bt_max[r], btbl)\n if bt_min[r] < 1e-6:\n bt_min[r] = btbl\n else:\n bt_max[r] = max(bt_max[r], btbl)\n bt_sum[r] += btbl\n for i in range(length):\n if invest_count[i] != 0:\n bt_mean[i] = bt_sum[i] / invest_count[i]\n ended_rate[i] = ended_count[i] / invest_count[i]\n home_rate[i] = home_count[i] / invest_count[i]\n non_home_rate[i] = non_home_count[i] / invest_count[i]\n entbase['INVEST_COUNT'] = pd.Series(invest_count, index=entbase.index)\n entbase['HOME_INVEST_COUNT'] = pd.Series(home_count, index=entbase.index)\n entbase['NON_HOME_INVEST_COUNT'] = pd.Series(non_home_count, index=entbase.index)\n entbase['ENDED_INVEST_COUNT'] = pd.Series(ended_count, index=entbase.index)\n entbase['ENDED_INVEST_RATE'] = pd.Series(ended_rate, index=entbase.index)\n entbase['HOME_INVEST_RATE'] = pd.Series(home_rate, index=entbase.index)\n entbase['NON_HOME_INVEST_RATE'] = pd.Series(home_rate, index=entbase.index)\n entbase['INVEST_BT_MAX'] = pd.Series(bt_max, index=entbase.index)\n entbase['INVEST_BT_MIN'] = pd.Series(bt_min, index=entbase.index)\n entbase['INVEST_BT_SUM'] = pd.Series(bt_sum, index=entbase.index)\n entbase['INVEST_BT_MEAN'] = pd.Series(bt_mean, index=entbase.index)\n\ndef count_right():\n length = len(entbase['EID'])\n right_count = np.zeros(length, dtype=np.int32)\n ended_count = np.zeros(length, dtype=np.int32)\n ended_rate = np.zeros(length, dtype=np.float32)\n for i in range(len(right['EID'])):\n r = row[right['EID'][i]]\n x = right['FBDATE'][i]\n right_count[r] += 1\n if not (isinstance(x, float) and np.isnan(x)):\n ended_count[r] += 1\n for i in range(length):\n if right_count[i] != 0:\n ended_rate[i] = ended_count[i] / right_count[i]\n entbase['RIGHT_COUNT'] = pd.Series(right_count, index=entbase.index)\n entbase['RIGHT_ENDED_COUNT'] = pd.Series(ended_count, index=entbase.index)\n entbase['RIGHT_ENDED_RATE'] = pd.Series(ended_rate, index=entbase.index)\n\ndef count_project():\n length = len(entbase['EID'])\n project_count = np.zeros(length, dtype=np.int32)\n home_count = np.zeros(length, dtype=np.int32)\n non_home_count = np.zeros(length, dtype=np.int32)\n home_rate = np.zeros(length, dtype=np.float32)\n non_home_rate = np.zeros(length, dtype=np.float32)\n for i in range(len(project['EID'])):\n r = row[project['EID'][i]]\n project_count[r] += 1\n if invest['IFHOME'][i] == 1:\n home_count[r] += 1\n else:\n non_home_count[r] += 1\n for i in range(length):\n if project_count[i] != 0:\n home_rate[i] = home_count[i] / project_count[i]\n non_home_rate[i] = non_home_count[i] / project_count[i]\n entbase['PROJECT_COUNT'] = pd.Series(project_count, index=entbase.index)\n entbase['PROJECT_HOME_COUNT'] = pd.Series(home_count, index=entbase.index)\n entbase['PROJECT_NON_HOME_COUNT'] = pd.Series(non_home_count, index=entbase.index)\n entbase['PROJECT_HOME_RATE'] = pd.Series(home_rate, index=entbase.index)\n entbase['PROJECT_NON_HOME_RATE'] = pd.Series(non_home_rate, index=entbase.index)\n\ndef count_lawsuit():\n length = len(entbase['EID'])\n lawsuit_count = np.zeros(length, dtype=np.int32)\n lawsuit_sum = np.zeros(length, dtype=np.int32)\n lawsuit_min = np.zeros(length, dtype=np.int32)\n lawsuit_max = np.zeros(length, dtype=np.int32)\n lawsuit_mean = np.zeros(length, dtype=np.int32)\n for i in range(len(lawsuit['EID'])):\n r = row[lawsuit['EID'][i]]\n x = lawsuit['LAWAMOUNT'][i]\n lawsuit_count[r] += 1\n lawsuit_sum[r] += x\n if lawsuit_min[r] == 0:\n lawsuit_min[r] = x\n else:\n lawsuit_min[r] = min(lawsuit_min[r], x)\n lawsuit_max[r] = max(lawsuit_max[r], x)\n for i in range(length):\n if lawsuit_count[i] != 0:\n lawsuit_mean[i] = lawsuit_sum[i] / lawsuit_count[i]\n entbase['LAWSUIT_COUNT'] = pd.Series(lawsuit_count, index=entbase.index)\n entbase['LAWSUIT_SUM'] = pd.Series(lawsuit_sum, index=entbase.index)\n entbase['LAWSUIT_MIN'] = pd.Series(lawsuit_min, index=entbase.index)\n entbase['LAWSUIT_MAX'] = pd.Series(lawsuit_max, index=entbase.index)\n entbase['LAWSUIT_MEAN'] = pd.Series(lawsuit_mean, index=entbase.index)\n\ndef count_breakfaith():\n length = len(entbase['EID'])\n breakfaith_count = np.zeros(length, dtype=np.int32)\n ended_count = np.zeros(length, dtype=np.int32)\n ended_rate = np.zeros(length, dtype=np.float32)\n for i in range(len(breakfaith['EID'])):\n r = row[breakfaith['EID'][i]]\n x = breakfaith['SXENDDATE'][i]\n if not (isinstance(x, float) and np.isnan(x)):\n ended_count[r] += 1\n for i in range(length):\n if breakfaith_count[i] != 0:\n ended_rate[i] = ended_count[i] / breakfaith_count[i]\n entbase['BREAKFAITH_COUNT'] = pd.Series(breakfaith_count, index=entbase.index)\n entbase['BREAKFAITH_ENDED_COUNT'] = pd.Series(ended_count, index=entbase.index)\n entbase['BREAKFAITH_ENDED_RATE'] = pd.Series(ended_count, index=entbase.index)\n\ndef count_recruit():\n length = len(entbase['EID'])\n recruit_count = np.zeros(length, dtype=np.int32)\n recruit_sum = np.zeros(length, dtype=np.int32)\n recruit_min = np.zeros(length, dtype=np.int32)\n recruit_max = np.zeros(length, dtype=np.int32)\n recruit_mean = np.zeros(length, dtype=np.float32)\n for i in range(len(recruit['EID'])):\n r = row[recruit['EID'][i]]\n x = recruit['RECRNUM'][i]\n recruit_count[r] += 1\n recruit_sum[r] += int(x + 0.5)\n if recruit_min[r] == 0:\n recruit_min[r] = x\n else:\n recruit_min[r] = min(recruit_min[r], x)\n recruit_max[r] = max(recruit_max[r], x)\n for i in range(length):\n if recruit_count[i] != 0:\n recruit_mean[i] = recruit_sum[i] / recruit_count[i]\n entbase['RECRUIT_COUNT'] = pd.Series(recruit_count, index=entbase.index)\n entbase['RECRUIT_SUM'] = pd.Series(recruit_sum, index=entbase.index)\n entbase['RECRUIT_MIN'] = pd.Series(recruit_min, index=entbase.index)\n entbase['RECRUIT_MAX'] = pd.Series(recruit_max, index=entbase.index)\n entbase['RECRUIT_MEAN'] = pd.Series(recruit_mean, index=entbase.index)\n\ndef other_features():\n length = len(entbase['EID'])\n log_zczb = np.log(np.array(entbase['ZCZB']) + 1e-5)\n entbase['LOG_ZCZB'] = pd.Series(log_zczb, index=entbase.index)\n log_mpnum = np.log(np.array(entbase['MPNUM']) + 1e-5)\n entbase['LOG_MPNUM'] = pd.Series(log_mpnum, index=entbase.index)\n log_inum = np.log(np.array(entbase['INUM']) + 1e-5)\n entbase['LOG_INUM'] = pd.Series(log_inum, index=entbase.index)\n log_finzb = np.log(np.array(entbase['FINZB']) + 1e-5)\n entbase['LOG_FINZB'] = pd.Series(log_finzb, index=entbase.index)\n log_fstinum = np.log(np.array(entbase['FSTINUM']) + 1e-5)\n entbase['LOG_FSTINUM'] = pd.Series(log_fstinum, index=entbase.index)\n log_tzinum = np.log(np.array(entbase['TZINUM']) + 1e-5)\n entbase['LOG_TZINUM'] = pd.Series(log_tzinum, index=entbase.index)\n\ncount_alter()\ncount_branch()\ncount_invest()\ncount_right()\ncount_project()\ncount_lawsuit()\ncount_breakfaith()\ncount_recruit()\nother_features()\n\ntrain_row = list(map(lambda x: row[x], train_idx))\ntrain_entbase = entbase.iloc[train_row, :]\ntest_row = list(map(lambda x: row[x], test_idx))\ntest_entbase = entbase.iloc[test_row, :]\ntrain_ds = pd.merge(train_entbase, train)\ntest_ds = test_entbase\n\ntrain_ds.to_csv('./train_ds.csv', index=False)\ntest_ds.to_csv('./test_ds.csv', index=False)\n","sub_path":"model/7/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":11280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"445981606","text":"import sys\nsys.path.append(\"..\")\nfrom MyXml import MyXml\n\nxml_file_path = r'G:\\Github_new\\python\\Work\\Common\\copy_chm_to_local_dir\\MyWork\\test\\test.xml'\n\nxml_file = MyXml(xml_file_path)\nxml_file.parser_xml()\nxml_file.change_att(\"platform\", \"taskbody\", \"ne40e\", \"ne40emm\")\ntry:\n xml_file.write()\nexcept Exception:\n print(\"write_error\")\n\n\n","sub_path":"Work/Common/copy_chm_to_local_dir/MyWork/test/testMyXml.py","file_name":"testMyXml.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"280863615","text":"import tensorflow as tf\n\n# mnist dataset is a samples from integers to floating-point numbers;\nmnist = tf.keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\n# NOTE, only user activation function \"sigmoid\" in output layer, other than that the hidden layer are useless.\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='sigmoid'),\n tf.keras.layers.Dense(10, activation='sigmoid')\n])\n\n\npredictions = model(x_train[:1]).numpy()\nloss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n\nmodel.compile(optimizer='adam',\n loss=loss_fn,\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=5, steps_per_epoch=10,)\n\nmodel.evaluate(x_test, y_test, verbose=2)\n\n# Without hidden layer\nprint(\"===========================================\")\nprint(\"WITHOUT HIDDEN LAYER \\n\")\nmodel2 = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(10, activation='sigmoid')\n])\n\n\npredictions = model2(x_train[:1]).numpy()\nloss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n\nmodel2.compile(optimizer='adam',\n loss=loss_fn,\n metrics=['accuracy'])\n\nmodel2.fit(x_train, y_train, epochs=5, steps_per_epoch=10,)\n\nmodel2.evaluate(x_test, y_test, verbose=2)\n","sub_path":"machine-learning/coursera/deep-learning-specialization/course1/exercise/2.activation_relu.py","file_name":"2.activation_relu.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"517122049","text":"import pandas as pd\nimport seaborn as sns\n\nsns.set_style(\"whitegrid\")\nsns.set_style(\"whitegrid\", {\"xtick.major.size\": 8, \"ytick.major.size\": 8})\n\ndata = pd.read_excel(r'C:\\Users\\marcinmandziej\\Desktop\\Faktury\\MGR\\charts.xlsx')\n\ndata_plot = data.melt(id_vars='Rok').rename(columns={'variable': 'Legenda',\n 'value': 'Liczba firm'})\n\nax = sns.barplot(x=\"Rok\", y=\"Liczba firm\", hue='Legenda', data=data_plot)\nax.set_xlabel('')\nax.set_ylabel('')\n","sub_path":"PRACA/MODELING/SUMMARY/charts_upadlosci.py","file_name":"charts_upadlosci.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"593059522","text":"import pandas as pd\nimport numpy as np\n\nfrom docx import Document\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\nfrom docx.enum.table import WD_ALIGN_VERTICAL\n\n\ndef get_split_df(subject_id, train_subjects, test_subjects):\n \n split_df = pd.DataFrame(columns = [subject_id, 'split'])\n split_df = split_df.set_index(subject_id)\n\n d = ['Train' for x in range(len(train_subjects))]\n d += ['Test' for x in range(len(test_subjects))]\n\n i = list(train_subjects) + list(test_subjects)\n split_df['split'] = pd.Series(data = d, index = i)\n\n return split_df\n\n\ndef filter_out_nans(dfs):\n \n no_nan_subjects = [dfs[i][~dfs[i].isna().any(axis=1)].index for i in range(len(dfs))]\n \n valid_subjects = no_nan_subjects[0]\n for i in range(1, len(dfs)):\n valid_subjects = np.intersect1d(valid_subjects, no_nan_subjects[i])\n \n dfs = [dfs[i].loc[valid_subjects] for i in range(len(dfs))]\n return dfs\n\n\ndef get_group_by(group_by, dfs, encoders, names, strat_u_name):\n \n if not isinstance(group_by, list):\n group_by = [group_by]\n \n gb_dfs = []\n gb_encoders = []\n gb_names = []\n\n for g in group_by:\n\n try:\n ind = names.index(g)\n except ValueError:\n ind = names.index(g + strat_u_name)\n\n gb_dfs.append(dfs.pop(ind))\n gb_encoders.append(encoders.pop(ind))\n gb_names.append(names.pop(ind))\n \n return gb_dfs, gb_encoders, gb_names\n\n\ndef get_all_df(df):\n \n col_name = list(df)[0]\n all_df = df[[col_name]].copy()\n all_df[col_name] = 'All'\n all_df = all_df.rename({col_name: 'All'}, axis=1)\n all_encoder = {'All': 'All'}\n\n return [all_df], [all_encoder], ['All']\n\n\ndef proc_group_by(group_by, include_all, dfs, encoders, names, strat_u_name):\n\n if group_by is not None:\n gb_dfs, gb_encoders, gb_names =\\\n get_group_by(group_by, dfs, encoders, names, strat_u_name)\n else:\n gb_dfs, gb_encoders, gb_names = [], [], []\n\n if group_by is None or include_all:\n all_df, all_encoder, all_name = get_all_df(dfs[0])\n\n gb_dfs = all_df + gb_dfs\n gb_encoders = all_encoder + gb_encoders\n gb_names = all_name + gb_names\n \n return gb_dfs, gb_encoders, gb_names\n\n\ndef get_subjects_by_group(df, encoder, name):\n \n if encoder is None:\n raise RuntimeError('Can only group by non-regression/float variables')\n \n if df.shape[1] == 1:\n subjects_by_group = [(df[name][df[name] == v]).index for v in np.unique(df)]\n \n else:\n subjects_by_group = [(df[c][df[c] == 1]).index for c in list(df)]\n \n return subjects_by_group\n\n\ndef get_base_title(display_df, name, ind, cat_show_original_name):\n \n if cat_show_original_name:\n title = display_df.loc[ind, 'Original Name']\n\n if isinstance(title, int):\n title = name + ' ' + str(title)\n elif isinstance(title, float):\n title = name + ' ' + str(int(title))\n \n elif 'int' in display_df.index.dtype.name:\n title = name + ' ' + str(ind)\n else:\n title = str(ind)\n \n return title\n\n\ndef add_c_entry(table, r, c, text, center=True):\n \n cell = table.rows[r].cells[c]\n\n if center:\n cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER\n cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER\n\n cell.paragraphs[0].text = text\n\n\ndef save_table(save_loc, gb_titles, indv_titles, gb_values,\n shape='long', heading='Data Summary', style=None,\n center=True):\n \n doc = Document()\n\n if heading is not None:\n doc.add_heading(heading)\n \n if shape == 'long':\n \n row_n, col_n = len(indv_titles)+1, len(gb_titles)+1\n table = doc.add_table(rows=row_n, cols=col_n, style=style)\n \n # Add group headers\n for c in range(1, col_n):\n add_c_entry(table, 0, c, gb_titles[c-1])\n \n # Fill in the rest of the rows\n for r in range(1, row_n):\n \n # Add row header\n add_c_entry(table, r, 0, indv_titles[r-1])\n \n # Fill in values\n for c in range(1, col_n):\n add_c_entry(table, r, c, gb_values[c-1][r-1])\n \n # Shape is wide\n else:\n row_n, col_n = len(gb_titles)+1, len(indv_titles)+1\n table = doc.add_table(rows=row_n, cols=col_n, style=style)\n \n # Add indv headers\n for c in range(1, col_n):\n add_c_entry(table, 0, c, indv_titles[c-1])\n \n # Fill in the rest of the rows\n for r in range(1, row_n):\n \n # Add row header\n add_c_entry(table, r, 0, gb_titles[r-1])\n \n # Fill in values\n for c in range(1, col_n):\n add_c_entry(table, r, c, gb_values[r-1][c-1])\n \n # Save\n doc.save(save_loc)","sub_path":"ABCD_ML/helpers/Table_Helpers.py","file_name":"Table_Helpers.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"33656325","text":"from django.views import generic\nfrom django.views import View\nfrom django.utils import timezone\nfrom django.shortcuts import render\n\n# Sequence related\nimport numpy as np\nimport pandas as pd\n\n# plotly\nfrom plotly.offline import plot\nfrom plotly.graph_objs import Scatter\nfrom plotly.tools import FigureFactory as FF\n\nimport plotly.graph_objs as go\nimport datetime\n\nclass IndexView(generic.TemplateView):\n template_name = 'chart/index.html'\n\n def get(self, request, **kwargs):\n\n ############################\n # candlestick: random number generation\n\n idx = pd.date_range('2015/01/01', '2015/12/31 23:59', freq='T')\n dn = np.random.randint(2, size=len(idx))*2-1\n rnd_walk = np.cumprod(np.exp(dn*0.0002))*100\n df = pd.Series(rnd_walk, index=idx).resample('B').ohlc()\n\n ############################\n # Moving average: random number generation\n\n d1 = datetime.date(2015,1,1)\n d1_list = []\n\n for i in range(0,365):\n temp = d1 + datetime.timedelta(i)\n d1_list.append(temp)\n\n X = np.random.randint(80,140,365)\n trace = go.Scatter(x = d1_list, y = X, mode = 'lines', name = 'Moving average line')\n trace_op = go.Scatter(x = d1_list, y = X, mode = 'lines', opacity=0.0, name = '     ')\n\n ############################\n\n # plotly configuration\n fig = FF.create_candlestick(df.open, df.high, df.low, df.close, dates=df.index)\n fig.update_layout(\n margin=dict(l=20, r=20, t=40, b=20),\n yaxis=dict(\n title = 'Stock price',\n ),\n )\n fig.add_trace(trace)\n\n fig2 = FF.create_candlestick(df.open, df.high, df.low, df.close, dates=df.index)\n fig2.update_layout(\n height=150,\n margin=dict(l=20, r=20, t=20, b=20),\n yaxis = dict(\n title = '',\n ),\n )\n fig2.add_trace(trace_op)\n\n plot_div = plot(\n fig,\n output_type='div',\n config=dict(\n displayModeBar=True,\n )\n )\n plot_div2 = plot(fig2, output_type='div', config=dict(displayModeBar=False))\n\n context = {\n 'plot_div': plot_div,\n 'plot_div2': plot_div2,\n }\n return self.render_to_response(context)\n\n\n","sub_path":"chart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"615285935","text":"import json\nimport logging\nimport re\n\nimport sqlalchemy as sa\nfrom sqlalchemy import orm\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.pool import NullPool\nfrom marshmallow import Schema, fields\nfrom werkzeug.routing import NotFound\n\nimport api\nfrom app import LambdaApp\nimport config\nfrom models import Base\n\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\nclass EventSchema(Schema):\n path = fields.String(required=True)\n method = fields.String(required=True)\n querystring = fields.Dict(required=True)\n path_params = fields.Dict(required=True)\n body = fields.Dict(required=True)\n user_arn = fields.String(required=True)\n\n\ndef main_handler(event, ctx):\n \"\"\"\n Handler to lambda invocation.\n\n Amazon API gateway gives the path without the templated variables\n subsituted. The handlers expect the raw path with the variables replaces.\n The regex in this function searches for patterns of {.*} in the path and\n replaces them with the path variables given in the event parameters.\n \"\"\"\n # Init App\n app = LambdaApp()\n api.init_app(app)\n app.config = config.get_config()\n urls = app.url_map.bind('', '/')\n\n # Setup Database\n db_uri = app.config['DATABASE_URI']\n engine = sa.create_engine(db_uri)\n logger.info(engine)\n Base.metadata.create_all(engine)\n Session = orm.sessionmaker(bind=engine)\n session = Session()\n\n try:\n event, errors = EventSchema(strict=True).load(event)\n logger.info(event)\n except Exception as e:\n logger.error(e)\n raise\n\n path = re.sub(\n r\"{(.*?)}\",\n lambda x: str(event['path_params'][x.group(1)]),\n event['path']\n )\n\n try:\n func, _ = urls.match(path, event['method'])\n except NotFound:\n logger.error(func, kwargs)\n raise\n\n handler = app.lambda_handlers.get(func)\n logger.info(handler)\n\n kwargs = {\n 'body': event['body'],\n 'parameters': event['querystring'],\n }\n\n try:\n response = handler(session, **kwargs)\n except Exception as e:\n logger.error(e)\n raise\n\n return json.dumps(response)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"180481225","text":"import numpy as np\n\ndef from_whole_brain_to_networks(connectivity_matrices, atlas_index_labels, hemi_flag=True):\n\n labels_file = open(atlas_index_labels, 'r', errors='ignore')\n labels_name = labels_file.readlines()\n labels_file.close()\n labels_networks = find_network_names(labels_name, hemi_flag)\n network_mask_dict = create_dict_of_networks_indices(labels_name, labels_networks, hemi_flag)\n if hemi_flag:\n networks_matrices, network_mask_vecs = create_networks_hemi_matrices(connectivity_matrices, network_mask_dict)\n else:\n networks_matrices, network_mask_vecs = create_networks_matrices(connectivity_matrices, network_mask_dict)\n\n return networks_matrices, network_mask_vecs\n\ndef find_network_names(labels_name, hemi_flag):\n label_networks = []\n for l in labels_name:\n label_parts = l.split('\\t')\n if hemi_flag:\n label_networks.append(label_parts[1].split('_')[2]+'_'+label_parts[1].split('_')[1])\n else:\n label_networks.append(label_parts[1].split('_')[2])\n label_networks = list(set(label_networks))\n\n return label_networks\n\ndef create_networks_hemi_matrices(connectivity_matrices, network_mask_dict):\n networks_matrices = {}\n network_mask_vecs = {}\n inter_network_mask_lh = np.zeros(connectivity_matrices.shape, dtype = bool)\n inter_network_mask_rh = np.zeros(connectivity_matrices.shape, dtype=bool)\n for network1 in network_mask_dict.keys():\n network1_name_parts = network1.split('_')\n for network2 in network_mask_dict.keys():\n network2_name_parts = network2.split('_')\n network_mask = np.zeros(connectivity_matrices.shape, dtype = bool)\n\n for r in network_mask_dict[network1]:\n for c in network_mask_dict[network2]:\n network_mask[r, c, :] = True\n if network1_name_parts[0]==network2_name_parts[0] and network1_name_parts[1]==network2_name_parts[1]:\n networks_matrices[network1] = connectivity_matrices*network_mask\n network_mask_vecs[network1] = network_mask[:,:,0].flatten()\n elif network1_name_parts[0]==network2_name_parts[0] and network1_name_parts[1]!=network2_name_parts[1]:\n networks_matrices[network1_name_parts[0]] = connectivity_matrices*network_mask\n network_mask_vecs[network1_name_parts[0]] = network_mask[:,:,0].flatten()\n elif network1_name_parts[1]==network2_name_parts[1]:\n if network1_name_parts[1] == 'LH':\n inter_network_mask_lh+=network_mask\n elif network2_name_parts[1] == 'RH':\n inter_network_mask_rh += network_mask\n\n networks_matrices['inter_network_LH'] = connectivity_matrices*inter_network_mask_lh\n network_mask_vecs['inter_network_LH'] = inter_network_mask_lh[:,:,0].flatten()\n networks_matrices['inter_network_RH'] = connectivity_matrices*inter_network_mask_rh\n network_mask_vecs['inter_network_RH'] = inter_network_mask_rh[:,:,0].flatten()\n\n return networks_matrices, network_mask_vecs\n\ndef create_networks_matrices(connectivity_matrices, network_mask_dict):\n networks_matrices = {}\n all_masks = []\n network_mask_vecs = {}\n\n for network in network_mask_dict.keys():\n network_mask = np.zeros(connectivity_matrices.shape, dtype = bool)\n for r in network_mask_dict[network]:\n for c in network_mask_dict[network]:\n network_mask[r, c, :] = True\n networks_matrices[network] = connectivity_matrices*network_mask\n network_mask_vecs[network] = network_mask[:,:,0].flatten()\n all_masks.append(network_mask)\n all_masks = np.asarray(all_masks)\n all_masks = np.sum(all_masks, axis = 0)\n not_mask = np.logical_not(all_masks)\n networks_matrices['inter_network'] = connectivity_matrices*not_mask\n network_mask_vecs['inter_network'] = not_mask[:,:,0].flatten()\n\n return networks_matrices, network_mask_vecs\n\ndef create_dict_of_networks_indices(labels_name, label_networks, hemi_flag):\n network_mask_dict = {}\n for network in label_networks:\n network_mask_dict[network] = []\n for l in labels_name:\n label_parts = l.split('\\t')\n if hemi_flag:\n network_mask_dict[label_parts[1].split('_')[2]+'_'+label_parts[1].split('_')[1]].append(int(label_parts[0]) - 1)\n else:\n network_mask_dict[label_parts[1].split('_')[2]].append(int(label_parts[0])-1)\n\n return network_mask_dict","sub_path":"yeo_sub_networks/from_wb_mat_to_subs.py","file_name":"from_wb_mat_to_subs.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"74707099","text":"\"\"\"\n\nFile: proj2b.py -- Fan Yang, May 5, 2018\n\nThis file contains an implementation of modified UCT algorithm.\n\nUCT is a Monte Carlo Tree Search algorithm that explores promising actions more frequently\nand prune out rapidly inferior options, with no action left untried.\nThe trade-off between the number of times an action a has been sampled in s and the\nvalue Q(s, a), i.e., the cost-to-go, can be tuned by adjusting the hyperparameter \"C\"\nin the following equation.\n\n Q(s, a) - C * sqrt(log(n(s))/n(s, a)\n\nThe \"main\" function takes three arguments: state, edge, walls.\n state is the current state. It should have the form ((x,y), (u,v))\n edge is the finish line. It should have the form ((x1,y1), (x2,y2))\n walls is a list of walls, each wall having the form ((x1,y1), (x2,y2))\n\n\"\"\"\nimport os\nimport math\nimport time\nimport shelve\nimport random\nfrom numpy import random as rand\nfrom itertools import product\nfrom heuristics import edist_grid\nfrom racetrack import crash\n\n#\n# \"edist\" is the 2D array returned by heuristics.edist_grid(fline, walls). It contains for\n# each position a rough estimate of the length of the shortest path to the finish line.\n#\n# \"envelope\" is a map that maps each of the visited states to the applicable actions at that\n# state. A value in \"envelop\" is itself a map that associates each of the applicable actions\n# with its information. Therefore, a key:value pair in \"envelope\" in the following form:\n#\n# {action1 : information of action1,\n# state : action2 : information of action2,\n# action3 : information of action3}\n#\n# There can be more or fewer than 3 actions for each of the states.\n#\n# The information of each action is a 4-tuple with the form of\n#\n# (times tried, cost-to-go, priority, possible child states)\n#\n# Within the above tuple, \"possible child states\" is again a map. It maps each of the child\n# states to the probability of getting to that state by taking the action.\n#\n# The data structure of \"envelope\" might be a bit overly complex, but it stores most of the\n# information we need to calculate the cost of roll-out of any visited state. With the help\n# of the information cached in \"envelope\" the program runs roughly 10~20 times faster.\n#\n# \"crash_cost\" if the cost of an action if it results in a crash. actions that don't result\n# in crashes have a cost of 1.\n#\n# \"h_max\" is the maximum depth that UCT algorithm explores\n#\n\nfline, goals, walls, edist, h_max, crash_cost, envelope = (None for i in range(7))\n\n\ndef main(s, f, w, time_limit=5):\n \"\"\"\n :param s: the starting state\n :param f: the finish line\n :param w: the walls that cannot be crossed\n :param time_limit: the maximum search time\n :return: the policy computed for state s\n\n This function is am implementation of modified UCT algorithm. Every time it computes a\n better move for state s, it prints the choice, followed by a linebreak, to a\n file called choices.txt\n \"\"\"\n t = time.time()\n\n # Calculate, or upload from the cache file, each of \"edist\", \"policy\", \"values\",\n # \"expanded\". Using cache make this algorithm run significantly faster.\n initialize(s, f, w)\n\n # action: the policy for state s, initialized to be the current velocity\n # count: the times that \"action\" has been tried\n # mark: the times that \"action\" has been tried when it is set to be the policy for s\n if s in envelope and envelope[s]:\n action = min(envelope[s], key=lambda a: envelope[s][a][1])\n count = mark = envelope[s][action][0]\n else:\n action = s[1]\n count = mark = 0\n\n open(\"choices.txt\", \"w\").write(str(action) + \"\\n\")\n\n # count - mark is the number of runs over which the policy at s has stayed the same.\n # If the policy for state s has stayed the same over the last 5000 runs, then it is\n # safe to say that the policy has become stable, thus we can terminate the loop.\n while count - mark < 5000:\n UCT(s, h_max)\n\n # \"candidates\" is a map that maps the applicable actions to their information\n candidates = envelope[s]\n\n # if the state is a dead end, just return the current velocity\n if not candidates: break\n\n # if the policy for state s has changed, print it to \"choices.txt\"\n action_new = min(candidates, key=lambda a: candidates[a][1])\n if action != action_new:\n action = action_new\n count = mark = envelope[s][action][0]\n file = open(\"choices.txt\", \"a\")\n file.write(str(action) + \"\\n\")\n file.close()\n\n # cache the data to disk periodically\n if time.time() - t > 0.9 * time_limit:\n t = time.time()\n update_cache()\n\n count += 1\n update_cache() # cache the data to disk when finish.\n return action\n\n\ndef UCT(s, h):\n \"\"\"\n :param s: the state to roll out\n :param h: the depth bound of the rollout\n :return: a tuple (cost, risk).\n\n In the returned tuple, \"cost\" is the cost of rollout without considering the risk of crashing\n into walls, and \"risk\" is the correction to \"cost\" that takes the walls into consideration.\n Cost of rollout can be computing by simply taking the sum of \"cost\" and \"risk\".\n The purpose of having these two separate values is to decrease the weight of the crashing cost\n as the rollout goes deeper. The intuition is simple: a crash that will happen next step should\n weigh more than a crash that will happen 10 steps later.\n \"\"\"\n if s in goals:\n return 0, 0\n\n if h == 0:\n return h_walldist(s), 0\n\n if s not in envelope: # s has not been explored before\n # the information for each action is (times tried, cost-to-go, priority, child states)\n actions = {action:(0, 0, -math.inf, results) for (action, results) in applicable(s).items()}\n envelope[s] = actions\n\n if not envelope[s]: # s has no applicable actions, thus is a dead end\n return h_walldist(s), crash_cost\n\n # find the action that has the highest (numerically smallest) priority\n action = choose_move(s)\n if action is None:\n return h_walldist(s), crash_cost\n\n # Randomly sample a child state. The sampled state can be \"None\", which represents a\n # crash resulted from taking the action.\n child = sample_child(s, action)\n\n if child is None:\n # \"None\" represents a crash\n cost, risk = h_walldist(s), crash_cost\n else:\n # recursively call UCT with a decremented depth bound\n cost_child = UCT(child, h - 1)\n cost, risk = 1 + cost_child[0], cost_child[1]/5\n\n cost_rollout = cost + risk\n n_all = sum([info[0] for info in envelope[s].values()])\n\n # update the information of the action\n # n, q, p, c = times tried, cost-to-go, priority, child states\n n, q, p, c = envelope[s][action]\n # q = (n * q + cost_rollout) / (n + 1)\n q = (n + 1) * q / (n + q / cost_rollout) if q > 0 else cost_rollout\n p = priority(q, n + 1, n_all + 1)\n envelope[s][action] = (n + 1, q, p, c)\n\n return cost, risk\n\n\ndef choose_move(s):\n if not envelope[s]: return None\n\n # if there is an action that has been tried fewer than 100 times, then choose that\n # action; else, choose the action that has the highest (smallest numerically) priority\n actions = envelope[s]\n under_tried = list(filter(lambda a: actions[a][0] < 100, actions))\n\n if under_tried:\n action = random.choice(under_tried)\n else:\n action = min(actions, key=lambda a: actions[a][2])\n\n if is_dead_move(s, action):\n envelope[s].pop(action)\n action = choose_move(s)\n\n return action\n\n\ndef sample_child(s, action):\n \"\"\"\n Sample a state from the child states that can be achieved by taking the action at\n state s. The probability of a child state getting sampled depends on the probabilities\n of steering errors.\n The sampled child state can be \"None\", in which case it's considered that a crash\n occurs when taking the action\n \"\"\"\n if s in envelope:\n child_states = envelope[s][action][3]\n else:\n child_states = children(s, action)\n\n states, probs = [], []\n for (state, prob) in child_states.items():\n states.append(state)\n probs.append(prob)\n states.append(None)\n probs.append(1 - sum(probs))\n return states[rand.choice(len(states), p=probs)]\n\n\ndef applicable(s):\n \"\"\"\n This function finds the applicable actions at s and associates with each of them the\n possible child states. It returns a map whose keys are the applicable actions and whose\n values are the possible results by taking the actions.\n \"\"\"\n actions = {(s[1][0] + u, s[1][1] + v) for u in [-1, 0, 1] for v in [-1, 0, 1]}\n if (0, 0) in actions:\n if (s[0], (0, 0)) in goals:\n actions = {(0, 0)}\n else:\n actions.remove((0, 0))\n\n usable = {}\n for action in actions:\n child_states = children(s, action)\n if child_states:\n usable[action] = child_states\n return usable\n\n\ndef is_dead_move(s, action):\n # Check if the action at s has no hope to result in a lawful state.\n if s in envelope:\n child_states = envelope[s][action][3]\n else:\n child_states = children(s, action)\n\n for child in child_states:\n if (child not in envelope) or (envelope[child] != {}):\n return False\n return True\n\n\ndef children(s, action):\n \"\"\"\n This function computes all of the possible child states that may be resulted from\n taking the action at state s, and it maps each of the possible child states with a\n possibility that depends on the velocity of the action.\n \"\"\"\n child_states = {}\n q = ({0:1}, {-1:0.2, 0:0.6, 1:0.2})[abs(action[0]) > 1]\n r = ({0:1}, {-1:0.2, 0:0.6, 1:0.2})[abs(action[1]) > 1]\n for e in [(e1, e2) for e1 in q for e2 in r]:\n p = tuple(map(sum, zip(s[0], action, e)))\n if not crash((s[0], p), walls):\n child_states[(p, action)] = q[e[0]] * r[e[1]]\n return child_states\n\n\ndef goal_states(f):\n # convert the finish line to a list of goal states.\n (x1, y1), (x2, y2) = f\n x = range(min(x1, x2), max(x1, x2) + 1)\n y = range(min(y1, y2), max(y1, y2) + 1)\n return {(p, (0, 0)) for p in set(product(x, y))}\n\n\ndef priority(cost_to_go, n_this, n_all):\n # In the slides the priority is calculated using the following formula\n # Q(s, a) - C * sqrt(log(n(s))/n(s, a)\n #\n # \"C\" is a constant that can be changed to control the expectation-exploration trade-off\n #\n # For reason of computational efficiency, it's approximated by\n # Q(s, a) - C * n(s)/n(s, a)\n return cost_to_go - n_all / (5 * n_this) # \"5\" may be changed to other numbers\n # return cost_to_go - 100*math.sqrt(math.log(n_all)/n_this)\n\n\ndef h_walldist(s):\n \"\"\"\n This is a lightly modified version of the provided heuristic function that approximates\n distance to the goal. It retrieves the cached values stored in edist and add an estimate\n of how long it will take to stop.\n \"\"\"\n ((x, y), (u, v)) = s\n hval = float(edist[x][y])\n\n # add a small penalty to favor short stopping distances\n au = abs(u)\n av = abs(v)\n sdu = au * (au - 1) / 2.0\n sdv = av * (av - 1) / 2.0\n sd = max(sdu, sdv)\n penalty = sd / 10.0\n\n # compute location after fastest stop, and add a penalty if it goes through a wall\n if u < 0: sdu = -sdu\n if v < 0: sdv = -sdv\n sx = x + sdu\n sy = y + sdv\n if crash([(x, y), (sx, sy)], walls):\n penalty += math.sqrt(au ** 2 + av ** 2)\n hval = max(hval + penalty, sd)\n return hval\n\n\ndef initialize(s, f, w):\n \"\"\"\n :param s: the state to start with\n :param f: the finish line\n :param w: the walls\n\n Calculate, or upload from the cache file, \"edist\" and \"envelop\".\n Using cache make this algorithm run much faster.\n\n Meanwhile, set the cost of crash to be 5 times the problem size,\n and the maximum depth bound to be one fourth of the problem size.\n \"\"\"\n global fline, goals, walls, edist, h_max, crash_cost, envelope\n fline, walls, = f, w\n goals = goal_states(f)\n crash_cost, h_max = 100, 5\n\n data_cache = shelve.open(\"cache2b\")\n if not data_cache or data_cache[\"fline\"] != fline or data_cache[\"walls\"] != walls:\n data_cache[\"fline\"] = fline\n data_cache[\"walls\"] = walls\n data_cache[\"edist\"] = edist_grid(fline, walls)\n data_cache[\"envelope\"] = {}\n\n edist = data_cache[\"edist\"]\n envelope = data_cache[\"envelope\"]\n data_cache.close()\n\n\ndef update_cache():\n # update the cached data.\n data_cache = shelve.open(\"cache\", 'n')\n data_cache[\"fline\"] = fline\n data_cache[\"walls\"] = walls\n data_cache[\"edist\"] = edist\n data_cache[\"envelope\"] = envelope\n data_cache.close()\n os.rename(\"cache.db\", \"cache2b.db\")\n","sub_path":"part2/proj2b.py","file_name":"proj2b.py","file_ext":"py","file_size_in_byte":12881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"636723187","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 ('courses', '0005_studentcourseprofile_skill_level'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='studentcourseprofile',\n name='skill_level',\n field=models.CharField(max_length=255, default='beginner', choices=[('beginner', 'Beginner'), ('intermediate', 'Intermediate'), ('advanced', 'Advanced')]),\n ),\n ]\n","sub_path":"courses/migrations/0006_auto_20151019_1127.py","file_name":"0006_auto_20151019_1127.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"127213746","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/4/20 18:33\n# @Author : Wei\n# @Email : 592190443@qq.com\n# @File : urls.py\n# @Software: PyCharm\nfrom django.urls import path,re_path\n\n\nfrom .views import CourseListView,CourseDetailView,CourseInfoView,CourseCommentView,AddCommentsView,CoursePlayView\n\n\napp_name = \"course\"\n\nurlpatterns = [\n path('list/',CourseListView.as_view(),name = 'course_list'),\n\n re_path('detail/(?P\\d+)/$', CourseDetailView.as_view(),name = 'course_detail'),#从公开课跳转到课程详情\n\n re_path('info/(?P\\d+)/$', CourseInfoView.as_view(), name='course_info'), # 从课程详情跳转到章节详情\n\n re_path('comment/(?P\\d+)/$', CourseCommentView.as_view(), name='course_comment'), # 从章节详情跳转到课程评论\n\n path('addcomment/',AddCommentsView.as_view(),name = 'add_comment'), #提交评论的ajax请求\n\n re_path('play/(?P\\d+)/$', CoursePlayView.as_view(), name='course_play'), # 从章节详情跳转视频播放\n\n]","sub_path":"mymooc/apps/course/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"327514172","text":"# -*- coding: utf-8 -*-\nfrom itertools import permutations, combinations\nfrom fractions import gcd\nfrom collections import Counter\nfrom math import sqrt\nimport sys\ninput = sys.stdin.readline\ndef lcm(x, y):\n return (x*y//gcd(x, y))\ndef small_letters():\n return [chr(i) for i in range(97, 97+26)]\ndef capital_letters():\n return [chr(i) for i in range(65, 65+26)]\ndef continual_letters(list_x):\n \"\"\"example\"\"\"\n \"\"\"[2,2,2,2,4,4,5,5,5,8,8,8,8,8] => [4,2,3,5]\"\"\"\n i,j = 0,0\n result = []\n k = len(list_x) - 1\n while(True):\n A = list_x[i]\n while(True):\n print(j)\n if list_x[j] != A:\n break\n if j >= k:\n break\n j += 1\n result.append(j-i)\n if i >= k:\n break\n i = j\n result[-1] += 1\n return result\n\n\ndef main():\n \"\"\"ここに書いてね\"\"\"\n H,A = map(int,input().split())\n print(-(-H//A))\n\nif __name__ == '__main__':\n main()\n","sub_path":"ABC/ABC153-A.py","file_name":"ABC153-A.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"225478473","text":"from django.urls import path, include\n\nfrom .views import EditalList, edital_view_adm, edital_add, edital_delete, edital_edit, \\\n inscricao_view, edital_view, \\\n pergunta_add, pergunta_edit, pergunta_delete, inscricao_do, inscricao_list_user, edital_list_adm, \\\n inscricao_view_user, edital_list_aluno, resultado_edital, inscricao_edit, inscricao_list,resultado_aluno\n\napp_name='editais'\nurlpatterns = [\n\n #----------------Edital-------------------\n path('', edital_list_adm, name='edital_list'),\n path('view/edital/', edital_view_adm, name='edital_view'),\n path('add/edital/', edital_add, name=\"edital_add\"),\n path('edit/edital/', edital_edit, name=\"edital_edit\"),\n path('delete/edital/', edital_delete, name='edital_delete'),\n\n path('alunos/edital/list/', edital_list_aluno, name='edital_list_inscri'),\n path('alunos/edital/', edital_view, name='edital_view_inscri'),\n\n path('resultado/edital/', resultado_edital, name='resultado_edital'),\n path('resultado/inscricao/aluno/', resultado_aluno, name='resultado_aluno'),\n\n #----------------Pergunta-------------------\n path('add/pergunta/', pergunta_add, name=\"pergunta_add\"),\n path('edit/pergunta/', pergunta_edit, name=\"pergunta_edit\"),\n path('delete/pergunta/', pergunta_delete, name='pergunta_delete'),\n\n\n #----------------Incrições-------------------\n path('inscricao/', inscricao_list, name='inscricao_list'),\n path('view/inscricao/', inscricao_view, name='inscricao_view'),\n path('alunos/inscricao/', inscricao_view_user, name='inscricao_view_user'),\n path('alunos/inscricao/', inscricao_list_user, name='inscricao_list_user'),\n\n\n path('inscricao/do/', inscricao_do, name='inscricao_do'),\n path('inscricao/edit/', inscricao_edit, name='inscricao_edit'),\n]","sub_path":"editais/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"445475209","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 5 23:24:57 2020\n\n@author: manelle nouar\n\"\"\"\n\n\"\"\"\nSupposons que L est un liste contenant des entiers. Ecrire une list comprehension permettant de créer une liste contenant les valeurs au carré de tous les élements impairs de L.\n\"\"\"\nLi = [ x**2 for x in L if x%2 != 0]\n\n# other\n\"\"\"\nFonction qui renvoie True si dans une phrase un mot est en doublon, False sinon ( si le mot est unique). \n\"\"\"\n\ndef f(phrase):\n\n d = { }\n x = phrase.lower.split()\n \n for i in x :\n d[i] = x.get(i,0) + 1\n\n for i in d.keys():\n if d[i] > 1 :\n return True\n \n return False\n","sub_path":"Contrôle n°1.py","file_name":"Contrôle n°1.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"646731631","text":"# -*- coding: utf-8 -*-\n\n#### 모듈을 import하는 세가지 방법\ndir() # 모듈 import 전 \n# 1. 모듈 직접 호출(권장)\nimport os\ndir() # 모듈 import 후\nos\nos.getcwd()\n# 2. 모듈에 포함된 임의의 함수 호출(프로그래밍 시 변수선언 충돌)\nfrom os import listdir\ndir()\nlistdir()\n# 3. 모듈 전체 호출\nfrom os import *\ndir()\ngetcwd()\n\n#### JSON 데이터\n# 웹 브라우저와 다른 어플리케이션이 HTTP 요청으로 데이터를 보낼 때 사용하는 파일 형식 중 하나\n# python dict와 유사, 객체의 key값은 문자열\nimport pandas as pd \nimport numpy as np\nobj = {'name': 'wes', 'places_lived': ['United States','Spain','Germany'], 'pet':np.nan,\n 'siblings':[{'name':'scott','age':25,'pet':'Zuko'},{'name':'katie','age':33,'pet':'Cisco'}]}\nimport json\nresult = json.dumps(obj) # 파이선 객체를 json 형태로 변환\nresult2 = json.loads(result) # json 형태를 python 객체로 변환, load(파일을 불러올 때)\nsiblings = pd.DataFrame(result2['siblings'],columns=['name','age','pet'])\n\n\n#### HTML yahoo_finance(웹 데이터 크롤링) \nimport requests\nfrom lxml.html import parse\nfrom io import StringIO\n\n# parsing \ntext = requests.get('http://finance.yahoo.com/q/op?s=AAPL+Options').text # Yahoo Finance사이트(AAPL, S&P 500)\nparsed = parse(StringIO(text))\ndoc = parsed.getroot() # doc객체에 모든 HTML 태그가 추출(table태그 포함)\nlinks = doc.findall('.//a') # 외부 연결 URL은 a태그로 지정, HTML 엘리먼트를 표현하는 객체일 뿐\n# 하나씩 호출\n\"\"\"\nlnk = links[27] \nlnk1 = links1[27]\nlnk.get('href') # URL과 링크 이름을 갖고올려면 각 엘리먼트에 대해 get 매서드(link의 url)를 호출\nlnk.text_content() # text 매서드를 사용해서 링크 이름 가져오기\n\"\"\"\nurls = [lnk.get('href') for lnk in doc.findall('.//a')] # html 문서에서 url목록을 가져오기\ntables = doc.findall('.//table')\ncalls = tables[0] # 옵션 만기일에 특정 상품을 정해진 가격대로 샇 수 있는 권리\nputs = tables[1] # 옵션 만기일에 특정 상품을 정해진 가격대로 팔 수 있는 권리\nrows = calls.findall('.//tr')\n\n# 셀안에 있는 텍스트 추출\ndef unpack(row, kind='td'):\n elts = row.findall('.//%s' % kind)\n return [val.text_content().strip().split('\\n')[0] for val in elts] # strip: 주어진 문자열에서 양쪽 끝 공백,'\\n' 기호 삭제, split: 텍스트간 구분자 설정\nunpack(rows[0], kind='th') # th셀 안에 헤더\nunpack(rows[2], kind='td') # td셀 안에 데이터\n\n# 웹에서 긁어온 데이터 DataFrame으로 변환\nfrom pandas.io.parsers import TextParser\ndef parse_option_data(table):\n rows = table.findall('.//tr')\n header = unpack(rows[0], kind='th')\n data = [unpack(r) for r in rows[1:]]\n return TextParser(data, names=header).get_chunk() \ncall_data = parse_option_data(calls)\nput_data = parse_option_data(puts)\n\na=pd.read_html('C:\\\\Users\\\\CYJ\\\\Desktop\\\\FUNDPRO.html') # 간단한 method\nb=pd.read_html('https://finance.naver.com/item/main.nhn?code=005930',encoding='euc-kr')\ncall_data=a[0]\nput_data=a[1]\n\n\n#### Naver에서 주식데이터 크롤링\na=pd.read_html('http://kind.krx.co.kr/corpgeneral/corpList.do?method=download&searchType=13', header=0) # 코스피, 코스탁 전종목(KRX)\na=a[0][['회사명','종목코드']]\na.종목코드=a.종목코드.map('{:06d}'.format)\na.columns=['name','code']\n# 종목별 코드로 일일 주가데이터 불러오기(url)\ndef get_url(item_name,a):\n a1 = a.query('name==\"{}\"'.format(item_name))['code'].to_string(index=False) # query(조건 설정)\n url='https://finance.naver.com/item/sise_day.nhn?code={}'.format(a1)\n print('url= {}'.format(url))\n return url\n# 종목별 일자데이터 불러오기\nitem_name=['CJ','삼성카드','카카오','넷마블']\nurl=[]\nfor i in item_name:\n url.append(get_url(i,a))\ndf=[]\nfor i in range(len(item_name)):\n df.append(pd.DataFrame())\n for j in range(1,30): # 기간설정\n pg_url = '{}&page={}'.format(url[i],j)\n df[i]=df[i].append(pd.read_html(pg_url, header=0)[0],ignore_index=True)\n df[i]=df[i].dropna() # 영업일 아닌 날짜 제거\n df[i]['수익률']=0 \n df[i]['수익률']=df[i]['종가'].pct_change()\nfor i in range(len(df)):\n df[i]=df[i].fillna('')\n df[i].columns=['DATE','CLOSE','DIFF','OPEN','HIGH','LOW','VOLUME','RETURN_PCT']\n df[i]['DATE']=pd.to_datetime(df[i]['DATE'])\n df[i]=df[i].sort_values(by='DATE').reset_index(drop=True)\n for j in range(len(df[i])):\n for k in range(len(df[i].columns)):\n if k == 0:\n df[i].iloc[j,k]=\"to_date('{}','yyyy-mm-dd hh24:mi:ss')\".format(df[i].iloc[j,0])\n else:\n df[i].iloc[j,k]=str(df[i].iloc[j,k])\n# DB table 생성 및 import \nimport cx_Oracle\ncon= cx_Oracle.connect('11834/11834@192.168.1.139:1521/FIMS2005')\ncur= con.cursor()\nfor i in range(len(item_name)):\n# cur.execute(\"DROP TABLE {} PURGE\".format(a.query('name==\"{}\"'.format(item_name[i]))['code'].to_string(index=False))\n cur.execute(\"CREATE TABLE STOCK_{} ({},{},{},{},{},{},{},{})\".format(a.query('name==\"{}\"'.format(item_name[i]))['code'].to_string(index=False), '\"{}\" DATE'.format(df[i].columns[0])\n , '\"{}\" NUMBER(8)'.format(df[i].columns[1]), '\"{}\" NUMBER(8)'.format(df[i].columns[2]), '\"{}\" NUMBER(8)'.format(df[i].columns[3]), '\"{}\" NUMBER(8)'.format(df[i].columns[4])\n , '\"{}\" NUMBER(8)'.format(df[i].columns[5]), '\"{}\" NUMBER(8)'.format(df[i].columns[6]), '\"{}\" NUMBER(20,12)'.format(df[i].columns[7])))\n cur.execute(\"COMMENT ON TABLE STOCK_{} IS '{}'\".format(a.query('name==\"{}\"'.format(item_name[i]))['code'].to_string(index=False),item_name[i]))\n for j in range(len(df[i])):\n cur.execute(\"INSERT INTO {} VALUES {}\".format('STOCK_{}'.format(a.query('name==\"{}\"'.format(item_name[i]))['code'].to_string(index=False)),tuple(df[i].iloc[j])).replace(\"\\\"\",\"\"))\ncon.commit()\ncon.close()\ncur.close()\n\n\n#### XML 파싱\n# 예제(완성도 떨어짐)\nfrom lxml import objectify\npath = 'C:\\\\Users\\\\CYJ\\\\Desktop\\\\Test\\\\Performance_XML_Data\\\\Performance_LIBUS.xml' # 파일 경로\nroot = objectify.parse(open(path)).getroot()\n\ndata=[]\nskip_fields=['INDICATOR_SEQ','PARENT_SEQ','DESIRED_CHANGE','DECIMAL_PLACES','INDICATOR_UNIT']\nfor i in root.INDICATOR:\n datas={}\n for j in i.getchildren(): # 각 INDICATOR의 XML데이터 \n if j.tag in skip_fields:\n continue\n else:\n datas[j]= j.pyval\n data.append(datas)\n\n## 샘플데이터\nimport xml.etree.ElementTree as elemTree\n# path = 'C:\\\\Users\\\\CYJ\\\\Desktop\\\\Test\\\\Performance_XML_Data\\\\Performance_LIBUS.xml' # 파일 경로\npath = '//192.168.233.101/default_utils/Study/#조용진/Performance_LIBUS.xml'\ntree = elemTree.parse(path).getroot()\ntree2 = tree.findall('./INDICATOR')\n# XML문서 칼럼명\na=[]\nfor i in range(len(tree2[0].getchildren())):\n a.append(tree2[0].getchildren()[i].tag) # tag: 부모인자\n# XML문서 데이터 \ndata=[]\nfor i in range(len(tree2)):\n datas=[]\n for j in range(len(tree2[i].getchildren())):\n if tree2[i][j].text == None:\n tree2[i][j].text=''\n datas.append(tree2[i][j].text)\n else:\n datas.append(tree2[i][j].text)\n data.append(datas)\ndf=pd.DataFrame(data,columns=a)\n\n\n## 엑셀로 저장 후 불러오기\n# XML파일 엑셀 시트에 끌어오기(수동으로)\ndf2=pd.read_excel('C:/Users/CYJ/Desktop/Test/Performance_XML_Data/Performance_LIBUS.xlsx')\ndf2=df2.fillna('')\ndf==df2\n","sub_path":"Python Script/loading.py","file_name":"loading.py","file_ext":"py","file_size_in_byte":7533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"65181354","text":"#------------------------------------------------------------------------------\n# query.py - Database query module\n#\n# November 2015, Phil Connell\n#------------------------------------------------------------------------------\n\n\"\"\"Target query functions.\"\"\"\n\n__all__ = (\n \"deps\",\n \"dep_chains\",\n \"all_deps_bf\",\n \"all_deps_df\",\n)\n\n\nimport collections\n\n\ndef deps(target):\n \"\"\"\n Iterator that yields immediate dependencies of a target.\n\n This function:\n\n - Takes account of Jam 'includes' as well as dependencies.\n - Won't yield the same target more than once.\n\n \"\"\"\n yield from target.deps\n # If X includes Y, all dependencies of Y are dependencies of X. Also need\n # to remove duplicates.\n seen = set(target.deps)\n inc_deps = (dep\n for inc in target.incs\n for dep in inc.deps)\n for dep in inc_deps:\n if dep not in seen:\n seen.add(dep)\n yield dep\n\n\ndef deps_rebuilt(target):\n \"\"\"\n Iterator that yields immediate rebuilt dependencies of a target.\n \"\"\"\n for dep in deps(target):\n if dep.rebuilt:\n yield dep\n\n\ndef dep_chains(target, *, max_depth=0, include_target=None):\n \"\"\"\n Iterator that yields dependency chains for a target.\n\n In each list:\n\n - The first target is the given target.\n - The target at index N depends on the target at index N + 1.\n - The final target doesn't depend on anything.\n\n The order that chains are produced in is arbitrary.\n\n :param max_depth:\n Terminate all chains at this depth, rather than going as deep as\n possible.\n\n :param include_target:\n Function to determine whether chains including a particular output may\n be included in this function's output.\n\n This is passed a target and should return a bool:\n\n - True indicates that chains involving the target *may* be returned.\n - False indicates that chains involving the target *must not* be\n returned.\n\n \"\"\"\n chains = []\n chains.append([target])\n while chains:\n extended_chains = []\n for chain in chains:\n next_deps = list(deps(chain[-1]))\n if not next_deps or (max_depth and len(chain) == max_depth):\n yield chain\n else:\n extended_chains.extend(\n chain + [dep]\n for dep in deps(chain[-1])\n if include_target is None or include_target(dep))\n chains = extended_chains\n\n\ndef dep_chains_rebuilt(target):\n \"\"\"Iterator that yields dependency chains that have (all) been rebuilt.\"\"\"\n yield from dep_chains(target, include_target=lambda target: target.rebuilt)\n\n\ndef rebuild_chains(target):\n \"\"\"\n Return the chains of targets that caused a given target to be rebuilt.\n \"\"\"\n chains = [_basic_rebuild_chain(target)]\n while True:\n extended_chains = []\n for chain in chains:\n for dep in deps_rebuilt(chain[-1]):\n extended_chains.append(chain + _basic_rebuild_chain(dep))\n if extended_chains:\n chains = extended_chains\n else:\n break\n return chains\n\n\ndef _basic_rebuild_chain(target):\n \"\"\"\n Get a rebuild chain based purely on 'rebuild info' from Jam.\n \"\"\"\n chain = [target]\n current = target\n while True:\n current = current.rebuild_info.dep\n if current is None:\n break\n else:\n chain.append(current)\n return chain\n\n\ndef all_deps_bf(target):\n \"\"\"\n Iterator that yields all dependencies of a target, breadth-first.\n\n This function may yield the same target more than once.\n\n \"\"\"\n queue = collections.deque()\n queue.extend(deps(target))\n while queue:\n current = queue.popleft()\n yield current\n queue.extend(deps(current))\n\n\ndef all_deps_df(target):\n \"\"\"\n Iterator that yields all dependencies of a target, depth-first.\n\n This function may yield the same target more than once.\n\n \"\"\"\n stack = []\n # Make sure we'll yield dependencies in Jam definition order!\n rev_deps = lambda target: reversed(list(deps(target)))\n stack.extend(rev_deps(target))\n while stack:\n current = stack.pop()\n yield current\n stack.extend(rev_deps(current))\n\n","sub_path":"jamjar/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"79776184","text":"import os\nimport csv\n\n#link to the csv data file for pybank project\npybank_csv = os.path.join(\"Resources\", \"budget_data.csv\")\n\n#set the initial row count to 0 to determine the total number of months\nmonth_count = 0\n#set the initial value for total profits\ntotal_profits = 0\n#array for the values of the profits/losses column\nprofits_and_losses = []\n#array for the changes in profits and Losses\nchange_in_profits = []\n\n#open csv data file for pybank project and make it readable\nwith open (pybank_csv, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n #pulls header row out\n csv_header = next(csvreader)\n #for each row in the csv file\n for row in csvreader:\n #adds one to the row count for each row\n month_count += 1\n #adds the profits/losses to previous total\n total_profits += int(row[1])\n #appends each value in the profits/losses column to the profits_and_losses array\n profits_and_losses.append(row[1])\n\n#creating amended lists of profits_and losses - one without the first value and one without the last value to zip and calculate the change in profits\nprofits_and_losses_no_first = profits_and_losses[1:]\nprofits_and_losses_no_last = profits_and_losses[:-1]\n\n#zip the new profits_and_losses lists together to form one list - and converting it to proper form\nnew_profits_and_losses = list(zip(profits_and_losses_no_last, profits_and_losses_no_first))\n\n#goes through the new_profits_and losses list\nfor set in new_profits_and_losses:\n #calculates the change between the values stored in each list item\n change = int(set[1]) - int(set[0])\n #adds the new value to the change in profits list\n change_in_profits.append(int(change))\n\n#takes the change_in profits list\nfor change in change_in_profits:\n #set a starting variable to hold the sum of all the changes\n sum_of_changes = 0\n #add each value together\n sum_of_changes += int(change)\n #divide the sum by the length on the change_in_profits list to find the average change\n avg_change = sum_of_changes / len(change_in_profits)\n\n#sorting the change_in_profits list\nsorted_change_in_profits = sorted(change_in_profits)\n\n#defining the greatest increase and decrease in profits using the sorted_change_in_profits list\ngreatest_increase = sorted_change_in_profits[-1]\ngreatest_decrease = sorted_change_in_profits[0]\n\n#searching the original change_in_profits for the index of the changes\nfor change in change_in_profits:\n if change == greatest_increase:\n #saves the index to a new variable\n index_greatest_increase = change_in_profits.index(change)\n elif change == greatest_decrease:\n #saves the index to a new variable\n index_greatest_decrease = change_in_profits.index(change)\n\n#change_in_profits is the same length as new_profits_and_losses - so the indicies are the same\n#finding the pair in new_profits_and_losses that matches the index of greatest_increase and greatest_decrease\nvalue_after_greatest_increase = new_profits_and_losses[index_greatest_increase][1]\nvalue_after_greatest_decrease = new_profits_and_losses[index_greatest_decrease][1]\n\n#going through the csv file to pull the change information\nwith open (pybank_csv, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n #pulls header row out\n csv_header = next(csvreader)\n #for each row in the csv file\n for row in csvreader:\n #looks for the value in the second column that matches the value after greatest_increase\n if row[1] == value_after_greatest_increase:\n #saves the row's date value to a variable\n date_greatest_increase = row[0]\n #looks for the value in the second column that matches the value after greatest_decrease\n elif row[1] == value_after_greatest_decrease:\n #saves the row's date value to a variable\n date_greatest_decrease = row[0]\n\nprint(\"Financial Analysis\")\nprint(\"-------------------------------\")\n#print total months as rows\nprint(f\"Total Months: {month_count}\")\n#prints the net profits\nprint(f\"Total: ${total_profits}\")\n#prints the average change in profits/Losses, rounded to 2 decimal places (since we're dealing with money)\nprint(f\"Average Change: ${round(avg_change, 2)}\")\n#prints the greatest increase in profits\nprint(f\"Greatest Increase in Profits: {date_greatest_increase} (${greatest_increase})\")\n#prints the greatest decrease in profits\nprint(f\"Greatest Decrease in Profits: {date_greatest_decrease} (${greatest_decrease})\")\n\n#writing the results to a txt file\nwith open ('Analysis\\pybank_results.txt', 'w') as txtfile:\n txtfile.write(\n \"Financial Analysis\\n\"\n \"-------------------------------\\n\"\n f\"Total Months: {month_count}\\n\"\n f\"Total: ${total_profits}\\n\"\n f\"Average Change: ${round(avg_change, 2)}\\n\"\n f\"Greatest Increase in Profits: {date_greatest_increase} (${greatest_increase})\\n\"\n f\"Greatest Decrease in Profits: {date_greatest_decrease} (${greatest_decrease})\\n\")\n","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"499643260","text":"import time\n\nfrom nio.modules.threading import sleep\nfrom nio.util.support.block_test_case import NIOBlockTestCase\nfrom nio.modules.scheduler import SchedulerModule\nfrom nio.common.signal.base import Signal\n\nfrom ..write_gpio_block import WriteGPIO, PinMode, IN, OUT\n\ndef make_value(value, num=1):\n return [Signal({\"value\": value}) for _ in range(num)]\n\nTHREADTIME = 0.05 # It takes some amount of time for the thread to actually wiggle the pin\n\nclass TestGpioWriteBlock(NIOBlockTestCase):\n def signals_notified(self, signals):\n self._signals = signals\n\n def test_gpio_write(self):\n \"\"\"wARNING: Uses pin 22 -- make sure it is clear of devices that can harm it or be harmed by it\"\"\"\n notified = 0\n\n gpio = WriteGPIO()\n config = {\n \"pins\": [{\n \"number\": 22,\n \"actuator\": \"{{$value}}\",\n \"mode\": PinMode.No,\n \"initial\": False\n }]\n }\n\n self.configure_block(gpio, config)\n gpio.start()\n time.sleep(THREADTIME)\n pin = gpio.gpio_pins[0][1]\n self.assertEqual(pin._mode, OUT)\n\n # Value should be low\n self.assertEqual(pin.read(), False)\n self.assertEqual(pin._value, False)\n\n # Value should be high\n gpio.process_signals(make_value(1))\n time.sleep(THREADTIME)\n self.assertEqual(pin.read(), True)\n self.assertEqual(pin._value, True)\n\n # Value should be low\n gpio.process_signals(make_value(0))\n time.sleep(THREADTIME)\n self.assertEqual(pin._value, False)\n self.assertEqual(pin.read(), False)\n\n gpio.stop()\n\n ## Test initial value\n gpio = WriteGPIO()\n config[\"pins\"][0][\"initial\"] = True\n self.configure_block(gpio, config)\n gpio.start()\n time.sleep(THREADTIME)\n pin = gpio.gpio_pins[0][1]\n self.assertEqual(pin._mode, OUT)\n\n # Value should be high\n self.assertEqual(pin._value, True)\n self.assertEqual(pin.read(), True)\n\n # Value should be low\n gpio.process_signals(make_value(0))\n time.sleep(THREADTIME)\n self.assertEqual(pin._value, False)\n self.assertEqual(pin.read(), False)\n\n gpio.stop()\n\n ## Test pullup / down resistors\n gpio = WriteGPIO()\n config[\"pins\"][0][\"mode\"] = PinMode.Internal\n self.configure_block(gpio, config)\n gpio.start()\n time.sleep(THREADTIME)\n pin = gpio.gpio_pins[0][1]\n self.assertEqual(pin._mode, IN)\n\n # Value should be high\n self.assertEqual(pin._value, True)\n self.assertEqual(pin.read(), True)\n\n # Value should be low\n gpio.process_signals(make_value(0))\n time.sleep(THREADTIME)\n self.assertEqual(pin._value, False)\n self.assertEqual(pin.read(), False)\n\n","sub_path":"write/tests/test_write_gpio_block.py","file_name":"test_write_gpio_block.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"610916659","text":"# -*_ coding:utf-8 -*-\r\n\r\n\r\nimport sys, socket, threading, time\r\n\r\n\r\n# A simple UDP echo server\r\ndef udp_server(port):\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n s.bind(('localhost', port))\r\n print('Server socket UDP is listening on ', s.getsockname())\r\n while True:\r\n data, addr = s.recvfrom(1024)\r\n print('Receive from %s:%s'%addr)\r\n s.sendto(b'Hello, %s!'%data, addr)\r\n\r\n\r\ndef udp_client(id, host, port):\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n for data in [b'Micheal', b'Isaac', b'Sarah']:\r\n s.sendto(data, ('localhost', 9999))\r\n print(s.recv(1024).decode('utf-8'))\r\n s.close()\r\n print('Client %d exit!'%id)\r\n\r\nif __name__ == '__main__':\r\n args = sys.argv\r\n if len(args) == 2 and args[1] == 'client':\r\n clients = []\r\n for i in range(5):\r\n t = threading.Thread(target=udp_client, args=(i, 'localhost', 9999))\r\n t.start()\r\n clients.append(t)\r\n print('All thread started.')\r\n else:\r\n udp_server(9999)\r\n","sub_path":"bin/use_socket_udp.py","file_name":"use_socket_udp.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"252111074","text":"import hashlib\nimport itertools\nimport os\nimport re\nimport sys\nfrom datetime import datetime, timedelta\nfrom enum import Enum\nfrom types import SimpleNamespace\nfrom typing import List, Union, Dict, Any, Optional, Tuple\n\nimport yaml\nfrom croniter import croniter\nfrom dataclasses import dataclass\nfrom dateutil.parser import parse\nfrom pydantic import BaseModel, validator, Field, root_validator\n\nfrom typhoon.core.cron_utils import aws_schedule_to_cron\nfrom typhoon.core.settings import Settings\n\nIDENTIFIER_REGEX = r'\\w+'\nIdentifier = Field(..., regex=r'\\w+')\n\n\n@dataclass\nclass Py:\n value: str\n key: Optional[str] = None\n args_dependencies: Optional[List[str]] = None\n\n def transpile(self) -> str:\n code = self.value\n code = code.replace('$BATCH_NUM', 'batch_num')\n code = code.replace('$BATCH', 'batch')\n code = re.sub(r'\\$DAG_CONTEXT(\\.(\\w+))', r'dag_context.\\g<2>', code)\n code = code.replace('$DAG_CONTEXT', 'dag_context')\n if self.key is not None:\n code = re.sub(r'\\$(\\d)+', r\"{key}_\\g<1>\".format(key=self.key), code)\n code = re.sub(r'\\$HOOK(\\.(\\w+))', r'get_hook(\"\\g<2>\")', code)\n code = re.sub(r'\\$VARIABLE(\\.(\\w+))', r'Settings.metadata_store().get_variable(\"\\g<2>\").get_contents()', code)\n code = re.sub(r'typhoon\\.(\\w+\\.\\w+)', r'typhoon_transformations.\\g<1>', code)\n return code\n\n @staticmethod\n def construct(loader: yaml.Loader, node: yaml.Node):\n return construct_custom_class(Py, loader, node)\n\n @classmethod\n def __get_validators__(cls):\n yield cls.validate\n\n @classmethod\n def validate(cls, v):\n if not isinstance(v, Py):\n raise TypeError(f'Expected Py object, found {v}')\n if not isinstance(v.value, str):\n raise TypeError(f'string required, found {v.value}')\n return v\n\n def __str__(self):\n \"\"\"If a key is set, unquoted string. Otherwise print Py(...)\"\"\"\n return self.transpile()\n\n def __repr__(self):\n return str(self)\n\n\ndef construct_custom_class(cls, loader: yaml.Loader, node: yaml.Node):\n result = cls.__new__(cls)\n yield result\n if isinstance(node, yaml.ScalarNode):\n value = loader.construct_scalar(node)\n elif isinstance(node, yaml.SequenceNode):\n value = loader.construct_sequence(node)\n elif isinstance(node, yaml.MappingNode):\n value = loader.construct_mapping(node)\n else:\n assert False\n result.__init__(value)\n\n\ndef construct_hook(loader: yaml.Loader, node: yaml.Node) -> Py:\n conn_name = loader.construct_yaml_str(node)\n if not re.match(r'\\w+', conn_name):\n raise ValueError(f'Error constructing hook. Expected connection name, found {conn_name}')\n return Py(f'$HOOK.{conn_name}')\n\n\ndef construct_variable(loader: yaml.Loader, node: yaml.Node) -> Py:\n var_id = loader.construct_yaml_str(node)\n if not re.match(r'\\w+', var_id):\n raise ValueError(f'Error constructing variable. Expected variable id, found {var_id}')\n return Py(f'$VARIABLE.{var_id}')\n\n\n@dataclass\nclass MultiStep:\n value: list\n key: Optional[str] = None\n config_name: str = 'config'\n\n @staticmethod\n def construct(loader: yaml.Loader, node: yaml.Node):\n return construct_custom_class(MultiStep, loader, node)\n\n @classmethod\n def __get_validators__(cls):\n yield cls.validate\n\n @classmethod\n def validate(cls, v):\n if not isinstance(v, MultiStep):\n raise TypeError(f'Expected MultiStep object, found {v}')\n if not isinstance(v.value, list):\n raise TypeError(f'list required, found {v.value}')\n return v\n\n def transpile(self) -> str:\n def add_key(item):\n if isinstance(item, Py):\n item.key = self.key\n elif isinstance(item, list):\n return [add_key(x) for x in item]\n elif isinstance(item, dict):\n return {k: add_key(v) for k, v in item.items()}\n else:\n return item\n steps = []\n for i, x in enumerate(self.value):\n add_key(x)\n steps.append(f'{self.key}_{i + 1} = {x}')\n return '\\n'.join(steps) + '\\n' + f\"{self.config_name}['{self.key}'] = {self.key}_{len(steps)}\"\n\n def __str__(self):\n if not isinstance(self.value, list) or self.key is None:\n return f'MultiStep({self.value.__repr__()})'\n else:\n return self.transpile()\n\n def __repr__(self):\n return str(self)\n\n\nItem = Union[int, str, float, Dict, List, Py, MultiStep]\n\n\nclass SpecialCronString(str, Enum):\n daily = '@daily'\n weekly = '@weekly'\n monthly = '@monthly'\n yearly = '@yearly'\n\n\nclass Node(BaseModel):\n function: str = Field(\n ...,\n regex=r'(typhoon\\.\\w+\\.\\w+|functions\\.\\w+\\.\\w+)',\n description=\"\"\"Python function that will get called when the node runs.\n If it is a built-in typhoon function it will have the following structure:\n typhoon.[MODULE_NAME].[FUNCTION_NAME]\n Whereas if it is a user defined function it will have the following structure:\n functions.[MODULE_NAME].[FUNCTION_NAME]\"\"\"\n )\n asynchronous: bool = Field(\n True,\n description=\"\"\"If set to TRUE it will run the function in a different lambda instance.\n This is useful when you want to increase parallelism. There is currently no framework cap on\n parallelism though so if that is an issue set it to FALSE so it will run the batches one by one.\"\"\"\n )\n config: Dict[str, Any] = Field(default={})\n\n @validator('config')\n def validate_config_keys(cls, v):\n for k in v.keys():\n if not re.match(r'\\w+(\\s*=>\\s*APPLY)?', k):\n raise ValueError(f'Config key \"{k}\" does not match pattern. Must be identifier with optional => APPLY')\n return v\n\n\nclass Edge(BaseModel):\n source: str = Field(..., regex=IDENTIFIER_REGEX, description='ID of source node')\n adapter: Dict[str, Item] = Field(\n ...,\n description='Adapts the output of the source node to the input of the destination node'\n )\n destination: str = Field(..., regex=IDENTIFIER_REGEX, description='ID of destination node')\n args_dict_name: Optional[str] = Field(default=None)\n component_args: Dict[str, Any] = Field(default={})\n\n @validator('adapter')\n def validate_adapter_keys(cls, v):\n for k in v.keys():\n if not re.match(r'\\w+(\\s*=>\\s*APPLY)?', k):\n raise ValueError(f'Config key \"{k}\" does not match pattern. Must be identifier with optional => APPLY')\n return v\n\n\nclass Granularity(str, Enum):\n YEAR = 'year'\n MONTH = 'month'\n DAY = 'day'\n HOUR = 'hour'\n MINUTE = 'minute'\n SECOND = 'second'\n\n\nclass DAG(BaseModel):\n name: str = Field(..., regex=IDENTIFIER_REGEX, description='Name of your DAG')\n schedule_interval: str = Field(\n ...,\n regex='(' + '@hourly|@daily|@weekly|@monthly|@yearly|' +\n r'((\\*|\\?|\\d+((\\/|\\-){0,1}(\\d+))*)\\s*){5,6}' + '|' +\n r'rate\\(\\s*1\\s+minute\\s*\\)' + '|' +\n r'rate\\(\\s*\\d+\\s+minutes\\s*\\)' + '|' +\n r'rate\\(\\s1*\\d+\\s+hour\\s*\\)' + '|' +\n r'rate\\(\\s*\\d+\\s+hours\\s*\\)' + '|' +\n ')',\n description='Schedule or frequency on which the DAG should run'\n )\n granularity: Granularity = Field(default=Granularity.DAY, description='Granularity of DAG')\n nodes: Dict[str, Node]\n edges: Dict[str, Edge]\n active: bool = Field(True, description='Whether to deploy the DAG or not')\n\n @root_validator\n def validate_undefined_nodes_in_edges(cls, values):\n if 'nodes' not in values.keys() or 'edges' not in values.keys():\n return values # Nodes did not pass upstream validations\n node_names = values['nodes'].keys()\n for edge_name, edge in values['edges'].items():\n if edge.source not in node_names:\n raise ValueError(f'Source for edge \"{edge_name}\" is not defined: \"{edge.source}\"')\n if edge.destination not in node_names:\n raise ValueError(f'Destination for edge \"{edge_name}\" is not defined: \"{edge.destination}\"')\n return values\n\n @property\n def structure(self) -> Dict[str, List[str]]:\n \"\"\"For every node all the nodes it's connected to\"\"\"\n structure = {}\n for _, edge in self.edges.items():\n if edge.source not in structure.keys():\n structure[edge.source] = [edge.destination]\n else:\n structure[edge.source].append(edge.destination)\n\n return structure\n\n @property\n def non_source_nodes(self) -> List[str]:\n \"\"\"All nodes that are the destination of an edge\"\"\"\n return [node for x in self.structure.values() for node in x]\n\n @property\n def sources(self) -> List[str]:\n \"\"\"Nodes that are sources of the DAG\"\"\"\n sources = set(self.structure.keys())\n destinations = set(self.non_source_nodes)\n return list(sources.difference(destinations))\n\n def get_edge(self, source: str, destination: str) -> Edge:\n for edge_name, edge in self.edges.items():\n if edge.source == source and edge.destination == destination:\n return edge\n assert False\n\n def get_edge_name(self, source: str, destination: str) -> str:\n for edge_name, edge in self.edges.items():\n if edge.source == source and edge.destination == destination:\n return edge_name\n assert False\n\n def get_edges_for_source(self, source: str) -> List[str]:\n return [edge_name for edge_name, edge in self.edges.items() if edge.source == source]\n\n def out_nodes(self, source: str) -> List[str]:\n return self.structure.get(source, ())\n\n @property\n def has_cycle(self):\n white, gray, black = 0, 1, 2\n color = {n: white for n in self.nodes.keys()}\n\n def dfs(node):\n color[node] = gray\n for dest in self.structure.get(node, []):\n if color[dest] == gray:\n return True\n elif color[dest] == white and dfs(dest):\n return True\n color[node] = black\n return False\n\n for n in self.nodes:\n if color[n] == white and dfs(n):\n return True\n return False\n\n\nclass DagContext(BaseModel):\n interval_start: datetime = Field(\n ..., description='Date representing the start of the interval for which we want to get data')\n interval_end: datetime = Field(\n ..., description='Date representing the end of the interval for which we want to get data')\n execution_time: datetime = Field(default_factory=lambda: datetime.now(), description='Date')\n granularity: Granularity = Field(default='daily', description='Granularity of DAG')\n\n def __init__(self, **data):\n super().__init__(**data)\n granularity = self.granularity\n if granularity == 'minute':\n self.interval_start = self.interval_start.replace(second=0, microsecond=0)\n self.interval_end = self.interval_end.replace(second=0, microsecond=0)\n elif granularity == 'hour':\n self.interval_start = self.interval_start.replace(minute=0, second=0, microsecond=0)\n self.interval_end = self.interval_end.replace(minute=0, second=0, microsecond=0)\n elif granularity == 'day':\n self.interval_start = self.interval_start.replace(hour=0, minute=0, second=0, microsecond=0)\n self.interval_end = self.interval_end.replace(hour=0, minute=0, second=0, microsecond=0)\n elif granularity == 'month':\n self.interval_start = self.interval_start.replace(day=0, hour=0, minute=0, second=0, microsecond=0)\n self.interval_end = self.interval_end.replace(day=0, hour=0, minute=0, second=0, microsecond=0)\n elif granularity == 'year':\n self.interval_start = self.interval_start.replace(month=0, day=0, hour=0, minute=0, second=0, microsecond=0)\n self.interval_end = self.interval_end.replace(month=0, day=0, hour=0, minute=0, second=0, microsecond=0)\n\n @staticmethod\n def from_cron_and_event_time(\n schedule_interval: str,\n event_time: Union[datetime, str],\n granularity: str,\n ) -> 'DagContext':\n if not isinstance(event_time, datetime):\n event_time = parse(event_time)\n cron = aws_schedule_to_cron(schedule_interval)\n iterator = croniter(cron, event_time + timedelta(seconds=1)) # In case the event is exactly on time\n interval_end = iterator.get_prev(datetime)\n interval_start = iterator.get_prev(datetime)\n return DagContext(interval_start=interval_start, interval_end=interval_end, granularity=granularity)\n\n\ndef hash_dag_code(dag_code: str) -> str:\n m = hashlib.sha1()\n m.update(dag_code.encode())\n return m.hexdigest()\n\n\nclass DagDeployment(BaseModel):\n dag_name: str\n deployment_date: datetime\n dag_code: str\n\n @property\n def deployment_hash(self) -> str:\n return hash_dag_code(self.dag_code)\n\n\nclass TestCase(BaseModel):\n batch: Any = Field(..., description='Sample batch')\n expected: Dict[str, Any] = Field(..., description='Expected result')\n batch_num: int = Field(\n default=1,\n description='Batch number for the test. If more than one is provided it will run the tests for each')\n interval_start: datetime = Field(\n ..., description='Date representing the start of the interval for which we want to get data')\n interval_end: datetime = Field(\n ..., description='Date representing the end of the interval for which we want to get data')\n\n @property\n def dag_context(self) -> DagContext:\n interval_start = self.interval_start or datetime.now()\n return DagContext(\n interval_start=interval_start,\n interval_end=interval_end or (interval_start - timedelta(days=1))\n )\n\n @property\n def custom_locals(self) -> dict:\n result = {}\n try:\n import pandas as pd\n result['pd'] = pd\n except ImportError:\n print('Warning: could not import pandas. Run pip install pandas if you want to use dataframes')\n return result\n\n @property\n def evaluated_batch(self):\n return evaluate_item(self.custom_locals, self.batch)\n\n @property\n def evaluated_expected(self):\n result = {}\n for k, v in self.expected.items():\n result[k] = evaluate_item(self.custom_locals, v)\n return result\n\n\ndef construct_python_object(loader: yaml.Loader, node: yaml.Node) -> SimpleNamespace:\n result = SimpleNamespace.__new__(SimpleNamespace)\n yield result\n attributes = loader.construct_mapping(node)\n if not isinstance(attributes, dict):\n raise ValueError(f'Error constructing PyObj. Expected dictionary, found {attributes}')\n result.__init__(**attributes)\n\n\n@dataclass\nclass DataFrameFuture:\n data: Union[List[dict], Dict[str, list]]\n\n\ndef construct_dataframe(loader: yaml.Loader, node: yaml.Node):\n result = DataFrameFuture.__new__(DataFrameFuture)\n yield result\n if isinstance(node, yaml.SequenceNode):\n data = loader.construct_sequence(node)\n elif isinstance(node, yaml.MappingNode):\n data = loader.construct_mapping(node)\n else:\n raise ValueError(f'Error constructing DataFrame. Expected dictionary or array of dictionaries, found {type(node)}')\n result.__init__(data)\n\n\ndef construct_template(loader: yaml.Loader, node: yaml.Node):\n template_str = loader.construct_yaml_str(node)\n return Py(f\"jinja2.Template('{template_str}')\")\n\n\ndef add_yaml_constructors():\n yaml.add_constructor('!Py', Py.construct)\n yaml.add_constructor('!Hook', construct_hook)\n yaml.add_constructor('!Var', construct_variable)\n yaml.add_constructor('!MultiStep', MultiStep.construct)\n yaml.add_constructor('!PyObj', construct_python_object)\n yaml.add_constructor('!DataFrame', construct_dataframe)\n yaml.add_constructor('!Template', construct_template)\n\n\ndef get_deps_uses_batch_and_warnings(item):\n deps = []\n warnings = []\n\n def _uses_batch(item):\n if isinstance(item, Py):\n nonlocal deps\n if item.args_dependencies:\n deps += item.args_dependencies\n return '$BATCH' in item.value\n if isinstance(item, MultiStep):\n return _uses_batch(item.value)\n elif isinstance(item, list):\n items_use_batch = [_uses_batch(x) for x in item]\n return any(items_use_batch)\n elif isinstance(item, dict):\n items_use_batch = [_uses_batch(v) for k, v in item.items()]\n return any(items_use_batch)\n elif isinstance(item, str):\n for x in ['$BATCH', '$DAG_CONTEXT', '$VARIABLE', '$HOOK', '$ARG']:\n if x in item:\n warnings.append('WARNING: Argument {arg} is a string and contains' + f' \"{x}\". Did you mean to make it !Py?')\n return False\n elif isinstance(item, (float, int)):\n return False\n assert False, f'Found type {type(item)} with value {item}'\n arg_uses_batch = _uses_batch(item)\n return deps, arg_uses_batch, warnings\n\n\nclass TaskDefinition(BaseModel):\n input: Union[str, List[str], None] = Field(\n default=None,\n description='Task or tasks that will send their output as input to the current node'\n )\n function: Optional[str] = Field(\n default=None,\n regex=r'(typhoon\\.\\w+\\.\\w+|functions\\.\\w+\\.\\w+)',\n description=\"\"\"Python function that will get called when the task runs.\n If it is a built-in typhoon function it will have the following structure:\n typhoon.[MODULE_NAME].[FUNCTION_NAME]\n Whereas if it is a user defined function it will have the following structure:\n functions.[MODULE_NAME].[FUNCTION_NAME]\"\"\"\n )\n component: Optional[str] = Field(\n default=None,\n regex=r'(typhoon\\.\\w+|components\\.\\w+)',\n description=\"\"\"Typhoon component that will get substituted for its tasks.\n If it is a built-in typhoon component it will have the following structure:\n typhoon.[COMPONENT_NAME]\n Whereas if it is a user defined component it will have the following structure:\n components.[COMPONENT_NAME]\"\"\"\n )\n asynchronous: bool = Field(\n default=True,\n description=\"\"\"If set to TRUE it will run the function in a different lambda instance.\n This is useful when you want to increase parallelism. There is currently no framework cap on\n parallelism though so if that is an issue set it to FALSE so it will run the batches one by one.\"\"\"\n )\n args: Dict[str, Any] = Field(default={})\n\n @validator('args')\n def validate_args_keys(cls, val):\n # Decorate MultiStep with key name if necessary\n for k, v in val.items():\n if not re.fullmatch(IDENTIFIER_REGEX, k):\n raise ValueError(f'Arg \"{k}\" should be an identifier')\n if isinstance(v, MultiStep):\n v.key = k\n return val\n\n @validator('function')\n def validate_function(cls, val, values, **kwargs):\n if val is not None and 'component' in values.keys():\n raise ValueError('Function and component are mutually exclusive')\n elif val is None and 'component' not in values.keys():\n raise ValueError('Either function or component is necessary')\n return val\n\n # def make_config(self) -> dict:\n # result = {}\n # for k, v in self.args.items():\n # if not uses_batch(v):\n # result[k] = v\n # return result\n\n # def make_adapter(self) -> dict:\n # result = {}\n # for k, v in self.args.items():\n # if uses_batch(v):\n # result[k] = v\n # return result\n\n def make_adapter_and_config(self) -> Tuple[dict, dict]:\n arg_deps = {}\n args_that_use_batch = []\n for k, v in self.args.items():\n deps, arg_uses_batch, warnings = get_deps_uses_batch_and_warnings(v)\n for warning in warnings:\n print(warning.format(arg=k))\n arg_deps[k] = deps\n if arg_uses_batch:\n args_that_use_batch.append(k)\n\n args_that_indirectly_use_batch = [\n x\n for x in self.args.keys() if not x.startswith('_') and any(d in args_that_use_batch for d in arg_deps[x])\n ]\n args_that_use_batch += args_that_indirectly_use_batch\n component_args_needed_by_args_that_use_batch = list(\n itertools.chain(*[arg_deps[x] for x in args_that_use_batch]))\n adapter = {}\n for arg in [*component_args_needed_by_args_that_use_batch, *args_that_use_batch]:\n adapter[arg] = self.args[arg]\n\n config = {}\n component_args_that_dont_use_batch = [\n x for x in self.args.keys() if not x.startswith('_') and x not in args_that_use_batch\n ]\n component_args_needed_by_args_that_dont_use_batch = list(\n itertools.chain(*[arg_deps[x] for x in component_args_that_dont_use_batch]))\n for arg in [*component_args_needed_by_args_that_dont_use_batch, *component_args_that_dont_use_batch]:\n config[arg] = self.args[arg]\n return adapter, config\n\n @staticmethod\n def load_custom_transformations_namespace() -> object:\n custom_transformation_modules = {}\n transformations_path = str(Settings.transformations_directory)\n for filename in os.listdir(transformations_path):\n if filename == '__init__.py' or not filename.endswith('.py'):\n continue\n module_name = filename[:-3]\n module = load_module_from_path(\n module_path=os.path.join(transformations_path, filename),\n module_name=module_name,\n )\n custom_transformation_modules[module_name] = module\n custom_transformations = SimpleNamespace(**custom_transformation_modules)\n return custom_transformations\n\n # noinspection PyUnresolvedReferences\n def execute_adapter(self, batch: Any, dag_context: DagContext, batch_num=1, no_custom_transformations=False)\\\n -> Dict[str, Any]:\n adapter, _ = self.make_adapter_and_config()\n if not no_custom_transformations:\n custom_transformations_ns = self.load_custom_transformations_namespace()\n else:\n custom_transformations_ns = None\n\n import typhoon.contrib.transformations as typhoon_transformations\n custom_locals = locals()\n custom_locals['Settings'] = Settings\n custom_locals['transformations'] = custom_transformations_ns\n custom_locals['typhoon_transformations'] = typhoon_transformations\n custom_locals['batch'] = batch\n custom_locals['batch_num'] = batch_num\n custom_locals['dag_context'] = dag_context\n\n os.environ['TYPHOON_ENV'] = 'dev'\n\n results = {}\n for k, v in adapter.items():\n results[k] = evaluate_item(custom_locals, v)\n\n return results\n\n\nclass BrokenImportError(object):\n pass\n\n\ndef load_module_from_path(module_path, module_name=None, must_exist=True):\n import sys\n from importlib import util\n\n sys.path.append(os.path.dirname(os.path.dirname(module_path)))\n if module_name is None:\n parts = module_path.split('/')\n module_name = parts[-2] + '.' + parts[-1].strip('.py')\n spec = util.spec_from_file_location(module_name, module_path)\n module = util.module_from_spec(spec)\n try:\n spec.loader.exec_module(module)\n except (NameError, SyntaxError, FileNotFoundError):\n if must_exist:\n raise BrokenImportError\n else:\n print(f'Module {module_name} at path {module_path} does not exist')\n return None\n return module\n\n\n@dataclass\nclass ArgEvaluationError:\n code: str\n error_type: Exception\n error_value: Exception\n traceback: object\n\n\ndef evaluate_item(custom_locals, item) -> Any:\n if isinstance(item, Py):\n code = item.transpile()\n try:\n result = eval(code, {}, custom_locals)\n except Exception as e:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n result = ArgEvaluationError(code, exc_type, exc_value, exc_traceback)\n print(code)\n raise e\n return result\n elif isinstance(item, MultiStep):\n custom_locals_copy = custom_locals.copy()\n sentinel = object()\n result = None\n for code_line in item.transpile().split('\\n'):\n left, right = code_line.split('=')\n name = left.strip()\n code = right.strip()\n try:\n result = eval(code, {}, custom_locals_copy)\n except Exception as e:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n result = ArgEvaluationError(code, exc_type, exc_value, exc_traceback)\n if 'config[' in name:\n return result\n else:\n custom_locals_copy[name] = result\n assert result is not sentinel\n return result\n elif isinstance(item, list):\n return [evaluate_item(custom_locals, x) for x in item]\n elif isinstance(item, dict):\n return {k: evaluate_item(custom_locals, v) for k, v in item.items()}\n elif isinstance(item, SimpleNamespace):\n for k, v in item.__dict__.items():\n item.__setattr__(k, evaluate_item(custom_locals, v))\n return item\n elif isinstance(item, DataFrameFuture):\n import pandas as pd\n return pd.DataFrame(item.data)\n else:\n return item\n\n\nclass DAGDefinitionV2(BaseModel):\n name: str = Field(..., regex=IDENTIFIER_REGEX, description='Name of your DAG')\n schedule_interval: str = Field(\n ...,\n regex='(' + '@hourly|@daily|@weekly|@monthly|@yearly|' +\n r'((\\*|\\?|\\d+((\\/|\\-){0,1}(\\d+))*)\\s*){5,6}' + '|' +\n r'rate\\(\\s*1\\s+minute\\s*\\)' + '|' +\n r'rate\\(\\s*\\d+\\s+minutes\\s*\\)' + '|' +\n r'rate\\(\\s1*\\d+\\s+hour\\s*\\)' + '|' +\n r'rate\\(\\s*\\d+\\s+hours\\s*\\)' + '|' +\n ')',\n description='Schedule or frequency on which the DAG should run'\n )\n granularity: Optional[Granularity] = Field(\n default=None,\n description='Granularity of DAG. If not specified it will guess based on the expected time between runs.',\n )\n active: bool = Field(True, description='Whether to deploy the DAG or not')\n tasks: Dict[str, TaskDefinition]\n tests: Optional[Dict[str, TestCase]]\n\n def guess_granularity(self) -> Granularity:\n cron = aws_schedule_to_cron(self.schedule_interval)\n iterator = croniter(cron) # In case the event is exactly on time\n interval = iterator.get_next(datetime)\n next_interval = iterator.get_next(datetime)\n delta = (next_interval - interval)\n if delta < timedelta(minutes=1):\n return Granularity.SECOND\n elif delta < timedelta(hours=1):\n return Granularity.MINUTE\n elif delta < timedelta(days=1):\n return Granularity.HOUR\n elif delta < timedelta(days=31):\n return Granularity.DAY\n elif delta < timedelta(days=365):\n return Granularity.MONTH\n else:\n return Granularity.YEAR\n\n # noinspection PyProtectedMember\n def make_dag(self) -> DAG:\n self.substitute_components()\n nodes = {}\n edges = {}\n edge_id = 1\n for task_name, task in self.tasks.items():\n adapter, config = task.make_adapter_and_config()\n nodes[task_name] = Node(\n function=task.function,\n asynchronous=task.asynchronous,\n config=config,\n )\n if task.input:\n inp = task.input if isinstance(task.input, list) else [task.input]\n for source_task_id in inp:\n edges[f'e{edge_id}'] = Edge(\n source=source_task_id,\n destination=task_name,\n adapter=adapter,\n )\n edge_id += 1\n elif adapter:\n raise ValueError(\n f'The task {task_name} in dag {self.name} is trying to use $BATCH or $BATCH_NUM but it has no input')\n\n return DAG(\n name=self.name,\n schedule_interval=self.schedule_interval,\n granularity=self.granularity if self.granularity is not None else self.guess_granularity(),\n active=self.active,\n nodes=nodes,\n edges=edges,\n )\n\n def assert_tests(self, task_name, batch, batch_num, dag_context):\n task = self.tasks[task_name]\n test_case = self.tests[task_name]\n execute_results = task.execute_adapter(batch, dag_context, batch_num)\n for k, v in test_case.expected.items():\n assert v == execute_results[k]\n\n def substitute_components(self):\n from typhoon.core.glue import load_components\n from typhoon.core import components\n\n typhoon_components = {\n c.name: c\n for c, _ in load_components(ignore_errors=False, kind='typhoon')\n }\n custom_components = {\n c.name: c\n for c, _ in load_components(ignore_errors=False, kind='custom')\n }\n tasks_to_add = {}\n tasks_to_remove = []\n for task_name, task in self.tasks.items():\n if task.input is not None and '.' in task.input:\n input_task, component_output = task.input.split('.')\n component_name = self.tasks[input_task].component\n if component_name.startswith('typhoon.'):\n component = typhoon_components.get(component_name.split('.')[1])\n else:\n component = custom_components.get(component_name.split('.')[1])\n if not component.can_connect(component_output):\n raise ValueError(f'Can not connect {component_name} in task {task_name}. Does not have output {component_output}')\n task.input = components.task_name(name_in_dag=input_task, task=component_output)\n if task.component is not None:\n component_name = task.component\n if component_name.startswith('typhoon.'):\n component = typhoon_components.get(component_name.split('.')[1])\n else:\n component = custom_components.get(component_name.split('.')[1])\n if component is None:\n raise ValueError(f'No component found for {component_name}')\n component_tasks = component.make_tasks(name_in_dag=task_name, input_task=task.input, input_arg_values=task.args)\n tasks_to_add.update(**component_tasks)\n tasks_to_remove.append(task_name)\n for task_name in tasks_to_remove:\n del self.tasks[task_name]\n self.tasks.update(**tasks_to_add)\n\n\ndef uses_batch(item):\n if isinstance(item, Py):\n return '$BATCH' in item.value\n if isinstance(item, MultiStep):\n return uses_batch(item.value)\n elif isinstance(item, list):\n return any(uses_batch(x) for x in item)\n elif isinstance(item, dict):\n return any(uses_batch(v) for k, v in item.items())\n elif isinstance(item, (str, float, int)):\n return False\n assert False, f'Found type {type(item)} with value {item}'\n\n\nif __name__ == '__main__':\n add_yaml_constructors()\n dag_v2 = \"\"\"\nname: example_v2\nschedule_interval: \"@hourly\"\n\ntasks:\n tables:\n function: typhoon.flow_control.branch\n args:\n branches:\n - sheep\n - dog\n \n extract:\n input: tables\n function: typhoon.relational.query\n asynchronous: False\n args:\n sql: !Py f'select * from {$BATCH}'\n hook: !Py $HOOKS.oracle_db\n batch_size: 500\n \n load:\n input: extract\n function: typhoon.filesystem.write_data\n args:\n hook: !Py $HOOKS.data_lake\n data: !Py typhoon.transformations.write_csv($BATCH.data)\n path: !Py f'{$BATCH.table_name}/part{$BATCH_NUM}.csv'\n \"\"\"\n print(yaml.dump(DAGDefinitionV2.parse_obj(yaml.load(dag_v2, yaml.FullLoader)).make_dag().dict(), Dumper=yaml.Dumper, sort_keys=False))\n","sub_path":"typhoon/core/dags.py","file_name":"dags.py","file_ext":"py","file_size_in_byte":32917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"374613572","text":"import numpy as np\nfrom tqdm import tqdm\nfrom sklearn.neighbors import KDTree\n\ncodes = np.load('data/latent_codes_embedded.npy')\nmin_value = np.min(codes, axis=0)\nmax_value = np.max(codes, axis=0)\ncodes -= (max_value + min_value) / 2\ncodes /= np.max(codes, axis=0)\n\ndef move(points, radius, amount):\n tree = KDTree(points)\n\n distances, indices = tree.query(points, k=2, return_distance=True)\n mask = distances[:, 1] < radius\n points_moved = np.count_nonzero(mask)\n indices = indices[mask, 1:]\n\n neighbors = points[indices[:, 0], :]\n for i in range(indices.shape[1] - 1):\n neighbors += points[indices[:, i + 1], :]\n neighbors /= indices.shape[1]\n directions = neighbors - points[mask, :]\n directions /= np.linalg.norm(directions, axis=0)\n\n points[mask] -= directions * amount\n return points, points_moved\n\nTILE_SIZE = 256\nIMAGE_SIZE = 128\nTILE_DEPTH = 8\nRADIUS = IMAGE_SIZE / 2 / TILE_SIZE / 2**TILE_DEPTH\n\ndef move_mutiple(points, radius=RADIUS, steps=10000):\n points_moved = points.shape[0]\n i = 0\n while points_moved > 100:\n try:\n points, points_moved = move(points, radius * 2, radius / 4)\n print(points_moved)\n i += 1\n except KeyboardInterrupt:\n print(\"Stopping after {:d} iterations.\".format(i))\n return points\n\ncodes = move_mutiple(codes)\n\nOUTPUT_FILENAME = 'data/latent_codes_embedded_moved.npy'\nmin_value = np.min(codes, axis=0)\nmax_value = np.max(codes, axis=0)\ncodes -= (max_value + min_value) / 2\ncodes *= 0.99 / np.max(codes, axis=0)\n\nnp.save(OUTPUT_FILENAME, codes)\nprint(\"Saved to {:s}.\".format(OUTPUT_FILENAME))","sub_path":"move_points.py","file_name":"move_points.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"374060143","text":"#!/usr/bin/env python\nfrom __future__ import division\n\nimport os\nfrom nipype.interfaces.fsl import Info, FSLCommand, MCFLIRT, MeanImage, TemporalFilter, IsotropicSmooth, BET, GLM, BinaryMaths\nfrom nipype.interfaces.freesurfer import BBRegister, MRIConvert\nfrom nipype.interfaces.ants import Registration, ApplyTransforms\nfrom nipype.interfaces.c3 import C3dAffineTool\nfrom nipype.interfaces.utility import Merge\nfrom nipype.pipeline.engine import Workflow, Node, MapNode\nfrom nipype.interfaces.io import DataSink, FreeSurferSource, DataGrabber\nfrom nipype.interfaces.utility import IdentityInterface, Function\nfrom argparse import ArgumentParser\n\nfrom nipypext import nipype_wrapper\nfrom extract_roi import extract_roi\n\n\ndef get_file(in_file):\n \"\"\"\n ApplyTransforms ouptu is a list. This function gets the path to warped file\n from the import generated list\n \"\"\"\n path2file = in_file[0]\n return path2file\n\n\ndef get_VOIs(preprocessed_image, segmented_image_path, segmented_regions_path,\n subject_id):\n '''Extract VOIs from preprocesssed image using the provided atlas and the\n corresponding Lookup table (where the different regions are labled)'''\n\n import os\n import numpy as np\n import nibabel as nib\n\n # Load segmented image and obtain data from the image\n segmented_image = nib.load(segmented_image_path)\n segmented_image_data = segmented_image.get_data()\n # Load the Lookup Table which assigns each region to one specific pixel\n # intensity\n segmented_regions = np.genfromtxt(segmented_regions_path, dtype=[('numbers',\n ' 0:\n all_type_list = json.loads(requests.get(\n f'https://api.boardgameatlas.com/api/game/{type}?pretty=true&client_id={CLIENT_ID}').text).get(type)\n\n for member in api_answer.get(type):\n for m in all_type_list:\n if (member.get('id') == m.get('id')):\n try:\n model.objects.get(name=m.get('name'))\n known.append(m.get('name'))\n except ObjectDoesNotExist:\n unknown.append(m.get('name'))\n return known, unknown\n\n\n@permission_required('ludorecherche.add_game') # decorator checking if user have right to add game\ndef add_a_game(request, game_id): # Register selected game from page to database if not present\n context = base(request)\n\n api_answer = requests.get(f'https://api.boardgameatlas.com/api/search?ids={game_id}&client_id={CLIENT_ID}')\n if api_answer.status_code != 200:\n context.update({\n 'message': 'Erreur de Board Game Atlas',\n })\n return render(request, 'ludogestion/find_a_game.html', context)\n\n api_answer = json.loads(api_answer.text)\n if 'games' not in api_answer:\n context.update({\n 'message': 'Erreur dans la requête de retour'\n })\n api_answer = api_answer.get('games')\n if len(api_answer) == 0:\n context.update({\n 'message': 'Erreur de Board Game Atlas',\n })\n return render(request, 'ludogestion/find_a_game.html', context)\n api_answer = api_answer[0]\n\n try:\n if api_answer.get('type') is None:\n context.update({\n 'message': 'type inconnu',\n })\n return render(request, 'ludogestion/find_a_game.html', context)\n elif api_answer.get('type') == 'game':\n Game.objects.get(name=api_answer.get('name'))\n elif api_answer.get('type') == 'expansion':\n try:\n AddOn.objects.get(name=api_answer.get('name'))\n except ObjectDoesNotExist:\n MultiAddOn.objects.get(name=api_answer.get('name'))\n context.update({\n 'message': 'Ce jeu est déjà dans la ludothèque',\n })\n return render(request, 'ludogestion/find_a_game.html', context)\n\n except ObjectDoesNotExist:\n add_form = AddAGameForm(initial={\n 'name': f\"{api_answer.get('name')}\",\n 'english_name': f\"{api_answer.get('name')}\",\n 'player_min': f\"{api_answer.get('min_players')}\",\n 'player_max': f\"{api_answer.get('max_players')}\",\n 'external_image': f\"{api_answer.get('image_url')}\",\n 'thumb_image': f\"{api_answer.get('thumb_url')}\",\n 'bgg_link': f\"{api_answer.get('url')}\",\n 'age': f\"{api_answer.get('min_age')}\",\n 'max_time': f\"{api_answer.get('max_playtime')}\",\n 'stock': 1,\n 'buying_price':0,\n 'difficulty': 'Famille'\n })\n\n if api_answer['type'] == 'game':\n context.update({'type': 'game'})\n add_form.initial[\"type\"] = \"Jeu\"\n else:\n add_form.initial[\"type\"] = \"Extension simple\"\n context.update({'type': 'extension'})\n if 'primary_designer' in api_answer:\n try:\n Designer.objects.get(name=api_answer.get('primary_designer').get('name'))\n add_form.initial['designer'] = api_answer.get('primary_designer').get('name')\n except ObjectDoesNotExist:\n add_form.initial['add_designer'] = api_answer.get('primary_designer').get('name')\n\n artists_list = api_answer.get('artists')\n known_artist = []\n unknown_artist = []\n for artist in artists_list:\n try:\n Artist.objects.get(name=artist)\n known_artist.append(artist)\n except ObjectDoesNotExist:\n unknown_artist.append(artist)\n add_form.initial['add_artist'] = \", \".join(unknown_artist)\n add_form.initial['artist'] = known_artist\n\n if 'primary_publisher' in api_answer:\n try:\n Publisher.objects.get(name=api_answer.get('primary_publisher').get('name'))\n add_form.initial['publisher'] = api_answer.get('primary_publisher').get('name')\n except ObjectDoesNotExist:\n add_form.initial['add_publisher'] = api_answer.get('primary_publisher').get('name')\n\n (known_mechanics, unknown_mechanics) = recall_api('mechanics', api_answer, Mechanism)\n add_form.initial['mechanism'] = known_mechanics\n add_form.initial['add_mechanism'] = \", \".join(unknown_mechanics)\n (known_topics, unknown_topics) = recall_api('categories', api_answer, Topic)\n add_form.initial['topic'] = known_topics\n add_form.initial['add_topic'] = \", \".join(unknown_topics)\n\n context.update({\n 'add_form': add_form,\n })\n return render(request, 'ludogestion/add_a_game.html', context)\n\n\ndef log_in_page(request):\n context = base(request)\n return render(request, 'ludogestion/login.html', context)\n\n\ndef log_in(request): # Handle login attempt\n context = base(request)\n if request.method == \"POST\":\n username = request.POST['name']\n password = request.POST['password']\n context.update({\n 'name': username,\n })\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n context['authentified'] = True\n return render(request, 'ludogestion/login_success.html', context)\n else:\n return render(request, 'ludogestion/login_failed.html', context)\n else:\n return render(request, 'ludogestion/login_failed.html', context)\n\n\ndef log_out(request): # handle logout attempt\n context = base(request)\n context['authentified'] = False\n logout(request)\n return render(request, 'ludogestion/logout_success.html', context)\n\n\ndef add_reservation(request, type_name, type_id):\n user = request.user\n reservation_result = 2\n reservation_number = Reservation.objects.filter(user_id=user)\n if len(reservation_number) < ReservationRule.objects.get(pk=1).max_number:\n reservation_result = 1\n reservation = Reservation.objects.create()\n reservation.reservation = ReservationRule.objects.get(pk=1)\n reservation.expired_at = reservation.created_at + datetime.timedelta(reservation.reservation.duration)\n reservation.user_id = user\n if type_name == \"game\":\n reservation_object = Game.objects.get(pk=type_id)\n reservation.game_id = reservation_object\n reservation.save()\n elif type_name == \"addon\":\n reservation_object = AddOn.objects.get(pk=type_id)\n reservation.addon_id = reservation_object\n reservation.save()\n else:\n reservation_object = MultiAddOn.objects.get(pk=type_id)\n reservation.multiaddon_id = reservation_object\n reservation.save()\n return reservation_page(request, reservation_result)\n\n\ndef reservation_page(request, reservation_result=0):\n reservations = Reservation.objects.filter(user_id=request.user.id)\n context = base(request)\n context.update({\n \"reservations\": reservations,\n \"reservation_result\": reservation_result,\n })\n return render(request, 'ludogestion/reservation.html', context)\n\n\ndef remove_reservation(request, reservation_id):\n reservation = Reservation.objects.get(id=reservation_id)\n reservation.delete()\n return reservation_page(request)\n\n\ndef register_main(table, form):\n entry = table.objects.create(\n name=form.data.get(\"name\", \"\"),\n english_name=form.data.get(\"name\", \"\"),\n player_min=form.data.get('min_players', None),\n player_max=form.data.get('max_players', None),\n playing_time=form.data.get('playing_time'),\n picture=form.data.get('picture', None),\n external_image=form.data.get('external_image', None),\n bgg_link=form.data.get('bgg_link', None),\n age=form.data.get('min_age', None),\n max_time=form.data.get('max_playtime', None),\n stock=form.data.get('stock', None),\n buying_price=form.data.get('buying_price', None)\n )\n thumb_image = form.data.get('external_thumb_image', None)\n if thumb_image:\n entry.thumb_image = thumb_image\n add_list(entry, Designer, \"designer\", form, entry.designers)\n add_list(entry, Artist, \"artist\", form, entry.artists)\n add_list(entry, Publisher, \"publisher\", form, entry.publishers)\n entry.difficulty = Difficulty.objects.get(name=form.data.get(\"difficulty\"))\n add_list(entry, PlayingMode, \"playing_mode\", form, entry.playing_mode)\n add_list(entry, Language, \"language\", form, entry.language)\n return entry\n\n\ndef add_list(entry, model, name, form, field):\n add_list = form.data.getlist(name, [])\n unknown = form.data.get(f\"add_{name}\", \"\")\n if unknown != \"\":\n for add_object in unknown.split(\",\"):\n try:\n to_add = model.objects.get(\n name=add_object\n )\n except ObjectDoesNotExist:\n to_add = model.objects.create(\n name=add_object\n )\n if to_add is not None:\n field.add(to_add)\n for add_object in add_list:\n field.add(model.objects.get(name=add_object))\n\n\n@transaction.atomic # ensure all the register go well or cancel change in database\ndef register_a_game(request):\n context = base(request)\n add_form = AddAGameForm(request.POST)\n type = add_form.data.get(\"type\", \"\")\n\n if not add_form.data.get(\"name\"):\n context.update({\n 'message': 'erreur nom invalide',\n 'add_form': add_form\n })\n return render(request, 'ludogestion/add_a_game.html', context)\n if type == \"Jeu\":\n try:\n Game.objects.get(name=add_form.data.get(\"name\"))\n context.update({\n 'message': 'jeu déjà enregistré',\n 'add_form': add_form\n })\n return render(request, 'ludogestion/add_a_game.html', context)\n except ObjectDoesNotExist:\n game = register_main(Game, add_form)\n add_list(game, Topic, \"topic\", add_form, game.topic)\n add_list(game, Tag, \"tag\", add_form, game.tag)\n add_list(game, Mechanism, \"mechanism\", add_form, game.mechanism)\n\n game.by_player = True if(add_form.data.get(\"by_player\")) else False\n game.save()\n elif type == \"Extension simple\":\n try:\n AddOn.objects.get(name=add_form.data.get(\"name\"))\n context.update({\n 'message': 'extension déjà enregistré',\n 'add_form': add_form\n })\n return render(request, 'ludogestion/add_a_game.html', context)\n except ObjectDoesNotExist:\n add_on = register_main(AddOn, add_form)\n if add_form.data.get(\"associated_game\"):\n print(add_form.data.get('associated_game'))\n add_on.game = Game.objects.get(name=add_form.data.get('associated_game'))\n add_on.save()\n else:\n try:\n multi_add_on = MultiAddOn.objects.get(name=add_form.data.get(\"name\"))\n context.update({\n 'message': 'extension déjà enregistré',\n 'add_form': add_form\n })\n return render(request, 'ludogestion/add_a_game.html', context)\n except ObjectDoesNotExist:\n multi_add_on = register_main(MultiAddOn, add_form)\n if add_form.data.get(\"associated_games\"):\n [multi_add_on.games.add(Game.objects.get(name=game)) for game in add_form.data.getlist('associated_games')]\n multi_add_on.save()\n context.update({\n 'message': 'Enregistrement réalisé avec succès',\n })\n return render(request, 'ludogestion/find_a_game.html', context)\n","sub_path":"réa5/python/ludogestion/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"454661292","text":"# -*- coding:utf-8 -*-\nimport numpy\nimport math\nfrom utils.mplcanvas import MplCanvas\n\nfrom PySide import QtGui, QtCore\nfrom controller import OnlineAnalyzerControllerBase as AnalyzerControllerBase\nfrom ui.ui_debugcore import Ui_DebugCore\n\nclass DebugCoreCanvas():\n def __init__(self, wgt):\n self.tabMain = QtGui.QTabWidget(wgt)\n self.capTab = QtGui.QWidget()\n self.capCanvas = MplCanvas.setupCanvasWidget(self.capTab)\n capFigure = self.capCanvas.getFigure()\n self.capAx = capFigure.add_subplot(1, 1, 1)\n\n self.fftTab = QtGui.QWidget()\n self.fftCanvas = MplCanvas.setupCanvasWidget(self.fftTab)\n fftFigure = self.fftCanvas.getFigure()\n self.fftAx = fftFigure.add_subplot(1, 1, 1)\n\n self.tabMain.addTab(self.capTab, \"capture\")\n self.tabMain.addTab(self.fftTab, \"fft\")\n\n self.plotCap([], None)\n self.plotFFT([], None)\n\n def plotCap(self, dataY, pattern = None):\n if not pattern:\n pattern = (\"\", \"\", \"\", \"\")\n title, xlabel, ylabel, draw_type = pattern\n MplCanvas.changeInfo(self.capAx, title + \"-CAP\", xlabel, ylabel)\n MplCanvas.plotAx(self.capAx, range(len(dataY)), dataY, draw_type)\n\n def plotFFT(self, dataY, pattern = None):\n if not pattern:\n pattern = (\"\", \"\", \"\", \"\")\n title, xlabel, ylabel, draw_type = pattern\n MplCanvas.changeInfo(self.fftAx, title + \"-FFT\", xlabel, ylabel)\n MplCanvas.plotAx(self.fftAx, range(len(dataY)), dataY, draw_type)\n\n def draw(self):\n self.capCanvas.draw()\n self.fftCanvas.draw()\n\n@AnalyzerControllerBase.bindUI(Ui_DebugCore)\n@AnalyzerControllerBase.bindAnalyzer(\"debugcore\")\nclass DebugCoreController(AnalyzerControllerBase):\n # funcName: (\n # u\"EventName\",\n # Pattern for Cap\n # (xLabel, yLable, drawType),\n # Pattern for FFT, if don't need FFT, this item should be None\n # (xLabel, yLable, drawType))\n EventDict = {\n \"rx_adc\": (\n u\"rx_adc\",\n (\"\", \"\", \"\"),\n (\"\", \"\", \"\")\n ), \"fgup_rx_adc\": (\n u\"rx_adc_fgup\",\n (\"\", \"\", \"\"),\n (\"\", \"\", \"\"),\n ), \"ldpc_err_rx_adc\": (\n u\"rx_adc_ldpc_err\",\n (\"\", \"\", \"\"),\n (\"\", \"\", \"\"),\n ), \"fg_dsm_rx_adc\": (\n u\"rx_adc_fg_dsm\",\n (\"\", \"\", \"\"),\n (\"\", \"\", \"\"),\n ), \"online_eye\": (\n u\"眼图\",\n (\"\", \"\", \".\"),\n None\n ), \"online_eye_error\": (\n u\"眼图(错误)\",\n (\"\", \"\", \".\"),\n None\n ), \"online_frequency\": (\n u\"频响\",\n (\"\", \"\", \"\"),\n None\n ), \"online_frequency_error\": (\n u\"频响(错误)\",\n (\"\", \"\", \"\"),\n None\n ),\n }\n\n def __init__(self, **kw):\n AnalyzerControllerBase.__init__(self, **kw)\n # setup wgtCanvas\n self.canvas = DebugCoreCanvas(self.ui.dbgcCanvas)\n\n self.eventList = None # init with __genEventList\n self.funcDict = None # init with __genEventList\n self.maxPoint = 8192\n self.dumpInfo = None\n self.fftInfo = None\n\n self.__genEventList()\n self.ui.dbgcEvents.clear()\n self.ui.dbgcEvents.addItems(self.eventList)\n self.__resetPoints()\n # ==================================\n # Setup & Inner Function\n # ==================================\n def __genEventList(self):\n funcList = self.analyzer.func_list()\n def transform(funcName):\n eventInfo = self.EventDict.get(funcName, None)\n if not eventInfo:\n return funcName\n else:\n return eventInfo[0]\n\n eventList = map(transform, funcList)\n self.funcDict = dict(zip(eventList, funcList))\n self.eventList = sorted(eventList)\n\n def __getCurrentPoints(self):\n return int(self.ui.dbgcPoint.text())\n\n def __getCurrentEventName(self):\n name = self.eventList[self.ui.dbgcEvents.currentIndex()]\n return self.funcDict[name]\n\n def __getCurrentEventInfo(self):\n eventName = self.__getCurrentEventName()\n emptyPattern = (\"\", \"\", \"\")\n return self.EventDict.get(eventName, (\"\", emptyPattern, emptyPattern))\n\n def __resetPoints(self):\n eventName = self.__getCurrentEventName()\n self.maxPoint = (\"adc\" in eventName) and 2048 or 8192\n self.ui.dbgcPoint.setText(str(self.maxPoint))\n self.__resetPrePoints()\n\n def __resetPrePoints(self):\n self.ui.dbgcPrepoint.clear()\n self.ui.dbgcPrepoint.setEnabled(False)\n self.ui.dbgcPrepointEn.setChecked(False)\n\n # return None or int\n # pre trigger point\n def __getCurrentPrePoint(self):\n if not self.ui.dbgcPrepointEn.isChecked():\n return None\n\n txt = str(self.ui.dbgcPrepoint.text())\n if not txt.isdigit():\n return None\n\n prePoint = int(txt)\n if prePoint >= self.maxPoint:\n return None\n\n return prePoing\n\n # ==================================\n # Event Callback\n # ==================================\n @QtCore.Slot(int)\n def on_dbgcEvents_activated(self, idx):\n if idx < 0:\n return\n\n eventName = self.eventList[idx]\n self.logStatus(\"idx %s = %s\" % (idx, eventName))\n self.__resetPoints()\n\n @QtCore.Slot()\n def on_dbgcCap_clicked(self):\n # dump info\n points = self.__getCurrentPoints()\n prePoint = self.__getCurrentPrePoint()\n eventName = self.__getCurrentEventName()\n dumpInfo = self.analyzer.trigger_func(eventName, points, prePoint)\n\n if not dumpInfo:\n self.logStatus(\"Capture Fail\")\n return\n else:\n self.logStatus(\"Capture Success\")\n\n title, capPattern, fftPattern = self.__getCurrentEventInfo()\n\n # draw dump info\n capX, capY, capType = capPattern\n self.canvas.plotCap(dumpInfo, (title, capX, capY, capType))\n\n # draw fft\n if fftPattern:\n fftX, fftY, fftType = fftPattern\n fftInfo = self.analyzer.fft(dumpInfo)\n self.canvas.plotFFT(fftInfo, (title, fftX, fftY, fftType))\n else:\n fftInfo = []\n self.canvas.plotFFT([])\n\n self.canvas.draw()\n\n # info backup\n self.dumpInfo = dumpInfo\n self.fftInfo = fftInfo\n\n @QtCore.Slot(int)\n def on_dbgcPrepointEn_stateChanged(self, state):\n if state == 2: # checked\n self.ui.dbgcPrepoint.setEnabled(True)\n self.ui.dbgcPrepointEn.setChecked(True)\n else: # unchecked\n self.ui.dbgcPrepoint.setEnabled(False)\n self.ui.dbgcPrepointEn.setChecked(False)\n","sub_path":"controller/dbgc.py","file_name":"dbgc.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"116467875","text":"from dls_css_utils import coordinates, config\nimport dls_epicsparser.releaseparser\nimport dls_epicsparser.parser\nimport os\n\nimport logging as log\n\n\nCONFIGURE_RELEASE = 'configure/RELEASE'\nEPICS_PREFIX = '/dls_sw/epics/'\nROOT = \"/dls_sw/prod/R3.14.12.3/\"\n\n# custom module name regex, matches versions starting dls (e.g. asyn/dls4-21beta)\nDLS_VERSION_PATTERNS = [r\".*/(.*)/(dls)[0-9]+[_\\-\\.][0-9]+.*\"]\n\nKNOWN_PARSE_ISSUES = [\n \"/dls_sw/prod/R3.14.12.3/ioc/BL18B/BL/3-47/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/ioc/BL03I/BL03I-MO-IOC-02/3-0/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/ioc/BL24I/BL/3-1/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/ADBinaries/2-2dls2/configure/RELEASE\", #EPICS_HOST_ARCH\n \"/dls_sw/prod/R3.14.12.3/support/adUtil/2-0/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/adUtil/2-4/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/aravisGigE/2-0/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/ffmpegServer/3-0dls0-1/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/ADPilatus/2-1dls5/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/ADCore/2-2dls3/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/ADCore/2-3dls4/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/ADCore/2-3dls5/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/dxp/3-5dls2/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/dxp/3-5dls4/configure/RELEASE\",\n \"/dls_sw/prod/R3.14.12.3/support/dtacq_adc/2-0/configure/RELEASE\"]\n\n\ndef is_valid(dependency, module_path=None):\n \"\"\" Simple test that dependency is 'valid'.\n i.e path and name defined,\n not EPICS base, or a child\n\n Args:\n dependency: Dependency to check with .path and .name attributes\n\n Returns:\n True if valid dependency\n \"\"\"\n valid = (dependency.path is not None\n and dependency.name is not None\n and not dependency.path.startswith(EPICS_PREFIX)\n and not dependency.path == module_path)\n\n return valid\n\n\nclass DependencyParser(object):\n\n @classmethod\n def from_path(cls, mod_path, module_name, additional_depends=None):\n \"\"\" Construct a dependency parser from a module path and name\n\n Args:\n mod_path: full path to this module\n module_name: name of module to explore\n additional_depends: list of rootless coords for dependencies not in RELEASE\n \"\"\"\n log.info('Preparing conversion of module %s', mod_path)\n return cls(mod_path, module_name, ROOT, additional_depends)\n\n @classmethod\n def from_coord(cls, module_coord, mirror_root=\"\", additional_depends=None):\n \"\"\" Construct a dependency parser from converter-style coord and root\n arguments.\n\n Args:\n module_coord: tuple containing path to search area, mod name and version\n mirror_root: root directory for module coordinate\n additional_depends: list of rootless coords for dependencies not in RELEASE\n \"\"\"\n assert module_coord.version is not None, \\\n \"Cannot find dependencies of module (%s) with no version\" % module_coord.module\n\n module_path = coordinates.as_path(module_coord)\n log.info('Preparing conversion of module %s', module_coord)\n\n if mirror_root:\n log.info(\"Prefix set for %s to %s\", module_coord.module, mirror_root)\n\n if mirror_root and not module_path.startswith(mirror_root):\n log.info(\"Prefixing shadow %s\", mirror_root)\n module_path = os.path.join(mirror_root, module_path[1:])\n return cls(module_path, module_coord.module, module_coord.root, additional_depends)\n\n def __init__(self, mod_path, module_name, root, additional_depends):\n \"\"\" Parse dependencies for IOC\n\n Args:\n module_coord: tuple containing path to search area, mod name and version\n module_name: name of module to explore\n root: root directory for module coordinate\n additional_depends: list of rootless coords for dependencies not in RELEASE\n \"\"\"\n self._additional = additional_depends\n self._module_path = mod_path\n self._module_name = module_name\n self._root = root\n\n def find_dependencies(self):\n \"\"\" Generate a dictionary of dependencies for this module\n\n Returns:\n Dictionary of {dependency name => ModCoord}\n \"\"\"\n dependencies = {}\n\n cr_path = os.path.join(self._module_path, CONFIGURE_RELEASE)\n log.debug(\">Parsing %s\", cr_path)\n\n try:\n r = dls_epicsparser.releaseparser.Release(cr_path, custom_patterns=DLS_VERSION_PATTERNS)\n for dependency in r.flatten():\n if is_valid(dependency, self._module_path):\n module_coord = coordinates.from_path(dependency.path)\n try:\n module_cfg = config.parse_module_config(dependency.path)\n name = config.module_name(module_cfg)\n except config.ConfigError:\n name = module_coord.module\n # The release parser often returns a dependency of this module,\n # these dependencies are valid so pass the above check but\n # should not be included; we filter them here.\n if not name == self._module_name:\n dependencies[name] = module_coord\n\n if self._additional is not None:\n for acoord in self._additional:\n log.info(\"Additional dependency %s/%s\", acoord.module, acoord.version)\n dependencies[acoord.module] = coordinates.update_root(acoord, self._root)\n\n except (dls_epicsparser.parser.ParseException, KeyError, AssertionError) as ex:\n log.error(\"Failed to parse RELEASE for %s: %s\", cr_path, ex.message)\n\n if cr_path not in KNOWN_PARSE_ISSUES:\n raise ex\n\n return dependencies\n\n","sub_path":"dls_css_utils/dependency.py","file_name":"dependency.py","file_ext":"py","file_size_in_byte":6060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"497217104","text":"# flag : CTF{Y0U_4R3_T0_B3_R3W4RD3D}\n\nfrom pwn import *\n\n#p = process('./challenge', env={'LD_PRELOAD':'./libc.so.6'})\np = remote('51.15.73.163',8088)\ne = ELF('./challenge')\nl = ELF('./libc.so.6')\n#gdb.attach(p, '''c''')\n\ndef add(content = 'AAAA'):\n p.sendafter('choice >', '1')\n p.sendafter('Enter content >', content)\n p.recvuntil('Created at ')\n return int(p.recvline()[:-2], 16) - 0x10\n\ndef delete(idx):\n p.sendafter('choice >', '2')\n p.sendlineafter('Enter index to delete note >', str(idx))\n\ndef helping():\n p.sendafter('choice >', '3')\n p.recvuntil('I am located at ')\n return int(p.recvline(), 16)\n\ndef exit():\n p.sendafter('choice >', '4')\n\n# 0\nchunk1 = add()\t\t\t\t\t# off-by-one\n# 1\nchunk2 = add()\t\t\t\t\t# victim\ndelete(0)\n\n# forge_chunk = chunk1 + 0x20\n# 2\nadd( \n\tflat( \n\t\tp64(chunk1 + 0x20), \t# 0x18\n\t\t'B'*8,\n\t\tp64(0xe1), \t\t\t\t# size\n\t\tp64(chunk1 + 0x0), \t\t# P->fd->bk == P\n\t\tp64(chunk1 + 0x8), \t\t# P->bk->fd == P\n\t\t'B'*0xc0, \n\t\tp64(0xe0), \t\t\t\t# prev_size == size\n\t\tp8(0x0)\t\t\t\t\t# clear inuse bit\n )\n\t) \ndelete(1)\t\t\t\t\t\t# consolidate forward with forge chunk\n\nget_shell = helping() - e.symbols['help'] + e.symbols['get_shell']\n# 3\nadd('A'*0xd8 + p64(get_shell)) \t# overwrite 1's func ptr\ndelete(1)\n\np.interactive()\n","sub_path":"backdoor2018/shelter/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"549937061","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ImageDescriptor(Model):\n \"\"\"Properties for a registry image.\n\n :param registry: The registry login server.\n :type registry: str\n :param repository: The repository name.\n :type repository: str\n :param tag: The tag name.\n :type tag: str\n :param digest: The sha256-based digest of the image manifest.\n :type digest: str\n \"\"\"\n\n _attribute_map = {\n 'registry': {'key': 'registry', 'type': 'str'},\n 'repository': {'key': 'repository', 'type': 'str'},\n 'tag': {'key': 'tag', 'type': 'str'},\n 'digest': {'key': 'digest', 'type': 'str'},\n }\n\n def __init__(self, **kwargs):\n super(ImageDescriptor, self).__init__(**kwargs)\n self.registry = kwargs.get('registry', None)\n self.repository = kwargs.get('repository', None)\n self.tag = kwargs.get('tag', None)\n self.digest = kwargs.get('digest', None)\n","sub_path":"azure-mgmt-containerregistry/azure/mgmt/containerregistry/v2018_02_01_preview/models/image_descriptor.py","file_name":"image_descriptor.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"387543320","text":"import tensorflow as tf\nNUMCLASSES = 3\n\ndef CNN_Model(features, labels, mode):\n \"\"\"Model function for CNN.\"\"\"\n # Input Layer\n print(\"Mode:\", mode)\n input_layer = tf.reshape(features, [-1, 40, 398, 3], name=\"image_input\")\n\n # Convolutional Layer #1\n conv1 = tf.layers.conv2d(\n inputs=input_layer,\n filters=32,\n kernel_size=[1, 5],\n strides=(1, 1),\n padding=\"valid\",\n activation=tf.nn.relu)\n \n # Pool Layer #1\n pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[5, 1], strides=(5,1))\n \n # Dense Layer\n _, height, width, depth = pool1.get_shape()\n print(\"CNN with final feature maps:\", height, \"x\", width, \"x\", depth)\n print(height*width*depth, \"total features\")\n final_flat = tf.reshape(pool1, [-1, height * width * depth])\n dense = tf.layers.dense(inputs=final_flat, units=1024, activation=tf.nn.relu)\n dropout = tf.layers.dropout(\n inputs=dense, rate=0.3, training=mode == tf.estimator.ModeKeys.TRAIN)\n\n # Logits Layer\n logits = tf.layers.dense(inputs=dropout, units=NUMCLASSES)\n\n predictions = {\n # Generate predictions (for PREDICT and EVAL mode)\n \"classes\": tf.argmax(input=logits, axis=1),\n # Add `softmax_tensor` to the graph. It is used for PREDICT and by the\n # `logging_hook`\n \"probabilities\": tf.nn.softmax(logits, name=\"softmax_tensor\")\n }\n\n #Put images in tensorboard\n if mode == tf.estimator.ModeKeys.TRAIN:\n tf.summary.image(\n \"Image\",\n input_layer,\n max_outputs=9\n )\n \n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n\n # Calculate Loss (for both TRAIN and EVAL modes)\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n\n # Configure the Training Op (for TRAIN mode)\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)\n train_op = optimizer.minimize(\n loss=loss,\n global_step=tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n\n # Add evaluation metrics (for EVAL mode)\n eval_metric_ops = {\n \"accuracy\": tf.metrics.accuracy(\n labels=labels, predictions=predictions[\"classes\"]),\n \"mean_accuracy\": tf.metrics.mean_per_class_accuracy(\n labels=labels, predictions=predictions[\"classes\"],\n num_classes=NUMCLASSES)\n }\n #modify eval_metric_ops to include accuracy for each class\n per_class_accuracy(predictions[\"classes\"],\n labels,\n eval_metric_ops)\n \n return tf.estimator.EstimatorSpec(\n mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)\n\ndef per_class_accuracy(predictions, labels, eval_metric_ops):\n \n print(labels)\n print(predictions)\n \n eval_metric_ops[\"test_metric\"] = (0.5, 0.5)\n \n \ndef parse_record(serialized_example): #parse a single binary example\n \"\"\"Parses a single tf.Example into image and label tensors.\"\"\"\n features = {'image/encoded': tf.FixedLenFeature([], tf.string),\n 'image/format': tf.FixedLenFeature([], tf.string),\n 'image/label': tf.FixedLenFeature([], tf.int64)}\n features = tf.parse_single_example(serialized_example, features)\n \n #print(\"JPG:\", features['image/encoded'])\n image = tf.image.decode_jpeg(features['image/encoded'], channels=0)\n #print(\"image:\", image)\n image = tf.reshape(image, [40, 398, 3])\n image = tf.image.convert_image_dtype(image, tf.float32)\n \n label = tf.cast(features['image/label'], tf.int32)\n \n return (image, label)\n \n# Define the input function for training\ndef train_input_fn():\n\n # Keep list of filenames, so you can input directory of tfrecords easily\n train_filenames = [\"data_processing/nsynth/train.record\"]\n test_filenames = [\"data_processing/nsynth/test.record\"]\n batch_size=256\n\n # Import data\n dataset = tf.data.TFRecordDataset(train_filenames)\n\n # Map the parser over dataset, and batch results by up to batch_size\n dataset = dataset.map(parse_record)\n dataset = dataset.batch(batch_size)\n dataset = dataset.repeat()\n #print(\"Dataset:\", dataset.output_shapes, \":::\", dataset.output_types)\n iterator = dataset.make_one_shot_iterator()\n\n features, labels = iterator.get_next()\n #print(\"Iterator:\", features)\n\n return (features, labels)\n\n# Our application logic will be added here\n\n# Define the input function for evaluating\ndef eval_input_fn():\n\n # Keep list of filenames, so you can input directory of tfrecords easily\n train_filenames = [\"data_processing/nsynth/train.record\"]\n test_filenames = [\"data_processing/nsynth/test.record\"]\n batch_size = 24\n\n # Import data\n dataset = tf.data.TFRecordDataset(test_filenames)\n\n # Map the parser over dataset, and batch results by up to batch_size\n dataset = dataset.map(parse_record)\n dataset = dataset.batch(batch_size)\n #print(\"Dataset:\", dataset.output_shapes, \":::\", dataset.output_types)\n iterator = dataset.make_one_shot_iterator()\n\n features, labels = iterator.get_next()\n #print(\"Iterator:\", features)\n\n return (features, labels)\n","sub_path":"cnn_models.py","file_name":"cnn_models.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"510300559","text":"\"\"\"\n1.熟练字符串的常用的函数\n2.str1 = \"hello hello hello world\"\n 统计字符串的长度\n 统计\"llo\"出现的次数\n 统计\"wor\"出现的位置\n\n3.str2 = \"hello\",将字符串长度-->11,左右两边使用-填充\n\"\"\"\n\n# str1 = \"hello hello hello world\"\n#\n# print(len(str1))\n# print(str1.count(\"llo\"))\n# print(str1.find(\"wor\"))\n#\n#\n# str2 = \"hello\"\n# print(str2.center(12, \"-\"))\n\n\nfor i in range(1, 10):\n for j in range(1, 10):\n if i >= j:\n print(\"%d*%d=%d\" % (i, j, i * j), end=\" \")\n print()\n\n\n","sub_path":"20171113/exercise/demo04_课堂练习.py","file_name":"demo04_课堂练习.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"471763613","text":"#%%\n#!pip install twython\n#%%\nfrom twython import Twython\nimport numpy as np \nimport os\n\n# %%\n\nAPP_KEY = os.getenv('TWITTER_APP_KEY')\nAPP_SECRET = os.getenv('TWITTER_APP_SECRET')\nOAUTH_TOKEN = os.getenv('TWITTER_OAUTH_TOKEN')\nOAUTH_TOKEN_SECRECT = os.getenv('TWITTER_OAUTH_TOKEN_SECRECT')\n\ntwitter = Twython(APP_KEY,APP_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRECT)\n\n# %%\ngop_tweets = [x['full_text'].replace('\\n',' ') for x in \ntwitter.get_user_timeline(screen_name='GOP', tweet_mode = 'extended', count = 500)]\ndem_tweets = [x['full_text'].replace('\\n',' ') for x in \ntwitter.get_user_timeline(screen_name='TheDemocrats',tweet_mode='extended', count=500)]\n\n\n# %%\ndef save_tweets(filename, tweets):\n with open(filename, \"wb\") as file:\n file.write(\"\\n\".join(tweets).encode('utf-8'))\n\n# %%\nsave_tweets('gop.txt',gop_tweets)\nsave_tweets('dems.txt',dem_tweets)\n\n# %%\n\n","sub_path":"TwitterAnalytics.py","file_name":"TwitterAnalytics.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"640733178","text":"import matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport matplotlib.dates as mdates\nfrom pandas.plotting import register_matplotlib_converters\nimport sys\n\n\"\"\" TODO:\n- Add possibility to color different segments of the time series\n\"\"\"\n\nclass TimeSeriesVisualizer():\n\n def __init__(self, fig, rect, repo, callbacks):\n\n register_matplotlib_converters()\n plt.ion()\n \n # the preprocessing window slide step\n self.step = 10\n \n # show all entities or just selected ones\n self.show_all = True\n \n self.fig = fig\n # add 10% margin to rect [left, bottom, width, height]\n self.rect = [rect[0]+rect[2]*0.065, rect[1]+rect[3]*0.05, rect[2]*0.9, rect[3]*0.9]\n self.repo = repo\n self.callbacks = callbacks \n \n if 'select_entities' not in callbacks:\n callbacks['select_entities'] = []\n if 'select_attributes' not in callbacks:\n callbacks['select_attributes'] = []\n self.callbacks['select_entities'].append(self.set_selected_entities)\n self.callbacks['select_attributes'].append(self.set_selected_attributes)\n self.draginfo = False\n\n self.indexattr = False\n self.timeattr = False\n self.entityattr = False\n self.classattr = False\n self.anomalyattr = False\n self.classcolfunc = None\n self.anomalycolfunc = None\n self.anomaly_threshold = 0.5\n \n self.all_entities = []\n self.selectedEntities = []\n self.selectedFeatures = []\n self.zoompropmin = 0.0\n self.zoompropmax = 1.0\n #self.timeWindowInHours = self.repo.get_time_window_seconds()/60/60\n\n # Create a list with rectangles for the plots\n rectangleList = self._getRectangleList(self.rect, len(self.selectedFeatures))\n\n # Create dict to hold all the feature information\n self.features = {}\n \n \n # Create anomalies dict to hold all the deviation plot info\n self.anomalies = { 'axes': fig.add_axes(rectangleList[0]),\n 'xMin': np.inf,#datetime.datetime.now(), \n 'xMax': -np.inf,#datetime.datetime(1900, 1, 1),\n 'yMin': sys.maxsize, \n 'yMax': -sys.maxsize - 1,\n 'entities': [] }\n \n self.anomalies['axes'].set_ylabel('')\n self.anomalies['axes'].set_title(self.anomalyattr if self.anomalyattr else \"\", fontdict={'fontSize': 10}, loc='left')\n self.anomalies['axes'].tick_params(labelsize=10)\n\n \n def add_entity(self, entity):\n \n # Only add entity when its not already in list\n if not entity in self.selectedEntities:\n \n # Add entity to list\n self.selectedEntities.append(entity)\n \n # Add entity to anomaly plot\n plotLine = self.anomalies['axes'].plot([], [])[0] #.scatter([], []) \n plotLabel = 'Entity - ' + str(entity)\n \n # Append entity anomaly plot info to list\n self.anomalies['entities'].append({'entity': entity, \n 'label': plotLabel,\n 'line': plotLine})\n\n\n# \n# # Add the entity to the legend (somehow the get_legend_handles_labels() did not return anything, \n# # thats why the get_legend() workaround is used)\n# currentLegend = self.anomalies['axes'].get_legend()\n# legendLabels = [] if currentLegend is None else [str(x._text) for x in currentLegend.texts]\n# legendPlotLines = [] if currentLegend is None else currentLegend.legendHandles\n# \n# # Append the label and the plotline to the legend\n# legendPlotLines = np.append(legendPlotLines, plotLine)\n# legendLabels = np.append(legendLabels, plotLabel)\n# \n# # Set the legend for the entities / features\n# self.anomalies['axes'].legend(legendPlotLines, legendLabels)\n\n # Add entity to all feature plots\n for feature in self.features:\n plotInfo = { 'entity': entity,\n 'line': self.features[feature]['axes'].plot([], [])[0] } #.scatter([], [])}\n \n # Match the entity color in the anomaly plot\n# plotInfo['line'].set_color(plotLine.get_color())\n \n # Add entity plot info to feature entity list\n self.features[feature]['entities'].append(plotInfo)\n\n \n def remove_entity(self, entity):\n \n # Only if entity is in list\n if entity in self.selectedEntities:\n \n # Remove entity from list\n self.selectedEntities.remove(entity)\n\n # Remove entity entry from from all the feature plots\n for feature in self.features:\n \n for index, entityPlotInfo in enumerate(self.features[feature]['entities']):\n \n if entityPlotInfo['entity'] == entity:\n \n # Remove line from plot\n #self.features[feature]['axes'].lines.remove(entityPlotInfo['line'])\n \n # Remove list entry\n self.features[feature]['entities'].pop(index)\n \n break\n\n \n# # Prepare to remove the entity from the legend (somehow the get_legend_handles_labels() did not return anything, \n# # thats why the get_legend() workaround is used)\n# currentLegend = self.anomalies['axes'].get_legend()\n# legendLabels = [] if currentLegend is None else [str(x._text) for x in currentLegend.texts]\n# legendPlotLines = [] if currentLegend is None else currentLegend.legendHandles\n#\n # Remove entity from anomaly plot\n for index, entityPlotInfo in enumerate(self.anomalies['entities']):\n \n if entityPlotInfo['entity'] == entity:\n\n # Remove line from legend and plot (with workaround to remove plotline)\n# legendPlotLines.pop(legendLabels.index(entityPlotInfo['label']))\n# legendLabels.remove(entityPlotInfo['label'])\n\n #self.anomalies['axes'].lines.remove(entityPlotInfo['line'])\n\n # Remove list entry\n self.anomalies['entities'].pop(index)\n \n break\n\n # Set the legend for the entities / features\n# self.anomalies['axes'].legend(legendPlotLines, legendLabels)\n\n\n def add_feature(self, feature):\n \n # Only if feature is not already show\n if not feature in self.features:\n \n # Add the feature to the selected features\n self.selectedFeatures.append(feature)\n \n # Add a new feature dict in self.features, the None values will be replaced later\n self.features[feature] = { 'axes': None, \n 'feature': feature,\n 'showTicks': None,\n 'xMin': np.inf,#datetime.datetime.now(), \n 'xMax': -np.inf,#datetime.datetime(1900, 1, 1),\n 'yMin': sys.maxsize, \n 'yMax': -sys.maxsize - 1,\n 'entities': [] }\n\n # Add all the selected entities to the new feature, the None value will be replaced later\n for entity in self.selectedEntities:\n plotInfo = { 'entity': entity,\n 'line': None }\n self.features[feature]['entities'].append(plotInfo)\n\n # Get new rectangles for the feature plots\n rectangleList = self._getRectangleList(self.rect, len(self.selectedFeatures))\n \n # Replace axes for the features based on new rectangle layout\n for index, feature in enumerate(self.selectedFeatures):\n \n if self.features[feature]['axes'] != None:\n self.features[feature]['axes'].remove()\n \n self.features[feature]['axes'] = self.fig.add_axes(rectangleList[index + 1])\n self.features[feature]['showTicks'] = False #(index == 0)\n \n self.features[feature]['axes'].set_ylabel('')\n \n if not self.features[feature]['showTicks']:\n self.features[feature]['axes'].set_xticklabels([])\n \n self.features[feature]['axes'].set_title(feature, fontdict={'fontSize': 10}, loc='left')\n \n # Rebuild the entity list of the feature plot\n for entityIndex, entity in enumerate(self.selectedEntities):\n plotInfo = { 'entity': entity,\n 'line': self.features[feature]['axes'].plot([], [])[0] } # .scatter([], [])}\n \n # Match the entity color in the anomalies plot\n anomalyEntityPlotInfo = next(item for item in self.anomalies['entities'] if item['entity'] == entity)\n# plotInfo['line'].set_color(anomalyEntityPlotInfo['line'].get_color())\n \n self.features[feature]['entities'][entityIndex] = plotInfo\n \n \n \n def remove_feature(self, feature):\n \n # Only if feature is shown\n if feature in self.features:\n \n # Remove the feature \n self.features[feature]['axes'].remove()\n del self.features[feature]\n self.selectedFeatures.remove(feature)\n \n # Get new rectangles for the features left\n rectangleList = self._getRectangleList(self.rect, len(self.selectedFeatures))\n \n # Replace axes for the still visible features based on new rectangle layout\n for index, feature in enumerate(self.selectedFeatures):\n \n self.features[feature]['axes'].remove()\n self.features[feature]['axes'] = self.fig.add_axes(rectangleList[index + 1])\n self.features[feature]['showTicks'] = False #(index == 0)\n \n self.features[feature]['axes'].set_ylabel('')\n \n if not self.features[feature]['showTicks']:\n self.features[feature]['axes'].set_xticklabels([])\n \n self.features[feature]['axes'].set_title(feature, fontdict={'fontSize': 10}, loc='left')\n \n # Rebuild the entity list of the feature plot\n for entityIndex, entity in enumerate(self.selectedEntities):\n plotInfo = { 'entity': entity,\n 'line': self.features[feature]['axes'].plot([], [])[0] } #.scatter([], [])}\n\n # Match the entity color in the anomalies plot\n anomalyEntityPlotInfo = next(item for item in self.anomalies['entities'] if item['entity'] == entity)\n# plotInfo['line'].set_color(anomalyEntityPlotInfo['line'].get_color())\n\n self.features[feature]['entities'][entityIndex] = plotInfo\n\n\n \n def _get_cols(self, ano, cl):\n cols = [None]*len(cl)\n \n for i in range(len(cl)):\n \n if ano[i] is not None and ano[i] > self.anomaly_threshold and self.anomalycolfunc is not None:\n cols[i] = self.anomalycolfunc(ano[i])\n elif cl[i] is not None and self.classcolfunc is not None:\n cols[i] = self.classcolfunc(cl[i])\n else:\n cols[i] = hsl_color(0.5, 0.5, -0.5)\n \n return cols\n \n def _to_lines(self, points, colors):\n if len(points) != len(colors):\n print('Error!! Points and colors are not the same length')\n return\n \n x0, y0 = points[0]\n lines=[]\n new_colors=[]\n for i in range(1, len(points)):\n x1, y1 = points[i]\n #skip line if missing data in between\n if x1-x0 > self.step:\n x0,y0 = x1,y1\n continue\n lines.append( ((x0,y0) , (x1,y1)) )\n new_colors.append(colors[i])\n x0,y0 = x1,y1\n return lines, new_colors\n\n \n def redraw_features(self):\n \n # this will be a lits of lists in the form [[time, entity, anomaly, class, sel_feat_1, sel_feat_2, ...],...]\n #all_data = self.repo.aget_values([self.anomalyattr, self.classattr]+self.selectedFeatures, True)\n all_data = self.repo.current_data()\n ent_dat = {}\n for d in all_data:\n t = mdates.epoch2num(d[self.timeattr]) if self.timeattr is not False else d[self.indexattr]\n e = d[self.entityattr] if self.entityattr is not False else True\n if e not in self.all_entities:\n self.all_entities.append(e)\n v = [t, e] + [d[f] for f in [self.anomalyattr, self.classattr]+self.selectedFeatures]\n if e not in ent_dat.keys():\n ent_dat[e] = [v]\n else:\n ent_dat[e].append(v)\n \n # transpose for easy access to features\n for k in ent_dat:\n ent_dat[k] = list(zip(*ent_dat[k]))\n \n if self.show_all:\n if len(self.selectedEntities) < len(self.all_entities):\n self.set_selected_entities([])\n \n #print(all_data)\n #print(ent_dat)\n \n #all_data[0] = [ datetime.fromtimestamp(t) for t in all_data[0]]\n \n # for all selected features\n for f in enumerate(self.selectedFeatures,start=4): # start=4 because 0-time, 1-entity, 2-anomaly, 3-class, 4-features \n # clear old data\n self.features[f[1]]['axes'].clear()\n self.features[f[1]]['axes'].set_title(f[1], fontdict={'fontSize': 10}, loc='left')\n self.features[f[1]]['axes'].set_ylabel('')\n self.features[f[1]]['axes'].set_xticklabels([])\n # and each entity in feature\n \n for entityPlotInfo in self.features[f[1]]['entities']:\n entity = entityPlotInfo['entity']\n dat = ent_dat[entity]\n if(len(dat) == 0):\n continue\n \n p = list(zip(dat[0], dat[f[0]]))\n c = self._get_cols(dat[2],dat[3])\n \n l,cc = self._to_lines(p,c)\n colored_lines = LineCollection(l, colors=cc, linewidths=(3,))\n self.features[f[1]]['axes'].add_collection(colored_lines)\n #entityPlotInfo['line'].set_offsets( p )\n #entityPlotInfo['line'].set_color(c)\n \n self._reAdjustMultiPlotLimits(self.features[f[1]], min(dat[0]), min(dat[f[0]]))\n self._reAdjustMultiPlotLimits(self.features[f[1]], max(dat[0]), max(dat[f[0]]))\n \n #Update the deviation plot\n self.anomalies['axes'].clear()\n self.anomalies['axes'].set_ylabel('')\n self.anomalies['axes'].set_title(self.anomalyattr if self.anomalyattr else \"\", fontdict={'fontSize': 10}, loc='left')\n \n for entityPlotInfo in self.anomalies['entities']:\n entity = entityPlotInfo['entity']\n dat = ent_dat[entity]\n \n \n if len(dat) > 0:\n\n p = list(zip(dat[0], dat[2]))\n c = self._get_cols(dat[2], dat[3])\n l,cc = self._to_lines(p,c)\n colored_lines = LineCollection(l, colors=cc, linewidths=(3,))\n self.anomalies['axes'].add_collection(colored_lines)\n \n #entityPlotInfo['line'].set_offsets( list(zip(dat[0], dat[2])) )\n #entityPlotInfo['line'].set_color(self._get_cols(dat[3]))\n \n dd = [d for d in dat[2] if d is not None]\n if dd:\n self._reAdjustMultiPlotLimits(self.anomalies, min(dat[0]), min(dd))\n self._reAdjustMultiPlotLimits(self.anomalies, max(dat[0]), max(dd))\n \n if len(dat)>0 and self.timeattr is not False:\n ax = self.anomalies['axes']\n #ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0,15,30,45]))\n #ax.xaxis.set_minor_locator(mdates.MinuteLocator())\n monthFmt = mdates.DateFormatter(\"%H:%M\")\n ax.xaxis_date()\n ax.xaxis.set_major_formatter(monthFmt)\n \n \n def handle_data(self, dict_msg):\n \n entity = (dict_msg[self.entityattr] if self.entityattr is not False else True)\n if not entity in self.all_entities:\n self.all_entities.append(entity)\n\n # Only act if the entity is in the entity list\n if entity in self.selectedEntities:\n\n if self.timeattr is not False:\n newXvalue = mdates.epoch2num(dict_msg[self.timeattr])\n #newXvalue = datetime.datetime.fromtimestamp(dict_msg[self.timeattr])\n else:\n newXvalue = dict_msg[self.indexattr]\n \n # For every selected feature\n for feature in self.features:\n\n newYvalue = dict_msg[feature]\n featurePlotInfo = self.features[feature]\n \n # Get the entity information from the feature plot\n entityPlotInfo = next(item for item in featurePlotInfo['entities'] if item[\"entity\"] == entity)\n\n newXvalues = np.append(entityPlotInfo['line'].get_xdata(), newXvalue)\n newYvalues = np.append(entityPlotInfo['line'].get_ydata(), newYvalue)\n\n self._set_data(entityPlotInfo['line'], newXvalues, newYvalues)\n self._reAdjustMultiPlotLimits(featurePlotInfo, newXvalue, newYvalue)\n self._removeDataNotVisible(featurePlotInfo['xMin'], entityPlotInfo['line'])\n \n # Update the deviation plot of the entity \n if self.anomalyattr is not False and dict_msg[self.anomalyattr] is not None:\n \n anomalyPlotInfo = next(item for item in self.anomalies['entities'] if item['entity'] == entity)\n \n xx = np.append(anomalyPlotInfo['line'].get_xdata(), newXvalue)\n yy = np.append(anomalyPlotInfo['line'].get_ydata(), dict_msg[self.anomalyattr])\n \n self._set_data(anomalyPlotInfo['line'], xx, yy)\n self._reAdjustMultiPlotLimits(self.anomalies, \n newXvalue, \n dict_msg[self.anomalyattr])\n self._removeDataNotVisible(self.anomalies['xMin'], anomalyPlotInfo['line'])\n self.anomalies['axes'].set_ylim(0, 1)\n \n \n def _set_data(self, line, xx, yy):\n \n line.set_xdata(xx)\n line.set_ydata(yy)\n\n \n def _removeDataNotVisible(self, xMin, line):\n pass\n # Remove the data that is not shown to improve memory use\n #line.set_xdata([x for x in line.get_xdata() if x >= xMin])\n #line.set_ydata(line.get_ydata()[-len(line.get_xdata()):])\n \n \n def _reAdjustMultiPlotLimits(self, plotInfo, x, y):\n if x is not None and y is not None:\n # Determine the new min and max values\n if x < plotInfo['xMin']:\n plotInfo['xMin'] = x\n\n if x > plotInfo['xMax']:\n plotInfo['xMax'] = x\n\n if y < plotInfo['yMin']:\n plotInfo['yMin'] = y\n\n if y > plotInfo['yMax']:\n plotInfo['yMax'] = y\n\n # Readjusting the x axis according the requested time window\n #xMax = datetime.fromtimestamp(self.repo.get_time_now())#plotInfo['xMax']\n #xMin = xMax - timedelta(hours = self.timeWindowInHours)\n xMax = plotInfo['xMax']\n xMin = plotInfo['xMin']\n \n # Set the x axis limits\n if xMin != xMax:\n plotInfo['axes'].set_xlim(xMin + (xMax-xMin)*self.zoompropmin, xMin + (xMax-xMin)*self.zoompropmax)\n \n # Adjust the y min and y max\n ydiff = plotInfo['yMax'] - plotInfo['yMin']\n if (ydiff > 0.0):\n yMin = plotInfo['yMin'] - 0.05 * ydiff\n yMax = plotInfo['yMax'] + 0.05 * ydiff\n else:\n yMin = plotInfo['yMin'] - 0.1\n yMax = plotInfo['yMax'] + 0.1\n \n plotInfo['axes'].set_ylim(yMin, yMax)\n \n \n def _getRectangleList(self, rect, numberOfFeatures):\n \n # Holds the list with rectangles to be returned\n rectangles = []\n \n # Just for easier reading\n margin = 0.01\n areaLeft = rect[0]\n areaBottom = rect[1]\n areaWidth = rect[2]\n areaHeight = rect[3]\n\n # The deviation rectangle takes half the space on the bottom\n rectangles.append([areaLeft, areaBottom, areaWidth, areaHeight / 4 - margin])\n \n if numberOfFeatures > 0:\n \n # The top half of the space is split among the feature rectangles\n featureRectangleHeight = (areaHeight*3 / 4 / numberOfFeatures) - margin\n\n previousBottom = 0\n\n for featureOrder in range(0, numberOfFeatures):\n\n if featureOrder == 0:\n featureBottom = (areaBottom + (areaHeight / 4)) + (1.5 * margin)\n else:\n featureBottom = previousBottom + featureRectangleHeight + (2.5 * margin)\n\n rectangles.append([areaLeft, featureBottom, areaWidth, featureRectangleHeight])\n\n previousBottom = featureBottom\n\n return rectangles\n\n \n def set_selected_entities(self,entity_list):\n if not entity_list:\n #the list is empty which means all entities\n entity_list = self.all_entities\n self.show_all = True\n else:\n self.show_all = False\n \n toadd = [x for x in entity_list if x not in self.selectedEntities]\n toremove = [x for x in self.selectedEntities if x not in entity_list]\n for i in toadd:\n self.add_entity(i)\n for i in toremove:\n self.remove_entity(i)\n self.redraw_features()\n \n def set_selected_attributes(self,attribute_list):\n features_to_show = 3\n \n if attribute_list:\n toadd = [x for x in attribute_list if x not in self.selectedFeatures]\n toremove = [x for x in self.selectedFeatures if x not in attribute_list]\n n_remove = len(toadd)+len(self.selectedFeatures)-features_to_show\n for i in toadd:\n self.add_feature(i)\n for i in range(0,n_remove):\n self.remove_feature(toremove[i])\n self.redraw_features()\n\n \n def default_params(self):\n return { 'index_attribute': False,\n 'time_attribute': False,\n 'entity_attribute': False,\n 'class_attribute': False,\n 'class_color': None,\n 'anomaly_attribute': False, \n 'anomaly_color': None,\n 'anomaly_threshold': 0.5 }\n\n def set_params(self, dic):\n if 'time_attribute' in dic:\n self.timeattr = dic['time_attribute']\n if 'index_attribute' in dic:\n self.indexattr = dic['index_attribute']\n if 'entity_attribute' in dic:\n self.entityattr = dic['entity_attribute']\n if 'class_attribute' in dic:\n self.classattr = dic['class_attribute']\n if 'class_color' in dic:\n self.classcolfunc = dic['class_color']\n if 'anomaly_attribute' in dic:\n self.anomalyattr = dic['anomaly_attribute']\n if 'anomaly_color' in dic:\n self.anomalycolfunc = dic['anomaly_color']\n if 'anomaly_threshold' in dic:\n self.anomaly_threshold = dic['anomaly_threshold']\n\n def redraw_model(self, moddict):\n pass\n \n def scroll_event(self, event):\n # p, pmin, pmax, fact -> qmin, qmax\n # (qmx-qmin) = (pmax-pmin)*fact\n # qmin + p*(qmax-qmin) = pmin + p*(pmax-pmin)\n ax = self.anomalies['axes']\n tr = ax.transAxes.inverted().transform((event.x,event.y))\n pp = tr[0]\n if event.button == \"up\":\n fact = 0.8\n else:\n fact = 1.25\n pdiff = (self.zoompropmax - self.zoompropmin)\n qdiff = min(1.0, (self.zoompropmax - self.zoompropmin)*fact)\n self.zoompropmin = min(1.0, max(0.0, self.zoompropmin + pp*(pdiff-qdiff)))\n self.zoompropmax = max(0.0, min(1.0, self.zoompropmin + qdiff))\n for feature in self.features:\n self._reAdjustMultiPlotLimits(self.features[feature], None, None)\n self._reAdjustMultiPlotLimits(self.anomalies, None, None)\n plt.draw()\n\n def button_press_event(self, event):\n if event.button == 1 and event.key == None:\n ax = self.anomalies['axes']\n trans = ax.transAxes.inverted()\n pp = trans.transform((event.x,event.y))[0]\n if pp >= 0.0 and pp <= 1.0:\n self.draginfo = (trans, pp, self.zoompropmin, self.zoompropmax)\n else:\n self.draginfo = False\n\n def motion_notify_event(self, event):\n if self.draginfo is not False:\n (trans, oldpp, oldzmin, oldzmax) = self.draginfo\n pp = max(0.0, min(1.0, trans.transform((event.x,event.y))[0]))\n diff = -(pp-oldpp)*(oldzmax-oldzmin)\n self.zoompropmin = min(1.0-(oldzmax-oldzmin), max(0.0, oldzmin + diff))\n self.zoompropmax = max(0.0+(oldzmax-oldzmin), min(1.0, oldzmax + diff))\n for feature in self.features:\n self._reAdjustMultiPlotLimits(self.features[feature], None, None)\n self._reAdjustMultiPlotLimits(self.anomalies, None, None)\n plt.draw()\n\n def button_release_event(self, event):\n if event.button == 1 and self.draginfo is not False:\n self.draginfo = False\n","sub_path":"bidaf/TimeSeriesVisualizer.py","file_name":"TimeSeriesVisualizer.py","file_ext":"py","file_size_in_byte":26826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"353511613","text":"from tkinter import *\nfrom tkinter import ttk\nfrom classes import user, getUser, addClient, delClient, readClients\nimport threading\nfrom guiChanges import changeUserUI, addClientUI, changeClientUI\nfrom filesfncs import getConfigSets\nimport os\n\n# labelUser = \"usuario\"\n\n\nclass ConfigFrame(Frame):\n\n def __init__(self, win, cfgSets):\n super().__init__()\n self.win = win\n self.initUI(win, cfgSets)\n\n def initUI(self, win, cfgSets):\n\n self.master.title(\"Arch-Timer 1.0\")\n\n l0 = Label(win, text=\"Cadastro/Usuário\")\n l0.grid(row=0, column=0, columnspan=4)\n\n labelUser = StringVar()\n l1 = Label(win, textvariable=labelUser)\n labelUser.set(getUser())\n l1.grid(row=1, column=0, columnspan=3)\n b1 = Button(win, text=\"Mudar usuário\", width=16,\n command=lambda: changeUserUI(labelUser, cfgSets))\n b1.grid(row=1, column=3)\n\n lb1 = Listbox(win, width=63, height=16, activestyle='dotbox')\n lb1.grid(row=2, column=0, rowspan=3, columnspan=3)\n # s = ttk.Scrollbar(win, orient=VERTICAL, command=lb1.yview)\n # s.grid(column=3, row=2)\n # lb1['yscrollcommand'] = s.set\n clients = readClients()\n id = 0\n for i in clients:\n id += 1\n lb1.insert(id, i.name + \" - Cod:\" + i.cod + \" - \" + i.path.strip())\n b2 = Button(win, text=\"Adicionar\\nCliente\", height=5,\n width=16, command=lambda: (addClientUI(id+1, lb1)))\n b2.grid(row=2, column=3)\n b3 = Button(win, text=\"Mudar\\nCliente\", height=5, width=16, command=lambda: (\n changeClientUI(lb1.get(lb1.curselection()[0]), lb1, END, lb1.curselection()[0])))\n b3.grid(row=3, column=3)\n b4 = Button(win, text=\"Remover\\nCliente\", height=5,\n width=16, command=lambda: (delClient(lb1.get(lb1.curselection()[0]), lb1, END)))\n b4.grid(row=4, column=3)\n\n l2 = Label(win, text=\"Relatórios\")\n l2.grid(row=5, column=0, columnspan=4)\n b5 = Button(win, text=\"Mensal por\\nUsuário\", width=16,\n command=(lambda: os.system(\"python relatorio1.py \"+lb1.get(lb1.curselection()[0]).split(\" - \")[2])))\n b5.grid(row=6, column=0)\n b6 = Button(win, text=\"Mensal por\\narquivo\", width=16,\n command=(lambda: os.system(\"python relatorio2.py \"+lb1.get(lb1.curselection()[0]).split(\" - \")[2])))\n b6.grid(row=6, column=1)\n b7 = Button(win, text=\"Total\\nUsuário\", width=16, command=(\n lambda: os.system(\"python relatorio3.py \"+lb1.get(lb1.curselection()[0]).split(\" - \")[2])))\n b7.grid(row=6, column=2)\n b8 = Button(win, text=\"Total\\nEscritorio\", width=16, command=(\n lambda: os.system(\"python relatorio4.py \"+lb1.get(lb1.curselection()[0]).split(\" - \")[2])))\n b8.grid(row=6, column=3)\n\n\ndef callUI(cfgSets):\n win = Tk()\n win.geometry(\"505x372\")\n app = ConfigFrame(win, cfgSets)\n win.mainloop()\n\n\ncfgSets = getConfigSets()\ncallUI(cfgSets)\n","sub_path":"ArchTimer/guiWin.py","file_name":"guiWin.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"229428951","text":"import os\n\nfrom selenium import webdriver\nfrom selenium.webdriver import DesiredCapabilities\nfrom selenium.webdriver.chrome.webdriver import Options as ChromeOptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.webdriver import Options as FirefoxOptions\nfrom selenium.webdriver.remote.webdriver import WebDriver\nfrom selenium.webdriver.support.expected_conditions import presence_of_element_located\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom setup.CustomWebElement import CustomWebElement\n\n\nclass BrowserTypes:\n CHROME = 'chrome'\n FIREFOX = 'firefox'\n\n\nclass Accessor:\n def __init__(self, max_wait_timeout=10):\n self.browser = os.environ.get('BROWSER', 'CHROME').lower()\n self.username = os.environ.get('USERNAME', 'test@test.test')\n self.password = os.environ.get('PASSWORD', 'testtest')\n self.max_wait_timeout = max_wait_timeout\n self.__waiter: WebDriverWait = None\n self.__driver: WebDriver = None\n self._init_driver()\n\n def _init_driver(self):\n if self.browser == BrowserTypes.FIREFOX:\n options = FirefoxOptions()\n desired_capabilities = DesiredCapabilities.FIREFOX\n elif self.browser == BrowserTypes.CHROME:\n options = ChromeOptions()\n options.add_argument('--allow-running-insecure-content')\n options.add_argument('--ignore-certificate-errors')\n\n desired_capabilities = DesiredCapabilities.CHROME\n else:\n raise Exception(\"please specify browser in BROWSER env variable\")\n\n self.__driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',\n desired_capabilities=desired_capabilities,\n options=options)\n self.__waiter = WebDriverWait(self.__driver, self.max_wait_timeout)\n\n def shutdown(self):\n if self.__driver is not None:\n self.__driver.quit()\n\n def wait_for_load(self, id_locator=None, css_locator=None):\n if id_locator is not None:\n self.waiter.until(presence_of_element_located((By.ID, id_locator))).click()\n elif css_locator:\n self.waiter.until(presence_of_element_located((By.CSS_SELECTOR, css_locator))).click()\n else:\n raise Exception(\"please specify type of selector\")\n\n def find_element_by_css_selector(self, selector: str) -> CustomWebElement:\n return CustomWebElement(self.driver.find_element_by_css_selector(selector), css_locator=selector)\n\n def find_element_by_id(self, selector: str) -> CustomWebElement:\n return CustomWebElement(self.driver.find_element_by_id(selector), id_locator=selector)\n\n def wait(self, sec: float):\n self.driver.implicitly_wait(sec)\n\n @property\n def driver(self) -> WebDriver:\n return self.__driver\n\n @property\n def current_url(self):\n return self.__driver.current_url\n\n @property\n def waiter(self) -> WebDriverWait:\n return self.__waiter\n","sub_path":"setup/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"356516698","text":"\"\"\"Code for building and managing the result table for the tests.\n The result table itself (the 'table' field of an object of this class)\n is a list of lists of strings. The first row is the header row.\n Columns are \"Test\", \"Input\" (optional), \"Expected\", \"Got\", \"iscorrect\", \"ishidden\"\n\"\"\"\nimport html\nfrom collections import defaultdict\n\nMAX_STRING_LENGTH = 2000 # 2k is default maximum string length\n\n\nclass ResultTable:\n def __init__(self, params):\n self.params = params\n self.mark = 0\n self.table = None\n self.failed_hidden = False\n self.aborted = False\n self.has_stdins = False\n self.has_tests = False\n self.hiding = False\n self.num_failed_tests = 0\n self.missing_tests = 0\n self.global_error = ''\n self.column_formats = None\n self.images = defaultdict(list)\n default_params = {\n 'stdinfromextra': False,\n 'strictwhitespace': True,\n 'ALL_OR_NOTHING': True\n }\n for param, value in default_params.items():\n if param not in params:\n self.params[param] = value\n\n\n def set_header(self, testcases):\n \"\"\"Given the set of testcases, set the header as the first row of the result table\n and set flags to indicate presence or absence\n of various table columns.\n \"\"\"\n header = ['iscorrect']\n self.column_formats = ['%s']\n if any(test.testcode.strip() != '' for test in testcases):\n header.append(\"Test\")\n self.has_tests = True\n # If the test code should be rendered in html then set that as column format.\n if any(getattr(test, 'test_code_html', None) for test in testcases):\n self.column_formats.append('%h')\n else:\n self.column_formats.append('%s')\n\n stdins = [test.extra if self.params['stdinfromextra'] else test.stdin for test in testcases]\n if any(stdin.rstrip() != '' for stdin in stdins):\n header.append('Input')\n self.column_formats.append('%s')\n self.has_stdins = True\n header += ['Expected', 'Got', 'iscorrect', 'ishidden']\n self.column_formats += ['%s', '%s', '%s', '%s']\n self.table = [header]\n\n def image_column_nums(self):\n \"\"\"A list of the numbers of columns containing images\"\"\"\n return sorted(set([key[0] for key in self.images.keys()]))\n\n def get_column_formats(self):\n \"\"\" An ordered list of the column formats. Columns containing images are forced into %h format.\n Don't have formats for iscorrect and ishidden columns.\n \"\"\"\n image_columns = self.image_column_nums()\n formats = [self.column_formats[i] if i not in image_columns else '%h' for i in range(len(self.column_formats))]\n return formats[1:-2]\n\n def get_table(self):\n \"\"\"Return the current result table, with images added to appropriate cells.\n Columns that contain images anywhere are converted to %h format and existing content in that column\n is html-escaped, newlines replaced with
and wrapped in a div.\n \"\"\"\n result_table = [row[:] for row in self.table] # Clone the result table\n\n # Htmlise all columns containing images\n for col_num in self.image_column_nums():\n for row_num in range(1, len(result_table)):\n result_table[row_num][col_num] = self.htmlise(result_table[row_num][col_num])\n\n # Append images\n for ((col,row), image_list) in self.images.items():\n for image in image_list:\n try:\n result_table[row][col] += \"
\" + image\n except IndexError:\n pass # Testing must have aborted so discard image\n\n return result_table\n\n def reset(self):\n if len(self.table) > 1:\n del self.table[1:]\n self.global_error = ''\n self.num_failed_tests = self.mark = 0\n self.failed_hidden = self.hiding = self.aborted = False\n\n def tests_missed(self, num):\n \"\"\"Record the fact that we're missing some test results (timeout?)\"\"\"\n self.missing_tests = num\n\n def record_global_error(self, error_message):\n \"\"\"Record some sort of global failure\"\"\"\n self.global_error = error_message\n\n def add_row(self, testcase, result, error=''):\n \"\"\"Add a result row to the table for the given test and result\"\"\"\n is_correct = self.check_correctness(result + error, testcase.expected)\n row = [is_correct]\n if self.has_tests:\n if getattr(testcase, 'test_code_html', None):\n row.append(testcase.test_code_html)\n else:\n row.append(testcase.testcode)\n if self.has_stdins:\n row.append(testcase.extra if self.params['stdinfromextra'] else testcase.stdin)\n row.append(testcase.expected)\n max_len = self.params.get('maxstringlength', MAX_STRING_LENGTH)\n result = sanitise(result.strip('\\n'), max_len)\n\n if error:\n error_message = '*** RUN TIME ERROR(S) ***\\n' + sanitise(error, max_len)\n if result:\n result = result + '\\n' + error_message\n else:\n result = error_message\n row.append(result)\n\n if is_correct:\n self.mark += testcase.mark\n else:\n self.num_failed_tests += 1\n row.append(is_correct)\n display = testcase.display.upper()\n is_hidden = (\n self.hiding or\n display == 'HIDE' or\n (display == 'HIDE_IF_SUCCEED' and is_correct) or\n (display == 'HIDE_IF_FAIL' and not is_correct)\n )\n row.append(is_hidden)\n if not is_correct and is_hidden:\n self.failed_hidden = True\n if not is_correct and testcase.hiderestiffail:\n self.hiding = True\n self.table.append(row)\n if error:\n self.aborted = True\n\n def get_mark(self):\n return self.mark if self.num_failed_tests == 0 or not self.params['ALL_OR_NOTHING'] else 0\n\n @staticmethod\n def htmlise(s):\n \"\"\"Convert the given string to html by escaping '<' and '>'.\n Wrap the whole lot in a div tag so the diff checker processes the whole table cell,\n and within that a pre tag for correct laylout.\n \"\"\"\n return '
' + html.escape(s) + '
'\n\n def add_image(self, image_html, column_name, row_num):\n \"\"\"Store the given html_image for later inclusion in the cell at the given row and given column.\n column_name is the name used for the column in the first (header) row.\n row_num is the row number (0 origin, not including the header row).\n \"\"\"\n column_num = self.table[0].index(column_name)\n self.images[column_num, row_num + 1].append(image_html)\n\n def check_correctness(self, expected, got):\n \"\"\"True iff expected matches got with relaxed white space requirements\"\"\"\n expected_lines = expected.strip().splitlines()\n got_lines = got.strip().splitlines()\n if len(got_lines) != len(expected_lines):\n return False\n else:\n for exp, got in zip(expected_lines, got_lines):\n if self.params['strictwhitespace']:\n if exp.rstrip() != got.rstrip():\n return False\n else:\n if exp.strip().split() != got.strip().split():\n return False\n return True\n\n\ndef sanitise(s, max_len=MAX_STRING_LENGTH):\n \"\"\"Replace non-printing chars with escape sequences, right-strip.\n Limit s to max_len by snipping out bits in the middle.\n \"\"\"\n result = ''\n if len(s) > max_len:\n s = s[0: max_len // 2] + \"\\n*** ***\\n\" + s[-max_len // 2:]\n lines = s.rstrip().splitlines()\n for line in lines:\n for c in line.rstrip() + '\\n':\n if c < ' ' and c != '\\n':\n if c == '\\t':\n c = r'\\t'\n elif c == '\\r':\n c = r'\\r'\n else:\n c = r'\\{:03o}'.format(ord(c))\n result += c\n return result.rstrip()\n","sub_path":"uoc_c_programming/resulttable.py","file_name":"resulttable.py","file_ext":"py","file_size_in_byte":8316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"138859997","text":"import os\r\nimport click\r\nimport pickle\r\n\r\nimport pandas as pd\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\n\r\ndef load_model(model_path: str) -> RandomForestClassifier:\r\n with open(model_path, \"rb\") as f:\r\n model = pickle.load(f)\r\n return model\r\n\r\n\r\ndef save_predictions(preds, output_path: str):\r\n y = pd.DataFrame({\"target\": preds})\r\n y.to_csv(output_path, index=False, header=None)\r\n\r\n\r\n@click.command(\"predict\")\r\n@click.option(\"--input-dir\")\r\n@click.option(\"--model-dir\")\r\n@click.option(\"--output-dir\")\r\ndef predict(input_dir: str, model_dir: str, output_dir: str):\r\n data_path = os.path.join(input_dir, \"data.csv\")\r\n data = pd.read_csv(data_path)\r\n\r\n model_path = os.path.join(model_dir, \"model.pkl\")\r\n model = load_model(model_path)\r\n\r\n preds = model.predict(data)\r\n os.makedirs(output_dir, exist_ok=True)\r\n preds_path = os.path.join(output_dir, \"predictions.csv\")\r\n save_predictions(preds, preds_path)\r\n\r\n\r\nif __name__ == '__main__':\r\n predict()\r\n","sub_path":"airflow_ml_dags/images/airflow-predict/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"182961898","text":"import json\r\n\r\ndef validateJSON(jsonData):\r\n try:\r\n json.loads(jsonData)\r\n except ValueError as err:\r\n return False\r\n return True\r\n\r\nInvalidJsonData = \"\"\"{ \"company\":{ \"employee\":{ \"name\":\"emma\", \"payble\":{ \"salary\":7000 \"bonus\":800} } } }\"\"\"\r\nisValid = validateJSON(InvalidJsonData)\r\n\r\nprint(\"Given JSON string is Valid\", isValid)\r\n","sub_path":"New file.py","file_name":"New file.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"69225072","text":"# -*- coding: utf-8 -*-\n\nimport threading\nimport time\nimport traceback\nimport sys\nimport re\n\nfrom .third_party import source_utils\nfrom .third_party.cloudscraper import cloudscraper\nfrom .third_party.source_utils import tools\nfrom .common_types import UrlParts\nfrom .utils import database\nfrom requests.compat import urlparse, urlunparse\n\n_head_checks = {}\n\ndef _is_cloudflare_iuam_challenge(resp, allow_empty_body=False):\n try:\n return (\n resp.headers.get('Server', '').startswith('cloudflare')\n and resp.status_code in [429, 503]\n and (allow_empty_body or re.search(\n r'action=\"/.*?__cf_chl_jschl_tk__=\\S+\".*?name=\"jschl_vc\"\\svalue=.*?',\n resp.text,\n re.M | re.DOTALL\n ))\n )\n except AttributeError:\n pass\n\n return False\n\ndef _get_domain(url): \n parsed_url = urlparse(url)\n scheme = parsed_url.scheme if parsed_url.scheme != '' else 'https'\n return \"%s://%s\" % (scheme, parsed_url.netloc)\n\ndef _get_head_check(url):\n result = _head_checks.get(url, None)\n if isinstance(result, bool):\n return (url, result)\n elif result is not None:\n return _get_head_check(result)\n\n return (url, None)\n\nclass Request(object):\n def __init__(self, sequental=False, timeout=None, wait=1):\n self._request = source_utils.randomUserAgentRequests()\n self._cfscrape = cloudscraper.create_scraper(interpreter='native')\n self._sequental = sequental\n self._wait = wait\n self._should_wait = False\n self._lock = threading.Lock()\n self._timeout = 10\n if timeout is not None:\n self._timeout = timeout\n self.has_timeout_exc = False\n self.exc_msg = ''\n self.skip_head = False\n\n def _verify_response(self, response):\n if response.status_code >= 400:\n self.exc_msg = 'response status code %s' % response.status_code\n if response.status_code in [429, 503]:\n self.exc_msg = '%s (probably Cloudflare)' % self.exc_msg\n raise Exception()\n\n def _request_core(self, request, sequental = None):\n self.has_timeout_exc = False\n self.exc_msg = ''\n\n if sequental is None:\n sequental = self._sequental\n\n response_err = lambda: None\n response_err.status_code = 501\n\n try:\n response = None\n if sequental is False:\n response = request()\n\n response_err = response\n self._verify_response(response)\n\n return response\n\n with self._lock:\n if self._should_wait:\n time.sleep(self._wait)\n self._should_wait = True\n response = request()\n\n response_err = response\n self._verify_response(response)\n\n return response\n except:\n if self.exc_msg == '':\n exc = traceback.format_exc(limit=1)\n if 'ConnectTimeout' in exc or 'ReadTimeout' in exc:\n self.has_timeout_exc = True\n self.exc_msg = 'request timed out'\n elif 'Cloudflare' in exc or '!!Loop Protection!!' in exc:\n self.exc_msg = 'failed Cloudflare protection'\n else:\n self.exc_msg = 'failed - %s' % exc\n\n tools.log('%s %s' % (request.url, self.exc_msg), 'notice')\n\n return response_err\n\n def _check_redirect(self, response):\n if response.status_code in [301, 302]:\n redirect_url = response.headers['Location']\n if not redirect_url.endswith('127.0.0.1') and not redirect_url.endswith('localhost'):\n return redirect_url\n return False\n\n def _head(self, url):\n global _head_checks\n\n if self.skip_head:\n return (url, 200)\n\n (url, head_check) = _get_head_check(url)\n if head_check:\n return (url, 200)\n elif head_check is False:\n return (url, 500)\n\n url = _get_domain(url)\n tools.log('HEAD: %s' % url, 'info')\n request = lambda: self._request.head(url, timeout=2)\n request.url = url\n response = self._request_core(request, sequental=False)\n if _is_cloudflare_iuam_challenge(response, allow_empty_body=True):\n response = lambda: None\n response.url = url\n response.status_code = 200\n\n try:\n head_check_key = _get_domain(response.url)\n except:\n response.url = url\n head_check_key = _get_domain(url)\n\n redirect_url = self._check_redirect(response)\n if redirect_url:\n _head_checks[head_check_key] = redirect_url\n return self._head(redirect_url)\n\n _head_checks[head_check_key] = response.status_code is 200\n\n return (response.url, response.status_code)\n\n def head(self, url):\n return database.get(self._head, 12, url)\n\n def find_url(self, urls):\n for url in urls:\n (response_url, status_code) = self.head(url.base)\n if status_code != 200:\n continue\n\n if response_url.endswith(\"/\"):\n response_url = response_url[:-1]\n\n return UrlParts(base=response_url, search=url.search)\n\n return None\n\n def get(self, url, headers={}, allow_redirects=True):\n parsed_url = urlparse(url)\n\n response = self.head(_get_domain(url))\n if response is None:\n return None\n\n (url, status_code) = response\n if status_code != 200:\n return None\n\n resolved_url = urlparse(url)\n url = urlunparse(\n (\n resolved_url.scheme,\n resolved_url.netloc,\n parsed_url.path,\n parsed_url.params,\n parsed_url.query,\n parsed_url.fragment,\n )\n )\n\n tools.log('GET: %s' % re.sub(r'\\?key=(.+?)&', '?', url), 'info')\n request = lambda: self._cfscrape.get(url, headers=headers, timeout=self._timeout, allow_redirects=allow_redirects)\n request.url = url\n\n return self._request_core(request)\n\n def post(self, url, data, headers={}):\n tools.log('POST: %s' % url, 'info')\n request = lambda: self._cfscrape.post(url, data, headers=headers, timeout=self._timeout)\n request.url = url\n return self._request_core(request)\n","sub_path":"cloudscraper/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":6481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"20348695","text":"import json\nimport logging\nimport os\nimport shutil\nimport sys\nfrom io import BytesIO\n\nimport redis\nfrom PIL import Image, ImageDraw, ImageFont\nfrom gevent import monkey\n\n# patches stdlib (including socket and ssl modules) to cooperate with other greenlets\nmonkey.patch_all()\n\nimport gevent\n\nimport cloudinary.uploader\nimport requests\n\nlog = logging.getLogger(\"bottomnine\")\nlog.setLevel(logging.DEBUG)\n# create file handler which logs even debug messages\nfh = logging.FileHandler(\"bottomnine.log\")\nfh.setLevel(logging.DEBUG)\n\nlog.addHandler(fh)\n\n# config\nwith open(\"config.json\") as file:\n config = json.loads(file.read())\n\nJSON_FOLDER = config[\"JSON_FOLDER\"]\nIMAGE_TEMP = config[\"IMAGE_TEMP\"]\n\nFONT = config[\"FONT\"]\nTEXT = config[\"TEXT\"]\n\ncloudinary.config(**config[\"CLOUDINARY\"])\n\nREDIS_ENDPOINT = config[\"REDIS_ENDPOINT\"]\nREDIS_PORT = config[\"REDIS_PORT\"]\nREDIS_PASSWORD = config[\"REDIS_PASSWORD\"]\n\ntry:\n conn = redis.Redis(REDIS_ENDPOINT, REDIS_PORT, password=REDIS_PASSWORD)\nexcept redis.RedisError as e:\n log.error(str(e))\n\n print(\"500\")\n sys.exit()\n\n# begin\n\nusername = sys.argv[1]\nposts_path = \"{}/{}.json\".format(JSON_FOLDER, username)\n\nif not os.path.isfile(posts_path):\n print(\"404\")\n\n sys.exit()\n\nprint(\"200\") # allow flask to respond to request. remainder of command runs in background\n\ntry:\n\n with open(posts_path, encoding=\"utf-8\") as file:\n posts = json.loads(file.read())\n\n # remove any posts not made in 2018\n\n log.info(\"sorting posts\")\n\n MIN_TIME = 1514764800\n MAX_TIME = 1546300800\n\n # sort posts\n\n i = 0\n while i < len(posts):\n if not (MIN_TIME <= posts[i][\"taken_at_timestamp\"] < MAX_TIME):\n del posts[i]\n else:\n i += 1\n\n posts = sorted(posts, key=lambda p: p[\"edge_media_preview_like\"][\"count\"])[:9]\n\n with open(posts_path, \"w\") as file:\n file.write(json.dumps(posts))\n\n # download images\n\n log.info(\"downloading grid images for {}\".format(username))\n\n\n def download_file(url, path):\n r = requests.get(url)\n with open(path, \"wb\") as file:\n file.write(r.content)\n\n return True\n\n\n img_temp = \"{}/{}\".format(IMAGE_TEMP, username)\n\n if not os.path.exists(img_temp):\n os.makedirs(img_temp)\n\n tasks = []\n i = 0\n\n for post in posts:\n tasks.append(gevent.spawn(download_file, post[\"display_url\"], \"{}/{}.jpg\".format(img_temp, i)))\n\n i += 1\n\n gevent.joinall(tasks, timeout=10)\n\n # determine grid size\n\n grid_size = 3\n\n if len(posts) < 9:\n grid_size = 2\n if len(posts) < 4:\n grid_size = 1\n\n cell_size = int(1200 / grid_size)\n\n # make grid !\n\n log.info(\"making grid\")\n\n img = Image.new(\"RGB\", (1200, 1400), \"white\")\n\n i = 0\n for y in range(grid_size):\n for x in range(grid_size):\n to_paste = Image.open(\"{}/{}.jpg\".format(img_temp, i))\n\n # make image square\n sx, sy = to_paste.size\n\n if sx != sy:\n if sx < sy:\n # portrait\n offset = (sy - sx) / 2\n crop = (0, offset, sx, sy - offset)\n\n to_paste = to_paste.crop(crop)\n else:\n # landscape\n offset = (sx - sy) / 2\n crop = (offset, 0, sx - offset, sy)\n\n to_paste = to_paste.crop(crop)\n\n # check whether downsizing or not\n mode = Image.ANTIALIAS if cell_size ** 2 > sx * sy else Image.BICUBIC\n\n to_paste = to_paste.resize((cell_size, cell_size), mode)\n\n img.paste(to_paste, (x * cell_size, y * cell_size))\n\n i += 1\n\n if i >= len(posts):\n break\n if i >= len(posts):\n break\n\n # add caption\n\n big = ImageFont.truetype(FONT, 64)\n small = ImageFont.truetype(FONT, 36)\n draw = ImageDraw.Draw(img)\n\n draw.rectangle((0, 1200, 1200, 1400), fill=(229, 45, 64))\n draw.rectangle((0, 1325, 1200, 1400), fill=(20, 20, 20))\n\n # big text\n tx, ty = draw.textsize(TEXT, big, spacing=6)\n draw.text((600 - tx / 2, 1255 - ty / 2), TEXT, fill=(255, 255, 255), font=big, spacing=6)\n\n # small text\n tx, ty = draw.textsize(\"http://paric.xyz/\", small, spacing=12)\n draw.text((600 - tx / 2, 1362 - ty / 2), \"http://paric.xyz/\", fill=(255, 255, 255), font=small, spacing=12)\n\n buffer = BytesIO()\n\n img.save(buffer, \"png\")\n\n buffer.seek(0)\n\n resp = cloudinary.uploader.upload(buffer)\n\n conn.set(\"images.{}\".format(username), resp[\"url\"])\n\n log.info(\"upload successful\")\n\n # delete tmp files and redis progress value\n\n shutil.rmtree(img_temp)\n os.remove(\"{}/{}.json\".format(JSON_FOLDER, username))\n\n conn.delete(username)\n\nexcept Exception as e:\n\n log.error(e.__class__.__name__ + \": \" + str(e))\n","sub_path":"background/makegrid.py","file_name":"makegrid.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"323580828","text":"import serial\nimport tkinter as tk\n\n\nesp32 = serial.Serial('COM6', 9600)\n\n\ndef key_handler(key):\n print(key)\n esp32.write(bytes(key, 'ascii'))\n\n\nif __name__ == '__main__':\n root = tk.Tk()\n root.bind(\"\", lambda e: key_handler(e.char))\n tk.Grid.rowconfigure(root, 0, weight=1)\n tk.Grid.columnconfigure(root, 0, weight=1)\n\n main = tk.Frame(root)\n tk.Grid.rowconfigure(main, 0, weight=1)\n tk.Grid.rowconfigure(main, 1, weight=0)\n tk.Grid.columnconfigure(main, [0, 2], weight=1)\n tk.Grid.columnconfigure(main, 1, weight=2)\n\n left_main = tk.Frame(main)\n tk.Grid.columnconfigure(left_main, 0, weight=1)\n tk.Grid.rowconfigure(left_main, 0, weight=1)\n\n mid_main = tk.Frame(main)\n tk.Grid.columnconfigure(mid_main, 0, weight=1)\n tk.Grid.rowconfigure(mid_main, [0, 1], weight=1)\n\n right_main = tk.Frame(main)\n tk.Grid.columnconfigure(right_main, 0, weight=1)\n tk.Grid.rowconfigure(right_main, 0, weight=1)\n\n forward_button = tk.Button(mid_main, text=\"FORWARD\", command=lambda: key_handler('w'))\n left_button = tk.Button(left_main, text=\"TURN LEFT\", command=lambda: key_handler('a'))\n back_button = tk.Button(mid_main, text=\"BACKWARD\", command=lambda: key_handler('s'))\n right_button = tk.Button(right_main, text=\"TURN RIGHT\", command=lambda: key_handler('d'))\n stop_button = tk.Button(main, text=\"STOP\", command=lambda: key_handler('e'))\n # play button\n # pause button\n\n main.grid(column=0, row=0, sticky=tk.NSEW)\n left_main.grid(column=0, row=0, sticky=tk.NSEW)\n mid_main.grid(column=1, row=0, sticky=tk.NSEW)\n right_main.grid(column=2, row=0, sticky=tk.NSEW)\n\n left_button.grid(column=0, row=0, sticky=tk.NSEW)\n forward_button.grid(column=0, row=0, sticky=tk.NSEW)\n back_button.grid(column=0, row=1, sticky=tk.NSEW)\n right_button.grid(column=0, row=0, sticky=tk.NSEW)\n stop_button.grid(column=0, row=1, sticky=tk.EW)\n\n tk.mainloop()\n","sub_path":"manual/manual_input.py","file_name":"manual_input.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"580996415","text":"import unittest\nimport qi\nimport time\nfrom AnimationPlayer import AnimationPlayer\n\nfrom Posture import rest_position\n\n\nclass PointMoveTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n self.session = qi.Session()\n self.session.connect('tcp://192.168.1.101:9559')\n self.motion = self.session.service('ALMotion')\n self.posture = self.session.service(\"ALRobotPosture\")\n self.animation_player = AnimationPlayer(self.session, motion=self.motion)\n self.motion.setCollisionProtectionEnabled('Arms', False)\n self.motion.setExternalCollisionProtectionEnabled('All', False)\n rest_position(session=self.session)\n\n def test_reaction_won(self):\n self.animation_player.play_win_animation()\n\n def test_reaction_lost(self):\n self.animation_player.play_lose_animation()\n\n def test_reaction_draw(self):\n self.animation_player.play_draw_animation()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"TicTacToe/tests/AnimationTest.py","file_name":"AnimationTest.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"124354893","text":"from bs4 import BeautifulSoup\n\nfrom app import app\n\ncfg = app.config\n\nbase_url = \"https://www.linguee.com/\"\n\n\ndef get_target_language(language: str):\n if language.lower() != 'french':\n return 'french'\n else:\n return 'english'\n\n\ndef get_sentences(word: str, language: str):\n url = base_url + language.lower() + '-' + get_target_language(language) + \\\n \"/search?source=auto&source=\" + language.lower() + \"&query=\" + word.replace(' ', '%20')\n print(\"Searching on {}\".format(url))\n cfg[\"web_driver\"].get_driver().get(url)\n soup = BeautifulSoup(cfg[\"web_driver\"].get_driver().page_source, 'html.parser')\n response = []\n for section in soup.find_all('div', 'lemma featured'):\n response = response + [example.string\n for example in section.find_all('span', 'tag_s')]\n\n response = [example.strip() for example in response if example != None and example.strip() != \"\"]\n print(\"Found sentences: {}\".format(response))\n return response\n","sub_path":"app/service/linguee.py","file_name":"linguee.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"408186874","text":"from setuptools import setup, find_packages\r\n\r\n\r\nwith open('README.md') as readme:\r\n long_description = readme.read()\r\n\r\n\r\nsetup(\r\n name='nbtlib',\r\n version='1.0.2',\r\n license='MIT',\r\n description='A python package to read and edit nbt data',\r\n long_description=long_description,\r\n long_description_content_type='text/markdown',\r\n\r\n author='Valentin Berlier',\r\n author_email='berlier.v@mail.com',\r\n url='https://github.com/vberlier/nbtlib',\r\n\r\n platforms=['any'],\r\n python_requires='>=3.6',\r\n classifiers=[\r\n 'Development Status :: 4 - Beta',\r\n 'Intended Audience :: Developers',\r\n 'License :: OSI Approved :: MIT License',\r\n 'Operating System :: OS Independent',\r\n 'Programming Language :: Python :: 3.6',\r\n 'Topic :: Software Development :: Libraries :: Python Modules',\r\n ],\r\n keywords='nbt schema minecraft package library parser reader module',\r\n\r\n packages=find_packages(),\r\n\r\n entry_points={\r\n 'console_scripts': [\r\n 'nbt=nbtlib.cli:main',\r\n ],\r\n }\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"192668959","text":"import numpy as np\nimport glob\nimport cv2\nimport os\nfrom arnold.utils.reporter import Reporter\n\nclass AgeGenderHelper:\n\tdef __init__(self, config):\n\t\tself.config = config\n\t\tself.ageBins = self.buildAgeBins()\n\t\tself.report = Reporter().report\n\n\tdef buildAgeBins(self):\n\t\tageBins = [(0, 2), (4, 6), (8, 13), (15, 20), (25, 32), (38, 43), (48, 53), (60, np.inf)]\n\t\treturn ageBins\n\n\tdef toLabel(self, age, gender):\n\t\tif self.config.DATASET_TYPE == \"age\":\n\t\t\treturn self.toAgeLabel(age)\n\n\t\treturn self.toGenderLabel(gender)\n\n\tdef toAgeLabel(self,age):\n\t\tlabel = None\n\n\t\tage = age.replace(\"(\", \"\").replace(\")\", \"\").split(\", \")\n\t\tageLower, ageUpper = np.array(age, dtype=\"int\")\n \n\n\t\tfor (lower, upper) in self.ageBins:\n\t\t\tif ageLower >=lower and ageUpper <= upper:\n\t\t\t\tlabel = \"{}_{}\".format(lower, upper)\n\t\t\t\tbreak\n\n\n\t\treturn label\n\n\tdef toGenderLabel(self, gender):\n\t\treturn 0 if gender == \"m\" else 1\n\n\tdef buildOneOffMappings(self, le):\n\t\tclasses = sorted(le.classes_, key=lambda x: int(x.decode(\"utf-8\").split(\"_\")[0]))\n\t\toneOff = {}\n\n\t\tfor i, name in enumerate(classes):\n\t\t\tcurrent = np.where(le.classes_ == name)[0][0]\n\t\t\tprev = -1\n\t\t\tnext = -1\n\n\t\t\tif i > 0:\n\t\t\t\tprev = np.where(le.classes_ == classes[i - 1])[0][0]\n\t\t\n\t\t\tif i < len(classes) - 1:\n\t\t\t\tnext = np.where(le.classes_ == classes[i + 1])[0][0]\n\n\t\n\t\t\toneOff[current] = (current, prev, next)\n\n\t\treturn oneOff\n\n\tdef buildPathsAndLabels(self):\n\n\t\tpaths = []\n\t\tlabels = []\n\n\t\tfoldPaths = os.path.sep.join([self.config.LABELS_PATH, \"*.txt\"])\n\t\tfoldPaths = glob.glob(foldPaths)\n\n\t\tfor foldPath in foldPaths:\n\t\t\trows = open(foldPath).read()\n\t\t\trows = rows.strip().split(\"\\n\")[1:]\n\n\t\t\tfor (i, row ) in enumerate(rows):\n\t\t\t\trow = row.split(\"\\t\")\n\t\t\t\tuserID, imagePath, faceID, age, gender = row[:5]\n\n\t\t\t\t#if age[0] != \"(\" or gender not in (\"m\", \"f\"):\n\t\t\t\t#\tcontinue\n\n\t\t\t\tp = \"landmark_aligned_face.{}.{}\".format(faceID, imagePath)\n\t\t\t\tp = os.path.sep.join([self.config.IMAGES_PATH, userID, p])\n\n\t\t\t\tfail = False\n\n\t\t\t\tif self.config.DATASET_TYPE == \"age\":\n\t\t\t\t\tif age.isdigit(): age = \"(\" + age + \", \" + age +\")\"\n\t\t\t\t\tif age[0] != \"(\": fail = True\n\n\t\t\t\t#if age[0] != \"(\" or gender not in (\"m\", \"f\"):\t\n\t\t\t\tif self.config.DATASET_TYPE == \"gender\" and gender not in (\"m\", \"f\"):\n\t\t\t\t\tfail = True\n\n\t\t\t\tif fail:\n\t\t\t\t\tself.report(\"[BAD FORMAT] age:{}, gender:{} --> {}\".format(age, gender, p))\n\t\t\t\t\tself.report(\"\\t\\tIn {} line {}\".format(foldPath, i+1))\n\t\t\t\t\tcontinue\n\n\t\t\t\tlabel = self.toLabel(age, gender)\n\n\t\t\t\tif label is None:\n\t\t\t\t\tself.report(\"[INVALID INPUT] age:{}, gender:{} --> {}\".format(age, gender, p))\n\t\t\t\t\tself.report(\"\\t\\tIn {} line {}\".format(foldPath, i+1))\n\t\t\t\t\tcontinue\n\n\t\t\t\tpaths.append(p)\n\t\t\t\tlabels.append(label)\n\n\t\treturn paths, labels \n\n\n\t# to be implemented \n\t# def visualizeAge page 214 refer to Chapter 11\n\t# def visualizeGender page 214","sub_path":"arnold/utils/agegenderhelper.py","file_name":"agegenderhelper.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"434800666","text":"import requests\r\nimport json\r\nimport jsonpath\r\n\r\nbase_url = 'https://api.thecatapi.com/v1/votes'\r\nheaders_xapi = {\r\n \"x-api-key\": \"DEMO-API-KEY\"\r\n}\r\nheaders_xapip = {\r\n \"x-api-key\": \"DEMO-API-KEY\",\r\n \"Content-Type\": \"application/json\"\r\n}\r\nassert base_url != \"\", \"Base URL is empty\"\r\nassert headers_xapi != \"\", \"Header is empty\"\r\nresponse = requests.get(base_url, headers = headers_xapi)\r\n#print(response.content)\r\njson_response = json.loads(response.text)\r\nprint((json_response))\r\nprint(response.status_code)\r\n#print(type(response.status_code))\r\nprint(type(json_response))\r\nassert response.status_code == 200, \"Get Request is successful\"\r\n\r\n\r\n\r\n\r\n#for i in json_response:\r\n# print(i['id'])\r\n\r\n#get the random ID\r\nID1 = json_response[1]['id']\r\nprint(ID1)\r\nassert ID1 == 31099, \"correct ID\"\r\n\r\n#for match in jsonpath.jsonpath(json_response, 'id'):\r\n# print(match)\r\n\r\n#Post data\r\nnew_resource = \"{\\\"image_id\\\":\\\"asf2\\\",\\\"sub_id\\\":\\\"my-user-1234\\\",\\\"value\\\":1}\"\r\n\r\nr = requests.post(base_url, headers = headers_xapip, data=new_resource)\r\nprint(r.status_code)\r\nassert r.status_code == 200, \"POST Successful\"\r\n\r\njr=(r.json())\r\nvote_id = str((jr['id']))\r\n\r\n\r\n#Get specific Vote\r\n\r\nurl1= \"https://api.thecatapi.com/v1/votes/\"\r\nresponse = requests.get(url1+vote_id, headers = headers_xapi)\r\njson_response = json.loads(response.text)\r\nprint((json_response))\r\nprint(response.status_code)\r\nassert response.status_code == 200, \"GET Successful for newly added ID\"\r\n\r\n#Delete the newly added Vote\r\nurl1= \"https://api.thecatapi.com/v1/votes/\"\r\nresponse = requests.delete(url1+vote_id, headers = headers_xapi)\r\njson_response = json.loads(response.text)\r\nprint((json_response))\r\nprint(response.status_code)\r\nassert response.status_code == 200, \"Delete Successful for newly added ID\"\r\n\r\n#Get the Deleted Vote\r\n\r\nurl1= \"https://api.thecatapi.com/v1/votes/\"\r\nresponse = requests.get(url1+vote_id, headers = headers_xapi)\r\njson_response = json.loads(response.text)\r\nprint((json_response))\r\nprint(response.status_code)\r\nassert response.status_code == 404, \"Didnot get deleted Vote ID\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"555669914","text":"#!/usr/bin/env python3\n# 15-1\nimport matplotlib.pyplot as plt\n\nplt.title(\"Cube Numbers\", fontsize=24)\nplt.xlabel(\"Value\", fontsize=14)\nplt.ylabel(\"Cube of Value\", fontsize=14)\n\n# x_values = [1, 2, 3, 4, 5]\nx_values = list(range(1, 5001))\ny_values = [x**3 for x in x_values]\n\nplt.plot(x_values, y_values, linewidth=5)\n\nplt.show()","sub_path":"chapter15/cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"414796129","text":"from django.shortcuts import render, redirect\nfrom professions import models as profs\nfrom user_test_main import models as score\nfrom django.db.models import Q\nfrom result_main import result_filters as filters\nfrom django.core import exceptions\nfrom django.core import serializers\n\n\n# Create your views here.\n\n\ndef result(request):\n user = request.GET.get('username')\n result_type = request.GET.get('result')\n try:\n fopt = score.Score.objects.filter(user__username=user)\n except exceptions.ObjectDoesNotExist:\n return render(request,\n 'result_main/result.html',\n context={\n 'error': 'Результат не найден'})\n sphere = profs.ProfSphere.objects.all()\n personality = profs.Personality.objects.all()\n direction = profs.Direction.objects.all()\n personality = filters.define_personality(personality, fopt)\n direction = filters.define_directions(direction, fopt)\n if result_type == 'common':\n sphere = filters.define_profspheres(sphere, fopt)\n return render(request, 'result_main/result.html', context={\n 'spheres': sphere,\n 'scales': personality,\n 'directions': direction})\n elif result_type == 'extended':\n profession = profs.Profession.objects.all()\n if score.Score.objects.get(user__username=user).specialchoice:\n sphere = filters.show_special_choice(sphere, fopt)\n elif score.Score.objects.get(user__username=user).school == '239':\n sphere = filters.define_profspheres_239(sphere, fopt)\n else:\n sphere = filters.define_profspheres(sphere, fopt)\n professions = filters.reject_uncompatible_professions(profession, fopt)\n professions = filters.define_professions(professions, sphere)\n if score.Score.objects.get(user__username=user).school == '239':\n professions = professions.order_by('order_239')\n else:\n professions = professions.order_by('profsphere')\n legend = profs.CareerTrace.objects.filter(category='legend').order_by('-id')\n tooltips = profs.CareerStage.objects.all()\n id_professions = serializers.serialize('json', list(professions), fields=('id'))\n tooltips = serializers.serialize('json', list(tooltips), fields=('name', 'description'))\n return render(request, 'result_main/result_special.html', context={\n 'spheres': sphere,\n 'professions': professions,\n 'scales': personality,\n 'directions': direction,\n 'legend': legend,\n 'tooltips': tooltips,\n 'id': id_professions})\n\n\ndef result_little_test(request):\n fl = ['nature_index',\n 'sign_index',\n 'image_index',\n 'tech_index',\n 'human_index',\n 'power_index']\n direction = profs.Direction.objects.all()\n try:\n fopt = score.ScoreLittle.objects.filter(username=request.user)\n direction = filters.define_directions(direction, fopt)\n return render(request, 'result_main/result_little_test.html', context={'directions': direction})\n except exceptions.ObjectDoesNotExist:\n return redirect('little_test')\n\n","sub_path":"result_main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"86274829","text":"from scrapers.functions.soupify import soupify\nimport pandas as pd\nimport re\nfrom fuzzywuzzy import process\n\ndef round_scraper(match_href, match_soup, team_hrefs, team_names):\n \n #Initialize dataframe used to store round results\n rounds_df = pd.DataFrame(columns = ['match_href', 'map_name','round','team_href','win_type'])\n \n #List of official map names to be utilized later\n official_map_names = ['de_cbble', 'de_overpass', 'de_mirage', 'de_dust2', 'de_cache', 'de_inferno', 'de_train', 'de_nuke']\n \n #Get match and map detailed stat id\n try:\n match_stat_id = match_soup.find('div', {'class': 'small-padding stats-detailed-stats'}).find('a').get('href').split('/')[3]\n except AttributeError as exception:\n if str(exception) == \"'NoneType' object has no attribute 'find'\":\n return pd.DataFrame([[match_href, None, None, None, None, None, None]])\n else:\n raise exception\n \n map_stat_ids = [x['id'] for x in match_soup.find_all('div', {'class': 'stats-content'}) if x['id'] != 'all-content']\n map_stat_ids = [re.compile('(?<=[a-z])[0-9]+(?=\\-)').search(re.sub('st2','',x)).group(0) for x in map_stat_ids]\n \n #Loop through deatailed stat pages\n for map_id in map_stat_ids:\n round_soup = soupify('https://www.hltv.org/stats/matches/mapstatsid/' + map_id + '/' + match_stat_id)\n \n #Convert map name to \"official\" map name\n map_name = round_soup.find('div', {'class': 'match-info-box'}).contents[3].strip()\n map_name = process.extractOne(map_name, official_map_names)[0]\n \n #Loop through round results stored in boxes by team and half\n team_rows = round_soup.find_all('div',{'class': 'round-history-team-row'})\n \n if team_rows == []:\n continue\n \n for team_row in team_rows:\n team_name = team_row.contents[0]['title']\n team_name = re.sub(r'[^\\x00-\\x7F]+','',team_name) if team_name != '?' else 'questionmark'\n team_href = team_hrefs[0] if process.extractOne(team_name, team_names)[0] == team_names[0] else team_hrefs[1]\n \n for half in team_row.find_all('div', {'class': 'round-history-half'}):\n for rnd in half.find_all('img', {'title': re.compile('[0-9]')}):\n rnd_num = sum(int(x) for x in rnd['title'].split('-'))\n win_type = re.compile('(?<=scoreboard\\/).*(?=\\.svg)').search(rnd['src']).group(0)\n \n rounds_df.loc[len(rounds_df)] = [match_href, map_name, rnd_num, team_href, win_type]\n \n if len(rounds_df) == 0:\n return pd.DataFrame([[match_href,None,None,None,None,None,None]])\n \n rounds_df = rounds_df.sort_values('round').reset_index(drop = True)\n\n #Some extra feature engineering\n for index, row in rounds_df.iterrows():\n if row['round'] in range(1,16):\n rounds_df.set_value(index,'half',1)\n elif row['round'] < range(16,31):\n rounds_df.set_value(index,'half',2)\n else:\n raise ValueError('unknown detailed results round number')\n \n if row['win_type'] in ['ct_win','bomb_defused','stopwatch']:\n rounds_df.set_value(index,'ct_href',row['team_href'])\n rounds_df.set_value(index,'t_href',list(set(team_hrefs) - set([row['team_href']]))[0])\n rounds_df.set_value(index,'ct_win',1)\n elif row['win_type'] in ['t_win','bomb_exploded']:\n rounds_df.set_value(index,'t_href',row['team_href'])\n rounds_df.set_value(index,'ct_href',list(set(team_hrefs) - set([row['team_href']]))[0])\n rounds_df.set_value(index,'ct_win',0)\n else:\n raise ValueError('unknown detailed results win_type')\n \n rounds_df.loc[:,'ct_href'] = rounds_df.loc[:,['half','ct_href']].groupby('half').ffill().bfill()\n rounds_df.loc[:,'t_href'] = rounds_df.loc[:,['half','t_href']].groupby('half').ffill().bfill()\n rounds_df.loc[:,'ct_win'] = rounds_df.apply(lambda x: 1 if (x['ct_href'] == x['team_href']) else 0, axis = 1)\n \n return rounds_df[['match_href', 'map_name', 'round', 't_href', 'ct_href', 'ct_win', 'win_type']]\n\nround_scraper.data_type = 'rounds'\nround_scraper.team_hrefs = True\nround_scraper.team_names = True","sub_path":"scrapers/functions/rounds.py","file_name":"rounds.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"256663886","text":"#Plotting nickname-change graph is also implemented in this code.\nimport os.path\nimport re\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pylab\nimport pygraphviz as pygraphviz\nimport numpy\nimport datetime\nimport time\nimport pandas as pd\n#added some new libraries\n\nrem_time= None #this variable is used to store the time when a nickname is changed by a user.\nfor iterator in range(1,5):\n\tfor fileiterator in range(1,5):\n\t\tif(fileiterator<10): \n\t\t\tsttring=\"/home/dhruvie/LOP/2013/\"+str(iterator)+\"/0\" \n\t\t\tsttring=sttring+str(fileiterator)+\"/#kubuntu-devel.txt\"\n\t\telse:\n\t\t\tsttring=\"/home/dhruvie/LOP/2013/\"+str(iterator)+\"/\" \n\t\t\tsttring=sttring+str(fileiterator)+\"/#kubuntu-devel.txt\" \n\t\tif not os.path.exists(sttring):\n\t\t\tcontinue \n\t\twith open(sttring) as f:\n\t\t\t\t\t\tcontent = f.readlines() #contents stores all the lines of the file kubunutu-devel\n\t\t\t\n\t\tnicks = [] #list of all the nicknames\n\t\tsend_time = [] #list of all the times a user sends a message to another user\n\t\tnickplots = [] #nickplots stores all those nicks from nicks[] list that do not have zero in and outdegree in our conversation graph\n\t\tindegree = [] #this list stores all the indegree corresponding to a particular nick\n\t\toutdegree = [] #this list stores all the outdegree corresponding to a particular nick\n\t\tchannel= \"#kubuntu-devel\" #channel name\n\t\t\t\t\t\n\t\t\n#code for getting all the nicknames in a list\n\t\tfor i in content:\n\t\t\tif(i[0] != '=' and \"] <\" in i and \"> \" in i):\n\t\t\t\tm = re.search(r\"\\<(.*?)\\>\", i)\n\t\t\t\tif m.group(0) not in nicks: \n\t\t\t\t\tnicks.append(m.group(0)) #used regex to get the string between <> and appended it to the nicks list\n\n\n\n\t\tfor i in xrange(0,len(nicks)):\n\t\t\tnicks[i] = nicks[i][1:-1] #removed <> from the nicknames\n\t\t\t\t\n\t\tfor i in xrange(0,len(nicks)):\n\t\t\tif(nicks[i][len(nicks[i])-1]=='\\\\'):\n\t\t\t\tnicks[i]=nicks[i][:-1]\n\t\t\t\tnicks[i]=nicks[i]+'CR'\n\n\t\tfor j in content:\n\t\t\tif(j[0]=='=' and \"changed the topic of\" not in j):\n\t\t\t\tline1=j[j.find(\"=\")+1:j.find(\" is\")]\n\t\t\t\tline2=j[j.find(\"wn as\")+1:j.find(\"\\n\")]\n\t\t\t\tline1=line1[3:]\n\t\t\t\tline2=line2[5:]\n\t\t\t\tif(line1[len(line1)-1]=='\\\\'):\n\t\t\t\t\tline1=line1[:-1]\n\t\t\t\t\tline1=line1 + 'CR' \n\t\t\t\tif(line2[len(line2)-1]=='\\\\'):\n\t\t\t\t\tline2=line2[:-1]\n\t\t\t\t\tline2=line2 + 'CR'\n\t\t\t\tif line1 not in nicks:\n\t\t\t\t\tnicks.append(line1)\n\t\t\t\tif line2 not in nicks:\n\t\t\t\t\tnicks.append(line2)\n\t\t\t\n\t\t#print(\"printing nicks***********************************\")\n\t\t#print(nicks)\n\t\t\t\t\n\t#code for forming list of lists for avoiding nickname duplicacy\n\n\t\tx=[[] for i in range(len(nicks))]\n\t\tfor line in content:\n\t\t\tif(line[0]=='=' and \"changed the topic of\" not in line):\n\t\t\t\tline1=line[line.find(\"=\")+1:line.find(\" is\")]\n\t\t\t\tline2=line[line.find(\"wn as\")+1:line.find(\"\\n\")]\n\t\t\t\tline1=line1[3:]\n\t\t\t\tline2=line2[5:]\n\t\t\t\tif(line1[len(line1)-1]=='\\\\'):\n\t\t\t\t\tline1=line1[:-1]\n\t\t\t\t\tline1=line1 + 'CR' \n\t\t\t\tif(line2[len(line2)-1]=='\\\\'):\n\t\t\t\t\tline2=line2[:-1]\n\t\t\t\t\tline2=line2 + 'CR'\n\t\t\t\tfor i in range(len(nicks)):\n\t\t\t\t\tif line1 in x[i]:\n\t\t\t\t\t\tx[i].append(line1)\n\t\t\t\t\t\tx[i].append(line2)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tif not x[i]:\n\t\t\t\t\t\tx[i].append(line1)\n\t\t\t\t\t\tx[i].append(line2)\n\t\t\t\t\t\tbreak\n\n\t\t#print(\"printing x****************************\")\n\t\t#print(x) \n\n\n\n#code for plotting the nickname changes\n\n\t\tG1=nx.MultiDiGraph() #using networkx\n\t\ty=-1\n\t\tfor i in content:\n\t\t\ty=y+1\n\t\t\tif(i[0] =='=' and \"changed the topic of\" not in i): #scan every line which starts with ===\n\t\t\t\tline1=i[i.find(\"=\")+1:i.find(\" is\")]\n\t\t\t\tline2=i[i.find(\"wn as\")+1:i.find(\"\\n\")]\n\t\t\t\tline1=line1[3:]\n\t\t\t\tline2=line2[5:]\n\t\t\t\tif(line1[len(line1)-1]=='\\\\'):\n\t\t\t\t\tline1=line1[:-1]\n\t\t\t\t\tline1=line1 + 'CR' \n\t\t\t\tif(line2[len(line2)-1]=='\\\\'):\n\t\t\t\t\tline2=line2[:-1]\n\t\t\t\t\tline2=line2 + 'CR'\n\t\t\t\tz=y\n\t\t\t\twhile z>=0:\n\t\t\t\t\tz= z-1 # What we want is to record the nickname change time. We consider the last value between[] encountered before\n\t\t\t\t\tif(content[z][0]!='='):# === line which we are currently working on. But if we have === line as the starting line in our log file, then we\n\t\t\t\t\t\tG1.add_edge(line1,line2,weight=content[z][1:6]) #need to consider last [] line of the previous days log file. We always store the last [] value in rem_time variable.\n\t\t\t\t\t\tbreak # these lines extract the from-to nicknames and strip them appropriately to make \n\t\t\t\tif(z==-1):\n\t\t\t\t\tG1.add_edge(line1,line2,weight=rem_time) #edge between them \n\t\t\n\t\tcount=len(content)-1\n\t\twhile(count>=0):\n\t\t\tif(content[count][0]!='='):\n\t\t\t\trem_time=content[count][1:6]\n\t\t\t\tbreak\n\t\t\tcount=count-1\n\t\t\n\n\t\t\n\t\t\n\t\t\n\t\tfor u,v,d in G1.edges(data=True):\n\t\t\t\t\t\td['label'] = d.get('weight','')\n\n\t\tbrilliant=channel+\"_\"+str(fileiterator)+\"_\"+str(iterator)+\"_2013_nickchanges.png\"\n\t\tprint(brilliant)\n\t\tA = nx.to_agraph(G1)\n\t\tA.layout(prog='dot')\n\t\tA.draw(brilliant) #graphviz helps to convert a dot file to PNG format for visualization\n\t\t\n\n#code for making relation map between clients\n\n\n\n\t\tG = nx.MultiDiGraph() #graph with multiple directed edges between clients used\n\t\tfor line in content:\n\t\t\tflag_comma = 0\n\t\t\tif(line[0] != '=' and \"] <\" in line and \"> \" in line):\n\t\t\t\tm = re.search(r\"\\<(.*?)\\>\", line)\n\t\t\t\tvar = m.group(0)[1:-1]\n\t\t\t\tif(var[len(var)-1]=='\\\\'):\n\t\t\t\t\tvar=var[:-1]\n\t\t\t\t\tvar=var + 'CR' \n\t\t\t\tfor d in range(len(nicks)):\n\t\t\t\t\tif var in x[d]:\n\t\t\t\t\t\tpehla = x[d][0]\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tpehla=var\n\t\t\t\t\t\t\n\n\t\t\t\tfor i in nicks:\n\t\t\t\t\tdata=[e.strip() for e in line.split(':')]\n\t\t\t\t\tdata[1]=data[1][data[1].find(\">\")+1:len(data[1])]\n\t\t\t\t\tdata[1]=data[1][1:]\n\t\t\t\t\tif not data[1]:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tfor ik in xrange(0,len(data)):\n\t\t\t\t\t\tif(data[ik] and data[ik][len(data[ik])-1]=='\\\\'):\n\t\t\t\t\t\t\tdata[ik]=data[ik][:-1]\n\t\t\t\t\t\t\tdata[ik]=data[ik] + 'CR'\n\t\t\t\t\tfor z in data:\n\t\t\t\t\t\tif(z==i):\n\t\t\t\t\t\t\tsend_time.append(line[1:6])\n\t\t\t\t\t\t\tif(var != i): \n\t\t\t\t\t\t\t\tfor d in range(len(nicks)):\n\t\t\t\t\t\t\t\t\tif i in x[d]:\n\t\t\t\t\t\t\t\t\t\tsecond=x[d][0]\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tsecond=i\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tG.add_edge(pehla,second,weight=line[1:6]) \n\t\t\t\t\t\t\t\n\t\t\t\t\tif \",\" in data[1]: \n\t\t\t\t\t\tflag_comma = 1\n\t\t\t\t\t\tdata1=[e.strip() for e in data[1].split(',')]\n\t\t\t\t\t\tfor ij in xrange(0,len(data1)):\n\t\t\t\t\t\t\tif(data1[ij] and data1[ij][len(data1[ij])-1]=='\\\\'):\n\t\t\t\t\t\t\t\tdata1[ij]=data1[ij][:-1]\n\t\t\t\t\t\t\t\tdata1[ij]=data1[ij] + 'CR'\n\t\t\t\t\t\tfor j in data1:\n\t\t\t\t\t\t\tif(j==i):\n\t\t\t\t\t\t\t\tsend_time.append(line[1:6])\n\t\t\t\t\t\t\t\tif(var != i): \n\t\t\t\t\t\t\t\t\tfor d in range(len(nicks)):\n\t\t\t\t\t\t\t\t\t\tif i in x[d]:\n\t\t\t\t\t\t\t\t\t\t\tsecond=x[d][0]\n\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tsecond=i\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tG.add_edge(pehla,second,weight=line[1:6]) \n\n\t\t\t\t\tif(flag_comma == 0):\n\t\t\t\t\t\tsearch2=line[line.find(\">\")+1:line.find(\", \")] \n\t\t\t\t\t\tsearch2=search2[1:]\n\t\t\t\t\t\tif(search2[len(search2)-1]=='\\\\'):\n\t\t\t\t\t\t\tsearch2=search2[:-1]\n\t\t\t\t\t\t\tsearch2=search2 + 'CR' \n\t\t\t\t\t\tif(search2==i):\n\t\t\t\t\t\t\tsend_time.append(line[1:6])\n\t\t\t\t\t\t\tif(var != i):\n\t\t\t\t\t\t\t\tfor d in range(len(nicks)):\n\t\t\t\t\t\t\t\t\tif i in x[d]:\n\t\t\t\t\t\t\t\t\t\tsecond=x[d][0]\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tsecond=i\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tG.add_edge(pehla,second,weight=line[1:6]) \n\t\t\t\t\t\t\n\t\t\t\t\n\n\n\t\tfor u,v,d in G.edges(data=True):\n\t\t\t\t\t\td['label'] = d.get('weight','')\n\n#scan through the nicks list and for which nick the in and out degrees are not null add them to nickplots along with the in and out degrees\n\t\tfor ni in nicks:\n\t\t\tif(bool(G.in_degree(ni)) is not False and bool(G.out_degree(ni)) is not False):\n\t\t\t\tnickplots.append(ni)\n\t\t\t\tindegree.append(G.in_degree(ni))\n\t\t\t\toutdegree.append(G.out_degree(ni))\n\t\t\n#if indegree and outdegree list is not zero then plot the bar graphs using pandas library as shown below\n\t\tif(len(indegree)!=0 and len(outdegree)!=0):\n\t\t\tdata = {'Nick': nickplots, #x axis\n\t\t\t\t\t'Indegree': indegree} #y axis\n\t\t\tdf = pd.DataFrame(data, columns = ['Nick', 'Indegree'])\n\t\t\tdf.index = df['Nick']\n\t\t\tdel df['Nick']\n\t\t\tdf #these 3 lines remove the first column that has serial number\n\t\t\tprint(df)\n\t\t\taxes = plt.gca()\n\t\t\taxes.set_ylim([0,200])\n\t\t\tdf.plot(kind='bar', ax=axes)\n\t\t\tname1 = channel+\"_\"+str(fileiterator)+\"_\"+str(iterator)+\"_2013_indegree.png\"\n\t\t\tplt.savefig(name1)\n\t\t\tplt.close()\n\n\t\t#same thing for outdegree\n\t\t\tdata = {'Nick': nickplots, \n\t\t\t\t\t\t\t\t\t'Indegree': outdegree}\n\t\t\tdf = pd.DataFrame(data, columns = ['Nick', 'Indegree'])\n\t\t\tdf.index = df['Nick']\n\t\t\tdel df['Nick']\n\t\t\tdf\n\t\t\tprint(df)\n\t\t\taxes = plt.gca()\n\t\t\taxes.set_ylim([0,200])\n\t\t\tdf.plot(kind='bar', ax=axes)\n\t\t\tname2 = channel+\"_\"+str(fileiterator)+\"_\"+str(iterator)+\"_2013_outdegree.png\"\n\t\t\tplt.savefig(name2)\n\t\t\tplt.close()\n\n\t\tn_brilli=channel+\"_\"+str(fileiterator)+\"_\"+str(iterator)+\"_2013_conversation.png\"\n","sub_path":"lib/deprecated/scripts/In-Out_degree && Nickname-change.py","file_name":"In-Out_degree && Nickname-change.py","file_ext":"py","file_size_in_byte":8682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"590722981","text":"import datetime\nimport mysql.connector as mdb\nimport logging\n\nclass CControlData:\n mTimeStamp = datetime.datetime.now();\n mSens1 = True;\n mSens2 = True;\n mSens3 = False;\n mEmail = False;\n mShutdown = False;\n mStop = False;\n mValveH = False;\n mValveN = False;\n mSaveH = False;\n eStop = False;\n db = None\n\ndata=CControlData()\n\ndef getValveH1():\n return data.mValveH\n\ndef getValveN1():\n return data.mValveN\n\ndef getMStop():\n return data.mStop\n \ndef getH1():\n return data.mSens1;\n\ndef getH2():\n return data.mSens2;\n\ndef getH3():\n return data.mSens3;\n\ndef connect():\n logging.debug( \"mysql: connect\")\n if(data.db is None):\n data.db = mdb.connect(host=\"localhost\",port=3306,user=\"root\",password='chemin',database='safex');\n #should do error checking here\n return data.db;\n\ndef createDataBase():\n logging.debug( \"mysql: createDataBase\")\n dummy = mdb.connect(host='localhost',user='root',password='chemin',port=3306);\n cur = dummy.cursor();\n cur.execute('DROP DATABASE safex');\n cur.execute('CREATE DATABASE safex');\n dummy.close();\n \n data.db = mdb.connect(host='localhost',user='root',password='chemin',port=3306,database='safex');\n cur = db.cursor();\n cur.execute(\"CREATE TABLE initialize(idnr INTEGER AUTO_INCREMENT PRIMARY KEY\"\\\n\t \", time_stamp DATETIME\"\\\n\t \", sens_1 BOOL NOT NULL DEFAULT 1, sens_2 BOOL NOT NULL DEFAULT 1, sens_3 BOOL NOT NULL DEFAULT 0\"\\\n\t \", e_mail BOOL NOT NULL DEFAULT 0, c_shutdown BOOL NOT NULL DEFAULT 0, c_stop BOOL NOT NULL DEFAULT 0\"\\\n\t \", valve_h BOOL NOT NULL DEFAULT 0, valve_n BOOL NOT NULL DEFAULT 0, save_h BOOL NOT NULL DEFAULT 1\"\\\n\t \", emergency_stop BOOL DEFAULT 0\"\\\n\t \");\");\n res = push();\n if res != 0:\n return res;\n cur.execute(\"CREATE TABLE H_1(idnr INTEGER AUTO_INCREMENT PRIMARY KEY, time_stamp DATETIME\"\\\n\t \", value INTEGER, temperature INTEGER);\");\n res = addData_H1(0,0);\n if res != 0:\n return res;\n\n cur.execute(\"CREATE TABLE H_2(idnr INTEGER AUTO_INCREMENT PRIMARY KEY, time_stamp DATETIME\"\\\n\t \", value INTEGER);\");\n res = addData_H2(0);\n if res != 0:\n return res;\n\n cur.execute(\"CREATE TABLE H_3(idnr INTEGER AUTO_INCREMENT PRIMARY KEY, time_stamp DATETIME\"\\\n\t \", value INTEGER);\");\n res = addData_H3(0);\n if res != 0:\n return res;\n\n return 0;\n\ndef pull():\n logging.debug( \"mysql: pull\")\t \n cur = data.db.cursor();\n cur.execute(\"SELECT *\"\\\n \"FROM initialize ORDER BY idnr DESC LIMIT 1;\");\n row = cur.fetchone();\n newDateTime = row[1];\n if data.mTimeStamp < newDateTime:\n data.mTimeStamp = newDateTime;\n data.mSens1 = row[2];\n data.mSens2 = row[3];\n data.mSens3 = row[4];\n data.mEmail = row[5];\n data.mShutdown = row[6];\n data.mStop = row[7];\n data.mValveH = row[8];\n data.mValveN = row[9];\n data.mSaveH = row[10];\n data.eStop = row[11];\n print( \"mysql: pull\", row)\t \n return 0;\n\ndef push():\n logging.info( \"mysql: push\") \n cur = data.db.cursor();\n query = 'INSERT INTO initialize VALUES(NULL, NOW(),%r,%r,%r,%r,%r,%r,%r,%r,%r,%r);'\\\n % (data.mSens1,data.mSens2,data.mSens3,data.mEmail,data.mShutdown,data.mStop,data.mValveH,data.mValveN,data.mSaveH,data.eStop);\n cur.execute(query);\n data.db.commit();\n return 0;\n\ndef getData_H1():\n logging.debug( \"mysql: getData_H1\")\n cur = data.db.cursor();\n cur.execute('SELECT time_stamp, value FROM H_1 ORDER BY time_stamp DESC LIMIT 1;');\n row = cur.fetchone();\n return row[0], row[1];\n\ndef addData_H1(_value,_temperature):\n logging.info( \"mysql: addData_H1: %d, %d\", _value, _temperature) \n cur = data.db.cursor();\n query = 'INSERT INTO H_1 VALUES(NULL, NOW(), %d, %d);' % (_value, _temperature);\n cur.execute(query);\n data.db.commit();\n return 0;\n\ndef getData_H2():\n logging.debug( \"mysql: getData_H2\") \n cur = data.db.cursor();\n cur.execute('SELECT time_stamp, value FROM H_2 ORDER BY time_stamp DESC LIMIT 1;');\n row = cur.fetchone();\n return row[0], row[1];\n\ndef addData_H2(_value):\n logging.info( \"mysql: addData_H2: %d\", _value) \n cur = data.db.cursor();\n query = 'INSERT INTO H_2 VALUES(NULL, NOW(), %d);' % (_value);\n cur.execute(query);\n data.db.commit();\n return 0;\n\ndef replaceData_H3(_value):\n logging.info( \"mysql: replaceData_H3\", _value) \n cur = data.db.cursor();\n cur.execute('DELETE * FROM H_3 VALUES;');\n query = 'INSERT INTO H_3 VALUES(NULL, NOW(), %d)' % (_value);\n cur.execute(query);\n data.db.commit();\n return 0;\n\ndef setEStop(_value):\n logging.info( \"mysql: setEStop %d\", _value) \n if(data.eStop != _value):\n data.eStop = _value;\n return push();\n return 0;\n\n","sub_path":"safex-py/src/main/MySqlClient.py","file_name":"MySqlClient.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"342788217","text":"import csv\nimport os\n\ndirectory = os.listdir('min-zlm')\nos.chdir('min-zlm')\nfor files in directory:\n\twith open(files, 'r')as f:\n\t\treader = csv.reader(f)\n\t\tprint(files)\n\t\tthreshold = 0.0\n\t\tcorrect = 0.0\n\t\tincorrect = 0.0\n\t\ttotalPair = 0.0\n\t\tprecision = 0.0\n\t\trecall = 0.0\n\t\tfscore = 0.0\n\t\tfor row in reader:\n\t\t\t#currentPrecision = float(row[5])\n\t\t\tcurrentRecall = float(row[6])\n\t\t\tif currentRecall > float(recall):\n\t\t\t#if currentPrecision > float(precision):\n\t\t\t\tthreshold = row[0]\n\t\t\t\tcorrect = row[1]\n\t\t\t\tincorrect = row[2]\n\t\t\t\ttotalPair = row[3]\n\t\t\t\tprecision = row[5]\n\t\t\t\trecall = row[6]\n\t\t\t\tfscore = row[7]\n\t\tprint(threshold+\",\"+correct+\",\"+incorrect+\",\"+totalPair+\",\"+precision+\",\"+recall+\",\"+fscore)","sub_path":"goldStandard/findBestThreshold.py","file_name":"findBestThreshold.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"226622184","text":"import os\nimport sys\nimport argparse\nimport warnings\nimport data_provider.image as dataset\nimport model.dhcs as model\nfrom pprint import pprint\nfrom util import Logger, str2bool\n\n\nlabel_dims = {'cifar10': 10, 'cifar10-s1': 10, 'cub': 200, 'nuswide_21': 21,\n 'nuswide_81': 81, 'coco': 80, 'imagenet': 100, 'cifar10_zero_shot': 10}\n\nRs = {'cifar10': 54000, 'cifar10-s1': 50000, 'nuswide_81': 5000, 'coco': 5000,\n 'nuswide_21': 5000, 'imagenet': 5000, 'cifar10_zero_shot': 15000}\n\n\ndef parse_args(argv):\n parser = argparse.ArgumentParser(description='Train and val model')\n\n # algorithm config\n algorithm_group = parser.add_argument_group(title='Algorithm config')\n algorithm_group.add_argument('--bit', type=int, default=32)\n algorithm_group.add_argument('--q-lambda', type=float, default=0.01)\n algorithm_group.add_argument('--b-lambda', type=float, default=0.0)\n algorithm_group.add_argument('--i-lambda', type=float, default=0.0)\n algorithm_group.add_argument('--alpha', type=float, default=5)\n # network config\n network_group = parser.add_argument_group(title='Network config')\n network_group.add_argument('--gpus', type=str, default='0')\n network_group.add_argument('--max-iter', type=int, default=10000)\n network_group.add_argument('--batch-size', type=int, default=128)\n network_group.add_argument('--val-batch-size', type=int, default=100)\n network_group.add_argument('--lr', type=float, default=0.0001)\n network_group.add_argument('--lr-decay-factor', type=float, default=0.5)\n network_group.add_argument('--decay-step', type=int, default=3000)\n network_group.add_argument('--network', type=str, default='alexnet')\n network_group.add_argument('--network-weights', type=str)\n network_group.add_argument('--finetune-all', type=str2bool, default=True)\n network_group.add_argument('--test', default=False, action='store_true')\n network_group.add_argument('--debug', default=False, action='store_true')\n # dataset config\n dataset_group = parser.add_argument_group(title='Dataset config')\n dataset_group.add_argument('--dataset', type=str, default='cifar10')\n dataset_group.add_argument('--prefix', type=str, default='1')\n dataset_group.add_argument('--suffix', type=str, default='exp')\n # config process\n config, rest = parser.parse_known_args()\n _dataset = config.dataset\n _save_dir = f'../snapshot/{config.dataset}_{config.network}_{config.bit}bit_{config.suffix}/' + \\\n f'{config.prefix}_q{config.q_lambda}'\n dataset_group.add_argument('--R', type=int, default=Rs[_dataset])\n dataset_group.add_argument('--label-dim', type=str, default=label_dims[_dataset])\n dataset_group.add_argument('--save-dir', type=str, default=_save_dir)\n\n return parser.parse_args(argv)\n\n\ndef main(config):\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n warnings.filterwarnings(\"ignore\", category=FutureWarning)\n os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = '3'\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = config.gpus\n\n if not os.path.exists(config.save_dir):\n os.makedirs(config.save_dir)\n sys.stdout = Logger(os.path.join(config.save_dir, 'train.log'))\n\n pprint(vars(config))\n data_root = os.path.join('../../data', config.dataset)\n config.wordvec_dict = f'{data_root}/wordvec.txt'\n img_tr = f'{data_root}/train.txt'\n img_te = f'{data_root}/test.txt'\n img_db = f'{data_root}/database.txt'\n\n if config.test == True:\n # config.save_dir = '../snapshot/cifar10_alexnet_32bit_hyper_sigmoid/debug'\n config.network_weights = os.path.join(config.save_dir, 'network_weights.npy')\n else:\n train_img = dataset.import_train(data_root, img_tr)\n network_weights = model.train(train_img, config)\n config.network_weights = network_weights\n\n sys.stdout = Logger(os.path.join(config.save_dir, 'test.log'))\n query_img, database_img = dataset.import_validation(data_root, img_te, img_db)\n maps = model.validation(database_img, query_img, config)\n\n for key in maps:\n print(f\"{key}: {maps[key]}\")\n\n\nif __name__ == \"__main__\":\n main(parse_args(sys.argv[1:]))","sub_path":"examples/dhcs/train_val_script.py","file_name":"train_val_script.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"387194794","text":"import sys\nfrom PyQt5.QtGui import QPainter, QColor\nfrom random import choice, randint\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton\nfrom random import randrange\n\n\nclass Example(QMainWindow):\n def __init__(self):\n super().__init__()\n self.initUI()\n self.x = -1\n self.y = -1\n self.radius = 0\n self.f = False\n self.qp = QPainter()\n self.btn.clicked.connect(self.trigger)\n\n def trigger(self):\n self.f = True\n self.update()\n\n def paintEvent(self, event):\n if self.f:\n self.qp.begin(self)\n self.draw()\n self.qp.end()\n\n def draw(self):\n self.radius = randint(1, 100)\n self.x = randrange(50, 800)\n self.y = randrange(50, 600)\n color = QColor(randrange(0, 255, 1), randrange(0, 255, 1), randrange(0, 255, 1))\n self.qp.setBrush(color)\n self.qp.drawEllipse(self.x, self.y, self.radius, self.radius)\n\n def initUI(self):\n self.setGeometry(0, 0, 950, 650)\n self.setWindowTitle('Слёзы Марины')\n self.btn = QPushButton('Кнопка', self)\n self.btn.resize(self.btn.sizeHint())\n self.btn.move(450, 300)\n self.show()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())","sub_path":"file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"193468510","text":"from datetime import date,timedelta\nfrom time import strptime\nimport sys\nimport getopt\nimport pickle\nimport os\nfrom global_config import *\n\ndef get_day(date=False):\n if not date:\n print(\"Manual input\")\n date = get_date()\n fn = date.strftime(\"%Y%m%d\")\n path = default_path+fn\n if os.path.exists(path):\n print(\"File found, fetching data!\")\n f=open(path,'rb')\n outclass = pickle.load(f)\n else:\n raise IOError('File not found')\n return outclass\n\ndef write_day(inday):\n fn = inday.date.strftime(\"%Y%m%d\")\n path = default_path+fn\n if os.path.exists(path):\n check=input(\"Data for this day already exits! Overwrite? (y/n) \")\n while True:\n if check in yeslist:\n print(\"Saving data\")\n f=open(path,'wb')\n pickle.dump(inday,f)\n break\n if check in nolist:\n print(\"Write cancelled\")\n raise UserWarning('Write cancelled by user')\n print(\"Unrecognized input, try again.\")\n else:\n print(\"Saving data\")\n f=open(path,'wb')\n pickle.dump(inday,f)\n\ndef get_date(instr=False):\n if instr:\n dstr=instr\n while True:\n if dstr in (\"today\",\"Today\"):\n return date.today()\n else:\n try:\n t=strptime(dstr,\"%d/%m/%Y\")\n return date(*t[:3])\n except ValueError:\n try:\n t=strptime(dstr,\"%d-%m-%Y\")\n return date(*t[:3])\n except ValueError:\n try:\n t=strptime(dstr,\"%d%m%Y\")\n return date(*t[:3])\n except ValueError:\n print(\"Unrecognized date format\")\n return False\n while True:\n dstr = input(\"Enter date: \")\n if dstr in (\"today\",\"Today\"):\n return date.today()\n else:\n try:\n t=strptime(dstr,\"%d/%m/%Y\")\n return date(*t[:3])\n except ValueError:\n try:\n t=strptime(dstr,\"%d-%m-%Y\")\n return date(*t[:3])\n except ValueError:\n try:\n t=strptime(dstr,\"%d%m%Y\")\n return date(*t[:3])\n except ValueError:\n print(\"Unrecognized date format, try again\")\n\ndef get_stats(startday,ndays):\n daylist = [None]*ndays\n wt_list = []\n calr = 0.\n cal = 0.\n lifts = {}\n nrec = 0\n for i in range(ndays):\n w_i = startday + timedelta(days=i)\n try:\n day=get_day(w_i)\n except IOError:\n print('%s not recorded!' %(w_i.strftime(\"%A\")))\n daylist[i] = False\n continue\n wt_list.append(day.weight)\n cal += day.calories\n calr += day.maintenance\n if day.daytype != \"Rest\":\n lifts[day.daytype] = [w_i.strftime(\"%A\"),day.lifts]\n daylist[i] = day\n nrec += 1\n if nrec == 0:\n raise IOError(\"No days in interval was recorded.\")\n #Assume maintenance calories consumed on days not recorded\n cal += (ndays-nrec)*calr/nrec\n calr += (ndays-nrec)*calr/nrec\n return wt_list,cal,calr,lifts,daylist\n\n","sub_path":"subs_tools.py","file_name":"subs_tools.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"159206345","text":"'''\nThis file contains the logic for the twitter bot to reply to mentions\n'''\n\nimport tweepy\nimport json\nimport requests\nimport utils\nfrom config import create_api\nimport time\nimport logging\nimport numpy as np\nimport random\nfrom urllib3.exceptions import ProtocolError, ReadTimeoutError\n\nusers = np.genfromtxt(\"data/users.txt\", dtype='str').tolist()\n\nlogging.basicConfig(filename=\"bot.log\",\n filemode='a',\n format='reply.py | %(asctime)s | %(levelname)s | %(message)s',\n datefmt='%D - %H:%M:%S',\n level=logging.DEBUG)\n\nlogging.info(\"Reply bot running\")\nlogger = logging.getLogger()\n\nclass MyStreamListener(tweepy.StreamListener):\n def __init__(self, api):\n self.api = api\n self.me = api.me()\n\n def on_status(self, tweet):\n if tweet.user.id == self.me.id:\n return\n if hasattr(tweet, 'retweeted_status'):\n return\n if str(tweet.user.id) not in users:\n return\n if \"die\" in tweet.text.lower() or \"death\" in tweet.text.lower() or \"dead\" in tweet.text.lower() or \"injury\" in tweet.text.lower():\n return\n print(f\"{tweet.user.name}:{tweet.text}\")\n p, t = utils.tweet_parser(tweet.text)\n\n #find a name/team\n r = random.randint(0, len(utils.categories)-1)\n r_category = utils.categories[r]\n r = random.randint(0, len(utils.years)-1)\n r_year = utils.years[r]\n \n if p == [] and t == []:\n print(\"Empty\")\n return\n elif p == []:\n msg = utils.team_stat(t[0], True, r_year, r_category)\n while msg == None:\n r = random.randint(0, len(utils.categories)-1)\n r_category = utils.categories[r]\n r = random.randint(0, len(utils.years)-1)\n r_year = utils.years[r]\n msg = utils.team_stat(t[0], True, r_year, r_category)\n print(\"Reply Parameters: \" + t[0] + r_year + r_category)\n else:\n msg = utils.player_stat(p[0], r_year, r_category)\n while msg == None or \"did not play\" in msg:\n r = random.randint(0, len(utils.categories)-1)\n r_category = utils.categories[r]\n r = random.randint(0, len(utils.years)-1)\n r_year = utils.years[r]\n msg = utils.player_stat(p[0], r_year, r_category)\n print(\"Reply Parameters: \" + p[0] + r_year + r_category)\n \n print(f\"Replying to {tweet.user.name} with {msg}\")\n \n try:\n self.api.update_status(\n status=msg,\n in_reply_to_status_id=tweet.id,\n auto_populate_reply_metadata=True\n )\n except:\n return\n\n def on_error(self, status):\n print(\"Error detected\")\n\ndef main():\n api = create_api()\n tweets_listener = MyStreamListener(api)\n stream = tweepy.Stream(api.auth, tweets_listener)\n print(users)\n stream.filter(follow=users, stall_warnings=True)\n\n \nif __name__ == \"__main__\":\n main()\n\n","sub_path":"NFLStatsbot/reply.py","file_name":"reply.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"590227847","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 ('analyse', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='mappingedfile',\n name='is_haina',\n field=models.BooleanField(default=False, verbose_name=b'\\xe6\\x98\\xaf\\xe5\\x90\\xa6\\xe7\\x94\\xbb\\xe5\\x83\\x8f\\xe6\\x8e\\xa5\\xe5\\x8f\\xa3\\xe5\\x8c\\xb9\\xe9\\x85\\x8d'),\n preserve_default=True,\n ),\n ]\n","sub_path":"tags/DTS/Mapping_2.2.1/Mapping/analyse/migrations/0002_mappingedfile_is_haina.py","file_name":"0002_mappingedfile_is_haina.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"95970167","text":"\"\"\"\n\n Student : Shahreen Shahjahan Psyche\n\n Time Complexity : NKlogK ; K is number of characters in each word and\n N is number of words \n Space Complexity: O(KN)\n\n This program successfully passed all test cases in Leetcode.\n\n\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n \n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n \n if strs is None or len(strs) == 0:\n return\n records = {}\n for i in strs:\n list_i = sorted(list(i)) # Time Complexity : K log K\n temp = \"\".join(list_i) \n if temp in records.keys():\n records[temp].append(i)\n else:\n records[temp] = [i]\n \n res = []\n for i in records.values():\n res.append(i)\n \n return res\n \n \n ","sub_path":"Problem_1.py","file_name":"Problem_1.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"65406233","text":"from django.conf.urls import url\n\nfrom api.views import (\n AccountTransactions,\n ListOfAccounts,\n AccountDetailInformation, AccountCreateView, TransactionsCreateView)\n\nurlpatterns = [\n url(r'^list_of_accounts', ListOfAccounts.as_view()),\n url(r'^account_transactions/(?P\\d{8})', AccountTransactions.as_view(), name='account_transactions'),\n url(r'^account_details/(?P\\d{8})', AccountDetailInformation.as_view()),\n url(r'^accounts', AccountCreateView.as_view()),\n url(r'^transactions', TransactionsCreateView.as_view())\n\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"503526779","text":"''' \nCode from\nhttps://github.com/matheusgadelha/MRTNet/blob/master/models/AutoEncoder.py\nhttps://github.com/matheusgadelha/MRTNet/blob/master/models/MRTDecoder.py\n\nrevised by Hyeontae Son\n'''\nimport torch\nimport torch.nn as nn\nfrom torch.nn import Sequential, Tanh, Conv1d, ModuleList\nfrom layers.srtdecoder import SRTDecoder\ntree_arch = {}\ntree_arch[4] = [4, 8, 8, 8]\ntree_arch[6] = [2, 4, 4, 4, 4, 4]\ntree_arch[8] = [2, 2, 2, 2, 2, 4, 4, 4]\ntree_arch[11] = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]\n\nclass SRTDecoderPG(SRTDecoder):\n def __init__(self, z_dim, nlevels, feat_dims, num_output_points):\n super(SRTDecoderPG, self).__init__(z_dim, nlevels, feat_dims, num_output_points)\n self.num_points_of_phase = self.num_nodes\n toPoint_list = []\n for intermediate_level in range(self.nlevels - 1):\n toPoint_list.append(Sequential(Conv1d(self.feat_dims[intermediate_level], 3, 1), Tanh()))\n\n self.toPoints = ModuleList(toPoint_list)\n\n def forward(self, z, phase, alpha):\n batch_size = z.shape[0]\n node = self.fc1(z).view(batch_size, -1, self.base_size)\n\n tree_node_list = []\n tree_node_list.append(node)\n\n for upconv in self.upconv_list[:phase]:\n node = upconv(node)\n tree_node_list.append(node)\n\n if phase == 0:\n pc = self.toPoints[phase](tree_node_list[-1])\n elif phase == self.nlevels:\n pc = self.final_conv(tree_node_list[-1])\n else:\n prev_phase_node = tree_node_list[-2]\n prev_pc = self.toPoints[phase - 1](prev_phase_node)\n curr_phase_node = tree_node_list[-1]\n if phase == self.nlevels - 1:\n curr_pc = self.final_conv(curr_phase_node)\n else:\n curr_pc = self.toPoints[phase](curr_phase_node)\n\n if alpha < 1.0:\n pc = nn.Upsample(scale_factor=int(self.tarch[phase]), mode='nearest')(prev_pc) * (1 - alpha) + curr_pc * alpha\n else:\n pc = curr_pc\n\n pc = torch.transpose(pc, 1, 2).contiguous()\n return pc","sub_path":"layers/srtdecoder_pg.py","file_name":"srtdecoder_pg.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"380721481","text":"A = 0\nT = 1\nC = 2\nG = 3\nN = 4\n\nSTART = 'ATG'\nSTOPS = ['TAG', 'TAA', 'TGA']\nCOMPLEMENTS = {'G' : 'C',\n 'C' : 'G',\n 'A' : 'T',\n 'T' : 'A',\n G : C,\n C : G,\n A : T,\n T : A}\n\ndef reverse_complement(seq):\n return_seq = \"\"\n for i in range(len(seq)-1, -1, -1):\n return_seq += COMPLEMENTS[seq[i]]\n return return_seq\n\n\n","sub_path":"nucleotides.py","file_name":"nucleotides.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"320479619","text":"import unittest\nimport shutil\nimport os\nimport numpy as np\nfrom extractors import SlowFastStrategy, I3DStrategy\nfrom extractors import ExtractorFactory\nfrom video import Video\n\n\nclass TestFeatureExtractor(unittest.TestCase):\n\n def setUp(self):\n self.video_path = \"./tests/assets/RoadAccidents010_x264.mp4\"\n\n def test_slowfast(self):\n slowfast = SlowFastStrategy()\n video = Video(self.video_path, ExtractorFactory.SLOWFAST.value)\n\n slowfast.extract(video)\n features = video.features()\n\n self.assertIsInstance(features, np.ndarray)\n assert features.shape == (17, 2304)\n\n def test_i3d(self):\n i3d = I3DStrategy()\n video = Video(self.video_path, ExtractorFactory.I3D.value)\n\n i3d.extract(video)\n features = video.features()\n\n self.assertIsInstance(features, np.ndarray)\n assert features.shape == (17, 2048)\n\n def test_extractor_factory(self):\n extractors = ExtractorFactory.values_list()\n assert isinstance(ExtractorFactory.get(extractors[0])(),\n SlowFastStrategy)\n assert isinstance(ExtractorFactory.get(extractors[1])(),\n I3DStrategy)\n\n def tearDown(self):\n if os.path.isdir(self.video_path+\"_features\"):\n shutil.rmtree(self.video_path+\"_features\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/tests/test_extractors.py","file_name":"test_extractors.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"105741567","text":"def main():\n\n # считываем количество вершин и количество ребер\n (count_of_nodes, count_of_edges) = (int(x) for x in input().split(maxsplit=1))\n\n # инициализируем список смежности\n graph = {x+1: [] for x in range(count_of_nodes)}\n\n # \"покраска\" графа\n visited = {x+1: False for x in range(count_of_nodes)}\n\n # заполняем список смежности\n for _ in range(count_of_edges):\n (node_1, node_2) = (int(x) for x in input().split(maxsplit=1))\n graph[node_1].append(node_2)\n graph[node_2].append(node_1)\n\n # поиск в глубину\n def dfs(arr):\n for node in arr:\n if visited[node]:\n continue\n visited[node] = True\n for relates in graph[node]:\n if visited[relates]:\n continue\n visited[relates] = True\n dfs(graph[relates])\n\n # компонента связности\n result = 0\n\n # обход каждой вершины\n for node, relates in graph.items():\n if visited[node]:\n continue\n visited[node] = True\n result +=1\n dfs(relates)\n\n print(result)\n\n\nif __name__ == '__main__':\n main()","sub_path":"fundamentals_of_graph_theory/trees_and_cycles/2.1/09/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"27294393","text":"import json, collections, os\n\nfrom main.module import Module\nfrom main.events import EmptyResponseError, event_hook\n\nclass Module(Module):\n def __init__(self, main):\n self.main = main\n self._config = collections.OrderedDict()\n\n def on_load(self, main):\n self._config = self.reload()\n\n def reload(self):\n out = collections.OrderedDict()\n for root, dirs, files in os.walk(\"config\"):\n dirs.sort()\n for filename in sorted(files):\n if not filename.startswith(\".\") and filename.endswith(\".json\"):\n config_path = root.split(\"/\")[1:] + [filename.rstrip(\".json\").lstrip(\"_\")]\n config_path = [a.split(\".\", 1)[-1] for a in config_path]\n with open(root + \"/\" + filename) as f:\n self.fold(out, json.load(f), config_path)\n return out\n\n def fold(self, target_map, source_map, path):\n for k in path:\n if k not in target_map:\n target_map[k] = collections.OrderedDict()\n target_map = target_map[k]\n\n for k,v in source_map.items():\n if isinstance(v, collections.Mapping):\n self.fold(target_map, v, k.split(\"/\"))\n else:\n target_map[k] = v\n\n def resolve(self, key):\n if not key: return None\n target = self._config\n for part in key.split(\"/\"):\n target = target.get(part)\n if target==None:\n raise EmptyResponseError()\n return target\n\n @event_hook(\"config/collect\")\n def collect(self, event):\n return self.resolve(event.key)\n\n @event_hook(\"config/keys\")\n def keys(self, event):\n return list(self.resolve(event.key).keys())\n\n","sub_path":"module/json_config.py","file_name":"json_config.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"102975496","text":"import os\n\nimport pytest\n\nimport DistRDF\nfrom DistRDF.Backends import Spark\n\nimport ROOT\n\n\ndef write_tree(treename, filename):\n df = ROOT.RDataFrame(10)\n df.Define(\"x\", \"rdfentry_\").Snapshot(treename, filename)\n\n\n@pytest.fixture(scope=\"class\")\ndef setup_testdefinepersample(request):\n \"\"\"\n Set up test environment for this class. Currently this includes:\n\n - Write a set of trees usable by the tests in this class\n - Initialize a Dask client for the tests in this class. This uses a\n `LocalCluster` object that spawns 2 single-threaded Python processes.\n \"\"\"\n\n request.cls.samples = [\"sample1\", \"sample2\", \"sample3\"]\n request.cls.filenames = [sample + \".root\" for sample in request.cls.samples]\n request.cls.maintreename = \"Events\"\n for filename in request.cls.filenames:\n write_tree(request.cls.maintreename, filename)\n yield\n for name in request.cls.filenames:\n os.remove(name)\n\n\n@pytest.mark.usefixtures(\"setup_testdefinepersample\")\nclass TestDefinePerSample:\n \"\"\"Check the working of merge operations in the reducer function.\"\"\"\n\n def test_definepersample_simple(self, connection):\n \"\"\"\n Test DefinePerSample operation on three samples using a predefined\n string of operations.\n \"\"\"\n\n df = Spark.RDataFrame(self.maintreename, self.filenames, sparkcontext=connection)\n\n # Associate a number to each sample\n definepersample_code = \"\"\"\n if(rdfsampleinfo_.Contains(\\\"{}\\\")) return 1;\n else if (rdfsampleinfo_.Contains(\\\"{}\\\")) return 2;\n else if (rdfsampleinfo_.Contains(\\\"{}\\\")) return 3;\n else return 0;\n \"\"\".format(*self.samples)\n\n df1 = df.DefinePerSample(\"sampleid\", definepersample_code)\n\n # Filter by the sample number. Each filtered dataframe should contain\n # 10 entries, equal to the number of entries per sample\n samplescounts = [df1.Filter(\"sampleid == {}\".format(id)).Count() for id in [1, 2, 3]]\n\n for count in samplescounts:\n assert count.GetValue() == 10\n\n def test_definepersample_withinitialization(self, connection):\n \"\"\"\n Test DefinePerSample operation on three samples using C++ functions\n declared to the ROOT interpreter.\n \"\"\"\n\n # Write initialization code that will be run in the workers to make the\n # needed functions available\n def declare_definepersample_code():\n ROOT.gInterpreter.Declare(\n '''\n #ifndef distrdf_test_definepersample_withinitialization\n #define distrdf_test_definepersample_withinitialization\n float sample1_weight(){\n return 1.0f;\n }\n\n float sample2_weight(){\n return 2.0f;\n }\n\n float sample3_weight(){\n return 3.0f;\n }\n\n float samples_weights(unsigned int slot, const ROOT::RDF::RSampleInfo &id){\n if (id.Contains(\"sample1\")){\n return sample1_weight();\n } else if (id.Contains(\"sample2\")){\n return sample2_weight();\n } else if (id.Contains(\"sample3\")){\n return sample3_weight();\n }\n return -999.0f;\n }\n\n std::string samples_names(unsigned int slot, const ROOT::RDF::RSampleInfo &id){\n return id.AsString();\n }\n #endif // distrdf_test_definepersample_withinitialization\n ''')\n\n DistRDF.initialize(declare_definepersample_code)\n df = Spark.RDataFrame(self.maintreename, self.filenames, sparkcontext=connection)\n df1 = df.DefinePerSample(\"sample_weight\", \"samples_weights(rdfslot_, rdfsampleinfo_)\")\\\n .DefinePerSample(\"sample_name\", \"samples_names(rdfslot_, rdfsampleinfo_)\")\n\n # Filter by the two defined columns per sample: a weight and the sample string representation\n # Each filtered dataset should have 10 entries, equal to the number of entries per sample\n weightsandnames = [(\"1.0f\", \"sample1.root/Events\"), (\"2.0f\", \"sample2.root/Events\"),\n (\"3.0f\", \"sample3.root/Events\")]\n samplescounts = [\n df1.Filter(\"sample_weight == {} && sample_name == \\\"{}\\\"\".format(weight, name)).Count()\n for (weight, name) in weightsandnames]\n\n for count in samplescounts:\n assert count.GetValue() == 10\n\n\nif __name__ == \"__main__\":\n pytest.main(args=[__file__])\n","sub_path":"python/distrdf/spark/check_definepersample.py","file_name":"check_definepersample.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"360352486","text":"\"\"\"\nYou are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).\nYou have to rotate the image in-place, which means you have to modify the input 2D matrix directly.\nDO NOT allocate another 2D matrix and do the rotation.\n\"\"\"\nfrom typing import List\n\n\ndef rotate(matrix: List[List[int]]) -> None:\n \"\"\"\n Explanation\n Again one I didn't get. But i'm ok not knowing this one.\n \"\"\"\n n = len(matrix[0])\n for i in range(n // 2 + n % 2):\n for j in range(n // 2):\n tmp = matrix[n - 1 - j][i]\n matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1]\n matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i]\n matrix[j][n - 1 - i] = matrix[i][j]\n matrix[i][j] = tmp\n\n\n\"\"\"\nRun DETAILS\nRuntime: 24 ms, faster than 99.08% of Python3 online submissions for Rotate Image.\nMemory Usage: 14.2 MB, less than 86.54% of Python3 online submissions for Rotate Image.\n\"\"\"\n","sub_path":"problems/rotate_image.py","file_name":"rotate_image.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"316916376","text":"# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n# greedy 尽量移除那些覆盖最广的区间\nclass Solution(object):\n def eraseOverlapIntervals(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: int\n \"\"\"\n if not intervals: return 0\n intervals = sorted(intervals, key=lambda x: x.start)\n currEnd, ans = intervals[0].end, 0\n for i in intervals[1:]:\n if i.start < currEnd:\n ans += 1\n currEnd = min(currEnd, i.end)\n else:\n currEnd = i.end\n return ans\n\na = Solution()\nprint(a.eraseOverlapIntervals([[1,2], [2,3], [3,4], [1,3]]))","sub_path":"bb/leetcode435.py","file_name":"leetcode435.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"204878814","text":"#!/usr/bin/python3\n#date: 23/09/2020\n\n#1 Write the message \"Novo grenal (1-sim 2-nao)\" and request a response.\n#2\n#3\n'''#4 \n3 grenais\nInter:2\nGremio:1\nEmpates:0\n'''\n\nswitch = 1 #switch is True. 0 for False.\n\nlista_goals = [0, 0] #lista de gols\n\n#Internacional\ninter_score = 0\ninter_vitorias = 0\n\n#Gremio\ngremio_score = 0\ngremio_vitorias = 0\n\n#Empate: sem ganhador\nempates = 0\n\n#Iterador\nresposta = 0 # 1 ou 2. 1=sim; 2=nao\ngrenais = 0\n\n\nwhile (switch == 1):\n\tlista_goals = [int(x) for x in input().split(' ')]\n\t#print(lista_goals)\n\n\t#1: Computando o Score ANTES da solicitação de novo Grenal\n\tinter_score += lista_goals[0]\n\tgremio_score += lista_goals[1]\n\n\t#2: Computando o número de vitórias ANTES da solicitação de novo Grenal\n\twhile lista_goals[0] > lista_goals[1]:\t\n\t\tinter_vitorias += 1\n\t\tbreak\n\twhile lista_goals[1] > lista_goals[0]:\t\n\t\tgremio_vitorias += 1\n\t\tbreak\n\twhile lista_goals[0] == lista_goals[1]:\t\n\t\tempates += 1\n\t\tbreak\n\n\t#3: Novo grenal?\n\twhile resposta != 2: # só cobre 1 e 2 INTEIROS.\n\t\tprint(\"Novo grenal (1-sim 2-nao)\")\n\t\tresposta = int(input())\n\t\tgrenais += 1\t\n\t\tbreak\n\t\n\t#4: Número de Grenais e vitorias de cada time\n\twhile resposta == 2: # só cobre 1 e 2 INTEIROS.\n\t\tprint(\"{} grenais\".format(grenais))\n\t\tprint(\"Inter:{}\".format(inter_vitorias))\n\t\tprint(\"Gremio:{}\".format(gremio_vitorias))\n\t\tprint(\"Empates:{}\".format(empates))\n\t\t'''#4 \n\t\tInter:2\n\t\tGremio:1\n\t\tEmpates:0\n\t\t'''\n\t\t#4.5: Time que venceu mais ou se não houve vencedor\t\t\n\t\twhile inter_score > gremio_score:\n\t\t\tprint(\"Inter venceu mais\")\n\t\t\tbreak\n\t\twhile gremio_score > inter_score:\n\t\t\tprint(\"Gremio venceu mais\")\n\t\t\tbreak\n\t\twhile inter_score == gremio_score:\n\t\t\tprint(\"Não houve vencedor\")\n\t\t\tbreak\n\t\tswitch = 0 #Breaks the loop\n\t\tbreak\n\t\n\n''' \nURI Online Judge | 1131\nGrenais\n\nAdapted by Neilor Tonin, URI Brazil\nTimelimit: 1\n\nThe Federação Gaúcha de Futebol invited you to write a program to present a statistical result\nof several GRENAIS. Write a program that read the number of goals scored by Inter and the\nnumber of goals scored by Gremio in a GRENAL. Write the message \"Novo grenal (1-sim 2-nao)\"\nand request a response. If the answer is 1, two new numbers must be read (another input case)\nasking the number of goals scored by the teams in a new departure, otherwise the program must\nbe finished, printing:\n\n- How many GRENAIS were part of the statistics.\n- The number of victories of Inter.\n- The number of victories of Gremio.\n- The number of Draws.\n- A message indicating the team that won the largest number of GRENAIS (or the message:\n\"Não houve vencedor\" if both team won the same quantity of GRENAIS).\nInput: The input contains two integer values​​, corresponding to the goals scored by both teams.\nThen there is an integer (1 or 2), corresponding to the repetition of the algorithm.\nOutput: After each reading of the goals it must be printed the message \"Novo grenal (1-sim 2-nao)\".\nWhen the program is finished, the program must print the statistics as the example below.\n'''\n","sub_path":"URI-VOAL/1131.py","file_name":"1131.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"172934519","text":"#动态规划算法求解硬币找零问题\ndef dpMakeChange(coinValueList,change,minCoins,coinused):\n for cents in range(1,change + 1):\n coinCount = cents\n newCoin = 0 \n for j in [c for c in coinValueList if c <= cents]:\n if minCoins[cents - j] + 1 < coinCount:\n coinCount = minCoins[cents - j] + 1\n newCoin = j\n minCoins[cents] = coinCount\n coinused[cents] = newCoin\n return minCoins[change]\n\ndef printCoins(coinsUsed,change):\n coin = change\n while coin > 0:\n thisCoin = coinsUsed[coin]\n print(thisCoin)\n coin = coin - thisCoin\n\namnt = 63\nclist = [1,5,10,21,25]\ncoinUsed = [0] * (amnt+1)\ncoinCount = [0] * (amnt+1)\nprint(\"Making change for\", amnt, \"requires\")\nprint(dpMakeChange(clist, amnt, coinCount,coinUsed), \"coins\")\nprint(\"They are:\")\nprintCoins(coinUsed, amnt)\nprint(\"The used list is as follows:\")\nprint(coinUsed)\n","sub_path":"week6/dpMakeChange.py","file_name":"dpMakeChange.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"6098648","text":"class Person:\n def __init__(self,name,age):\n self.name=name\n self.age=age\n def showage(self):\n print(\"{0.name} 'age is {0.age}\".format(self))\n\ntom = Person('tom',18)\njerry= Person('Je',20)\n\ntom.showage()\njerry.showage()","sub_path":"oop/normalobject.py","file_name":"normalobject.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"374726850","text":"import unittest\n\nfrom matrix.common.aws.redshift_handler import TableName\nfrom matrix.common.etl.transformers.cell_expression import CellExpressionTransformer\n\n\nclass TestCellExpressionTransformer(unittest.TestCase):\n def setUp(self):\n self.transformer = CellExpressionTransformer(\"\")\n\n def test_parse_from_metadatas(self):\n parsed = self.transformer._parse_from_metadatas(\"tests/functional/res/etl/bundle\")\n\n cell_table = parsed[0][0]\n cell_rows = parsed[0][1]\n self.assertEqual(cell_table, TableName.CELL)\n self.assertEqual(cell_rows[0],\n \"635badd5-7d62-4db3-b509-f290a12a1336|635badd5-7d62-4db3-b509-f290a12a1336|\"\n \"c3ba122b-9158-4447-b379-6f5983a2416d|80bd863b-d92c-4c5f-98b6-4c32d7b2e806|\"\n \"265ab074-6db1-4038-836c-fba3cc2d09cb|f6ff0075-f93e-478a-8ba3-8c798e7f5021||3859\\n\")\n\n expression_table = parsed[1][0]\n expression_rows = parsed[1][1]\n self.assertEqual(expression_table, TableName.EXPRESSION)\n self.assertEqual(expression_rows[0], \"635badd5-7d62-4db3-b509-f290a12a1336|ENST00000373020|TPM|92.29\\n\")\n","sub_path":"tests/unit/common/etl/transformers/test_cell_expression.py","file_name":"test_cell_expression.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"71337864","text":"from dados import carregar_acessos\nfrom sklearn.naive_bayes import MultinomialNB\n\n# Minha abordagem inicial foi:\n# 1. Separar 90% para treino e 10% para teste. Resultado: 88.89% de precisão.\n\nX, Y = carregar_acessos()\n\ntreino_dados = X[:90]\ntreino_marcacoes = Y[:90]\n\nteste_dados = X[-9:]\nteste_marcacoes = Y[-9:]\n\nmodelo = MultinomialNB()\nmodelo.fit(treino_dados, treino_marcacoes)\n\n# 1 - Acessou a home\n# 2 - Acessou como funciona\n# 3 - Acessou o contato\n# ? - Efetuou a compra?\n\nresultado = modelo.predict(teste_dados)\ndiferencas = resultado - teste_marcacoes\nacertos = [d for d in diferencas if d == 0]\ntotal_de_acertos = len(acertos)\ntotal_de_elementos = len(teste_dados)\ntaxa_de_acerto = 100.0 * (total_de_acertos / total_de_elementos)\n\nprint(taxa_de_acerto)\nprint(total_de_elementos)","sub_path":"classifica_acesso.py","file_name":"classifica_acesso.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"547896444","text":"import dlib;\nimport cv2;\nimport imutils;\nimport utils;\nfrom imutils import face_utils;\n\nDLIB_FACE_LANDMARK_DETECTOR_PATH = \"shape_predictor_68_face_landmarks.dat\";\n\nclass faceLandmarkDetector(object):\n def __init__(self):\n self._landmarkPredictorPath = DLIB_FACE_LANDMARK_DETECTOR_PATH;\n self._landmarkPredictor = dlib.shape_predictor(self._landmarkPredictorPath);\n self._faceDetector = dlib.get_frontal_face_detector();\n\n def setFrame(self, frame, frameResizedWidth = 400):\n self._frame = frame;\n self._originalFrame = frame;\n l = len(self._frame.shape);\n if l == 3:\n # image is RGB. Convert to grey scale\n self._frame = cv2.cvtColor(self._frame, cv2.COLOR_BGR2GRAY);\n elif l > 3:\n raise Exception(\"A grayscale or RGB image is required.\");\n self._resizeRatio, self._resizedFrame = utils.frameResize(self._frame, new_width = frameResizedWidth);\n\n def _detectFaces(self):\n return self._faceDetector(self._resizedFrame, 0);\n\n def _detectLandmarks(self):\n faces = self._detectFaces();\n\n self._faceLandmarksList = []; # an array that contains tuples containing a face and the respective facial landmarks.\n\n for rect in faces:\n landmarks = self._landmarkPredictor(self._resizedFrame, rect);\n np_landmarks = face_utils.shape_to_np(landmarks);\n\n landmarksList = [];\n for (x,y) in np_landmarks:\n rx = int (x / self._resizeRatio);\n ry = int (y / self._resizeRatio);\n landmarksList.append((rx,ry));\n \n # dlib rectangle to cv bounding box\n rectx = int(rect.left() / self._resizeRatio);\n recty = int(rect.top() / self._resizeRatio);\n rectw = int((rect.right() - rect.left()) / self._resizeRatio);\n recth = int((rect.bottom() - rect.top()) / self._resizeRatio);\n rect = (rectx, recty, rectw, recth);\n \n self._faceLandmarksList.append((rect, landmarksList))\n \n\n def detect(self):\n self._detectLandmarks();\n return self._faceLandmarksList;","sub_path":"EyeTracker/faceLandmarkDetector.py","file_name":"faceLandmarkDetector.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"178750982","text":"import random\nfrom Marian import connectMysql\nfrom math import ceil\nimport datetime\nimport operator\nimport copy\nfrom threading import Thread\nfrom multiprocessing.pool import ThreadPool\nimport multiprocessing\nimport inspect\n\ndef getRepeatedNumbers(fromDate, toDate, tierSize=4):\n msql = connectMysql()\n cursor = msql.cursor()\n numberDistribution = []\n for i in range(1, 81):\n query = \"select count(*) as distribution from pots where (num1=%s or num2=%s or num3=%s or num4=%s or num5=%s or \\\n num6=%s or num7=%s or num8=%s or num9=%s or num10=%s or \\\n num11=%s or num12=%s or num13=%s or num14=%s or num15=%s or \\\n num16=%s or num17=%s or num18=%s or num19=%s or num20=%s) \\\n and datetime between %s and %s\"\n data = (\"%s\" % i,) * 20 + (fromDate, toDate)\n cursor.execute(query, data)\n numberDistribution.append((i, cursor.fetchone()[0]))\n \n numberDistribution.sort(key=lambda x: x[1])\n tiers = []\n ranging = int(80 / tierSize)\n for i in range(ranging):\n tier = [i[0] for i in numberDistribution[i * tierSize: i * tierSize + tierSize]]\n tiers.append(tier)\n \n msql.close()\n return tiers\n \ndef ceilDatetime(dt):\n deltaMin = int(ceil(dt.minute / 5.) * 5)\n if deltaMin == 60:\n dt = dt + datetime.timedelta(minutes=60)\n deltaMin = 0\n \n return dt.replace(second=0, microsecond=0, minute=deltaMin)\n\ndef getNumberDistribution(number, fromDate, toDate):\n msql = connectMysql()\n distribution = {\n \"hits\":[],\n \"avgHits\":0,\n \"misses\":[],\n \"combined\":[],\n \"avgMisses\":0,\n }\n count = 0\n cursor = msql.cursor()\n trend = None\n \n while fromDate != toDate:\n query = \"select * from pots where datetime=%s\"\n cursor.execute(query, (fromDate,))\n\n try:\n numbers = cursor.fetchone()[2:]\n \n if number in numbers:\n if trend is not None and trend == -1:\n distribution[\"misses\"].append(count)\n distribution[\"combined\"].append(-count)\n count = 0\n \n count += 1\n trend = 1\n else: \n if trend is not None and trend == 1:\n distribution[\"hits\"].append(count)\n distribution[\"combined\"].append(count)\n count = 0\n \n count += 1\n trend = -1\n except:\n continue\n finally:\n fromDate += datetime.timedelta(minutes=5)\n \n if trend is not None and trend == -1:\n distribution[\"misses\"].append(count)\n distribution[\"combined\"].append(-count)\n count = 0\n if trend is not None and trend == 1:\n distribution[\"hits\"].append(count)\n distribution[\"combined\"].append(count)\n count = 0\n \n distribution[\"avgHits\"] = max(distribution[\"hits\"]) / 2\n distribution[\"avgMisses\"] = max(distribution[\"misses\"]) / 2\n distribution[\"hitRatio\"] = len(distribution[\"hits\"]) / len(distribution[\"hits\"])\n \n msql.close()\n return distribution\n\ndef findPatterns(distribution, patternWidth=1):\n patterns = {}\n meta = {\n \"hitPatterns\": 0,\n \"missPatterns\": 0,\n }\n try:\n for index, point in enumerate(distribution):\n pattern = distribution[index:index+patternWidth]\n nextTrend = 1 if distribution[index+patternWidth] > 0 else -1\n \n if nextTrend == 1:\n meta[\"hitPatterns\"] += 1\n else:\n meta[\"missPatterns\"] += 1\n \n pattern.append(nextTrend)\n pattern = tuple(pattern)\n patternCount = patterns.get(pattern, 0)\n if patternCount == 0: patterns[pattern] = 0\n \n patterns[pattern] += 1 \n except IndexError:\n pass\n \n return patterns, meta\n \ndef getPatternProbability(sortedPatterns, patterns):\n patternProbabilities = {}\n \n for pattern, quantity in sortedPatterns:\n trend = pattern[-1]\n pattern = pattern[:-1]\n \n counterPattern = pattern + (-trend,)\n counterPatternQuantity = patterns.get(counterPattern, 0)\n if counterPatternQuantity == 0:\n probability = 100\n else:\n probability = quantity / counterPatternQuantity\n \n patternProbabilities[pattern] = (probability, trend)\n# print(pattern, probability, trend, quantity)\n \n return patternProbabilities\n\ndef buildPatternProbability(fromDate, toDate, patternWidth=2, toPass=3):\n \n manager = multiprocessing.Manager()\n numberPatternProbability = manager.dict()\n \n number = 1\n for _ in range(1):\n jobs = []\n for _ in range(8):\n p = multiprocessing.Process(target=_numberProbability, args=(number, fromDate, toDate, patternWidth, numberPatternProbability, toPass))\n jobs.append(p)\n p.start()\n \n number += 1\n \n for job in jobs:\n job.join()\n \n return numberPatternProbability\n\ndef _numberProbability(number, fromDate, toDate, patternWidth=2, target=None, toPass=3):\n # Pass1\n distribution = getNumberDistribution(number, fromDate, toDate)\n \n if toPass == 1:\n if target is None:\n return distribution\n else:\n target[number] = distribution[\"combined\"]\n \n # Pass2\n patterns, meta = findPatterns(distribution[\"combined\"], patternWidth=patternWidth)\n allHits, allMisses, maxHits, maxMisses = sum(distribution[\"hits\"]), sum(distribution[\"misses\"]), \\\n max(distribution[\"hits\"]), max(distribution[\"misses\"])\n \n sortedPatterns = sorted(patterns.items(), key=operator.itemgetter(1))\n \n if toPass == 2:\n if target is None:\n return sortedPatterns\n else:\n target[number] = sortedPatterns\n\n # Pass 3\n patternProbabilities = getPatternProbability(copy.deepcopy(sortedPatterns), patterns)\n \n if toPass == 3: \n if target is None:\n return patternProbabilities\n else:\n target[number] = patternProbabilities, distribution[\"combined\"]\n\n \n","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":6654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"462634541","text":"import FWCore.ParameterSet.Config as cms\n\n\nhltHighLevelMuons = cms.EDFilter(\"HLTHighLevel\",\n TriggerResultsTag = cms.InputTag(\"TriggerResults\",\"\",\"REDIGI38X\"),\n HLTPaths = cms.vstring('HLT_Mu9','HLT_Mu11','HLT_IsoMu9'),\n eventSetupPathsKey = cms.string(''), \n andOr = cms.bool(True), #True (OR) accept if ANY is true, False (AND) accept if ALL are true\n throw = cms.bool(True) \n )\n\n\n\nprimaryVertexFilter = cms.EDFilter(\"GoodVertexFilter\",\n vertexCollection = cms.InputTag('offlinePrimaryVertices'),\n minimumNDOF = cms.uint32(4) ,\n maxAbsZ = cms.double(24),\t\n maxd0 = cms.double(2)\t\n )\n\nscrapping = cms.EDFilter(\"FilterOutScraping\",\n applyfilter = cms.untracked.bool(True),\n debugOn = cms.untracked.bool(False),\n numtrack = cms.untracked.uint32(10),\n thresh = cms.untracked.double(0.25)\n )\n\nselectedPatJetsCountFilter = cms.EDFilter(\"PATCandViewCountFilter\",\n minNumber = cms.uint32(0),\n maxNumber = cms.uint32(999999),\n src = cms.InputTag('selectedPatJetsPFlow')\n )\n\nallEventsFilter = cms.EDFilter(\"AllEventsFilter\")\n\nnoiseCleanedEventsFilter = allEventsFilter.clone()\n","sub_path":"eToTaufakeRate/python/filters_ZmumuPlusJets_cff.py","file_name":"filters_ZmumuPlusJets_cff.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"615903921","text":"# the server\nimport socket\n\nsock = socket.socket()\n\nserver = socket.gethostname()\nport = 8501\nbacklogQueue = 3\nsock.bind((server, port)) # bind to a local address\nsock.listen(backlogQueue) # num connections to allow (queue) before refusing\nprint('Server running on port {num}'.format(num=port))\nwhile True:\n client_conn, client_address = sock.accept() # wait for an incoming connection, returns client connection and client address\n print('Client connected: ', client_address)\n client_conn.send(b'Welcome to my server!')\n client_conn.close()","sub_path":"Optum Tech/IN1468 available until 12-31-20/IN1468_student_files/student_files/ch04_network_prog/02_server.py","file_name":"02_server.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"643820060","text":"from django.template import Context, Template\n\nt = Template(\"My name is {{ name }}.\")\n# drukuje obiekt template\n# print(t)\n\n# TemplateSyntaxError:\n# niewłaściwy tag\n# niewłaściwy argument do właściwego tagu\n# niewłaściwy filtr\n# niewłaściwy argument do właściwego filtra\n# niewłaściwa składnia szablonu\n# niezamknięte tagi (wymagające zamknięcia)\n\n# kontekst - zmienna z powiązaną wartością,\n# posiada dodatkową funkcjonalność w porównaniu do słownika\nc = Context({\"name\": \"gulci\"})\nt.render(c)\n\n# czyszczenie wyjścia konsoli\n# import os\n# os.system('cls')\n","sub_path":"djmaster/template_example.py","file_name":"template_example.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"295792259","text":"#! /usr/bin/env python\n\nfrom nsx import NSX\n\nedgeid = raw_input(\"Edge id: \")\n\ninputs = 'inputs/nsx.yml'\n\n# NSX Manager credentials\ncred = credentials(inputs)\nnsx = NSX(*cred)\n\n\n# Find uplink IP\nprint(nsx.getuplinkip(edgeid))\n\n\n","sub_path":"nsx_edge_uplinkip_id.py","file_name":"nsx_edge_uplinkip_id.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"609299952","text":"import urllib.request\r\nfrom bs4 import BeautifulSoup\r\n\r\nif __name__ == \"__main__\":\r\n url = \"http://www.naver.com\"\r\n req = urllib.request.Request(url);\r\n data = urllib.request.urlopen(req).read()\r\n bs = BeautifulSoup(data, 'html.parser')\r\n # BeautifulSoup 생성자에서 html_doc를 파싱하고\r\n # 그 결과를 BeautifulSoup 객체로 반환한다.\r\n # print(bs.prettify())\r\n lis = bs.find_all(\"li\",{\"class\":\"ah_item\"})\r\n #print(type(lis))\r\n #print(len(lis))\r\n #print(lis[0])\r\n #print(\"_\"*90)\r\n for li in lis:\r\n a = li.select(\"a\")\r\n if len(a)==2:\r\n span = li.select('span')\r\n print(span[0].string, span[1].string)\r\n a_href = li.find('a')['href']\r\n print(a_href)","sub_path":"Hello/BeautifulSoupEx/HTML/Naver.py","file_name":"Naver.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"420108829","text":"# 튜플 - 문자열 - 64065\n# 특정 튜플을 표현하는 집합이 담긴 문자열 s가 매개변수로 주어질 때, s가 표현하는 튜플을 배열에 담아 return 하도록 solution 함수를 완성해주세요.\n\n# [제한사항]\n# s의 길이는 5 이상 1,000,000 이하입니다.\n# s는 숫자와 '{', '}', ',' 로만 이루어져 있습니다.\n# 숫자가 0으로 시작하는 경우는 없습니다.\n# s는 항상 중복되는 원소가 없는 튜플을 올바르게 표현하고 있습니다.\n# s가 표현하는 튜플의 원소는 1 이상 100,000 이하인 자연수입니다.\n# return 하는 배열의 길이가 1 이상 500 이하인 경우만 입력으로 주어집니다.\n\ndef solution(s):\n answer = []\n s = s.replace('{{', \"\")\n s = s.replace('}}', \"\")\n arr = s.split('},{')\n # s.lstrip('{').rstrip('}').split('},{') 이런 파싱법도 있다.\n # 정규식으로 하는 풀이도 있더라.\n\n # remind! : sort(key = len)을 이용하여 길이에 따른 정렬이 가능하다.\n arr.sort(key=len)\n\n for i in arr:\n temp = i.split(',') # ,로 다시 split하고\n for t in temp:\n if int(t) not in answer: # 정수형으로 바꾼 것들이 answer에 없을경우\n answer.append(int(t)) # answer에 대입해준다\n\n return answer\n\n\ns1 = \"{{2},{2,1},{2,1,3},{2,1,3,4}}\"\ns2 = \"{{1,2,3},{2,1},{1,2,4,3},{2}}\"\n\nprint(solution(s1))\nprint(solution(s2))\n","sub_path":"python/programmers/문자열처리/[64065_문자열처리_튜플]홍종완.py","file_name":"[64065_문자열처리_튜플]홍종완.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"68312441","text":"from __future__ import print_function\n\nimport errno\nimport hashlib\nimport os\nimport sys\nimport tarfile\n\nimport torch.utils.data as data\nfrom PIL import Image\n\nfrom six.moves import urllib\nimport numpy as np\nimport torch\n\n\nclass VOCSegmentation(data.Dataset):\n CLASSES = [\n 'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',\n 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse',\n 'motorbike', 'person', 'potted-plant', 'sheep', 'sofa', 'train',\n 'tv/monitor', 'ambigious'\n ]\n\n URL = \"http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar\"\n FILE = \"VOCtrainval_11-May-2012.tar\"\n MD5 = '6cd6e144f989b92b3379bac3b3de84fd'\n BASE_DIR = os.path.join('VOCdevkit', 'VOC2012')\n\n def __init__(self,\n root,\n train=True,\n transform=None,\n target_transform=None,\n download=False):\n self.root = root\n _voc_root = os.path.join(self.root, self.BASE_DIR)\n _mask_dir = os.path.join(_voc_root, 'SegmentationClass')\n _image_dir = os.path.join(_voc_root, 'JPEGImages')\n self.transform = transform\n self.target_transform = target_transform\n self.train = train\n\n if download:\n self._download()\n\n if not self._check_integrity():\n raise RuntimeError('Dataset not found or corrupted.' +\n ' You can use download=True to download it')\n # train/val/test splits are pre-cut\n _splits_dir = os.path.join(_voc_root, 'ImageSets', 'Segmentation')\n _split_f = os.path.join(_splits_dir, 'train.txt')\n if not self.train:\n _split_f = os.path.join(_splits_dir, 'trainval.txt')\n\n self.images = []\n self.masks = []\n with open(os.path.join(_split_f), \"r\") as lines:\n for line in lines:\n _image = os.path.join(_image_dir, line.rstrip('\\n') + \".jpg\")\n _mask = os.path.join(_mask_dir, line.rstrip('\\n') + \".png\")\n assert os.path.isfile(_image)\n assert os.path.isfile(_mask)\n self.images.append(_image)\n self.masks.append(_mask)\n assert (len(self.images) == len(self.masks)) \n\n\n def __getitem__(self, index):\n \n _img = Image.open(self.images[index]).convert('RGB')\n _target = Image.open(self.masks[index])\n\n if self.transform is not None:\n _img = self.transform(_img)\n # todo(bdd) : perhaps transformations should be applied differently to masks? \n if self.target_transform is not None:\n _target = self.target_transform(_target)\n\n return _img, _target\n\n def __len__(self):\n return len(self.images)\n\n def _check_integrity(self):\n _fpath = os.path.join(self.root, self.FILE)\n if not os.path.isfile(_fpath):\n print(\"{} does not exist\".format(_fpath))\n return False\n _md5c = hashlib.md5(open(_fpath, 'rb').read()).hexdigest()\n if _md5c != self.MD5:\n print(\" MD5({}) did not match MD5({}) expected for {}\".format(\n _md5c, self.MD5, _fpath))\n return False\n return True\n\n def _download(self):\n _fpath = os.path.join(self.root, self.FILE)\n\n try:\n os.makedirs(self.root)\n except OSError as e:\n if e.errno == errno.EEXIST:\n pass\n else:\n raise\n\n if self._check_integrity():\n print('Files already downloaded and verified')\n return\n else:\n print('Downloading ' + self.URL + ' to ' + _fpath)\n\n def _progress(count, block_size, total_size):\n sys.stdout.write('\\r>> %s %.1f%%' %\n (_fpath, float(count * block_size) /\n float(total_size) * 100.0))\n sys.stdout.flush()\n\n urllib.request.urlretrieve(self.URL, _fpath, _progress)\n\n # extract file\n cwd = os.getcwd()\n print('Extracting tar file')\n tar = tarfile.open(_fpath)\n os.chdir(self.root)\n tar.extractall()\n tar.close()\n os.chdir(cwd)\n print('Done!')\n\n\n\nclass VOCSegmentationClasses(VOCSegmentation):\n\n def __init__(self,\n root,\n train=True,\n transform=None,\n target_transform=None,\n download=False):\n super(VOCSegmentationClasses, self).__init__(root, train, transform, target_transform, download)\n\n def __getitem__(self, index):\n _img = Image.open(self.images[index]).convert('RGB')\n _target = Image.open(self.masks[index])\n _img = _img.resize((32, 32), Image.ANTIALIAS)\n _img = np.array(_img)\n if self.transform is not None:\n _img = self.transform(_img)\n if self.target_transform is not None:\n _target = self.target_transform(_target)\n # _target_labels = np.zeros(len(self.CLASSES), dtype=np.long)\n # _target_labels = torch.LongTensor(len(self.CLASSES)).fill_(0)\n _target_labels = torch.LongTensor(len(self.CLASSES)-2).fill_(0)\n for c in range(len(self.CLASSES)-2): # ignore first and last classes: background and ambiguous\n classes = [item[1] for item in _target.getcolors()]\n if c+1 in classes:\n _target_labels[c] = 1\n return _img, _target_labels\n","sub_path":"scripts/pascal.py","file_name":"pascal.py","file_ext":"py","file_size_in_byte":5529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"177398200","text":"from random import randint\n\n\nclass BaseCharacter:\n \"\"\"\n Base Hero Class, with random atributes and specified information\n This class must evolve into sht more specified for\n diffrent classes under this one for example:\n Barbarian must have more srength than mage.\n Strength must affect HP in stat_dict\n Wisdom must affect Mana in stat_dict\n\n \"\"\"\n def __init__(self):\n for attribute in self.attribute_dict:\n self.attribute_dict[attribute] = randint(25, 50)\n self.stat_dict['HP'] = 50\n self.stat_dict['Mana'] = 5\n self.stat_dict['LVL'] = 1\n self.stat_dict['XP'] = 0\n self.attribute_points = 10\n self.lvl_points = 0\n self.const_dict = self.attribute_dict.copy()\n self.const_stat_dict = self.stat_dict.copy()\n self.item_list = []\n self. parry_bonus = 0\n\n parry_bonus = 0\n item_list = []\n img = ''\n back_img = ''\n info_dict = {'CLASS NAME': '', 'NAME': '', 'BIO': ''}\n\n hero_ini = \"You Hit this nigga with: \"\n\n attribute_dict = {\n 'Strength': 0,\n 'Agility': 0,\n 'Wisdom': 0,\n 'Charisma': 0,\n 'Perception': 0,\n 'Luck': 0,\n 'Vigor': 0,\n }\n\n const_dict = {}\n\n stat_dict = {\n 'HP': 0,\n 'Mana': 0,\n 'XP': 0,\n 'LVL': 0,\n }\n\n attribute_points = 0\n lvl_points = 0\n\n # behaviour that every character will have\n\n def attack(self, dice):\n return self.attribute_dict['Strength'] + dice.k4_roll()\n\n def count_resistance(self, dice):\n return (self.attribute_dict['Vigor'] - 15) + dice.k4_roll()\n\n def set_name(self, name_string):\n self.info_dict['name'] = name_string\n\n\nclass Barbarian(BaseCharacter):\n def __init__(self):\n BaseCharacter.__init__(self)\n self.img = \"barb.png\"\n self.back_img = \"tyl_barb.png\"\n\n info_dict = {'CLASS NAME': 'Barbarian', 'NAME': 'Socrates'}\n bio = 'A barbarian is a human who is perceived to be uncivilised or primitive. The designation is usually applied as generalization based on a popular stereotype; barbarians can be any member of a nation judged by some to be less civilised or orderly (such as a tribal society), but may also be part of a certain \"primitive\" cultural group (such as nomads) or social class (such as bandits) both within and outside ones own nation'\n\n stat_dict = {\n 'HP': 30,\n 'Mana': 10,\n 'XP': 0,\n \"LVL\": 1,\n }\n\n\nclass Hunter(object, BaseCharacter):\n def __init__(self):\n BaseCharacter.__init__(self)\n self.img = \"lowca_pop.png\"\n self.back_img = \"tyl_lowcy.png\"\n info_dict = {'CLASS NAME': 'Hunter', 'NAME': 'Jacke'}\n bio = 'Hunters are usually associated with the wisdom of nature. Rangers tend to be wise, hardy, cunning, and perceptive in addition to being skilled woodsmen. Many are skilled in woodcraft, stealth, wilderness survival, beast-mastery, herbalism, tracking, and sometimes \"nature magic\" or have a resistance to magic.'\n\n stat_dict = {\n 'HP': 20,\n 'Mana': 10,\n 'XP': 0,\n \"LVL\": 1,\n }\n\n\nclass Mage(object, BaseCharacter):\n def __init__(self):\n BaseCharacter.__init__(self)\n self.img = \"wiekszy mag.png\"\n self.back_img = \"tyl_maga.png\"\n info_dict = {'CLASS NAME': 'Mage', 'NAME': 'Elendinr'}\n bio = 'Mage is someone who uses or practices magic derived from supernatural or occult sources. Magicians are common figures in works of fantasy, such as fantasy literature and role-playing games, and enjoy a rich history in mythology, legends, fiction, and folklore.'\n stat_dict = {\n 'HP': 15,\n 'Mana': 25,\n 'XP': 0,\n \"LVL\": 1,\n }\n","sub_path":"base_class.py","file_name":"base_class.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"153888569","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Tests for the unique hashes analysis plugin.\"\"\"\n\nimport unittest\n\nfrom dfvfs.path import fake_path_spec\n\nfrom plaso.analysis import file_hashes\nfrom plaso.lib import definitions\n\nfrom tests.analysis import test_lib\n\n\nclass UniqueHashesTest(test_lib.AnalysisPluginTestCase):\n \"\"\"Test for the unique hashes analysis plugin.\"\"\"\n\n _TEST_EVENTS = [\n {'data_type': 'test:event',\n 'md5_hash': '4',\n 'path_spec': fake_path_spec.FakePathSpec(\n location='/var/testing directory with space/file.txt'),\n 'timestamp': '2015-01-01 17:00:00',\n 'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN},\n {'data_type': 'test:event',\n 'md5_hash': '4',\n 'path_spec': fake_path_spec.FakePathSpec(\n location='C:\\\\Windows\\\\a.file.txt'),\n 'timestamp': '2015-01-01 17:00:01',\n 'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN},\n {'data_type': 'test:event',\n 'md5_hash': '4',\n 'pathspec': fake_path_spec.FakePathSpec(location='/opt/dfvfs'),\n 'timestamp': '2015-01-01 17:00:02',\n 'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN},\n {'alternate_test_hash': '5',\n 'data_type': 'test:event',\n 'md5_hash': '4',\n 'pathspec': fake_path_spec.FakePathSpec(location='/opt/2hash_file'),\n 'sha256_hash': '5',\n 'timestamp': '2015-01-01 17:00:03',\n 'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN},\n {'data_type': 'test:event',\n 'pathspec': fake_path_spec.FakePathSpec(location='/opt/no_hash_file'),\n 'timestamp': '2015-01-01 17:00:04',\n 'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN}]\n\n def testExamineEventAndCompileReport(self):\n \"\"\"Tests the ExamineEvent and CompileReport functions.\"\"\"\n plugin = file_hashes.FileHashesPlugin()\n storage_writer = self._AnalyzeEvents(self._TEST_EVENTS, plugin)\n\n self.assertEqual(len(storage_writer.analysis_reports), 1)\n\n analysis_report = storage_writer.analysis_reports[0]\n\n expected_text = (\n 'Listing file paths and hashes\\n'\n 'FAKE:/opt/2hash_file: md5_hash=4 sha256_hash=5\\n'\n 'FAKE:/opt/dfvfs: md5_hash=4\\n'\n 'FAKE:/opt/no_hash_file:\\n'\n 'FAKE:/var/testing directory with space/file.txt: md5_hash=4\\n'\n 'FAKE:C:\\\\Windows\\\\a.file.txt: md5_hash=4\\n')\n\n self.assertEqual(expected_text, analysis_report.text)\n self.assertEqual(analysis_report.plugin_name, 'file_hashes')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/analysis/file_hashes.py","file_name":"file_hashes.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"86640953","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass Brewery(models.Model):\n name = models.CharField(max_length=200)\n state = models.CharField(max_length=200)\n city = models.CharField(max_length=200)\n country = models.CharField(max_length=200)\n description = models.TextField(blank=True)\n website = models.URLField()\n def __unicode__(self):\n return self.name\n# flagship = models.ForeignKey(Beer)\n\nclass Style(models.Model):\n name = models.CharField(max_length=200)\n description = models.TextField(blank=True)\n lowabv = models.DecimalField(max_digits=3,decimal_places=1)\n highabv = models.DecimalField(max_digits=3,decimal_places=1)\n def __unicode__(self):\n return self.name\n\nclass Beer(models.Model):\n brewery = models.ForeignKey(Brewery)\n name = models.CharField(max_length=200)\n description = models.TextField(blank=True)\n style = models.ForeignKey(Style)\n abv = models.DecimalField(max_digits=3,decimal_places=1)\n #uploads to MEDIA_ROOT/beershots need to serve from apache or S3(eventually)\n #need to figure out how to rename to name of beer and put in folder for brewery\n picture = models.ImageField(upload_to='beershots')\n def __unicode__(self):\n return self.name\n\nclass Taster(models.Model):\n first = models.CharField(max_length=200)\n last = models.CharField(max_length=200)\n nickName = models.CharField(max_length=250,blank=True)\n email = models.EmailField(max_length=254)\n description = models.TextField(blank=True)\n def __unicode__(self):\n return self.nickName\n\nclass Rating(models.Model):\n beer = models.ForeignKey(Beer)\n taster = models.ForeignKey(Taster)\n date = models.DateField()\n overallRating = models.DecimalField(max_digits=3,decimal_places=1)\n volumeRating = models.DecimalField(max_digits=3,decimal_places=1,blank=True)\n notes = models.TextField(blank=True)\n def _get_drunk(self):\n \"Returns the drunkability\"\n return (beer.abv * self.VolumeRating)/10\n drunkRating = property(_get_drunk)\n\n","sub_path":"tracker/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"646950220","text":"import socket\nimport psutil\nfrom datetime import datetime\n\n\ndef get_disks(all_partitions=False):\n disks = [\n (dp, psutil.disk_usage(dp.mountpoint))\n for dp in psutil.disk_partitions(all_partitions)\n ]\n disks.sort(key=lambda d: d[1].total, reverse=True)\n return disks\n\n\ndef get_users():\n users = []\n for u in psutil.users():\n dt = datetime.fromtimestamp(u.started)\n user = {\n 'name': u.name.decode('utf-8'),\n 'terminal': u.terminal,\n 'started': dt.strftime('%Y-%m-%d %H:%M:%S'),\n 'host': u.host.decode('utf-8')\n }\n\n users.append(user)\n return users\n\n\ndef get_process_environ(pid):\n with open('/proc/%d/environ' % pid) as f:\n contents = f.read()\n env_vars = dict(row.split('=', 1) for row in contents.split('\\0') if '=' in row)\n\n return env_vars\n\n\ndef socket_constants(prefix):\n return dict((getattr(socket, n), n) for n in dir(socket) if n.startswith(prefix))\n\n\nsocket_families = socket_constants('AF_')\nsocket_types = socket_constants('SOCK_')\n","sub_path":"psdash/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"455503433","text":"import numpy as np\nimport unittest\n\nimport sys, os\nsys.path.append( os.path.expanduser('~') )\nfrom kemp.fdtd3d.util import common_random\nfrom kemp.fdtd3d import cpu, naive\n\n\nclass TestCore(unittest.TestCase):\n def __init__(self, args):\n super(TestCore, self).__init__()\n self.args = args\n\n\n def runTest(self):\n ufunc, nx, ny, nz, coeff_use, precision_float, use_cpu_core, tmax = self.args\n qtask = cpu.QueueTask()\n fields = cpu.Fields(qtask, nx, ny, nz, coeff_use, precision_float, use_cpu_core)\n cpu.Core(fields)\n\n fields_ref = naive.Fields(nx, ny, nz, precision_float, segment_nbytes=16)\n naive.Core(fields_ref)\n\n # allocations\n ns = fields.ns\n dtype = fields.dtype\n\n ehs = common_random.generate_ehs(nx, ny, nz, dtype, ufunc)\n fields.set_ehs(*ehs)\n fields_ref.set_ehs(*ehs)\n\n ces, chs = common_random.generate_cs(nx, ny, nz, dtype, coeff_use)\n if 'e' in coeff_use:\n fields.set_ces(*ces)\n fields_ref.set_ces(*ces)\n if 'h' in coeff_use:\n fields.set_chs(*chs)\n fields_ref.set_chs(*chs)\n\n # verify\n strf_list = ['ex', 'ey', 'ez', 'hx', 'hy', 'hz']\n\n if ufunc == 'e':\n for tstep in xrange(0, tmax):\n for instance in fields.instance_list:\n instance.update_e('pre')\n instance.update_e('post')\n fields_ref.update_e()\n fields.enqueue_barrier()\n\n for strf, eh in zip(strf_list, ehs)[:3]:\n norm = np.linalg.norm(fields.get(strf) - fields_ref.get(strf))\n max_diff = np.abs(fields.get(strf) - fields_ref.get(strf)).max()\n self.assertEqual(norm, 0, '%s, %s, %g, %g' % (self.args, strf, norm, max_diff) )\n\n elif ufunc == 'h':\n for tstep in xrange(0, tmax):\n for instance in fields.instance_list:\n instance.update_h('pre')\n instance.update_h('post')\n fields_ref.update_h()\n fields.enqueue_barrier()\n\n for strf, eh in zip(strf_list, ehs)[3:]:\n norm = np.linalg.norm(fields.get(strf) - fields_ref.get(strf))\n max_diff = np.abs(fields.get(strf) - fields_ref.get(strf)).max()\n self.assertEqual(norm, 0, '%s, %s, %g, %g' % \\\n (self.args, strf, norm, max_diff) )\n\n\n\nif __name__ == '__main__':\n suite = unittest.TestSuite() \n\n nx, ny = 3, 50\n suite.addTest(TestCore( ('e', nx, ny, 64, '', 'single', 0, 1) ))\n\n args_list = [ \\\n (ufunc, nx, ny, nz, coeff_use, precision_float, use_cpu_core, 1) \\\n for ufunc in ['e', 'h'] \\\n for nz in [61, 62, 63, 64] \\\n for coeff_use in ['', 'e', 'h'] \\\n for precision_float in ['single', 'double'] \\\n for use_cpu_core in [0, 1] ]\n test_size = int( len(args_list)*0.1 )\n test_list = [args_list.pop( np.random.randint(len(args_list)) ) for i in xrange(test_size)]\n suite.addTests(TestCore(args) for args in test_list) \n\n suite.addTest(TestCore( ('e', nx, ny, 64, 'e', 'single', 0, 10) ))\n suite.addTest(TestCore( ('e', nx, ny, 64, 'e', 'double', 0, 10) ))\n\n unittest.TextTestRunner().run(suite) \n","sub_path":"KEMP.kkh/fdtd3d/cpu/test/test_core_split.py","file_name":"test_core_split.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"613267953","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport json\nimport os\nimport urllib\nimport datetime\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import UserPassesTestMixin\nfrom django.core.mail import EmailMessage\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom django.urls import reverse_lazy\nfrom django.views.generic import DetailView, ListView, TemplateView\nfrom django.views.generic.edit import (CreateView, DeleteView, FormView,\n UpdateView)\nfrom django_filters.views import FilterView\nfrom common_data.forms import AuthenticateForm\n\nfrom rest_framework.generics import ListAPIView, RetrieveAPIView\nfrom rest_framework.viewsets import ModelViewSet\nfrom wkhtmltopdf import utils as pdf_tools\nfrom wkhtmltopdf.views import PDFTemplateView\n\nfrom common_data.forms import SendMailForm\nfrom common_data.models import GlobalConfig\nfrom common_data.utilities import *\nfrom common_data.views import PaginationMixin, EmailPlusPDFView, PDFDetailView\nfrom inventory import filters, forms, models, serializers\nfrom invoicing.models import SalesConfig\nfrom accounting.models import Expense, JournalEntry, Account, Journal\n\nfrom .common import CREATE_TEMPLATE\n\n\nclass OrderAPIView(ModelViewSet):\n queryset = models.Order.objects.all()\n serializer_class = serializers.OrderSerializer\n\n\nclass OrderPOSTMixin(object):\n def post(self, request, *args, **kwargs):\n update_flag = isinstance(self, UpdateView)\n try:\n items = json.loads(urllib.parse.unquote(request.POST[\"items\"]))\n except json.JSONDecodeError:\n messages.info(request, 'Please populate the form with the lines of inventory to be ordered.')\n if update_flag:\n return HttpResponseRedirect(\n '/inventory/order-update/{}'.format(self.object.pk))\n return HttpResponseRedirect('/inventory/order-create')\n\n resp = super().post(request, *args, **kwargs)\n\n if not self.object:\n return resp\n\n order = self.object\n if update_flag and len(items) > 0: \n for i in self.object.orderitem_set.all():\n i.delete()\n\n for data in items:\n id= data['item'].split('-')[0] \n pk = id\n \n unit_id = 1 # default value\n if data['unit'] != \"\":\n unit_id = data['unit'].split('-')[0]\n \n unit = models.UnitOfMeasure.objects.get(\n pk=unit_id)\n item = models.InventoryItem.objects.get(pk=pk)\n if item.type != 0:\n continue #filter non products\n order.orderitem_set.create(\n item=item,\n quantity=data['quantity'],\n unit=unit,\n order_price=data['order_price'])\n \n #create transaction after loading all the items\n #vary based on order status\n \n if not update_flag:\n if self.request.POST.get('make_payment', None):\n pmt = models.OrderPayment.objects.create(\n order=order,\n date=datetime.date.today(),\n amount=order.total,\n comments=\"Autogenerated payment for order %d\" % order.pk\n )\n pmt.create_entry()\n return resp \n\nclass OrderCreateView( ContextMixin, \n OrderPOSTMixin, CreateView):\n '''The front end page combines with react to create a dynamic\n table for entering items in the form.\n The two systems communicate of json encoded strings \n passed as hidden input fields on the form as part of a\n list of 'items[]'. '''\n form_class = forms.OrderForm\n model = models.Order\n template_name = os.path.join(\"inventory\", \"order\", \"create.html\")\n extra_context = {\n \"title\": \"Create Purchase Order\",\n \"description\": \"Use this form to order inventory for sale from suppliers. Equipment and Consumables are purchased under 'Manage Equipment' or 'Manage Consumables' Forms.\",\n \"related_links\": [\n {\n 'name': 'Add Vendor',\n 'url': '/inventory/supplier/create'\n },{\n 'name': 'Add Product',\n 'url': '/inventory/product-create/'\n },\n\n ],\n 'box_array': urllib.parse.quote(json.dumps(\n [{\n 'model': 'supplier',\n 'app': 'inventory',\n 'id': 'id_supplier'\n }\n ]))\n }\n\n def get_initial(self):\n if self.kwargs.get('supplier', None):\n return {\n 'supplier': self.kwargs['supplier']\n }\n \n\n\nclass OrderUpdateView( ContextMixin, \n OrderPOSTMixin,UpdateView):\n form_class = forms.OrderUpdateForm\n model = models.Order\n template_name = os.path.join(\"inventory\", \"order\", \"update.html\")\n extra_context = {\"title\": \"Update Existing Purchase Order\"}\n\n\nclass OrderListView( ContextMixin, \n PaginationMixin, FilterView):\n paginate_by = 20\n filterset_class = filters.OrderFilter\n template_name = os.path.join(\"inventory\", \"order\", \"list.html\")\n extra_context = {\"title\": \"Purchase Order List\",\n \"new_link\": reverse_lazy(\"inventory:order-create\")}\n\n def get_queryset(self):\n return models.Order.objects.all().order_by('pk').reverse()\n\n\nclass OrderStatusView( ContextMixin, DetailView):\n template_name = os.path.join('inventory', 'order', 'status.html')\n model = models.Order\n\n\nclass OrderDeleteView( DeleteView):\n model = models.Order\n template_name = os.path.join('common_data', 'delete_template.html')\n success_url = reverse_lazy('inventory:order-list')\n\n\nclass OrderDetailView( ContextMixin, \n ConfigMixin, MultiPageDocument, DetailView):\n model = models.Order\n template_name = os.path.join('inventory', 'order', 'detail.html')\n extra_context = {\n 'title': 'Purchase Order',\n 'form': AuthenticateForm()\n }\n page_length=20\n \n def get_multipage_queryset(self):\n self.get_object()\n return models.OrderItem.objects.filter(order=self.object)\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n context['pdf_link'] =True\n if self.object.status == \"draft\":\n context['actions'] = [\n {\n 'name': 'Verify Order',\n 'url': '/inventory/order/{}/verify'.format(\n self.object.pk)\n },\n ]\n context['title'] = \"Purchase Order(Draft)\"\n return context\n\n\nclass OrderPaymentDetailView( \n ConfigMixin, DetailView):\n model = models.Order\n template_name = os.path.join('inventory', 'order', 'payment_list.html')\n \n\n\nclass OrderPaymentCreateView( ContextMixin,\n ConfigMixin, CreateView):\n model = models.OrderPayment\n template_name= CREATE_TEMPLATE\n success_url = \"/inventory/\"\n form_class = forms.OrderPaymentForm\n extra_context = {\n 'title': 'Make payment on order'\n }\n\n def get_initial(self):\n return {\n 'order': self.kwargs['pk']\n }\n\n def post(self, request, *args, **kwargs):\n resp = super().post(request, *args, **kwargs)\n\n if self.object:\n self.object.create_entry()\n\n return resp\n\nclass OrderItemAPIView(ModelViewSet):\n queryset = models.OrderItem.objects.all()\n serializer_class = serializers.OrderItemSerializer \n\n\n#pdf and email\nclass OrderPDFView(ConfigMixin, MultiPageDocument, PDFTemplateView):\n template_name = os.path.join(\"inventory\", \"order\",\n 'pdf.html')\n file_name = 'order.pdf'\n page_length=20\n\n def get_multipage_queryset(self):\n obj = models.Order.objects.get(pk=self.kwargs['pk'])\n return models.OrderItem.objects.filter(order=obj)\n\n def get_context_data(self, *args, **kwargs):\n context = super(OrderPDFView, self).get_context_data(*args, **kwargs)\n context['object'] = models.Order.objects.get(pk=self.kwargs['pk'])\n return context\n\nclass OrderEmailSendView(ConfigMixin, EmailPlusPDFView):\n inv_class = models.Order\n pdf_template_name = os.path.join(\"inventory\", \"order\",\n 'pdf.html')\n success_url = reverse_lazy('inventory:order-list')\n \n\nclass ShippingCostDetailView(DetailView):\n # TODO test\n template_name = os.path.join(\"inventory\", \"order\", \"shipping_list.html\")\n model = models.Order\n\n\nclass ShippingAndHandlingView( \n ContextMixin, FormView):\n template_name = CREATE_TEMPLATE\n form_class = forms.ShippingAndHandlingForm\n success_url = reverse_lazy(\"inventory:order-list\")\n extra_context = {\n 'title': 'Record Shipping and handling'\n }\n\n def get_initial(self):\n return {\n 'reference': 'ORD{}'.format(self.kwargs['pk'])\n }\n \n def form_valid(self, form):\n resp = super().form_valid(form)\n entry = JournalEntry.objects.create(\n date=form.cleaned_data['date'], \n memo=form.cleaned_data['description'], \n journal=Journal.objects.get(pk=2),#disbursements\n created_by=form.cleaned_data['recorded_by'],\n draft=False\n )\n # the unit cost changes but the journal entry for the cost \n # of the order remains the same\n entry.simple_entry(\n form.cleaned_data['amount'],\n Account.objects.get(pk=1000),\n Account.objects.get(pk=4009)\n )\n \n order = models.Order.objects.get(pk=self.kwargs['pk'])\n order.shipping_cost_entries.add(entry)\n order.save()\n\n\n return resp\n\n \nclass DebitNoteCreateView(CreateView):\n form_class = forms.DebitNoteForm\n template_name = os.path.join(\"inventory\", \"order\", \"debit_note\", \"create.html\")\n model = models.DebitNote\n\n def get_initial(self):\n return {\n 'order': self.kwargs['pk']\n }\n\n def post(self, request, *args, **kwargs):\n resp = super().post(request, *args, **kwargs)\n\n if not self.object:\n return resp\n\n data = json.loads(urllib.parse.unquote(request.POST['returned-items']))\n\n for line in data:\n pk = line['item'].split('-')[0]\n item = models.OrderItem.objects.get(pk=pk)\n if float(line['returned_quantity']) > 0:\n models.DebitNoteLine.objects.create(\n note=self.object,\n item=item,\n quantity=float(line['returned_quantity'])\n )\n # TODO test\n item._return_to_vendor(float(line['returned_quantity']))\n \n self.object.create_entry()\n return resp\n\nclass DebitNoteListView(DetailView):\n template_name = os.path.join(\"inventory\", \"order\", \"debit_note\", \"list.html\")\n model = models.Order\n\nclass DebitNoteDetailView(ContextMixin, \n ConfigMixin, \n MultiPageDocument, \n DetailView):\n template_name = os.path.join(\"inventory\", \"order\", \"debit_note\", \n \"detail.html\")\n model = models.DebitNote\n extra_context = {\n 'title': 'Debit Note',\n 'pdf_link': True\n }\n page_length =16\n\n def get_multipage_queryset(self):\n return models.DebitNoteLine.objects.filter(\n note=models.DebitNote.objects.get(\n pk=self.kwargs['pk']))\n\n\nclass DebitNotePDFView(ConfigMixin, MultiPageDocument, PDFDetailView):\n template_name = os.path.join(\"inventory\", \"order\", \"debit_note\", \n \"detail.html\")\n model = models.DebitNote\n context = {\n 'title': 'Debit Note'\n }\n page_length =16\n\n def get_multipage_queryset(self):\n return models.DebitNoteLine.objects.filter(\n note=models.DebitNote.objects.get(\n pk=self.kwargs['pk']))\n\ndef verify_order(request, pk=None):\n order = get_object_or_404(models.Order, pk=pk)\n form = AuthenticateForm(request.POST)\n if form.is_valid():\n order.status = 'order'\n order.validated_by = form.cleaned_data['user']\n order.save()\n\n order.create_entry()\n\n\n return HttpResponseRedirect('/inventory/order-detail/{}'.format(pk))\n \n","sub_path":"inventory/views/order_views.py","file_name":"order_views.py","file_ext":"py","file_size_in_byte":12531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"3091502","text":"#!python\n# THIS CODE IS USED TO PERFORM SOME RANDOM SHARDING\n\n\n\n#############\n# IMPORTS\n#############\n\n\nimport sys\nsys.path.append('..')\nfrom blockchain_parser.blockchain import Blockchain\nfrom blockchain_parser.transaction import Transaction\nimport random\nfrom time import process_time\nimport numpy as np\nimport networkx as nx\nimport printAndPlot\nfrom ChainSpaceMeasures import reader\n\nimport argparse as ap\nimport matplotlib.pyplot as plt\n\n\n\n#############\n# VARIABLES AND PARAMETERS INITIALIZATION\n#############\n\nrunning_example = False \t# Set to True to print some useful information while doing the running example\n\nUser = \"A\" \t\t\t\t# Set to anything except \"Max\" when Alexandre is running the program, \"Max\" is when Maxime is running it\nif(User == \"Max\"):\n\tpath = \"/media/maxime/My Passport/MasterThesis/blocks\"\n\tpath2 = '/home/maxime/Documents/Mémoire'\n\nelse:\n\tpath = \"/media/alexandre/AlexLinux/blockchain/blocks\"\n\tpath2 = '/home/alexandre/Desktop/thesis'\nblockchain = Blockchain(path)\n\nstart = 300000 # Start the sharding at this block (in the real blockchain)\nend = 300100 # until this one\n\nnbrShards = 10 \t\t# Number of shards used for the sharding\nnbrTrans = 0\t\t# Nbr of transactions sharded\ntransToShard = {} # key: transaction hash -> shard it has been placed in\ni = 0\t\t\t\t# Current block number (will be initiated to start)\n\nShards = [[] for elem in range(nbrShards)] \t\t# A list of processed transactions for each shard\nSizeShards = [[] for elem in range(nbrShards)] \t# A blockchain size for each shard in function of the number of arrived transactions\nlistTrans = []\n\nmode = 5 \t\t\t\t# Mode to encode our transactions sharded to give to ChainSpace (4: 1 to 1 and 5: all inputs to all outputs)\nBoolWriteTrans = False \t# Whether to write the sharding in mode \"mode\" in a text file for ChainSpace\nfile = \"\"\noutrememb = [] # used for mode 8\ninrememb = [] # used for mode 8\n\nloadGraph = False\ninterval = -1\n\ncomputeLoadScore = True\n\n\n\n#############\n# SUBFUNCTIONS\n#############\n\n#############\n# Print the repartition of transactions among shards\n#############\ndef fullprint(tableau):\n\n\tsh = 0\n\tfor row in tableau:\n\t\tprint(\"Shard \" + str(sh) + \" : \" + str(len(row)) + \" transactions processed\")\n\t\tsh += 1\n\n\n#############\n# Place transaction randomly in a shard\n# Used in : main()\n#############\ndef randomSharding(transaction):\n\n\tglobal Shards, transToShard, SizeShards\n\n\tfinal_choice = random.randint(0, nbrShards - 1) \t# Make a totally random choice among shards for the transaction\n\n\tif (interval + 1) * 50 > nbrTrans or computeLoadScore: # If we will have a correct load_balance graph or if need for load_balance score computation:\n\t\tfor elem in range(nbrShards): # Update SizeShards\n\t\t\tif elem == final_choice:\n\t\t\t\tif len(SizeShards[elem]) == 0:\n\t\t\t\t\tSizeShards[elem].append(1)\n\t\t\t\tSizeShards[elem].append(SizeShards[elem][-1] + 1)\n\t\t\telse:\n\t\t\t\tif len(SizeShards[elem]) == 0:\n\t\t\t\t\tSizeShards[elem].append(0)\n\t\t\t\tSizeShards[elem].append(SizeShards[elem][-1])\n\n\ttransToShard[transaction.hash] = final_choice # Update the mapping transaction -> shard\n\tif loadGraph: Shards[final_choice].append(transaction.hash) # Update the processed transactions\n\n\n#############\n# Count the number of cross-shard transactions implied by the transaction \"transaction\" without using G1\n# Return the number of such cross-shard edges and the total number of edges implied by this transaction\n# Used in : main()\n#############\ndef count_crossSansG1(transaction):\n\n\tglobal file, inrememb, outrememb\n\n\tnbrEdges = 0\n\tnbrCrossings = 0\n\tshardOfInput = transToShard[transaction.hash] # Shard in which the transaction was put (and therefore its outputs)\n\n\tif BoolWriteTrans: # For ChainSpace measures\n\n\t\ttext = \"\"\n\n\t\tif mode == 5: # Encode transactions all inputs -> all outputs\n\t\t\tindice = 0\n\t\t\tdontAppend = True\n\t\t\tpremier = True\n\t\t\tfor inp in transaction.inputs: # Go through all inputs of the transaction\n\n\t\t\t\tif inp.transaction_hash in transToShard:\n\n\t\t\t\t\tif not premier:\n\t\t\t\t\t\ttext = text + \",\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tpremier = False\n\n\t\t\t\t\tnbrEdges = nbrEdges + 1\n\t\t\t\t\ttext = text + str(transToShard[inp.transaction_hash])\n\t\t\t\t\t# if indice != len(transaction.inputs)-1:\n\t\t\t\t\t# \ttext = text + \",\"\n\t\t\t\t\tif transToShard[inp.transaction_hash] != shardOfInput:\n\t\t\t\t\t\tnbrCrossings += 1 # If one input transaction was in another shard, we have a cross-shard transaction\n\t\t\t\t\tdontAppend = False\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\t\tindice = indice + 1\n\n\t\t\ttext = text + \":\"\n\n\t\t\tif dontAppend == False:\n\t\t\t\tfirst = True\n\t\t\t\tfor output in transaction.outputs:\n\t\t\t\t\tfor address in output.addresses:\n\n\t\t\t\t\t\tif first:\n\t\t\t\t\t\t\ttext = text + str(shardOfInput)\n\t\t\t\t\t\t\tfirst = False\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttext = text + \",\" + str(shardOfInput)\n\t\t\t\ttext = text + \"\\n\"\n\t\t\t\tfile.write(text)\n\n\t\telif mode == 4: \t# Encode transactions 1 -> 1\n\n\t\t\tfor inp in transaction.inputs: \t# Go through all inputs of the transaction\n\t\t\t\tif inp.transaction_hash in transToShard: # This was an edge in our sharding so we add it as a transaction in the text\n\t\t\t\t\tnbrEdges = nbrEdges + 1\n\t\t\t\t\ttext = text + str(transToShard[inp.transaction_hash]) + ':' + str(shardOfInput) + '\\n'\n\t\t\t\t\tif transToShard[inp.transaction_hash] != shardOfInput:\n\t\t\t\t\t\tnbrCrossings += 1 # If one input transaction was in another shard, we have a cross-shard transaction\n\n\t\t\tfile.write(text)\n\n\t\telif mode == 6: \t# Encode transactions 2 -> 2\n\n\t\t\ti = 0\n\t\t\tlistOfOnePair = []\n\t\t\tlastSeen = -1\n\t\t\twhile i < len(transaction.inputs): \t# Go through all inputs of the transaction\n\n\t\t\t\tif transaction.inputs[i].transaction_hash in transToShard: # This was an edge in our sharding so we add it as a transaction in the text\n\t\t\t\t\tnbrEdges = nbrEdges + 1\n\t\t\t\t\tlistOfOnePair.append(i)\n\t\t\t\t\tif lastSeen == -1:\n\t\t\t\t\t\tlastSeen = i\n\t\t\t\t\tif transToShard[transaction.inputs[i].transaction_hash] != shardOfInput:\n\t\t\t\t\t\tnbrCrossings += 1 # If one input transaction was in another shard, we have a cross-shard transaction\n\n\t\t\t\tif len(listOfOnePair) >= 2: # We have a pair, so we write it down\n\t\t\t\t\ttext = text + str(transToShard[transaction.inputs[listOfOnePair[0]].transaction_hash]) + \",\"\n\t\t\t\t\ttext = text + str(transToShard[transaction.inputs[listOfOnePair[1]].transaction_hash])\n\t\t\t\t\ttext = text + ':' + str(shardOfInput) + \",\" + str(shardOfInput) + '\\n'\n\t\t\t\t\tlastSeen = listOfOnePair[1]\n\t\t\t\t\tlistOfOnePair = []\n\t\t\t\ti += 1\n\t\t\tif len(listOfOnePair) > 0: # We still have a last valid input to combine with another input and write the whole thing\n\t\t\t\ttext = text + str(transToShard[transaction.inputs[listOfOnePair[0]].transaction_hash]) + \",\"\n\t\t\t\ttext = text + str(transToShard[transaction.inputs[lastSeen].transaction_hash])\n\t\t\t\ttext = text + ':' + str(shardOfInput) + \",\" + str(shardOfInput) + '\\n'\n\n\t\t\tfile.write(text)\n\n\n\t\telif mode == 7: # Encode tansactions 4 -> 4 by augmenting it\n\t\t\ti = 0\n\t\t\tinputs = [] #shards\n\t\t\twhile i < len(transaction.inputs): \t# Go through all inputs of the transaction\n\n\t\t\t\tif transaction.inputs[i].transaction_hash in transToShard: # This was an edge in our sharding so we add it as a transaction in the text\n\t\t\t\t\tnbrEdges = nbrEdges + 1\n\t\t\t\t\tinputs.append(transToShard[transaction.inputs[i].transaction_hash])\n\n\t\t\t\t\tif transToShard[transaction.inputs[i].transaction_hash] != shardOfInput:\n\t\t\t\t\t\tnbrCrossings += 1 # If one input transaction was in another shard, we have a cross-shard transaction\n\n\t\t\t\tif len(inputs) == 4:\n\t\t\t\t\t#create trans\n\t\t\t\t\ttext = text + str(inputs[0]) + \",\"\n\t\t\t\t\ttext = text + str(inputs[1]) + \",\"\n\t\t\t\t\ttext = text + str(inputs[2]) + \",\"\n\t\t\t\t\ttext = text + str(inputs[3])\n\t\t\t\t\ttext = text + ':'\n\t\t\t\t\ttext = text + str(shardOfInput) + \",\"\n\t\t\t\t\ttext = text + str(shardOfInput) + \",\"\n\t\t\t\t\ttext = text + str(shardOfInput) + \",\"\n\t\t\t\t\ttext = text + str(shardOfInput) + '\\n'\n\t\t\t\t\tinputs = []\n\t\t\t\ti += 1\n\n\t\t\tnbrInputDiffOfOut = 0\n\n\t\t\tif len(inputs) > 0:\n\t\t\t\tfor elem in inputs:\n\t\t\t\t\tif elem != shardOfInput:\n\t\t\t\t\t\tnbrInputDiffOfOut += 1\n\t\t\t\tproportion = (nbrInputDiffOfOut/len(inputs))\n\t\t\t\tif proportion == 0.5:\n\t\t\t\t\tinputs.extend(inputs)\n\t\t\t\telse:\n\t\t\t\t\tproportion = round(proportion)\n\t\t\t\t\twhile len(inputs) < 4:\n\t\t\t\t\t\tif proportion:\n\t\t\t\t\t\t\tinputs.append(inputs[0])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tinputs.append(shardOfInput)\n\t\t\t\tif len(inputs) == 4:\n\t\t\t\t\t#create trans\n\t\t\t\t\ttext = text + str(inputs[0]) + \",\"\n\t\t\t\t\ttext = text + str(inputs[1]) + \",\"\n\t\t\t\t\ttext = text + str(inputs[2]) + \",\"\n\t\t\t\t\ttext = text + str(inputs[3])\n\t\t\t\t\ttext = text + ':'\n\t\t\t\t\ttext = text + str(shardOfInput) + \",\"\n\t\t\t\t\ttext = text + str(shardOfInput) + \",\"\n\t\t\t\t\ttext = text + str(shardOfInput) + \",\"\n\t\t\t\t\ttext = text + str(shardOfInput) + '\\n'\n\t\t\t\t\tinputs = []\n\n\t\t\tfile.write(text)\n\n\n\t\telif mode == 8: \t# Encode transactions 4 -> 4 by mixing outputs\n\n\t\t\ti = 0\n\t\t\tlastSeen = -1\n\t\t\twhile i < len(transaction.inputs): \t# Go through all inputs of the transaction\n\n\t\t\t\tif transaction.inputs[i].transaction_hash in transToShard: # This was an edge in our sharding so we add it as a transaction in the text\n\t\t\t\t\tnbrEdges = nbrEdges + 1\n\t\t\t\t\tinrememb.append(transToShard[transaction.inputs[i].transaction_hash])\n\t\t\t\t\toutrememb.append(shardOfInput)\n\t\t\t\t\tif lastSeen == -1:\n\t\t\t\t\t\tlastSeen = i\n\t\t\t\t\tif transToShard[transaction.inputs[i].transaction_hash] != shardOfInput:\n\t\t\t\t\t\tnbrCrossings += 1 # If one input transaction was in another shard, we have a cross-shard transaction\n\n\n\t\t\t\tif len(inrememb) >= 4: # We have a pair, so we write it down\n\t\t\t\t\ttext = text + str(inrememb[0]) + \",\"\n\t\t\t\t\ttext = text + str(inrememb[1]) + \",\"\n\t\t\t\t\ttext = text + str(inrememb[2]) + \",\"\n\t\t\t\t\ttext = text + str(inrememb[3])\n\t\t\t\t\ttext = text + ':'\n\t\t\t\t\ttext = text + str(outrememb[0]) + \",\"\n\t\t\t\t\ttext = text + str(outrememb[1]) + \",\"\n\t\t\t\t\ttext = text + str(outrememb[2]) + \",\"\n\t\t\t\t\ttext = text + str(outrememb[3]) + '\\n'\n\t\t\t\t\tlastSeen = inrememb[3]\n\t\t\t\t\tinrememb = []\n\t\t\t\t\toutrememb = []\n\t\t\t\ti += 1\n\n\t\t\tfile.write(text)\n\n\n\telse: # No ChainSpace measures needed\n\t\tfor inp in transaction.inputs: \t# Go through all inputs of the transaction\n\t\t\tif inp.transaction_hash in transToShard: # This was an edge in our sharding so we add it as a transaction in the text\n\t\t\t\tnbrEdges = nbrEdges + 1\n\t\t\t\tif transToShard[inp.transaction_hash] != shardOfInput:\n\t\t\t\t\tnbrCrossings += 1 # If one input transaction was in another shard, we have a cross-shard transaction\n\n\treturn nbrCrossings, nbrEdges\n\n\n#############\n# Count the number of cross-shard transactions in listTrans without using G1\n# Return the number of such cross-shard edges and the total number of edges implied by al the transaction in listTrans\n# Used in : main()\n#############\ndef nbrCrossShard(testornot, listTrans):\n\n\tglobal file, outrememb, inrememb\n\n\tnbrOfCrossShard = 0\n\tnbrOfEdges = 0\n\tnbrOfCrossTrans = 0\n\tnbrOfBasisTrans = 0\n\n\tif testornot == \"False\": # Use the real blockchain\n\t\tfor block in blockchain.get_ordered_blocks(path + '/index', start = start, end = end):\n\t\t\tfor transaction in block.transactions:\n\t\t\t\tnCross, nEdges = count_crossSansG1(transaction)\n\t\t\t\tnbrOfCrossShard = nbrOfCrossShard + nCross\n\t\t\t\tnbrOfEdges = nbrOfEdges + nEdges\n\t\t\t\tif nCross > 0: nbrOfCrossTrans += 1\n\t\t\t\tif nEdges == 0: nbrOfBasisTrans += 1\n\n\telse: # Use another list of transactions\n\t\tfor transaction in listTrans:\n\t\t\tnCross, nEdges = count_crossSansG1(transaction)\n\t\t\tnbrOfCrossShard = nbrOfCrossShard + nCross\n\t\t\tnbrOfEdges = nbrOfEdges + nEdges\n\t\t\tif nCross > 0: nbrOfCrossTrans += 1\n\t\t\tif nEdges == 0: nbrOfBasisTrans += 1\n\n\treturn nbrOfCrossShard, nbrOfEdges, nbrOfCrossTrans, nbrOfBasisTrans\n\n\n\n#############\n# MAIN FUNCTION\n#############\ndef main(user, testornot, listTran, nbrSh, starti, endi, mod, BoolWriteTran):\n\n\tglobal User, path, path2, blockchain, start, end, nbrShards, nbrTrans, Shards, transToShard, i\n\tglobal Shards, SizeShards, listTrans\n\tglobal mode, BoolWriteTrans, file, loadGraph, interval\n\tglobal outrememb, inrememb\n\n\t###############\n\t# Update those variables accordingly to the arguments\n\tUser = user\n\tif(User == \"Max\"): # Set to anything except \"Max\" when Alexandre is running the program, \"Max\" is when Maxime is running it\n\t\tpath = \"/media/maxime/My Passport/MasterThesis/blocks\"\n\t\tpath2 = '/home/maxime/Documents/Mémoire'\n\n\telse:\n\t\tpath = \"/media/alexandre/AlexLinux/blockchain/blocks\"\n\t\tpath2 = '/home/alexandre/Desktop/thesis'\n\tblockchain = Blockchain(path)\n\n\tstart = starti \t# Start the sharding at this block (in the real blockchain)\n\tend = endi \t\t# until this one\n\n\tnbrShards = nbrSh \t# Number of shards used for the sharding\n\tnbrTrans = 0\t\t# Nbr of transactions sharded\n\ttransToShard = {} # key: transaction hash -> shard it has been placed in\n\n\tShards = [[] for elem in range(nbrShards)] \t\t# A list of processed transactions for each shard\n\tSizeShards = [[] for elem in range(nbrShards)]\t# A blockchain size for each shard in function of the number of arrived transactions\n\tlistTrans = listTran \t\t\t\t\t\t\t# Given list of transactions if we don't want to use the blockchain\n\n\tmode = mod \t\t\t\t\t\t# Mode to encode our transactions sharded to give to ChainSpace (4: 1 to 1 and 5: all inputs to all outputs)\n\tBoolWriteTrans = BoolWriteTran \t# Whether to write the sharding in mode \"mode\" in a text file for ChainSpace\n\tif BoolWriteTrans:\n\t\tfile = open(\"ChainSpaceMeasures/Random/Random_\" + str(nbrShards) + \"Mode_\" + str(mode) + \".txt\", \"w+\") # Text file to give to ChainSpace to precise which shard is supposed to process which transaction\n\toutrememb = [] # used for mode 8\n\tinrememb = [] # used for mode 8\n\n\tloadGraph = False # Whether to check for the load balance among shards\n\n\tif loadGraph:\n\t\tloadBalanceList = [[0] for elem in range(nbrShards)] # A list to remember the loadBalance of each shard at given intervals\n\t\tinterval = 654 \t# Number of transactions to compute an interval for the loadBalanceList\n\t\t\t\t\t\t# Relevant graph with interval > nbrTrans / 200\n\telse:\n\t\tinterval = -1\n\n\n\t###############\n\n\t# Global prints\n\tprint(\"\t\t||--- -------------- ---||\")\n\tprint(\"\t\t||--- Random version ---||\")\n\tprint(\"\t\t||--- -------------- ---||\")\n\n\tprint(\" --> Number of shards used : \" + str(nbrSh))\n\tprint(\" --> Sharding from block \" + str(start) + \" to block \" + str(end))\n\n\tif testornot == \"False\":\n\n\t\ttotalTime = 0.0 # Time needed for the sharding\n\n\t\ti = start\n\t\tfor block in blockchain.get_ordered_blocks(path + '/index', start = start, end = end):\n\n\t\t\t# Print at which block we are during the simulation\n\t\t\tif i % 10 == 0:\n\t\t\t\tprint(\"We are at the block \" + str(i))\n\n\t\t\tfor transaction in block.transactions:\n\t\t\t\tt_start = process_time()\n\t\t\t\trandomSharding(transaction)\t\t# Shard each transaction\n\t\t\t\tt_end = process_time()\n\t\t\t\ttotalTime += t_end - t_start\n\n\t\t\t\tlistTrans.append(transaction)\t# If none listTrans was given we build one to use it in nbrCrossShard\n\t\t\t\tnbrTrans = nbrTrans + 1\t\t\t# Count each transaction\n\n\t\t\t\tif loadGraph:\n\t\t\t\t\tif nbrTrans % interval == 0: # Update loadBalanceList at each interval\n\t\t\t\t\t\tfor sh in range(nbrShards):\n\t\t\t\t\t\t\tprevious = loadBalanceList[sh][-1]\n\t\t\t\t\t\t\tloadBalanceList[sh][-1] = len(Shards[sh]) - previous\n\t\t\t\t\t\t\tloadBalanceList[sh].append(len(Shards[sh]))\n\n\t\t\ti = i + 1\n\n\t\tt_end = process_time()\n\t\tprint(\"\\n\")\n\t\tprint(\" ----------------------------- Time analysis -------------------------\")\n\t\tprint(\"Time needed only to shard \" + str(nbrTrans) + \" transactions, in seconds: \", totalTime)\n\t\tprint(\"This is \" + str((totalTime) / float(nbrTrans)) + \" second per transaction\")\n\n\t\tif loadGraph:\n\t\t\t# Final update of loadBalanceList\n\t\t\tfor sh in range(nbrShards):\n\t\t\t\t# We sometimes miss the last transactions because of interval size...\n\t\t\t\t# So we end the intervals here with a last step (even if smaller interval)\n\t\t\t\t# If no transaction was processed, then 0 is added then removed so no problem\n\t\t\t\tprevious = loadBalanceList[sh][-1]\n\t\t\t\tloadBalanceList[sh][-1] = len(Shards[sh]) - previous\n\t\t\t\tloadBalanceList[sh].append(len(Shards[sh]))\n\t\t\t\tloadBalanceList[sh] = loadBalanceList[sh][:-1]\n\n\n\t\t\t# Safety check for the loadBalanceList\n\t\t\tprint(\"\\n\")\n\t\t\tprint(\"------------------------------------------\")\n\t\t\tprint(\" \t- Safety check load balancing - \")\n\n\t\t\tsameSize = True\n\t\t\ttotalSeenTrans = 0\n\t\t\ttotalSeenTransPerShard = [0 for sh in range(nbrShards)]\n\t\t\tfor sh in range(len(loadBalanceList)):\n\t\t\t\tif len(loadBalanceList[sh]) != len(loadBalanceList[0]): sameSize = False\n\t\t\t\ttotalSeenTrans += sum(loadBalanceList[sh])\n\t\t\t\ttotalSeenTransPerShard[sh] += sum(loadBalanceList[sh])\n\n\n\t\t\tprint(\"All the shards were observed in a same number of intervals : \" + str(sameSize))\n\t\t\tprint(\"Total number of seen transactions : \" + str(totalSeenTrans))\n\t\t\tfor sh in range(nbrShards):\n\t\t\t\tprint(\"In shard \" + str(sh) + \" we had : \" + str(totalSeenTransPerShard[sh]) + \" transactions.\")\n\t\t\tprint(\"------------------------------------------\")\n\t\t\tprint(\"\\n\")\n\n\t\t# Print a graph for the load balance of the shards\n\t\tif loadGraph:\n\t\t\tprintAndPlot.randomLoadBalance(path2, nbrShards, loadBalanceList, interval, start, end)\n\t\t\tfullprint(Shards) # Make a useful print of the final shard balance\n\n\t\t# only works if we have 50 intervals :\n\t\tif (interval + 1) * 50 > nbrTrans: printAndPlot.load_balance_Analyse(path2, SizeShards, nbrShards, 0, \"random\", start, end)\n\n\t\t# Compute the load balance score\n\t\tif computeLoadScore: load_balance = printAndPlot.load_balance_score(SizeShards, nbrShards)\n\t\telse: load_balance = 0\n\n\telse: # We use a manually designed list of transactions to shard\n\t\tfor transaction in listTrans:\n\t\t\trandomSharding(transaction) # Shard each transaction\n\t\t\tnbrTrans = nbrTrans + 1 \t# Count each transaction\n\n\t\tprint(\" ----------------------------- Final sharding -----------------------\")\n\t\tfullprint(Shards) # Make a useful print of the final shard balance\n\t\tprint(\"\\n\")\n\n\t# Count the cross\n\tnbrcrossfinal, nbredgesfinal, nbrcrosstransfinal, nbrbasistransfinal = nbrCrossShard(testornot, listTrans)\n\n\t# Final print (results)\n\tprint(\" ----------------------------- Results ------------------------------\")\n\tprint(\"Basis trans : \" + str(nbrbasistransfinal))\n\tl = [ \"Total number of edges : \" , \"Number of cross shard edges : \", \"Percentage of cross shard edges : \", \"Number of sharded transactions : \", \"Number of cross shard transactions : \", \"Percentage of cross shard transactions : \", \"Percentage of real cross shard transactions : \"]\n\tl2 = [nbredgesfinal, nbrcrossfinal, 100.0 * float(nbrcrossfinal) / float(nbredgesfinal), nbrTrans, nbrcrosstransfinal, 100.0 * float(nbrcrosstransfinal) / float(nbrTrans), 100.0 * float(nbrcrosstransfinal) / float(nbrTrans - nbrbasistransfinal)]\n\tfor i in range(len(l)) :\n\t\tprint(\"| \" + str(l[i]) + \" \" * (47 - len(l[i])) + str(l2[i]) + \" \" * (20 - len(str(l2[i]))) + str(\"|\"))\n\tprint(\" --------------------------------------------------------------------\")\n\n\tif BoolWriteTrans:\n\t\tnedges, ncrosedges, ntrans, ncrostrans = reader.main(file, True, path2, \"Random\", nbrShards, nbrTrans)\n\t\tprint(\"For ChainSpace : \" + str(ncrosedges) + \"/\" + str(nedges) + \" cross edges and \" + str(ncrostrans) + \"/\" + str(ntrans) + \" cross transactions\" )\n\t\tprint(\" -> \" + str(100.0 * float(ncrosedges) / float(nedges)) + \"% of cross edges\")\n\t\tprint(\" -> \" + str(100.0 * float(ncrostrans) / float(ntrans)) + \"% of cross transactions\")\n\n\n\treturn nbrcrossfinal, nbredgesfinal, nbrTrans, nbrcrosstransfinal, nbrbasistransfinal, 0, load_balance\n\n\n\n#############\n# To launch the main function\n#############\n\nif __name__ == \"__main__\":\n\tparser = ap.ArgumentParser()\n\tparser.add_argument('-s', '--testornot', type = str) # The sentence to analyze\n\tparser.add_argument('-d', '--listTrans', type = list) # The sentence to analyze\n\tparser.add_argument('-n', '--numberOfShards', type = int) # The sentence to analyze\n\n\targs = parser.parse_args()\n\tif (args.testornot != None and args.listTrans != None and args.numberOfShards != None):\n\t\tprint('Called with the given arguments')\n\t\tmain(User, args.testornot, args.listTrans, args.numberOfShards, start, end, 4, False)\n\telse:\n\t\tprint('Called with the default arguments')\n\t\tmain(User, \"False\", [], nbrShards, start, end, 4, False)\n","sub_path":"Implem/Random_Sharding.py","file_name":"Random_Sharding.py","file_ext":"py","file_size_in_byte":19870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"441981533","text":"#!/usr/bin/python3\nimport glob\nfrom PIL import Image\n\n# get all the jpg files from the current folder\nfor infile in glob.glob(\"*.jpg\"):\n im = Image.open(infile)\n # convert to thumbnail image\n im.thumbnail((500, 500), Image.ANTIALIAS)\n # don't save if thumbnail already exists\n if infile[0:2] != \"T_\":\n # prefix thumbnail file with T_\n im.save(\"thumbs/T_\" + infile, \"JPEG\")\n","sub_path":"scripts/mk_thumbs.py","file_name":"mk_thumbs.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"174612764","text":"#!/usr/bin/env python\n#\n# Created by Samvel Khalatyan on Mar 23, 2014\n# Copyright (c) 2014 Samvel Khalatyan. All rights reserved\n#\n# Use of this source code is governed by a license that can be found in\n# the LICENSE file.\n\nimport copy\nimport random\nimport unittest\n\nfrom lib import unigraph\n\n\ndef copy_graph(graph):\n return copy.deepcopy(graph)\n\n\nclass TestGraphCopy(unittest.TestCase):\n def setUp(self):\n self.graph = unigraph.Unigraph(random.randrange(10, 15))\n for x in range(2 * self.graph.vertices()):\n f, t = (random.randrange(0, self.graph.vertices())\n for x in range(2))\n self.graph.add_edge(f, t)\n\n def test_copy_graph(self):\n graph_ = copy_graph(self.graph)\n self.assertEqual(str(graph_), str(self.graph))\n\n def test_independent_graph_copy(self):\n graph_ = copy_graph(self.graph)\n for i in range(5):\n f, t = (random.randrange(0, graph_.vertices()) for x in range(2))\n graph_.add_edge(f, t)\n\n self.assertNotEqual(str(graph_), str(self.graph))\n\n\nif \"__main__\" == __name__:\n unittest.main()\n","sub_path":"ch4/python/ch4_ex4.1.3.py","file_name":"ch4_ex4.1.3.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"605536724","text":"# 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\nfrom util.common_imports import *\n\nclass Solution:\n def binaryTreePaths(self, root: TreeNode) -> List[str]:\n if not root: return []\n\n ans = []\n def dfs(pre, node):\n nonlocal ans\n\n pre += '->' + str(node.val)\n if not node.left and not node.right: # leaf\n ans.append(pre[2:])\n\n if node.left:\n dfs(pre, node.left)\n if node.right:\n dfs(pre, node.right)\n \n dfs('', root)\n return ans\n\nprint(Solution().binaryTreePaths(createTree('[3,9,20,null,null,15,7]')))\n","sub_path":"tree/257_二叉树的所有路径.py","file_name":"257_二叉树的所有路径.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"335678704","text":"from skimage import io\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n\r\ndef showgraph(image):\r\n z = np.copy(image)\r\n z = np.abs(z)\r\n length = z.shape[0]\r\n width = z.shape[1]\r\n x = np.linspace( -math.pi, math.pi, width )\r\n y = np.linspace( -math.pi, math.pi, length )\r\n x, y = np.meshgrid( x, y )\r\n x = x.reshape(length*width)\r\n y = y.reshape(length*width)\r\n z = z.reshape(length*width)\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n ax.scatter(x, y, z, s=1 , c='r', marker='o')\r\n ax.set_xlabel('X Label')\r\n ax.set_ylabel('Y Label')\r\n ax.set_zlabel('Z Label')\r\n plt.show()\r\n \r\ndef gaussian( sigma, x, y ):\r\n g = math.exp( -(x**2+y**2)/(2*sigma**2) )/ ( (2*math.pi)*sigma**2 )\r\n return g\r\n\r\ndef make_gfilter( sigma, n ):\r\n gfilter = np.zeros((n,n))\r\n X = np.linspace( int(-n/2) , int(n/2), n )\r\n print(X)\r\n for x in X :\r\n for y in X :\r\n gfilter[ int(y+n/2-1), int(x+n/2-1) ] = gaussian( sigma, x, y)\r\n return gfilter\r\n\r\ndef expandgaussian( gaussian, length, width ):\r\n egaussian = np.zeros( (length, width) )\r\n for i in range( gaussian.shape[0] ) :\r\n for j in range( gaussian.shape[1] ):\r\n egaussian[ int(length/2)-int(gaussian.shape[0]/2)+i, int(width/2)-int(gaussian.shape[1]/2)+j ] = gaussian[i,j] \r\n \r\n return egaussian \r\n\r\ndef PSNR( image, target ):\r\n length = image.shape[0]\r\n width = image.shape[1]\r\n mse = [0,0,0]\r\n for i in range(length):\r\n for j in range(width):\r\n for k in range(3):\r\n mse[k] += (image[i,j,k]-target[i,j,k])**2\r\n \r\n mse = np.array(mse)* 255**2/(length*width)\r\n mse = np.sum( 10*np.log((255**2)/mse))\r\n return mse\r\n\r\ndef wiener( ffilter, fimage, k ):\r\n H = (1/ffilter)*(np.abs(ffilter)**2)/(np.abs(ffilter)**2 + k )\r\n #print(H)\r\n return np.multiply( H, fimage)\r\n\r\ndef main():\r\n target = np.array( io.imread(\"input1_ori.bmp\"), dtype = float)/255\r\n image = np.array( io.imread(\"input1.bmp\"), dtype=float) # RGB\r\n gaussian = make_gfilter( 8, 101 )\r\n gaussian /= np.sum(gaussian) #normalization\r\n #expand gaussian mask to the image size\r\n egaussian = expandgaussian( gaussian, image.shape[0], image.shape[1])\r\n imager = np.fft.fft2( image[:,:,0] ) #2D fft\r\n imageg = np.fft.fft2( image[:,:,1] )\r\n imageb = np.fft.fft2( image[:,:,2] )\r\n \r\n \r\n egaufft = np.fft.fft2(egaussian) #fouriers transform\r\n egaufft = np.abs( egaufft ) #find the magnitude\r\n H = np.amax(egaufft) / egaufft\r\n np.clip( H, 1, 2, out=H)\r\n\r\n b = np.fft.fftshift( egaufft ) #put frequency (0. , 0.) to middle\r\n io.imshow( 20*np.log(b+1), cmap='gray')\r\n plt.show()\r\n\r\n b = np.fft.fftshift( H ) #put frequency (0. , 0.) to middle\r\n io.imshow( 20*np.log(b), cmap='gray')\r\n plt.show()\r\n\r\n '''\r\n for i in range( egaufft.shape[0] ):\r\n for j in range( egaufft.shape[1]):\r\n if( egaufft[i,j]== 0 ):\r\n egaufft[i,j] = 0.0001\r\n \r\n #print(egaufft)\r\n \r\n #showgraph(egaufft)\r\n \r\n #inverse filter\r\n '''\r\n imager = np.multiply( imager, H )\r\n imageg = np.multiply( imageg, H )\r\n imageb = np.multiply( imageb, H )\r\n\r\n a = 20*np.log(np.abs(np.fft.fftshift( imageb ))+1)\r\n #showgraph(a)\r\n io.imshow(a,cmap='gray')\r\n plt.show()\r\n\r\n #imager = wiener( egaufft, imager, 0.05 )\r\n #imageg = wiener( egaufft, imageg, 0.05 )\r\n #imageb = wiener( egaufft, imageb, 0.05 ) \r\n\r\n imager = np.fft.ifft2( imager ) #inverse 2D fft\r\n imageg = np.fft.ifft2( imageg )\r\n imageb = np.fft.ifft2( imageb )\r\n image2 = np.dstack((imager,imageg))\r\n image2 = np.dstack((image2,imageb))\r\n image2 = np.abs(image2)\r\n \r\n #print(image.shape)\r\n for i in range(image2.shape[0]):\r\n for j in range( image2.shape[1]):\r\n for k in range(3):\r\n if ( image2[i,j,k]>255 ):\r\n image2[i,j,k] = 255\r\n #showgraph(image)\r\n image /= 255 \r\n image2 /= 255\r\n print( PSNR(image2,target) )\r\n print( PSNR(image,target) )\r\n print( PSNR(image2,target)/PSNR(image,target) )\r\n io.imsave(\"output1-2.bmp\",image2 )\r\n \r\nif __name__== \"__main__\":\r\n main()\r\n\r\n","sub_path":"image processing/image restoration/lab4-1.py","file_name":"lab4-1.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"308438916","text":"#\n#-----------------------------------------------------------------------------\n# Copyright 2007-2011 Mentor Graphics Corporation\n# Copyright 2007-2011 Cadence Design Systems, Inc.\n# Copyright 2010 Synopsys, Inc.\n# Copyright 2019 Tuomas Poikela\n# All Rights Reserved Worldwide\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in\n# compliance with the License. You may obtain a copy of\n# the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in\n# writing, software distributed under the License is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See\n# the License for the specific language governing\n# permissions and limitations under the License.\n#-----------------------------------------------------------------------------\n\nfrom .sv import sv\nfrom .uvm_recorder import UVMRecorder\nfrom .uvm_object import UVMObject\nfrom .uvm_pool import UVMEventPool\n\n\nclass UVMTransaction(UVMObject):\n \"\"\"\n The `UVMTransaction` class is the root base class for UVM transactions.\n Inheriting all the methods of `UVMObject`, `UVMTransaction` adds a timing and\n recording interface.\n\n This class provides timestamp properties, notification events, and transaction\n recording support.\n\n Use of this class as a base for user-defined transactions\n is deprecated. Its subtype, `uvm_sequence_item`, shall be used as the\n base class for all user-defined transaction types.\n\n The intended use of this API is via a `uvm_driver` to call `accept_tr`,\n `begin_tr`, and `end_tr` during the course of\n sequence item execution. These methods in the component base class will\n call into the corresponding methods in this class to set the corresponding\n timestamps (`accept_time`, `begin_time`, and `end_time`), trigger the\n corresponding event (`begin_event` and `end_event`, and, if enabled,\n record the transaction contents to a vendor-specific transaction database.\n\n Note that get_next_item/item_done when called on a `uvm_seq_item_pull_port`\n will automatically trigger the `begin_event` and `end_event` via calls to `begin_tr` and `end_tr`.\n While convenient, it is generally the responsibility of drivers to mark a\n transaction's progress during execution. To allow the driver or layering sequence\n to control sequence item timestamps, events, and recording, you must call\n `UVM_SEQ_ITEM_PULL_IMP.disable_auto_item_recording` at the beginning\n of the driver's `run_phase` task.\n\n Users may also use the transaction's event pool, `events`,\n to define custom events for the driver to trigger and the sequences to wait on. Any\n in-between events such as marking the beginning of the address and data\n phases of transaction execution could be implemented via the\n `events` pool.\n\n In pipelined protocols, the driver may release a sequence (return from\n `finish_item` or it's `uvm_do` macro) before the item has been completed.\n If the driver uses the `begin_tr`/`end_tr` API in `UVMComponent`, the sequence can\n wait on the item's `end_event` to block until the item was fully executed,\n as in the following example.\n\n .. code-block:: systemverilog\n\n task uvm_execute(item, ...)\n // can use the `uvm_do macros as well\n start_item(item)\n item.randomize()\n finish_item(item)\n item.self.end_event.wait_on()\n // get_response(rsp, item.get_transaction_id()); //if needed\n endtask\n\n\n A simple two-stage pipeline driver that can execute address and\n data phases concurrently might be implemented as follows:\n\n .. code-block:: systemverilog\n\n task run()\n\n // this driver supports a two-deep pipeline\n fork\n do_item()\n do_item()\n join\n endtask\n\n\n task do_item()\n\n forever begin\n mbus_item req\n\n lock.get()\n\n seq_item_port.get(req); // Completes the sequencer-driver handshake\n\n accept_tr(req)\n\n // request bus, wait for grant, etc.\n\n begin_tr(req)\n\n // execute address phase\n\n // allows next transaction to begin address phase\n lock.put()\n\n // execute data phase\n // (may trigger custom \"data_phase\" event here)\n\n end_tr(req)\n\n end\n\n endtask: do_item\n \"\"\"\n\n # // Variable: events\n # //\n # // The event pool instance for this transaction. This pool is used to track\n # // various milestones: by default, begin, accept, and end\n #\n # const uvm_event_pool events = new\n #\n #\n # // Variable: self.begin_event\n # //\n # // A ~uvm_event#(uvm_object)~ that is triggered when this transaction's actual execution on the\n # // bus begins, typically as a result of a driver calling .\n # // Processes that wait on this event will block until the transaction has\n # // begun.\n # //\n # // For more information, see the general discussion for .\n # // See for details on the event API.\n # //\n # uvm_event#(uvm_object) self.begin_event\n #\n # // Variable: self.end_event\n # //\n # // A ~uvm_event#(uvm_object)~ that is triggered when this transaction's actual execution on\n # // the bus ends, typically as a result of a driver calling .\n # // Processes that wait on this event will block until the transaction has\n # // ended.\n # //\n # // For more information, see the general discussion for .\n # // See for details on the event API.\n # //\n # //| virtual task my_sequence::body()\n # //| ...\n # //| start_item(item); \\\n # //| item.randomize(); } `uvm_do(item)\n # //| finish_item(item); /\n # //| // return from finish item does not always mean item is completed\n # //| item.self.end_event.wait_on()\n # //| ...\n # //\n # uvm_event#(uvm_object) self.end_event\n\n # Function: new\n #\n # Creates a new transaction object. The name is the instance name of the\n # transaction. If not supplied, then the object is unnamed.\n #\n def __init__(self, name=\"\", initiator=None):\n UVMObject.__init__(self, name)\n self.initiator = initiator\n self.m_transaction_id = -1\n self.events = UVMEventPool()\n self.begin_event = self.events.get(\"begin\")\n self.end_event = self.events.get(\"end\")\n self.stream_handle = None # For recording\n self.tr_recorder = None\n\n self.begin_time = -1\n self.end_time = -1\n self.accept_time = -1\n\n\n # // Function: accept_tr\n # //\n # // Calling ~accept_tr~ indicates that the transaction item has been received by\n # // a consumer component. Typically a would call ,\n # // which calls this method-- upon return from a ~get_next_item()~, ~get()~, or ~peek()~\n # // call on its sequencer port, .\n # //\n # // With some\n # // protocols, the received item may not be started immediately after it is\n # // accepted. For example, a bus driver, having accepted a request transaction,\n # // may still have to wait for a bus grant before beginning to execute\n # // the request.\n # //\n # // This function performs the following actions:\n # //\n # // - The transaction's internal accept time is set to the current simulation\n # // time, or to accept_time if provided and non-zero. The ~accept_time~ may be\n # // any time, past or future.\n # //\n # // - The transaction's internal accept event is triggered. Any processes\n # // waiting on the this event will resume in the next delta cycle.\n # //\n # // - The method is called to allow for any post-accept\n # // action in derived classes.\n #\n # extern function void accept_tr (time accept_time = 0)\n def accept_tr(self, accept_time=0):\n e = None\n if accept_time != 0:\n self.accept_time = accept_time\n else:\n self.accept_time = sv.realtime()\n\n self.do_accept_tr()\n e = self.events.get(\"accept\")\n if e is not None:\n e.trigger()\n\n\n # // Function: do_accept_tr\n # //\n # // This user-definable callback is called by just before the accept\n # // event is triggered. Implementations should call ~super.do_accept_tr~ to\n # // ensure correct operation.\n #\n # extern virtual protected function void do_accept_tr ()\n def do_accept_tr(self):\n return\n\n #\n # // Function: begin_tr\n # //\n # // This function indicates that the transaction has been started and is not\n # // the child of another transaction. Generally, a consumer component begins\n # // execution of a transactions it receives.\n # //\n # // Typically a would call , which\n # // calls this method, before actual execution of a sequence item transaction.\n # // Sequence items received by a driver are always a child of a parent sequence.\n # // In this case, begin_tr obtains the parent handle and delegates to .\n # //\n # // See for more information on how the\n # // begin-time might differ from when the transaction item was received.\n # //\n # // This function performs the following actions:\n # //\n # // - The transaction's internal start time is set to the current simulation\n # // time, or to begin_time if provided and non-zero. The begin_time may be\n # // any time, past or future, but should not be less than the accept time.\n # //\n # // - If recording is enabled, then a new database-transaction is started with\n # // the same begin time as above.\n # //\n # // - The method is called to allow for any post-begin action in\n # // derived classes.\n # //\n # // - The transaction's internal begin event is triggered. Any processes\n # // waiting on this event will resume in the next delta cycle.\n # //\n # // The return value is a transaction handle, which is valid (non-zero) only if\n # // recording is enabled. The meaning of the handle is implementation specific.\n #\n #\n # extern function integer begin_tr (time begin_time = 0)\n def begin_tr(self, begin_time=0):\n return self.m_begin_tr(begin_time)\n\n #\n # // Function: begin_child_tr\n # //\n # // This function indicates that the transaction has been started as a child of\n # // a parent transaction given by ~parent_handle~. Generally, a consumer\n # // component calls this method via to indicate\n # // the actual start of execution of this transaction.\n # //\n # // The parent handle is obtained by a previous call to begin_tr or\n # // begin_child_tr. If the parent_handle is invalid (=0), then this function\n # // behaves the same as .\n # //\n # // This function performs the following actions:\n # //\n # // - The transaction's internal start time is set to the current simulation\n # // time, or to begin_time if provided and non-zero. The begin_time may be\n # // any time, past or future, but should not be less than the accept time.\n # //\n # // - If recording is enabled, then a new database-transaction is started with\n # // the same begin time as above. The inherited method\n # // is then called, which records the current property values to this new\n # // transaction. Finally, the newly started transaction is linked to the\n # // parent transaction given by parent_handle.\n # //\n # // - The method is called to allow for any post-begin\n # // action in derived classes.\n # //\n # // - The transaction's internal begin event is triggered. Any processes\n # // waiting on this event will resume in the next delta cycle.\n # //\n # // The return value is a transaction handle, which is valid (non-zero) only if\n # // recording is enabled. The meaning of the handle is implementation specific.\n #\n # extern function integer begin_child_tr (time begin_time = 0,\n # integer parent_handle = 0)\n #Use a parent handle of zero to link to the parent after begin\n def begin_child_tr(self, begin_time=0, parent_handle=0):\n return self.m_begin_tr(begin_time, parent_handle)\n\n #\n #\n # // Function: do_begin_tr\n # //\n # // This user-definable callback is called by and just\n # // before the begin event is triggered. Implementations should call\n # // ~super.do_begin_tr~ to ensure correct operation.\n #\n # extern virtual protected function void do_begin_tr ()\n def do_begin_tr(self):\n pass\n\n\n # // Function: end_tr\n # //\n # // This function indicates that the transaction execution has ended.\n # // Generally, a consumer component ends execution of the transactions it\n # // receives.\n # //\n # // You must have previously called or for this\n # // call to be successful.\n # //\n # // Typically a would call , which\n # // calls this method, upon completion of a sequence item transaction.\n # // Sequence items received by a driver are always a child of a parent sequence.\n # // In this case, begin_tr obtain the parent handle and delegate to .\n # //\n # // This function performs the following actions:\n # //\n # // - The transaction's internal end time is set to the current simulation\n # // time, or to ~end_time~ if provided and non-zero. The ~end_time~ may be any\n # // time, past or future, but should not be less than the begin time.\n # //\n # // - If recording is enabled and a database-transaction is currently active,\n # // then the record method inherited from uvm_object is called, which records\n # // the final property values. The transaction is then ended. If ~free_handle~\n # // is set, the transaction is released and can no longer be linked to (if\n # // supported by the implementation).\n # //\n # // - The method is called to allow for any post-end\n # // action in derived classes.\n # //\n # // - The transaction's internal end event is triggered. Any processes waiting\n # // on this event will resume in the next delta cycle.\n #\n # extern function void end_tr (time end_time=0, bit free_handle=1)\n def end_tr(self, end_time=0, free_handle=1):\n self.end_time = end_time\n if end_time == 0:\n self.end_time = sv.realtime()\n self.do_end_tr() # Callback prior to actual ending of transaction\n\n if(self.is_recording_enabled() and (self.tr_recorder is not None)):\n self.record(self.tr_recorder)\n self.tr_recorder.close(self.end_time)\n\n if free_handle:\n # once freed, can no longer link to\n self.tr_recorder.free()\n self.tr_recorder = None\n\n self.end_event.trigger()\n\n\n # // Function: do_end_tr\n # //\n # // This user-definable callback is called by just before the end event\n # // is triggered. Implementations should call ~super.do_end_tr~ to ensure correct\n # // operation.\n #\n # extern virtual protected function void do_end_tr ()\n def do_end_tr(self):\n return\n\n\n # // Function: get_tr_handle\n # //\n # // Returns the handle associated with the transaction, as set by a previous\n # // call to or `begin_tr` with transaction recording enabled.\n #\n # extern function integer get_tr_handle ()\n def get_tr_handle (self):\n if self.tr_recorder is not None:\n return self.tr_recorder.get_handle()\n else:\n return 0\n\n\n # // Function: disable_recording\n # //\n # // Turns off recording for the transaction stream. This method does not\n # // effect a 's recording streams.\n def disable_recording(self):\n self.stream_handle = None\n\n\n # // Function: enable_recording\n # // Turns on recording to the ~stream~ specified.\n # //\n # // If transaction recording is on, then a call to ~record~ is made when the\n # // transaction is ended.\n def enable_recording(self, stream):\n self.stream_handle = stream\n\n\n # // Function: is_recording_enabled\n # //\n # // Returns 1 if recording is currently on, 0 otherwise.\n #\n # extern function bit is_recording_enabled()\n def is_recording_enabled(self):\n return self.stream_handle is not None\n\n # // Function: is_active\n # //\n # // Returns 1 if the transaction has been started but has not yet been ended.\n # // Returns 0 if the transaction has not been started.\n #\n # extern function bit is_active ()\n def is_active(self):\n return self.end_time == -1\n\n\n # // Function: get_event_pool\n # //\n # // Returns the event pool associated with this transaction.\n # //\n # // By default, the event pool contains the events: begin, accept, and end.\n # // Events can also be added by derivative objects. An event pool is a\n # // specialization of , e.g. a ~uvm_pool#(uvm_event)~.\n #\n # extern function uvm_event_pool get_event_pool ()\n def get_event_pool(self):\n return self.events\n\n\n # // Function: set_initiator\n # //\n # // Sets initiator as the initiator of this transaction.\n # //\n # // The initiator can be the component that produces the transaction. It can\n # // also be the component that started the transaction. This or any other\n # // usage is up to the transaction designer.\n #\n # extern function void set_initiator (uvm_component initiator)\n def set_initiator(self, initiator):\n self.initiator = initiator\n\n\n # // Function: get_initiator\n # //\n # // Returns the component that produced or started the transaction, as set by\n # // a previous call to set_initiator.\n # extern function uvm_component get_initiator ()\n\n\n # // Function: get_accept_time\n #\n def get_accept_time(self):\n return self.accept_time\n\n # // Function: get_begin_time\n #\n def get_begin_time(self):\n return self.begin_time\n\n\n # // Function: get_end_time\n # //\n # // Returns the time at which this transaction was accepted, begun, or ended,\n # // as by a previous call to , , , or .\n #\n # extern function time get_end_time ()\n def get_end_time(self):\n return self.end_time\n\n\n # // Function: set_transaction_id\n # //\n # // Sets this transaction's numeric identifier to id. If not set via this\n # // method, the transaction ID defaults to -1.\n # //\n # // When using sequences to generate stimulus, the transaction ID is used along\n # // with the sequence ID to route responses in sequencers and to correlate\n # // responses to requests.\n def set_transaction_id(self, id):\n self.m_transaction_id = id\n\n # // Function: get_transaction_id\n # //\n # // Returns this transaction's numeric identifier, which is -1 if not set\n # // explicitly by ~set_transaction_id~.\n # //\n # // When using a to generate stimulus, the transaction\n # // ID is used along\n # // with the sequence ID to route responses in sequencers and to correlate\n # // responses to requests.\n def get_transaction_id(self):\n return self.m_transaction_id\n\n # //----------------------------------------------------------------------------\n # //\n # // Internal methods properties; do not use directly\n # //\n # //----------------------------------------------------------------------------\n\n # //Override data control methods for internal properties\n # extern virtual function void do_print (uvm_printer printer)\n\n # extern virtual function void do_record (uvm_recorder recorder)\n\n # extern virtual function void do_copy (uvm_object rhs)\n\n # extern protected function integer m_begin_tr (time begin_time=0,\n # integer parent_handle=0)\n def m_begin_tr(self, begin_time=0, parent_handle=0):\n m_begin_tr = 0\n tmp_time = begin_time\n if begin_time == 0:\n tmp_time = sv.realtime()\n parent_recorder = None\n\n if parent_handle != 0:\n parent_recorder = UVMRecorder.get_recorder_from_handle(parent_handle)\n\n # If we haven't ended the previous record, end it.\n if self.tr_recorder is not None:\n # Don't free the handle, someone else may be using it...\n self.end_tr(tmp_time)\n\n # May want to establish predecessor/successor relation\n # (don't free handle until then)\n if self.is_recording_enabled():\n db = self.stream_handle.get_db()\n self.end_time = -1\n self.begin_time = tmp_time\n\n if (parent_recorder is None):\n self.tr_recorder = self.stream_handle.open_recorder(self.get_type_name(),\n self.begin_time,\n \"Begin_No_Parent, Link\")\n else:\n self.tr_recorder = self.stream_handle.open_recorder(self.get_type_name(),\n self.begin_time,\n \"Begin_End, Link\")\n\n if (self.tr_recorder is not None):\n pass\n #link = uvm_parent_child_link::get_link(parent_recorder, self.tr_recorder)\n # TODO\n #db.establish_link(link)\n\n if (self.tr_recorder is not None):\n m_begin_tr = self.tr_recorder.get_handle()\n else:\n m_begin_tr = 0\n else:\n self.tr_recorder = None\n self.end_time = -1\n self.begin_time = tmp_time\n m_begin_tr = 0\n\n self.do_begin_tr() # execute callback before event trigger\n self.begin_event.trigger()\n return m_begin_tr\n\n #endfunction\n\n #\n #endclass\n\n#------------------------------------------------------------------------------\n# IMPLEMENTATION\n#------------------------------------------------------------------------------\n\n# get_initiator\n# ------------\n#\n#function uvm_component uvm_transaction::get_initiator()\n# return initiator\n#endfunction\n#\n#\n#\n# do_print\n# --------\n#\n#function void uvm_transaction::do_print (uvm_printer printer)\n# string str\n# uvm_component tmp_initiator; //work around $swrite bug\n# super.do_print(printer)\n# if(accept_time != -1)\n# printer.print_time(\"accept_time\", accept_time)\n# if(begin_time != -1)\n# printer.print_time(\"begin_time\", begin_time)\n# if(end_time != -1)\n# printer.print_time(\"end_time\", end_time)\n# if(initiator is not None):\n# tmp_initiator = initiator\n# $swrite(str,\"@%0d\", tmp_initiator.get_inst_id())\n# printer.print_generic(\"initiator\", initiator.get_type_name(), -1, str)\n# end\n#endfunction\n#\n#function void uvm_transaction::do_copy (uvm_object rhs)\n# uvm_transaction txn\n# super.do_copy(rhs)\n# if(rhs is None) return\n# if(!$cast(txn, rhs) ) return\n#\n# accept_time = txn.accept_time\n# begin_time = txn.begin_time\n# end_time = txn.end_time\n# initiator = txn.initiator\n# stream_handle = txn.stream_handle\n# self.tr_recorder = txn.self.tr_recorder\n#endfunction\n#\n# do_record\n# ---------\n#\n#function void uvm_transaction::do_record (uvm_recorder recorder)\n# string s\n# super.do_record(recorder)\n# if(accept_time != -1)\n# recorder.record_field(\"accept_time\", accept_time, $bits(accept_time), UVM_TIME)\n# if(initiator is not None):\n# uvm_recursion_policy_enum p = recorder.policy\n# recorder.policy = UVM_REFERENCE\n# recorder.record_object(\"initiator\", initiator)\n# recorder.policy = p\n# end\n#endfunction\n#\n","sub_path":"src/uvm/base/uvm_transaction.py","file_name":"uvm_transaction.py","file_ext":"py","file_size_in_byte":24490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"313856794","text":"from flask import Flask,render_template, flash, request,redirect, url_for, session,logging, send_from_directory\nfrom flask_mysqldb import MySQL\nfrom wtforms import Form, StringField, TextAreaField, PasswordField, validators,IntegerField\nfrom passlib.hash import sha256_crypt #for password encryption\nfrom functools import wraps #for decorator\nfrom flask_ckeditor import CKEditorField,CKEditor\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.file import FileField, FileRequired, FileAllowed\nfrom werkzeug.utils import secure_filename\nfrom sklearn.neighbors import NearestNeighbors #for model design\nfrom sklearn.neighbors import KNeighborsClassifier #for model design\nimport os\nimport numpy as np\n#from settings import PROJECT_ROOT\n\n# from data import Posts\n\n#instantiate Flask method\napp = Flask(__name__)\n\n#logging.basicConfig(level=logging.DEBUG)\n# config MySQL\napp.config['MYSQL_HOST'] = 'localhost'\napp.config['MYSQL_USER'] = 'root'\napp.config['MYSQL_PASSWORD'] = ''\napp.config['MYSQL_DB'] = 'movie_app'\napp.config['MYSQL_CURSORCLASS'] = 'DictCursor'\n\n#initialize MySQL\nmysql = MySQL(app)\n\n#initialize ckeditor\nckeditor = CKEditor(app)\n\n# Posts = Posts()\n#create the home route\n@app.route(\"/\")\ndef home():\n #create cursor\n cur = mysql.connection.cursor()\n\n #Get articles \n result = cur.execute(\"SELECT * FROM movies LIMIT 30\")\n\n movies = cur.fetchall() #fecth in dictionary format\n\n if result > 0:\n return render_template('home.html', movies=movies)\n else:\n msg = 'No Articles found'\n return render_template('home.html', msg=msg)\n\n #commit connection\n cur.commit()\n\n #close connection\n cur.close()\n\n #return render_template(\"home.html\")\n\n#about us\n@app.route(\"/aboutus.html\")\ndef aboutus():\n return render_template(\"aboutus.html\")\n\n#posts\n@app.route(\"/posts.html\")\ndef posts():\n #create cursor\n cur = mysql.connection.cursor()\n\n #Get articles \n result = cur.execute(\"SELECT * FROM articles\")\n\n articles = cur.fetchall() #fecth in dictionary format\n\n if result > 0:\n return render_template('posts.html', articles=articles)\n else:\n msg = 'No Articles found'\n return render_template('posts.html', msg=msg)\n\n #close connection\n cur.close()\n\n#post\n@app.route(\"/post//\")\ndef post(id):\n #create cursor\n cur = mysql.connection.cursor()\n\n #Get articles \n result = cur.execute(\"SELECT * FROM articles WHERE id= %s\", [id])\n if result == 1: #this is just to make use of result,it's not needed\n article = cur.fetchone() #fecth in dictionary format\n return render_template(\"post.html\", article=article)\n\n#register form\nclass RegisterForm(Form):\n name = StringField('Name', [validators.length(min=1, max=50), validators.DataRequired()])\n email = StringField('Email', [validators.length(min=6, max=50), validators.DataRequired()])\n password = PasswordField('Password', [\n validators.DataRequired(),\n validators.EqualTo('confirm', message='Passwords do not match')\n ])\n confirm = PasswordField('Confirm Password')\n\n#register\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n form = RegisterForm(request.form)\n # check if it's a POST reqiest and validate\n if request.method == 'POST' and form.validate():\n #get the data in the form\n name = form.name.data\n email = form.email.data\n password = sha256_crypt.encrypt(str(form.password.data))\n\n #Create cursor\n cur = mysql.connection.cursor()\n\n cur.execute('INSERT INTO users(name, email, password) VALUES(%s, %s, %s)', (name, email, password))\n\n #commit to db\n mysql.connection.commit()\n\n #close connection\n cur.close()\n\n #set a flash message\n flash('Registeration is successful. You can now log in.', 'success')\n\n return redirect(url_for('login'))\n return render_template('register.html', form=form)\n\n#user login\n@app.route('/login', methods = ['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n #Get from fields, note we are not using wtform here instead we are using the request method to get the data from the form.\n email = request.form['email']\n password_candidate = request.form['password']\n\n #create a cursor\n cur = mysql.connection.cursor()\n\n #get user by email\n result = cur.execute(\"SELECT * FROM users WHERE email = %s\", [email]) \n\n #check the result if any is found\n if result > 0:\n #get stored hashed password\n data = cur.fetchone()\n password = data['password']\n\n #compare passwords\n if sha256_crypt.verify(password_candidate, password):\n session['logged_in'] = True\n session['email'] = email\n num = data['user_id'] #get the user_id\n session['num'] = num #keep user_id in session\n\n flash('You are now logged in', 'success')\n return redirect(url_for('dashboard', id=data['user_id']))\n \n else:\n error = 'Invalid login'\n return render_template('login.html', error=error)\n #close connection\n cur.close()\n else:\n error = 'Email not found'\n return render_template('login.html', error=error)\n\n return render_template('login.html')\n\n#check if user logged\ndef is_logged_in(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if 'logged_in' in session:\n return f(*args, **kwargs)\n else:\n flash('Unauthorized, Please Login', 'danger')\n return redirect(url_for('login'))\n return wrap\n \n#logout\n@app.route('/logout')\n@is_logged_in\ndef logout():\n session.clear()\n flash('You are logged out', 'success')\n return redirect(url_for('home'))\n\n#dashboaed with id\n@app.route('/dashboard//')\n@is_logged_in\ndef dashboard(id):\n #fetch all aeticles from database\n #create cursor\n cur = mysql.connection.cursor()\n\n #Get articles \n result = cur.execute(\"SELECT articles.*, users.* \\\n FROM articles \\\n INNER JOIN users ON articles.author = users.email \\\n WHERE users.user_id = %s\",[id])\n\n articles = cur.fetchall() #fecth in dictionary format\n\n if result > 0:\n return render_template('dashboard.html', articles=articles)\n else:\n msg = 'No Articles found'\n return render_template('dashboard.html', msg=msg)\n\n #close connection\n cur.close()\n\n#Article form class\nclass ArticleForm(Form):\n title = StringField('Title', [validators.length(min=1, max=200), validators.DataRequired()])\n body = CKEditorField('Body', [validators.length(min=30), validators.DataRequired()]) \n\n#Add Articles\n@app.route('/add_article/', methods=['GET','POST'])\n@is_logged_in\ndef add_article(id):\n #instantiate the ArticleForm\n form = ArticleForm(request.form)\n #check the request method and validation\n if request.method == 'POST' and form.validate():\n title = form.title.data #get the title field\n body = form.body.data #get the body field\n\n #Create Cursor\n cur = mysql.connection.cursor()\n\n #Execute\n cur.execute('INSERT INTO articles(title, body, author) VALUES(%s, %s, %s)', (title, body, session['email']))\n\n #Connect to DB\n mysql.connection.commit()\n\n #close connection\n cur.close()\n\n flash('Article Created', 'success')\n\n return redirect(url_for('dashboard',id=id)) \n #return render_template('dashboard.html')\n\n return render_template('add_article.html', form=form) \n\n#Edit Articles\n@app.route('/edit_article/', methods=['GET','POST'])\n@is_logged_in\ndef edit_article(id):\n #we need to get the the row we want to query\n cur = mysql.connection.cursor()\n\n #get the article by id \n result = cur.execute(\"SELECT * FROM articles WHERE id = %s\", [id])\n if result == 1:\n article = cur.fetchone()\n\n #instantiate the ArticleForm\n form = ArticleForm(request.form)\n\n #populate article from fields\n form.title.data = article['title']\n form.body.data = article['body']\n\n #check the request method and validation\n if request.method == 'POST' and form.validate():\n title = request.form['title'] #get the title field\n body = request.form['body'] #get the body field\n\n #Create Cursor\n cur = mysql.connection.cursor()\n\n #Execute\n cur.execute('UPDATE articles SET title=%s, body=%s WHERE id=%s', (title, body, [id]))\n\n #Connect to DB\n mysql.connection.commit()\n\n #close connection\n cur.close()\n\n flash('Article Edited', 'success')\n\n return redirect(url_for('dashboard', id=session['num'])) \n\n return render_template('edit_article.html', form=form)\n\n#delete route\n@app.route('/delete_article/', methods=['POST'])\n@is_logged_in\ndef delete_article(id):\n #create cursor\n cur = mysql.connection.cursor()\n\n #execute\n cur.execute(\"DELETE FROM articles WHERE id = %s\", [id])\n\n #connect to db\n mysql.connection.commit()\n\n #close connection\n cur.close()\n\n #send a flash success message\n flash('Article Deleted', 'success')\n\n return redirect(url_for('dashboard', id=session['num']))\n\n#form class for posting movies to database\nclass MoviesForm(FlaskForm):\n title = StringField('Title', [validators.length(min=3), validators.DataRequired()])\n rating = IntegerField(' Give Rating',[validators.DataRequired()])\n movie_image = FileField('Upload Movie Picture', validators=[FileRequired()])\n\n#app.instance_path\napp.config['ALLOWED_IMAGE_EXTENSIONS'] = ['PNG', 'JPG', 'JPEG', 'GIF']\napp.config['IMAGE_UPLOADS'] = 'static/uploads/movie_image/'\n#app.config['MAX_IMAGE_LENGTH'] = 16 * 1024 * 1024\n\ndef allowed_image(filename):\n\n if not '.' in filename:\n flash('Invalid file', category='error')\n return redirect(request.url)\n\n #split filename from the right\n ext = filename.rsplit('.', 1)[1]\n\n if ext.upper() in app.config['ALLOWED_IMAGE_EXTENSIONS']:\n return True\n else:\n return False\n\n@app.route('/add_movie', methods=['GET', 'POST'])\ndef upload_file():\n\n form = MoviesForm()\n\n if request.method == 'POST':\n\n title = form.title.data #get the title field\n \n rating = form.rating.data #get the rating field\n \n movie_image = form.movie_image.data #get the image field\n \n #check for an empty field\n if movie_image.filename == '':\n flash('No image selected',category='error')\n return redirect(request.url)\n\n #check for the correct extension\n if not allowed_image(movie_image.filename):\n flash('Invalid image extension', category='error')\n return redirect(request.url)\n\n else:\n #sanitize the filename\n filename = secure_filename(movie_image.filename)\n \n #save the image\n movie_image.save(os.path.join(app.config['IMAGE_UPLOADS'], filename)) \n #.filename is an attribute of the movie_image object\n\n #create cursor\n cur = mysql.connection.cursor()\n\n #send to db\n cur.execute(\"INSERT INTO movies(title, rating, image) VALUES(%s, %s, %s)\", (title, rating, filename))\n\n #commit\n cur.connection.commit()\n\n #close connection\n cur.close()\n \n flash('Infomation saved successfully!', category='success')\n return redirect(url_for('dashboard'))\n\n return render_template('add_movie.html', form=form)\n\n#each movie\n@app.route('/movie//')\ndef movie(id):\n #create cursor\n cur = mysql.connection.cursor()\n\n #get all movies,rating and vote count\n all_data = cur.execute(\"SELECT id, rating, popularity FROM movies\")\n\n #fetch in dictionary format\n data = cur.fetchall()\n\n #connect to db\n cur.connection.commit()\n #close connection\n #cur.close()\n\n #Get a movie \n result = cur.execute(\"SELECT id, title, rating, image, popularity, overview, date, movie_url FROM movies WHERE id= %s\", [id])\n if result == 1: #this is just to make use or result,it's not needed\n movie = cur.fetchone() #fecth in dictionary format\n\n #model to get recommendation\n #1 instantiate the NearestNeighbor class\n knn = NearestNeighbors(metric='cosine', algorithm='brute', n_neighbors=15)\n value = [m for m in movie.values() if (type(m) == int) | (type(m) == float)] #select values for x\n data_list = [] #create an empty list\n for i in data: #get each value in the tuple data\n data_list.append(list(i.values())) #append only the values in the dictionary and convert to list\n #print(a)\n knn.fit(data_list) #train the model\n distances,indices = knn.kneighbors([value], n_neighbors=4) \n print(indices)\n\n #query the database to get all data in movies table\n #this is to get all the data as we dont have them in the other queries in this function for all data\n #create cursor\n cur = mysql.connection.cursor()\n\n #get all movies,rating and vote count\n movies = cur.execute(\"SELECT * FROM movies\")\n\n #fetch in dictionary format\n movies = cur.fetchall()\n\n #connect to db\n cur.connection.commit()\n\n #iterate throughthe indices to get each values\n for i in indices:\n rec_movies = np.array(movies)[i]\n #print(rec_movies)\n\n return render_template(\"movie.html\", movie=movie, rec_movies=rec_movies)\n\n\nif __name__ == \"__main__\":\n app.secret_key='secret123'\n app.run(debug=True)\n \n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"616866750","text":"#Untitled Goose Game Asset deconstruction\nmajor=0\nminor=1\n\nimport sys\nfrom colorama import Fore, Back, Style, init\nimport time\nimport progressbar\n\ninit()\n#open asset file from command line\nasset_file = open(sys.argv[1], \"r\")\n\nYAML_LINE = asset_file.readlines()\n\nasset_name='NA'\nindex_count='NA'\nvertex_count='NA'\nindex_buffer='NA'\nvertex_buffer='NA'\nvertex_buffer_size='NA'\nvertex_buffer_block_size='NA'\n\ncount=0\n#comb through file, line by line\nprint(\"Reading File...\")\nfor line in YAML_LINE: \n #print(\"Line{}: {}\".format(count, line.strip()))\n if \"m_Name:\" in line:\n asset_name=str(line.split(\":\", maxsplit=1)[1].strip())\n if \"m_VertexCount:\" in line:\n vertex_count=int(line.split(\":\", maxsplit=1)[1].strip())\n if \"indexCount\" in line:\n index_count=int(line.split(\":\", maxsplit=1)[1].strip())\n if \"m_IndexBuffer:\" in line:\n index_buffer=str(line.split(\":\", maxsplit=1)[1].strip())\n if \"m_DataSize:\" in line:\n vertex_buffer_size=int(line.split(\":\", maxsplit=1)[1].strip())\n if \"_typelessdata:\" in line:\n vertex_buffer=str(line.split(\":\", maxsplit=1)[1].strip())\n count+=1\n\nprint(\"Extracted Header\")\nprint(\"Asset Name: \"+Fore.GREEN + str(asset_name)+Style.RESET_ALL)\nprint(\"Indexs: \"+Fore.GREEN +str(index_count)+Style.RESET_ALL)\nprint(\"Vertexs: \"+Fore.GREEN +str(vertex_count)+Style.RESET_ALL)\nprint(\"Vertex Buffer Size: \"+ Fore.GREEN +str(vertex_buffer_size)+Style.RESET_ALL)\nvertex_buffer_block_size=(vertex_buffer_size/vertex_count)\nprint(\"Vertex Buffer Block Size: \" +Fore.GREEN+ str(vertex_buffer_block_size)+Style.RESET_ALL)\nprint(\"Raw Buffers\")\nprint(\"INDEX BUFFER: \" + Fore.RED + str(index_buffer)+Style.RESET_ALL)\nprint(\"VERTEX BUFFER: \"+ Fore.RED + str(vertex_buffer)+Style.RESET_ALL)\n\n\nbar = progressbar.ProgressBar(max_value=vertex_buffer_size*2)\ncsv_file = open(\"vertex_test_csv_data.csv\", \"w\")\nbyte_count=0\nblock_count=0\ncount=0\nfor byte in vertex_buffer: \n bar.update(count)\n csv_file.write(str(byte))\n byte_count+=1\n block_count+=1\n if byte_count == 4:\n csv_file.write(\",\")\n byte_count=0\n if block_count == (vertex_buffer_block_size*2):\n csv_file.write(\"\\n\")\n block_count=0\n count+=1\nprint(\"Ending Byte Count: \" + str(byte_count))\nprint(\"Ending Block Count: \" + str(block_count))\nprint(\"Ending Write Count: \" + str(count))\ncsv_file.close \n\n\n\n\n\nprint(\"Script Complete\")\nasset_file.close\n\n\n\n \n","sub_path":"scripts/asset_decompile.py","file_name":"asset_decompile.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"543943300","text":"\"\"\"\nModule implementing vector class\n\"\"\"\n\nimport logging\nimport numpy\nimport math\nfrom Polygon import Polygon\nfrom Polygon.IO import writeSVG\n\nLOGGER = logging.getLogger(\"dpLogger\")\nEPS = 0.001\n\n\nclass Plane(object):\n \"\"\"\n Plain in 3D\n \"\"\"\n\n def __init__(self, first, second, third):\n \"\"\"\n Constructor of plain in 3D given by 3 points\n\n @param first: First point\n @param second: Second point\n @param third: Third point\n \"\"\"\n self.normal = ((second - first) * (third - first)).normalize()\n self.offset = self.normal.x * first.x + self.normal.y * first.y + \\\n self.normal.z * first.z\n\n def get_y(self, x, z):\n \"\"\"\n Returns Y coordinate in the plane\n \"\"\"\n left = [list(self), list(PLANE_YZ), list(PLANE_XY)]\n right = [self.offset, x, z]\n return numpy.linalg.solve(left, right)[1]\n\n def __repr__(self):\n \"\"\"\n String representation\n \"\"\"\n return \"%.3f*x + %.3f*y + %.4f*z + %.3f = 0\" % (self.normal.x,\n self.normal.y,\n self.normal.z,\n self.offset)\n\n def __iter__(self):\n \"\"\"\n \"\"\"\n for coord in self.normal:\n yield coord\n\n\nclass Line(object):\n \"\"\"\n Class representing line in analytic geometry\n \"\"\"\n\n def __init__(self, origin, direction):\n \"\"\"\n Creates basic line equation for analytic geometry\n\n @param origin: Vector to origin of edge (First point)\n @param direction: Vector of edge direction (Second point)\n \"\"\"\n dir_vec = direction - origin\n self.normal = dir_vec.ort().normalize()\n self.offset = self.normal.x * origin.x + self.normal.y * origin.y\n\n def get_intersect(self, other, offset=None):\n \"\"\"\n Computes intersect of two lines\n \"\"\"\n if offset is None:\n offset = self.offset\n left = [list(self), list(other)]\n right = [offset, other.offset]\n try:\n intersect = (numpy.linalg.solve(left, right))\n except numpy.linalg.LinAlgError as liae:\n LOGGER.warn(\"Cannot solve equations:\\n\\t%s\\t%s\\nGot error: \"\n \"%s\\nOffset of first equation was %f\" %\n (self, other, liae, offset))\n return None\n return Vector2(intersect[0], intersect[1])\n\n def __iter__(self):\n \"\"\"\n Iterates over normal\n \"\"\"\n for coord in self.normal:\n yield coord\n\n def __repr__(self):\n \"\"\"\n Prints equation\n \"\"\"\n return \"%.3f*x + %.3f*y + %.3f = 0\" % (self.normal.x, self.normal.y,\n self.offset)\n\n\n __str__ = __repr__\n\n\n def has_point(self, point):\n \"\"\"\n Return true if point lays on this line\n \"\"\"\n return self.normal.x * point.x + self.normal.y * point.y \\\n - self.offset == 0.0\n\n\nclass Line3(object):\n \"\"\"\n Representing line in 3D\n \"\"\"\n\n def __init__(self, origin, direction):\n \"\"\"\n Creates basic line equation for analytic geometry\n\n @param origin: Vector to origin of edge (First point)\n @param direction: Vector of edge direction (Second point)\n \"\"\"\n self.origin = origin\n self.direction = direction\n\n def has_point(self, point):\n \"\"\"\n Decides whether point is on this line\n \"\"\"\n if point == self.origin or point == self.direction:\n return True\n vec1 = (point - self.origin).normalize()\n vec2 = (point - self.direction).normalize()\n return vec1 == vec2 or vec1.invert() == vec2\n\n def __repr__(self):\n \"\"\"\n Prints two points\n \"\"\"\n return \"%s --- %s\" %(self.origin, self.direction)\n\n __str__ = __repr__\n\n\nclass Vector3(object):\n \"\"\"\n 3D vector\n \"\"\"\n\n def __init__(self, x=0.0, y=0.0, z=0.0):\n \"\"\"\n Constructor\n \"\"\"\n self.x = x\n self.y = y\n self.z = z\n\n def __repr__(self):\n \"\"\"\n Representation\n \"\"\"\n output = \"(%f, %f, %f)\" % (self.x, self.y, self.z)\n return output\n\n __str__ = __repr__\n\n def __add__(self, other):\n \"\"\"\n Vector addition\n \"\"\"\n new_vec = Vector3()\n new_vec.x = self.x + other.x\n new_vec.y = self.y + other.y\n new_vec.z = self.z + other.z\n return new_vec\n\n def __sub__(self, other):\n \"\"\"\n Vector substraction\n \"\"\"\n new_vec = Vector3()\n new_vec.x = self.x - other.x\n new_vec.y = self.y - other.y\n new_vec.z = self.z - other.z\n return new_vec\n\n def __ne__(self, other):\n \"\"\"\n True if self != other\n\n @param other: Other Vector3 object\n \"\"\"\n return not (self == other)\n\n def __eq__(self, other):\n \"\"\"\n If has equal coordinates\n\n @param other: Other Vector3 object\n \"\"\"\n x_diff = abs(self.x - other.x)\n y_diff = abs(self.y - other.y)\n z_diff = abs(self.z - other.z)\n return x_diff < EPS and y_diff < EPS and z_diff < EPS\n\n def __mul__(self, other):\n \"\"\"\n Vector or scalar product\n \"\"\"\n new_vec = Vector3()\n if isinstance(other, Vector3):\n new_vec.x = self.y * other.z - self.z * other.y\n new_vec.y = self.z * other.x - self.x * other.z\n new_vec.z = self.x * other.y - self.y * other.x\n else:\n new_vec.x = self.x * other\n new_vec.y = self.y * other\n new_vec.z = self.z * other\n return new_vec\n\n def __div__(self, scalar):\n \"\"\"\n Divide each coordination of vector by scalar\n \"\"\"\n scalar = float(scalar)\n new_vec = Vector3()\n new_vec.x = self.x / scalar\n new_vec.y = self.y / scalar\n new_vec.z = self.z / scalar\n\n return new_vec\n\n def __getitem__(self, index):\n \"\"\"\n Hack for compatibility with tuple computing in 2D\n \"\"\"\n if index == 0:\n return self.x\n elif index == 1:\n return self.z\n else:\n raise IndexError(\"Out of range: %d\", index)\n\n def invert(self):\n \"\"\"\n Makes vector with opposite direction\n \"\"\"\n return self * (-1)\n\n def normalize(self):\n \"\"\"\n Normalize vector\n \"\"\"\n norm = self.length\n return Vector3(self.x / norm, self.y / norm, self.z / norm)\n\n def direction(self, vector, normalize=True):\n \"\"\"\n Computes direction vector from this vector to another vector\n\n @param vector: Another vector\n @return: Vector that's directing from this vector to another\n \"\"\"\n vec = vector - self\n if normalize:\n vec = vec.normalize()\n return vec\n\n def __iter__(self):\n \"\"\"\n Iterates over coordinations\n \"\"\"\n yield self.x\n yield self.y\n yield self.z\n\n @property\n def length(self):\n \"\"\"\n Computes lenght of this vector\n \"\"\"\n return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)\n\n\nclass Vector2(object):\n \"\"\"\n 2D vector\n \"\"\"\n\n def __init__(self, x=0.0, y=0.0):\n \"\"\"\n Constructor\n \"\"\"\n self.x = x\n self.y = y\n\n def __repr__(self):\n \"\"\"\n Representation\n \"\"\"\n output = \"(%f, %f)\" % (self.x, self.y)\n return output\n\n __str__ = __repr__\n\n def __add__(self, other):\n \"\"\"\n Vector addition\n \"\"\"\n new_vec = Vector2()\n new_vec.x = self.x + other.x\n new_vec.y = self.y + other.y\n return new_vec\n\n def __sub__(self, other):\n \"\"\"\n Vector substraction\n \"\"\"\n new_vec = Vector2()\n new_vec.x = self.x - other.x\n new_vec.y = self.y - other.y\n return new_vec\n\n def __mul__(self, other):\n \"\"\"\n Scalar product\n \"\"\"\n if isinstance(other, Vector2):\n return self.x * other.x + self.y * other.y\n else:\n new_vec = Vector2()\n new_vec.x = self.x * other\n new_vec.y = self.y * other\n return new_vec\n\n def __eq__(self, other):\n \"\"\"\n If has equal coordinates\n \"\"\"\n x_diff = abs(self.x - other.x)\n y_diff = abs(self.y - other.y)\n return x_diff < EPS and y_diff < EPS\n\n def __getitem__(self, key):\n \"\"\"\n Index supporting, for compatibility with tuples\n \"\"\"\n if key == 0:\n return self.x\n if key == 1:\n return self.y\n raise IndexError(\"Vector2 has only 2 items, item %d is unknown\", key)\n\n def normalize(self):\n \"\"\"\n Normalize vector\n \"\"\"\n norm = math.sqrt(self.x ** 2 + self.y ** 2)\n return Vector2(self.x / norm, self.y / norm)\n\n def ort(self):\n \"\"\"\n Computes ortogonal vector\n \"\"\"\n return Vector2(self.y, -1 * self.x)\n\n def invert(self):\n \"\"\"\n Computes opposite vector\n \"\"\"\n return Vector2(-1 * self.x, -1 * self.y)\n\n def direction(self, node2, normalize=True):\n \"\"\"\n Computes direction vector between last point in way and point node\n\n @param node2: Point (Vector2) towards will be direction computed\n @return direction vector (Vector2)\n \"\"\"\n vec = node2 - self\n if normalize:\n vec = vec.normalize()\n return vec\n\n @property\n def length(self):\n \"\"\"\n Computes lenght of this vector\n \"\"\"\n return math.sqrt(self.x * self.x + self.y * self.y)\n\n def angle(self, other):\n \"\"\"\n Gets angle between self and other vector\n \"\"\"\n arg = self * other / (self.length * other.length)\n if arg > 1.0:\n arg = 1.0\n elif arg < -1.0:\n arg = -1.0\n return math.acos(arg)\n\n def __iter__(self):\n \"\"\"\n Iterates over coordinations\n \"\"\"\n yield self.x\n yield self.y\n\n\nPLANE_XY = Plane(Vector3(0, 0, 0), Vector3(1, 0, 0), Vector3(0, 1, 0))\nPLANE_YZ = Plane(Vector3(0, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1))\nPLANE_XZ = Plane(Vector3(0, 0, 0), Vector3(1, 0, 0), Vector3(0, 0, -1))\n\n\ndef sign(vec1, vec2, vec3):\n \"\"\"\n Algorithm for decision whether\nhttp://www.gamedev.net/topic/295943-is-this-a-better-point-in-triangle-test-2d/\n\n\n @param vec1: Point of triangle\n @param vec2: Point of triangle\n @param vec3: Point of triangle\n \"\"\"\n\n if isinstance(vec1, Vector3):\n return (vec1.x - vec3.x) * (vec2.z - vec3.z) - \\\n (vec2.x - vec3.x) * (vec1.z - vec3.z)\n elif isinstance(vec1, Vector2):\n return (vec1.x - vec3.x) * (vec2.y - vec3.y) - \\\n (vec2.x - vec3.x) * (vec1.y - vec3.y)\n\n\ndef contains_point(poi, vec1, vec2, vec3):\n \"\"\"\n Decides whether point poi is between vectors vec1, vec2 and vec3, which\n make triangle\n \"\"\"\n b1 = sign(poi, vec1, vec2) < 0.0\n b2 = sign(poi, vec2, vec3) < 0.0\n b3 = sign(poi, vec3, vec1) < 0.0\n\n return ((b1 == b2) and (b2 == b3))\n\n\ndef fits_interval(vec, start, end):\n \"\"\"\n Checks, if vector vec fits into interval given by start and end\n\n @param vec: Vector pointing to the point we want to check\n @param start: Vector pointing to the start of interval\n @param end: VEctor pointing to the end of interval\n \"\"\"\n return (start.x < vec.x < end.x) and (start.y < vec.y < end.y)\n\n\nclass RectangleLine(object):\n \"\"\"\n Testing purposes, draws line\n \"\"\"\n width = 0.01\n\n def __init__(self, start, end):\n \"\"\"\n start end are Vector2\n \"\"\"\n direction = (end - start).normalize()\n ortogonal = direction.ort() * self.width\n ortogonal_opposite = ortogonal.invert()\n lu = end + ortogonal\n lb = end + ortogonal_opposite\n ru = start + ortogonal\n rb = start + ortogonal_opposite\n self.polygon = Polygon([tuple(lu), tuple(lb), tuple(rb), tuple(ru)])\n\n def draw(self, filename):\n writeSVG(\"%s.svg\" % filename, self.polygon)\n\n\ndef get_distance(a, b, c):\n \"\"\"\n Computes distance of point C from stroke A, B\n\n @param a: Point A of stroke AB\n @param b: Point B of stroke AB\n @param c: Point C\n \"\"\"\n pi_h = math.pi / 2\n\n vec_ab = b - a\n vec_ba = a - b\n vec_bc = c - b\n vec_ac = c - a\n if vec_ba.angle(vec_bc) >= pi_h:\n return vec_bc.length\n angle_ab_ac = vec_ab.angle(vec_ac)\n length = vec_ac.length\n if angle_ab_ac >= pi_h:\n return vec_ac.length\n return math.sin(angle_ab_ac) * length\n\n\ndef get_x_stroke_coordinate(stroke, y):\n \"\"\"\n Gets X coordinate on given stroke\n\n @param stroke: Tuple of (start, end, line), where\n - start is starting coordinate of the stroke (Vector2)\n - end is the end coordinate of the stroke (Vector2)\n - stroke is Line object\n @param y: Y-coordinate\n \"\"\"\n start, end, line = stroke\n if start.y > end.y:\n start, end = end, start\n if start.y > y or end.y < y or line.normal.x == 0:\n return None\n return (-1) * (line.normal.y * y + line.offset) / line.normal.x\n\n\ndef get_y_stroke_coordinate(stroke, x):\n \"\"\"\n Gets Y coordinate on given stroke\n\n @param stroke: Tuple of (start, end, line), where\n - start is starting coordinate of the stroke (Vector2)\n - end is the end coordinate of the stroke (Vector2)\n - stroke is Line object\n @param y: X-coordinate\n \"\"\"\n start, end, line = stroke\n if start.x > end.x:\n start, end = end, start\n if start.x > x or end.x < x or line.normal.y == 0:\n return None\n return (-1) * (line.normal.x * x + line.offset) / line.normal.y\n\n\ndef draw_polygon(vertices, indices, filename):\n \"\"\"\n Helping function for drawing polygons to files\n \"\"\"\n poly = Polygon()\n for i in range(0, len(indices), 3):\n i1 = indices[i]\n i2 = indices[i+1]\n i3 = indices[i+2]\n poly.addContour([vertices[i1], vertices[i2], vertices[i3]])\n if poly.nPoints() > 0:\n writeSVG(\"%s.svg\" % filename, poly)\n\n\nif __name__ == \"__main__\":\n start = Vector2(0, 0)\n end = Vector2(2, 2)\n direction = (start - end).normalize()\n stroke = (end, start, Line(end, direction))\n assert get_x_stroke_coordinate(stroke, 0) == 0\n assert get_y_stroke_coordinate(stroke, 0) == 0\n assert get_x_stroke_coordinate(stroke, 3) == None\n assert get_y_stroke_coordinate(stroke, 3) == None\n assert get_x_stroke_coordinate(stroke, 1) == 1\n assert get_y_stroke_coordinate(stroke, 1) == 1\n","sub_path":"dp/computations/ageometr.py","file_name":"ageometr.py","file_ext":"py","file_size_in_byte":14986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"113882526","text":"from Glib import *\r\n\r\ndef draw ():\r\n global vid\r\n background (0, 200, 190)\r\n if isVideoPlaying(vid):\r\n text (\"playing\", 10, 40)\r\n else:\r\n text (\"Not playing\", 10, 40)\r\n whr = whereVideo(vid)\r\n text (\"Frame \"+str(getFrameNumber(vid)), 10, 60)\r\n text (\"Length \"+ str(whr)+\" of \"+str(lengthVideo(vid)), 40, 370)\r\n\r\ndef keyPressed(k):\r\n global vid\r\n if k == K_p:\r\n pauseVideo(vid)\r\n\r\nstartdraw(500, 500)\r\nvid = loadVideo(\"carclub2.mpg\")\r\nlocVideo(vid, 100, 100, 200, 200)\r\nplayVideo(vid)\r\nenddraw()","sub_path":"275-Langs/Python/python_anintroductiontoprogramming_supplement/Glib pygame/tests/23videoa.py","file_name":"23videoa.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"512999149","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n'''\n@author: Tsuyoshi Hombashi\n'''\n\nfrom __future__ import with_statement\nimport sys\n\nimport thutils\nimport tcconfig\n\n\ndef parse_option():\n parser = thutils.option.ArgumentParserObject()\n parser.make(version=tcconfig.VERSION)\n\n group = parser.add_argument_group(\"Traffic Control\")\n group.add_argument(\n \"--device\", required=True,\n help=\"network device name\")\n group.add_argument(\n \"--rate\",\n help=\"network bandwidth [K|M|G bps]\")\n group.add_argument(\n \"--delay\", type=float, default=0,\n help=\"round trip network delay [ms] (default=%(default)s)\")\n group.add_argument(\n \"--loss\", type=float, default=0,\n help=\"round trip packet loss rate [%%] (default=%(default)s)\")\n group.add_argument(\n \"--overwrite\", action=\"store_true\", default=False,\n help=\"overwrite existing setting\")\n\n return parser.parse_args()\n\n\n@thutils.main.Main\ndef main():\n options = parse_option()\n\n thutils.initialize_library(__file__, options)\n thutils.common.verify_install_command([\"tc\"])\n\n subproc_wrapper = thutils.subprocwrapper.SubprocessWrapper()\n\n if options.overwrite:\n tcconfig.delete_tc(subproc_wrapper, options.device)\n\n tcconfig.set_tc(subproc_wrapper, options.device,\n options.rate, options.delay, options.loss)\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"tcconfig/tcset.py","file_name":"tcset.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"479382174","text":"class KthLargest:\n\n def __init__(self, k: int, nums: List[int]):\n self.hp = nums\n self.k = k\n heapq.heapify(self.hp)\n while len(self.hp) > self.k:\n heapq.heappop(self.hp)\n\n\n def add(self, val: int) -> int:\n if len(self.hp) < self.k:\n heapq.heappush(self.hp, val)\n else:\n heapq.heappushpop(self.hp, val)\n return self.hp[0]\n \n\n# Your KthLargest object will be instantiated and called as such:\n# obj = KthLargest(k, nums)\n# param_1 = obj.add(val)","sub_path":"703.py","file_name":"703.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"24199426","text":"#!/usr/bin/python3\n\nimport sys\nimport os\nimport pickle\n\nfrom portfolio import Portfolio\nfrom report import Table\n\nclass Menu(object):\n \"\"\"Display a menu and respond to user's choices when run.\"\"\"\n\n def __init__(self):\n self.portfolio = False \n self.choices = {\n 'list': self.show_items,\n 'add': self.add_item,\n 'buy': self.buy,\n 'sell': self.sell,\n 'clear': self.clear_screen,\n 'quit': self.quit_program,\n 'report': self.report_text,\n 'save': self.save,\n 'load': self.load\n }\n self._choices_keys = \" \".join(self.choices.keys())\n self.SAVE_FILE = \"save/save\"\n self.REPORT_FILE = \"reports/report.html\"\n\n def show_items(self):\n \"\"\"Print a formatted command line report about every stock.\"\"\"\n print(\"Profit = {profit}, Capital = {capital}, Stocks = {stocks}, Cash = {cash}\".format(\n profit = self.portfolio.get_profit(),\n capital = self.portfolio.get_capital(),\n stocks = self.portfolio.get_value(),\n cash = self.portfolio.get_cash()))\n \n for stock in self.portfolio.get_stocks():\n print(\"{symbol}: {name} €{price}\\n\\tShares: {shares} Value: €{value}\".format(\n symbol = stock.symbol,\n name = stock.name,\n price = stock.price,\n shares = stock.shares,\n value = round(stock.price * stock.shares, 2)))\n\n def add_item(self):\n symbol = input(\"Enter the symbol (ticker): \")\n name = input(\"Enter the name of the company: \")\n # TODO: fetch from Yahoo\n price = float(input(\"Enter the latest price: \"))\n self.portfolio.add_stock(symbol, name, price)\n print(\"The stock has been added.\")\n\n def buy(self):\n symbol = input(\"Enter the symbol: \")\n\n if symbol in self.portfolio.get_symbols():\n shares = int(input(\"How many shares: \"))\n price = float(input(\"Price: \"))\n self.portfolio.buy_shares(symbol, price, shares)\n else:\n print(\"Sorry, that stock is not in your portfolio.\")\n choice = input(\"Would you like to create a new stock? (yes/no) \")\n if choice.lower() in ['yes', 'y']:\n self.add_item()\n else:\n return None\n \n def sell(self):\n symbol = input(\"Enter the symbol: \")\n\n if symbol in self.portfolio.get_symbols():\n shares = int(input(\"How many shares: \"))\n price = float(input(\"Price: \"))\n self.portfolio.sell_shares(symbol, price, shares)\n else:\n print(\"Sorry, that stock is not in your portfolio.\")\n\n def clear_screen(self):\n os.system('clear')\n\n def quit_program(self):\n # TODO: save everything.\n print(\"Thank you for using your portfolio today.\")\n sys.exit(0)\n\n def save(self):\n \"\"\"Save the portfolio to disk with pickle.\"\"\"\n done = False\n\n while True:\n if done:\n break\n filename = input(\"Enter the filename (press Enter for default file): \")\n if filename == \"\":\n filename = self.SAVE_FILE\n try:\n with open(filename, 'wb') as f:\n # Pickle the 'data' dictionary using the highest protocol available.\n pickle.dump(self.portfolio, f, pickle.HIGHEST_PROTOCOL)\n done = True\n except:\n answer = input(\"That file could not be opened. Try again?\")\n if answer.lower() in ['yes', 'y']:\n continue\n else:\n done = True\n\n\n def load(self):\n \"\"\"Load a portfolio from disk.\"\"\"\n\n done = False\n\n while True:\n if done:\n break\n filename = input(\"Enter the filename (press Enter for default file): \")\n if filename == \"\":\n filename = self.SAVE_FILE\n try:\n with open(filename, 'rb') as f:\n self.portfolio = pickle.load(f)\n done = True\n except:\n print(\"That file could not be be opened. Try again.\")\n\n def display_menu(self):\n while not self.portfolio:\n choice = input(\"load create\\n\")\n if choice == \"load\":\n self.load()\n break\n elif choice == \"create\":\n starting_cash = input(\"How much would you like to deposit? \")\n self.portfolio = Portfolio(float(starting_cash))\n break\n if self.portfolio:\n print(self._choices_keys)\n\n def run(self):\n \"\"\"Display the menu and respond to choices.\"\"\"\n while True:\n self.display_menu()\n\n choice = input(\"> \")\n action = self.choices.get(choice.lower())\n\n if action:\n action()\n else:\n print(\"{0} is not a valid choice.\".format(choice))\n\n def report_text(self):\n \"\"\"Write a short report showing the shares.\"\"\"\n t = Table()\n t.add_head([\"Company\", \"Shares\", \"Price\"])\n \n for stock in self.portfolio.get_stocks():\n t.add_row([stock.name, stock.shares, stock.price])\n\n html = t.get_html()\n\n with open(self.REPORT_FILE, mode='w', encoding='UTF-8') as f:\n f.write(html)\n \n # TODO: append timestamp to file.\n print(\"Wrote the report to {location}\".format(location = self.REPORT_FILE))\n\n\nif __name__ == '__main__':\n menu = Menu()\n menu.run()\n","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":5713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"413759576","text":"import json\n\nfrom khl import TextMsg, Bot, Cert\n\n# load config from config/config.json, replace `path` points to your own config file\n# config template: `./config/config.json.example`\nwith open('./config/config.json', 'r', encoding='utf-8') as f:\n config = json.load(f)\n\n# init Cert for Bot OAuth\ncert = Cert(client_id=config['client_id'],\n client_secret=config['client_secret'],\n token=config['token'])\n\n# init Bot\nbot = Bot(cmd_prefix=['!', '!'], cert=cert)\n\n\n# register command\n# invoke this via saying `!hello` in channel\n@bot.command(name='hello')\nasync def roll(msg: TextMsg):\n # quote reply\n await msg.reply('world for you!')\n # msg from reply_temp & send_temp will be cleaned when you restart client or refresh browser\n await msg.reply_temp('world only for you!')\n\n # send to current channel\n await msg.ctx.send('world for all!')\n # send to current channel, but only visible to `msg.author`\n # same as `msg.reply_temp()`, but can set `temp_target_id` explicitly\n await msg.ctx.send_temp('world only for you too!', msg.author.id)\n\n\n# everything done, go ahead now!\nbot.run()\n","sub_path":"example/ex04_reply/ex04.py","file_name":"ex04.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"293928032","text":"import numpy as np\nimport itertools as it\nimport re\nfrom typing import List, Dict, Tuple, Set, AnyStr, Type\n\nsolution_list: List[Type[np.ndarray]] = []\nplacements: Dict[str, Dict[int, List[Type[np.ndarray]]]] = {}\n\n\ndef compute_blocks(line_len: int, blocks: Tuple):\n \"\"\"\n Given line and a tuple of blocks, generate valid start and stop positions for each block\n Examples:\n (line_len = 10, blocks = (1, )) : 10 possible options [(0, ), (1, ) ... (9, )]\n (line_len = 10, blocks = (3, 3, 2, )) : 1 possible option [(0, 4, 8, )]\n \"\"\"\n block_buffer: List[int] = []\n for i, block in enumerate(blocks):\n if i == 0 and i == len(blocks) - 1:\n # Only 1 block\n block_buffer.append(block)\n elif i != 0 and i == len(blocks) - 1:\n # Last block out of many\n block_buffer.append(block)\n else:\n # Many blocks. Current block can be any of them except the last one\n block_buffer.append(block + 1)\n assert sum(block_buffer) <= line_len\n block_pos: List[Tuple[int, int]] = []\n start, stop = None, None\n for i in range(len(block_buffer)):\n if i == 0:\n start = 0\n else:\n start = block_pos[i - 1][0] + block_buffer[i - 1]\n stop = (line_len - 1) - sum(block_buffer[(i + 1):]) - (block_buffer[i] - 1)\n block_pos.append((start, stop))\n # For each placement of blocks, check if length constraints are met\n result: List[Tuple] = []\n for pos in it.product(*[range(start, stop + 1) for start, stop in block_pos]):\n # Check if block_buffer length between each consecutive block is met\n invalid_flag = False\n for i in range(len(pos)):\n if i == len(pos) - 1:\n block_space = line_len - pos[i]\n else:\n block_space = pos[i + 1] - pos[i]\n if block_space < block_buffer[i]:\n invalid_flag = True\n break\n if not invalid_flag:\n result.append(pos)\n return result\n\n\ndef enumerate_blocks(block_start: List[Tuple], block_size: Tuple, total_size: int):\n \"\"\"\n Given starting position and size, generates list of arrays, each array representing placed blocks\n \"\"\"\n result = []\n for option in block_start:\n line = np.zeros(total_size, dtype=np.int8)\n for start, length in zip(option, block_size):\n line[start:(start + length)] = 1\n result.append(line.copy())\n return result\n\n\ndef valid_groups(arg: Tuple, line: AnyStr):\n groups = re.split('0+', line)\n groups = [g for g in groups if g != '']\n group_sums = tuple([len(g) for g in groups])\n if group_sums != arg:\n return False\n else:\n return True\n\n\ndef valid(row_args: List[Tuple], col_args: List[Tuple], partial_solution: Type[np.ndarray],\n completed_rows: Set[int], completed_cols: Set[int]):\n global placements\n # Check row and column constraints - sum and grouping\n for r, row_constraints in enumerate(row_args):\n if r in completed_rows:\n # Strict check - sum and grouping\n if sum(row_constraints) != np.sum(partial_solution[r, :]):\n return False\n str_ = ''.join(partial_solution[r, :].astype('int').astype('str'))\n if not valid_groups(row_constraints, str_):\n return False\n elif np.all(partial_solution[r, :] == -1):\n # Row hasn't been touched yet\n continue\n else:\n # Partially solved row. Check that sum isn't exceeded and that 1's are consistent with row's placements\n if sum(row_constraints) < np.sum(partial_solution[r, :] == 1):\n return False\n consistent_ones = False\n for placement in placements['row'][r]:\n if np.all(\n np.bitwise_and(\n np.select([partial_solution[r, :] == -1], [0], default=partial_solution[r, :]),\n placement\n ) == np.select([partial_solution[r, :] == -1], [0], default=partial_solution[r, :])\n ):\n consistent_ones = True\n break\n if not consistent_ones:\n return False\n \n for c, col_constraints in enumerate(col_args):\n if c in completed_cols:\n # Strict check - sum and grouping\n if sum(col_constraints) != np.sum(partial_solution[:, c]):\n return False\n str_ = ''.join(partial_solution[:, c].astype('int').astype('str'))\n if not valid_groups(col_constraints, str_):\n return False\n elif np.all(partial_solution[:, c] == -1):\n # Column hasn't been touched yet\n continue\n else:\n # Partially solved column. Check that sum isn't exceeded and 1's are consistent with column's placements\n if sum(col_constraints) < np.sum(partial_solution[:, c] == 1):\n return False\n consistent_ones = False\n for placement in placements['column'][c]:\n if np.all(\n np.bitwise_and(\n np.select([partial_solution[:, c] == -1], [0], default=partial_solution[:, c]),\n placement\n ) == np.select([partial_solution[:, c] == -1], [0], default=partial_solution[:, c])\n ):\n consistent_ones = True\n break\n if not consistent_ones:\n return False\n \n return True\n\n\ndef infer_values(solution_array: Type[np.ndarray],\n placements_dict: Dict[str, Dict[int, List[Type[np.ndarray]]]]):\n # Set cell values as 1/0 for rows. If value can be either 1 or 0, set as -1.\n for r in placements_dict['row']:\n row_ones = np.ones(solution_array.shape[1], dtype=np.int8)\n row_zeros = np.zeros(solution_array.shape[1], dtype=np.int8)\n for placement in placements_dict['row'][r]:\n row_ones = np.bitwise_and(row_ones, placement)\n row_zeros = np.bitwise_or(row_zeros, placement)\n row_ones = np.select([row_ones == 1, row_ones == 0], [1, -1])\n row_zeros = np.select([row_zeros == 0, row_zeros == 1], [0, -1])\n # Check for contradiction between cell value set by row vs cell value set by column\n for c in range(solution_array.shape[1]):\n # If cell-value via row is 0 and via col is 1 then this fails\n assert not (partial_solution[r, c] == 0 and row_ones[c] == 1)\n assert not (partial_solution[r, c] == 1 and row_zeros[c] == 0)\n solution_array[r, :] = np.select(\n [np.bitwise_and(row_ones == -1, row_zeros == -1), np.bitwise_and(row_ones == -1, row_zeros == 0),\n np.bitwise_and(row_ones == 1, row_zeros == -1), np.bitwise_and(row_ones == 1, row_zeros == 0)],\n [-1, 0, 1, -2]\n )\n # Set cell values as 1/0 for columns. If value can be either 1 or 0, set as -1.\n for c in placements_dict['column']:\n col_ones = np.ones(solution_array.shape[0], dtype=np.int8)\n col_zeros = np.zeros(solution_array.shape[0], dtype=np.int8)\n for placement in placements_dict['column'][c]:\n col_ones = np.bitwise_and(col_ones, placement)\n col_zeros = np.bitwise_or(col_zeros, placement)\n col_ones = np.select([col_ones == 1, col_ones == 0], [1, -1])\n col_zeros = np.select([col_zeros == 0, col_zeros == 1], [0, -1])\n # Check for contradiction between cell value set by row vs cell value set by column\n for r in range(solution_array.shape[0]):\n # If cell-value via row is 0 and via col is 1 then this fails\n assert not (partial_solution[r, c] == 0 and col_ones[r] == 1)\n assert not (partial_solution[r, c] == 1 and col_zeros[r] == 0)\n solution_array[:, c] = np.select(\n [np.bitwise_and(col_ones == -1, col_zeros == -1), np.bitwise_and(col_ones == -1, col_zeros == 0),\n np.bitwise_and(col_ones == 1, col_zeros == -1), np.bitwise_and(col_ones == 1, col_zeros == 0)],\n [partial_solution[:, c], 0, 1, -2]\n )\n\n\ndef update_completions(solution_array: Type[np.ndarray]):\n rows_completed = set(np.where(np.all(solution_array != -1, axis=1))[0].tolist())\n cols_completed = set(np.where(np.all(solution_array != -1, axis=0))[0].tolist())\n return rows_completed, cols_completed\n\n\ndef update_placements(solution_array: Type[np.ndarray],\n placements_dict: Dict[str, Dict[int, List[Type[np.ndarray]]]],\n completed_rows: Set[int], completed_columns: Set[int]):\n # Update comprises of 2 changes\n # 1. Remove completed rows and completed columns entirely. This doesn't change update flag.\n # 2. For remaining rows/columns, check all possible arrays vs corresponding line in solution_array to filter out\n # incompatible options. Changes update flag to True (as it's possible solution_array can be further narrowed)\n updated = False\n indexes_for_deletion = []\n for r in placements_dict['row']:\n if r in completed_rows:\n indexes_for_deletion.append(r)\n else:\n valid_placements = []\n for option in placements_dict['row'][r]:\n valid = np.all(\n np.select(\n [np.bitwise_and(option == 0, solution_array[r, :] == 1),\n np.bitwise_and(option == 1, solution_array[r, :] == 0)],\n [False, False], default=True\n )\n )\n if valid:\n valid_placements.append(option)\n if len(valid_placements) != len(placements_dict['row'][r]):\n # Some options were pruned away\n updated = True\n placements_dict['row'][r] = valid_placements.copy()\n for idx in indexes_for_deletion:\n del placements_dict['row'][idx]\n \n indexes_for_deletion = []\n for c in placements_dict['column']:\n if c in completed_columns:\n indexes_for_deletion.append(c)\n else:\n valid_placements = []\n for option in placements_dict['column'][c]:\n valid = np.all(\n np.select(\n [np.bitwise_and(option == 0, solution_array[:, c] == 1),\n np.bitwise_and(option == 1, solution_array[:, c] == 0)],\n [False, False], default=True\n )\n )\n if valid:\n valid_placements.append(option)\n if len(valid_placements) != len(placements_dict['column'][c]):\n # Some options were pruned away\n updated = True\n placements_dict['column'][c] = valid_placements.copy()\n for idx in indexes_for_deletion:\n del placements_dict['column'][idx]\n \n return updated, placements_dict\n\n\ndef backtrack(solution_array: Type[np.ndarray], row_placements: Dict[int, List[Type[np.ndarray]]],\n row_args: List[Tuple], col_args: List[Tuple], completed_rows: Set[int], completed_cols: Set[int]):\n assert (len(completed_rows) == len(row_args) and len(completed_cols) == len(col_args)) or \\\n (len(completed_rows) != len(row_args) and len(completed_cols) != len(col_args))\n \n if len(completed_rows) == len(row_args):\n solution_already_found = False\n for solution in solution_list:\n if solution.tobytes() == partial_solution.tobytes():\n solution_already_found = True\n break\n if not solution_already_found:\n solution_list.append(partial_solution.copy())\n return\n \n for row in row_placements:\n line = solution_array[row, :]\n line_copy = line.copy()\n for option in row_placements[row]:\n line[:] = option.copy()\n completed_rows_next, completed_cols_next = update_completions(solution_array)\n row_placements_next = {r: opt for r, opt in row_placements.items() if r != row}\n if not valid(row_args, col_args, partial_solution, completed_rows_next, completed_cols_next):\n # Undo this choice and continue\n line[:] = line_copy.copy()\n continue\n backtrack(solution_array, row_placements_next, row_args, col_args, completed_rows_next, completed_cols_next)\n line[:] = line_copy.copy()\n\n\nif __name__ == \"__main__\":\n # Easy case 1\n # row_args = [(1, ), (2, )]\n # col_args = [(2, ), (1, )]\n \n # Easy case 2 - non-unique\n # row_args = [(1,), (2,)]\n # col_args = [(1, ), (1, ), (1, )]\n \n # Medium case 1\n # row_args = [(2,), (2,), (1,), (1, 1,), (3,)]\n # col_args = [(1,), (2, 1,), (2, 2,), (1, 1,)]\n \n # Medium case 2\n # row_args = [\n # (5,), (1, 3,), (6,), (2, 5,), (3, 4,),\n # (3, 7,), (3, 10,), (3, 11,), (5, 7,), (5, 5,),\n # (5, 6,), (13,), (9,), (1, 1,), (2, 1, 4,)\n # ]\n # col_args = [\n # (6,), (8,), (9,), (4,), (6,),\n # (2, 5,), (1, 1, 3, 2, 1,), (8, 2,), (1, 7, 2, 1,), (9, 3,),\n # (13, 1,), (3, 8, 1,), (8, 1,), (9,), (5,)\n # ]\n \n # Hard case 1\n row_args = [\n (3, 2, 3, ), (3, 1, 1, 1, 3, ), (1, 5, 2, 1, ), (4, 6, 1, ), (3, 6, ),\n (1, 4, 7, ), (4, 2, 2, 6, ), (3, 5, ), (2, 1, 3, ), (7, ),\n (3, 4, 2, ), (1, 2, 3, 4, ), (5, 2, 2, ), (4, 1, 4, ), (5, 5, 1, ),\n (5, 5, ), (2, 1, 6, ), (1, 2, 2, 7, ), (2, 2, 1, 8, ), (7, 1, 7, )\n ]\n col_args = [\n (3, 4, 1, 3, ), (2, 3, 2, ), (3, 2, 1, ), (1, 1, 1, 7, ), (4, 8, ),\n (3, 1, 4, 1, ), (4, 1, 4, 1, ), (1, 1, 3, 2, ), (2, 1, 3, 4, ), (1, 2, 1, 1, ),\n (2, 2, ), (2, 1, 2, ), (4, 3, 4, ), (4, 1, 11, ), (4, 3, 6, ),\n (5, 2, 6, ), (5, 1, 1, 7, ), (8, 6, ), (10, 1, ), (8, 4, )\n ]\n \n # Generate possibilities for each row and column\n row_vector_len = len(col_args)\n col_vector_len = len(row_args)\n placements['row'] = {}\n for i, arg in enumerate(row_args):\n blocks = compute_blocks(row_vector_len, arg)\n placements['row'][i] = enumerate_blocks(blocks, arg, row_vector_len)\n placements['column'] = {}\n for i, arg in enumerate(col_args):\n blocks = compute_blocks(col_vector_len, arg)\n placements['column'][i] = enumerate_blocks(blocks, arg, col_vector_len)\n \n # Infer values\n partial_solution = -1 * np.ones((col_vector_len, row_vector_len), dtype=np.int8)\n completed_rows = set()\n completed_columns = set()\n updated = True\n while updated:\n infer_values(partial_solution, placements)\n completed_rows, completed_columns = update_completions(partial_solution)\n updated, placements = update_placements(partial_solution, placements.copy(), completed_rows, completed_columns)\n \n assert (len(placements['row']) == 0 and len(placements['column']) == 0) or \\\n (len(placements['row']) != 0 and len(placements['column']) != 0)\n \n if len(placements['row']) == 0:\n solution_list.append(partial_solution)\n else:\n # Backtrack through the rest of the unsolved rows\n print('Solving via backtracking')\n backtrack(partial_solution, placements['row'], row_args, col_args, completed_rows, completed_columns)\n \n for solution in solution_list:\n print(solution)\n","sub_path":"enumerative_backtracking_solver.py","file_name":"enumerative_backtracking_solver.py","file_ext":"py","file_size_in_byte":15510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"407706099","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom fake_useragent import UserAgent\nfrom datetime import datetime\nfrom user import User\n\nfrom time import time, sleep\n\nfrom random import choice, uniform\n\nimport sys\n\n\ndef timer(func):\n def wrapper(self, *args, **kwargs):\n start = time()\n res = func(self, *args, **kwargs)\n print('({}) Function {} ---> {} sec'.format(self.ENGINE, func.__name__, time() - start))\n if func.__name__ == '__fetch_results':\n print('Timeout:', kwargs['timeout'])\n print()\n return res\n\n return wrapper\n\n\nclass EngineParser:\n def __init__(self, engine='google'):\n # Set engine\n self.ENGINE = engine.lower()\n\n def __fetch_results(self, query, number, language_code, user_agent=None, proxy=None, timeout=5, user: User = None):\n url = ''\n\n # preparation of request link\n if self.ENGINE == 'bing':\n url = 'https://www.bing.com/search?q={}&count={}'.format(query, number)\n elif self.ENGINE == 'google':\n url = 'https://www.google.com/search?q={}&num={}&hl={}'.format(query, number, language_code)\n elif self.ENGINE == 'yahoo':\n url = 'https://search.yahoo.com/search?p={}&n={}&ei=UTF-8'.format(query, number)\n elif self.ENGINE == 'youtube':\n url = 'https://www.youtube.com/results?search_query={}'.format(query)\n\n # delay between requests\n sleep(timeout)\n\n if user is None:\n # get page with timeout = 5sec (for imitation user activity)\n response = requests.get(url, headers=user_agent, proxies=proxy, timeout=timeout)\n else:\n session = requests.Session()\n session.cookies = user.cookies\n response = session.get(url, headers=user.agent, proxies=proxy, timeout=timeout)\n user.cookies = session.cookies\n\n # print('User.name = {}\\nUser.user_agent = {}\\nUser.cookies={}'\n # .format(user.name,user.user_agent,user.cookies))\n # input()\n\n # error checking\n response.raise_for_status()\n\n # return HTML code of page\n return response.text\n\n def __parse_bing_html(self, html, query):\n # print('---------------' + self.ENGINE)\n soup = BeautifulSoup(html, 'lxml')\n\n found_results = []\n index = 1\n result_block = soup.find_all('li', attrs={'class': 'b_algo'})\n for result in result_block:\n\n link = result.find('a', href=True)\n title = result.find('h2')\n description = result.find('p')\n if link and title:\n link = link['href']\n title = title.get_text().strip()\n split = link.split('/url?q=')\n if split[0] == '':\n link = 'http://www.bing.com/url?q=' + split[1]\n # print(link)\n if description:\n description = description.get_text().strip()\n if link != '#' and description is not None:\n found_results.append({'index': index, 'query': query,\n 'link': link, 'title': title,\n 'description': description,\n 'time': datetime.now(),\n 'engine': self.ENGINE})\n index += 1\n return found_results\n\n def __parse_youtube_html(self, html, query):\n soup = BeautifulSoup(html, 'lxml')\n\n found_results = []\n index = 1\n result_block = soup.findAll('div', attrs={'class': 'yt-lockup-content'})\n # print('Url= ', result_block)\n # input()\n\n for result in result_block:\n\n link = result.find('a', href=True)\n title = link['title']\n description = result.find('div', attrs={'class': 'yt-lockup-description'})\n # print('Link = ',link, '\\ntitle = ', title, '\\ndescription=', description)\n if link and title:\n link = link['href']\n title = title.strip()\n if 'https://www.youtube.com' not in link:\n link = 'https://www.youtube.com' + link\n if description:\n description = description.get_text().strip()\n if link != '#' and description is not None:\n found_results.append({'index': index, 'query': query,\n 'link': link, 'title': title,\n 'description': description,\n 'time': datetime.now(),\n 'engine': self.ENGINE})\n\n index += 1\n # print(found_results)\n return found_results\n\n def __parse_google_html(self, html, query):\n # print('---------------' + self.ENGINE)\n soup = BeautifulSoup(html, 'lxml')\n\n found_results = []\n index = 1\n result_block = soup.find_all('div', attrs={'class': 'g'})\n for result in result_block:\n\n link = result.find('a', href=True)\n title = result.find('h3')\n description = result.find('span', attrs={'class': 'st'})\n if link and title:\n link = link['href']\n title = title.get_text().strip()\n split = link.split('/url?url=')\n if split[0] == '':\n link = 'http://www.google.com/url?url=' + split[1]\n # print(link)\n if description:\n description = description.get_text().strip()\n if link != '#' and description is not None:\n found_results.append({'index': index, 'query': query,\n 'link': link, 'title': title,\n 'description': description,\n 'time': datetime.now(),\n 'engine': self.ENGINE})\n index += 1\n return found_results\n\n def __parse_yahoo_html(self, html, query):\n soup = BeautifulSoup(html, 'lxml')\n\n found_results = []\n index = 1\n result_block = soup.findAll('div', attrs={'class': 'dd algo algo-sr Sr'})\n # print('Url= ', result_block)\n # input()\n\n for result in result_block:\n\n link = result.find('a', href=True)\n title = result.find('h3')\n description = result.find('p', attrs={'class': 'lh-16'})\n # print('Link = ',link, '\\ntitle = ', title, '\\ndescription=', description)\n if link and title:\n link = link['href']\n title = title.get_text().strip()\n # split = link.split('')\n if description:\n description = description.get_text().strip()\n if link != '#' and description is not None:\n found_results.append({'index': index, 'query': query,\n 'link': link, 'title': title,\n 'description': description,\n 'time': datetime.now(),\n 'engine': self.ENGINE})\n\n index += 1\n # print(found_results)\n return found_results\n\n def __scrape(self, query, number, language_code, use_proxy, timeout_range, user=None):\n # set User-Agent header\n ua = UserAgent()\n user_agent = {\"User-Agent\": ua.random}\n\n # set proxy\n if use_proxy:\n with open('proxies.txt') as file:\n proxies = file.read().split('\\n')\n proxy = {'http': 'http://' + choice(proxies)}\n else:\n proxy = None\n\n # set timeout value\n timeout = uniform(*timeout_range)\n\n try:\n # get HTML code of some page\n html = self.__fetch_results(query=query, number=number, language_code=language_code,\n user_agent=user_agent, proxy=proxy, timeout=timeout, user=user)\n\n # parse results\n if self.ENGINE == 'bing':\n return self.__parse_bing_html(html=html, query=query)\n elif self.ENGINE == 'google':\n return self.__parse_google_html(html=html, query=query)\n elif self.ENGINE == 'yahoo':\n return self.__parse_yahoo_html(html=html, query=query)\n elif self.ENGINE == 'youtube':\n return self.__parse_youtube_html(html=html, query=query)\n\n except AssertionError:\n raise Exception(\"Incorrect arguments parsed to function\")\n except requests.HTTPError:\n raise Exception(\"You appear to have been blocked by {}\".format(self.ENGINE))\n except requests.RequestException:\n raise Exception(\"Appears to be an issue with your connection\")\n\n def start_engine_scrapping(self, query: str, number: int = 10,\n language_code: str = 'ru',\n engine: str = 'google',\n timeout_range=(3, 5),\n print_output: bool = False,\n use_proxy: bool = False,\n user: User = None):\n # set search engine\n self.ENGINE = engine.lower()\n\n # get results\n results = self.__scrape(query=query, number=number,\n language_code=language_code,\n use_proxy=use_proxy,\n user=user,\n timeout_range=timeout_range)\n\n if print_output:\n print('---------------{}---------------'.format(self.ENGINE))\n for res in results:\n for key in res.keys():\n if key == 'index':\n print(key + ': ' + str(res[key]))\n else:\n print('\\t' + key + ': ' + str(res[key]))\n print()\n print('---------------END---------------\\n')\n\n return results\n\n\nif '__main__' == __name__:\n \"\"\"\n query <---> your search query\n number <---> how many links you want to see\n language_code <---> code of language of your query\n print_output <---> print output flag\n use_proxy <---> use proxy flag\n\n How to run this script? (example):\n python main.py \"право постійного користування земельною ділянкою\" 3 ru\n \"\"\"\n engine_parser = EngineParser('Google')\n engine_parser.start_engine_scrapping(query=sys.argv[1], number=int(sys.argv[2]),\n language_code=sys.argv[3], print_output=True,\n use_proxy=True, engine=engine_parser.ENGINE,\n timeout_range=(3, 5))\n","sub_path":"engine_parser.py","file_name":"engine_parser.py","file_ext":"py","file_size_in_byte":11145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"107305044","text":"from ..dbpnet.dbpnet_model import DBPNet\r\nfrom ..resunet.resunet_model import ResUNet\r\nfrom .model_parts import *\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass Net(nn.Module):\r\n def __init__(self, in_channels, out_channels, middle_channels=32):\r\n super(Net, self).__init__()\r\n self.in_channels = in_channels\r\n self.out_channels = out_channels\r\n\r\n # ResUNet part\r\n self.net1 = ResUNet(in_channels, middle_channels)\r\n\r\n # middle supervising part\r\n self.middle1 = nn.Sequential(\r\n nn.Conv2d(middle_channels, middle_channels, kernel_size=1, padding=0, bias=False),\r\n nn.BatchNorm2d(middle_channels),\r\n nn.ReLU(inplace=True),\r\n )\r\n self.middle2 = nn.Conv2d(middle_channels, middle_channels, kernel_size=1, padding=0, bias=False)\r\n self.middle3 = nn.Conv2d(middle_channels, out_channels, kernel_size=1, padding=0, bias=False)\r\n self.middle4 = nn.Conv2d(out_channels, middle_channels, kernel_size=1, padding=0, bias=False)\r\n\r\n # DBPNet part\r\n self.down = DownResBlock(middle_channels, middle_channels)\r\n self.net2 = DBPNet(\r\n in_channels=middle_channels, out_channels=out_channels,\r\n base_filter=64, feat=256, num_stages=7,\r\n scale_factor=2,\r\n )\r\n\r\n def forward(self, input):\r\n # ResUnet\r\n x = self.net1(input)\r\n\r\n # Middle Part\r\n x = self.middle1(x)\r\n x1 = self.middle2(x)\r\n supervisor = self.middle3(x)\r\n x2 = self.middle4(supervisor)\r\n x = x1 + x2\r\n\r\n # DBPNet\r\n x = self.down(x)\r\n x = self.net2(x)\r\n return x, supervisor\r\n","sub_path":"src/neural_network1/model/net/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"148206175","text":"from tfidf import *\nfrom filepreprocessing import *\nfrom finalData import *\nclass feedback_score:\n def __init__(self):\n self.name=\"kundan\"\n\n def getresult(self):\n tfres=tfidfcal()\n #res={}\n #res=tfres.getscore_matrix()\n final=[res1[1] for res1 in self.res]\n print(final)\n feedback=[]\n\n def recieve_feedback(self,feedbackfiles,fin):\n length=len(fin)\n bar=dict(fin)\n\n for i in range(len(feedbackfiles)):\n bar[feedbackfiles[i]]=bar[feedbackfiles[i]]+0.7\n if(len(fin)>30):\n for i in range(21,30 ):\n bar[fin[i][0]]=bar[fin[i][0]]+0.6\n sorted_by_value = sorted(bar.items(), key=lambda kv: kv[1], reverse=True)\n return sorted_by_value\n '''t={}\n i=0\n for doc in bar.keys():\n t[doc]=0.5-i*(0.5/length)\n i=i+1\n for i in range(len(feedbackfiles)):\n bar[feedbackfiles[i]]=1/2*t[feedbackfiles[i]]-1/2*0.5\n for j'''\n\n#feedbackfiles=[3947,4226]\n\n\n\n","sub_path":"feedback_score.py","file_name":"feedback_score.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"498466057","text":"#(4963) 섬의 개수\n\nimport sys\nfrom collections import deque\n\nmoves = [(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1),(0,1),(0,-1)]\n\ndef bfs(island,x,y):\n queue = deque()\n queue.append((x,y))\n island[x][y] = 0\n while queue:\n x, y = queue.popleft()\n for move in moves:\n nx = x + move[0]\n ny = y + move[1]\n if nx < 0 or ny < 0 or nx >= len(island) or ny >= len(island[0]):\n continue\n if island[nx][ny] == 1:\n island[nx][ny] = 0\n queue.append((nx,ny))\n\nwhile True :\n w, h = map(int, sys.stdin.readline().split())\n island = []\n count = 0\n if w == 0 and h == 0:\n break\n for _ in range(h):\n island.append(list(map(int, sys.stdin.readline().split())))\n\n for x in range(h):\n for y in range(w):\n if island[x][y] != 0:\n bfs(island,x,y)\n count += 1\n print(count)\n\n\n\n\n","sub_path":"code/4963.py","file_name":"4963.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"25110327","text":"# -*- coding: utf-8 -*-\n# *******************************************************\n# ____ _ _\n# / ___|___ _ __ ___ ___| |_ _ __ ___ | |\n# | | / _ \\| '_ ` _ \\ / _ \\ __| | '_ ` _ \\| |\n# | |__| (_) | | | | | | __/ |_ _| | | | | | |\n# \\____\\___/|_| |_| |_|\\___|\\__(_)_| |_| |_|_|\n#\n# Sign up for free at http://www.comet.ml\n# Copyright (C) 2015-2020 Comet ML INC\n# This file can not be copied and/or distributed without the express\n# permission of Comet ML Inc.\n# *******************************************************\n\nfrom __future__ import print_function\n\nimport io\nimport logging\nimport os\nimport os.path\n\nimport six\nfrom everett.manager import (\n NO_VALUE,\n ConfigDictEnv,\n ConfigEnvFileEnv,\n ConfigManager,\n ConfigOSEnv,\n ListOf,\n listify,\n parse_bool,\n)\n\nfrom ._typing import Any, Dict, List, Optional\nfrom .utils import log_once_at_level\n\ntry: # everett version 1.0.1 or greater\n from everett.ext.inifile import ConfigIniEnv\nexcept ImportError: # everett version 0.9 for Python 2\n from everett.manager import ConfigIniEnv as UpstreamConfigIniEnv\n\n class ConfigIniEnv(UpstreamConfigIniEnv):\n \"\"\" Backport of everett ConfigIniEnv in Python 3 that save the path when found\n \"\"\"\n\n def __init__(self, possible_paths):\n super(ConfigIniEnv, self).__init__(possible_paths)\n\n if self.cfg:\n self.path = os.path.abspath(os.path.expanduser(possible_paths.strip()))\n\n\nLOGGER = logging.getLogger(__name__)\n\nDEBUG = False\n\n# Global experiment placeholder. Should be set by the latest call of Experiment.init()\nexperiment = None\n\nDEFAULT_UPLOAD_SIZE_LIMIT = 100 * 1024 * 1024 # 100 MebiBytes\n\nDEFAULT_ASSET_UPLOAD_SIZE_LIMIT = 2500 * 1024 * 1024 # 2.5GB\n\nDEFAULT_STREAMER_MSG_TIMEOUT = 5 * 60\n\nADDITIONAL_STREAMER_UPLOAD_TIMEOUT = 10 * 60\n\n\ndef get_global_experiment():\n global experiment\n return experiment\n\n\ndef set_global_experiment(new_experiment):\n global experiment\n experiment = new_experiment\n\n\ndef parse_str_or_identity(_type):\n def parse(value):\n if not isinstance(value, str):\n return value\n\n return _type(value.strip())\n\n return parse\n\n\nclass ParseListOf(ListOf):\n \"\"\"\n Superclass to apply subparser to list items.\n \"\"\"\n\n def __init__(self, _type, _parser):\n super(ParseListOf, self).__init__(_type)\n self._type = _type\n self._parser = _parser\n\n def __call__(self, value):\n f = self._parser(self._type)\n if not isinstance(value, list):\n value = super(ParseListOf, self).__call__(value)\n return [f(v) for v in value]\n\n\nPARSER_MAP = {\n str: parse_str_or_identity(str),\n int: parse_str_or_identity(int),\n float: parse_str_or_identity(float),\n bool: parse_str_or_identity(parse_bool),\n list: ParseListOf(str, parse_str_or_identity),\n \"int_list\": ParseListOf(int, parse_str_or_identity(int)),\n}\n\n\n# Vendor generate_uppercase_key for Python 2\ndef generate_uppercase_key(key, namespace=None):\n \"\"\"Given a key and a namespace, generates a final uppercase key.\"\"\"\n if namespace:\n namespace = [part for part in listify(namespace) if part]\n key = \"_\".join(namespace + [key])\n\n key = key.upper()\n return key\n\n\nclass Config(object):\n def __init__(self, config_map):\n self.config_map = config_map\n self.override = {} # type: Dict[str, Any]\n self.backend_override = ConfigDictEnv({})\n config_override = os.environ.get(\"COMET_INI\")\n if config_override is not None:\n log_once_at_level(\n logging.WARNING, \"COMET_INI is deprecated; use COMET_CONFIG\"\n )\n else:\n config_override = os.environ.get(\"COMET_CONFIG\")\n self.manager = ConfigManager(\n [ # User-defined overrides\n ConfigOSEnv(),\n ConfigEnvFileEnv(\".env\"),\n ConfigIniEnv(config_override),\n ConfigIniEnv(\"./.comet.config\"),\n ConfigIniEnv(\"~/.comet.config\"),\n # Comet-defined overrides\n self.backend_override,\n ],\n doc=(\n \"See https://comet.ml/docs/python-sdk/getting-started/ for more \"\n + \"information on configuration.\"\n ),\n )\n\n def __setitem__(self, name, value):\n self.override[name] = value\n\n def _set_backend_override(self, cfg, namespace):\n # Reset the existing overrides\n self.backend_override.cfg = {}\n\n for key, value in cfg.items():\n namespaced_key = \"_\".join(namespace.split(\"_\") + [key])\n full_key = generate_uppercase_key(namespaced_key)\n self.backend_override.cfg[full_key] = value\n\n def keys(self):\n return self.config_map.keys()\n\n def get_raw(self, user_value, config_name, default=None, not_set_value=None):\n # type: (Any, str, Optional[Any], Optional[Any]) -> Any\n \"\"\"\n Returns the correct config value based on the following priority list:\n * User_value if set and not None\n * The override value from the Backend\n * The configured value\n * The default value passed in argument if not None\n * The configured value default\n \"\"\"\n\n # 1. User value\n if user_value is not not_set_value:\n return user_value\n\n # 2. Override\n if config_name in self.override:\n override_value = self.override[config_name]\n\n if override_value is not None:\n return override_value\n\n # 3. Configured value\n config_type = self.config_map[config_name].get(\"type\", str)\n parser = PARSER_MAP[config_type]\n\n # Value\n splitted = config_name.split(\".\")\n\n config_value = self.manager(\n splitted[-1], namespace=splitted[:-1], parser=parser, raise_error=False\n )\n\n if config_value != NO_VALUE:\n return config_value\n\n else:\n # 4. Provided default\n if default is not None:\n return default\n\n # 5. Config default\n config_default = parser(self.config_map[config_name].get(\"default\", None))\n return config_default\n\n def get_string(self, user_value, config_name, default=None, not_set_value=None):\n # type: (Any, str, Optional[str], Any) -> str\n \"\"\"\n Returns the correct config value based on the following priority list:\n * User_value if set and not None\n * The override value from the Backend\n * The configured value\n * The default value passed in argument if not None\n * The configured value default\n\n In addition make sure the returned value is a string\n \"\"\"\n\n value = self.get_raw(\n user_value=user_value,\n config_name=config_name,\n default=default,\n not_set_value=not_set_value,\n )\n\n return value\n\n def get_bool(self, user_value, config_name, default=None, not_set_value=None):\n # type: (Any, str, Optional[bool], Any) -> bool\n \"\"\"\n Returns the correct config value based on the following priority list:\n * User_value if set and not None\n * The override value from the Backend\n * The configured value\n * The default value passed in argument if not None\n * The configured value default\n\n In addition make sure the returned value is a bool\n \"\"\"\n\n value = self.get_raw(\n user_value=user_value,\n config_name=config_name,\n default=default,\n not_set_value=not_set_value,\n )\n\n return value\n\n def get_int(self, user_value, config_name, default=None, not_set_value=None):\n # type: (Any, str, Optional[int], int) -> bool\n \"\"\"\n Returns the correct config value based on the following priority list:\n * User_value if set and not None\n * The override value from the Backend\n * The configured value\n * The default value passed in argument if not None\n * The configured value default\n\n In addition make sure the returned value is an int\n \"\"\"\n\n value = self.get_raw(\n user_value=user_value,\n config_name=config_name,\n default=default,\n not_set_value=not_set_value,\n )\n\n return value\n\n def get_int_list(self, user_value, config_name, default=None, not_set_value=None):\n # type: (Any, str, Optional[int], int) -> List[int]\n \"\"\"\n Returns the correct config value based on the following priority list:\n * User_value if set and not None\n * The override value from the Backend\n * The configured value\n * The default value passed in argument if not None\n * The configured value default\n\n In addition make sure the returned value is a list of int\n \"\"\"\n\n value = self.get_raw(\n user_value=user_value,\n config_name=config_name,\n default=default,\n not_set_value=not_set_value,\n )\n\n return value\n\n def get_string_list(\n self, user_value, config_name, default=None, not_set_value=None\n ):\n # type: (Any, str, Optional[int], int) -> List[str]\n \"\"\"\n Returns the correct config value based on the following priority list:\n * User_value if set and not None\n * The override value from the Backend\n * The configured value\n * The default value passed in argument if not None\n * The configured value default\n\n In addition make sure the returned value is a list of str\n \"\"\"\n\n value = self.get_raw(\n user_value=user_value,\n config_name=config_name,\n default=default,\n not_set_value=not_set_value,\n )\n\n return value\n\n def get_deprecated_raw(\n self,\n old_user_value,\n old_config_name,\n new_user_value,\n new_config_name,\n new_not_set_value=None,\n ):\n # type: (Any, str, Any, str, Any) -> Any\n \"\"\"\n Returns the correct value for deprecated config values:\n * New user value\n * Old user value\n * New config value\n * Old config value\n * New config default\n\n Note: The old config default is not used and should be set to None\n \"\"\"\n old_config_value = self.get_raw(None, old_config_name, default=NO_VALUE)\n\n if new_user_value is not new_not_set_value:\n if old_user_value:\n LOGGER.warning(\n \"Deprecated config key %r was set, but ignored as new config key %r is set\",\n old_config_name,\n new_config_name,\n )\n elif old_config_value:\n LOGGER.warning(\n \"Deprecated config key %r was set in %r, but ignored as new config key %r is set\",\n old_config_name,\n self.get_config_origin(old_config_name),\n new_config_name,\n )\n return new_user_value\n\n # Deprecated parameter default value must be None\n if old_user_value is not None:\n LOGGER.warning(\n \"Config key %r is deprecated, please use %r instead\",\n old_config_name,\n new_config_name,\n )\n return old_user_value\n\n new_config_value = self.get_raw(None, new_config_name, default=NO_VALUE)\n if new_config_value is not NO_VALUE:\n return new_config_value\n\n old_config_value = self.get_raw(None, old_config_name, default=NO_VALUE)\n if old_config_value is not NO_VALUE:\n LOGGER.warning(\n \"Config key %r is deprecated (was set in %r), please use %r instead\",\n old_config_name,\n self.get_config_origin(old_config_name),\n new_config_name,\n )\n return old_config_value\n\n config_type = self.config_map[new_config_name].get(\"type\", str)\n parser = PARSER_MAP[config_type]\n return parser(self.config_map[new_config_name].get(\"default\", None))\n\n def get_deprecated_bool(\n self,\n old_user_value,\n old_config_name,\n new_user_value,\n new_config_name,\n new_not_set_value=None,\n ):\n # type: (Any, str, Any, str, bool) -> bool\n \"\"\"\n Returns the correct value for deprecated config values:\n * New user value\n * Old user value\n * New config value\n * Old config value\n * New config default\n\n Note: The old config default is not used and should be set to None\n \"\"\"\n value = self.get_deprecated_raw(\n old_user_value,\n old_config_name,\n new_user_value,\n new_config_name,\n new_not_set_value=new_not_set_value,\n )\n\n return value\n\n def get_subsections(self):\n \"\"\"\n Return the subsection config names.\n \"\"\"\n sections = set()\n for key in self.keys():\n parts = key.split(\".\", 2)\n if len(parts) == 3:\n sections.add(parts[1])\n return sections\n\n def __getitem__(self, name):\n # type: (str) -> Any\n # Config\n config_type = self.config_map[name].get(\"type\", str)\n parser = PARSER_MAP[config_type]\n config_default = self.config_map[name].get(\"default\", None)\n\n if name in self.override:\n return self.override[name]\n\n # Value\n splitted = name.split(\".\")\n\n value = self.manager(\n splitted[-1], namespace=splitted[:-1], parser=parser, raise_error=False\n )\n\n if value == NO_VALUE:\n return parser(config_default)\n\n return value\n\n def display(self, display_all=False):\n \"\"\"\n Show the Comet config variables and values.\n \"\"\"\n n = 1\n print(\"=\" * 65)\n print(\"Comet config variables and values, in order of preference:\")\n print(\" %d) Operating System Variable\" % n)\n n += 1\n for path in [\"./.env\", \"~/.comet.config\", \"./.comet.config\"]:\n path = os.path.abspath(os.path.expanduser(path))\n if os.path.exists(path):\n print(\" %d) %s\" % (n, path))\n n += 1\n print(\"=\" * 65)\n print(\"Settings:\\n\")\n last_section = None\n for section, setting in sorted(\n [key.rsplit(\".\", 1) for key in self.config_map.keys()]\n ):\n key = \"%s.%s\" % (section, setting)\n value = self[key]\n if \".\" in section:\n section = section.replace(\".\", \"_\")\n if value is None:\n value = \"...\"\n default_value = self.config_map[key].get(\"default\", None)\n if value == default_value or value == \"...\":\n if display_all:\n if section != last_section:\n if last_section is not None:\n print() # break between sections\n print(\"[%s]\" % section)\n last_section = section\n print(\"%s = %s\" % (setting, value))\n else:\n if section != last_section:\n if last_section is not None:\n print(\"\") # break between sections\n print(\"[%s]\" % section)\n last_section = section\n print(\"%s = %s\" % (setting, value))\n print(\"=\" * 65)\n\n def save(self, directory=\"./\", save_all=False, **kwargs):\n \"\"\"\n Save the settings to .comet.config (default) or\n other path/filename. Defaults are commented out.\n\n Args:\n directory: the path to save the .comet.config config settings.\n save_all: save unset variables with defaults too\n kwargs: key=value pairs to save\n \"\"\"\n directory = os.path.expanduser(directory)\n filename = os.path.abspath(os.path.join(directory, \".comet.config\"))\n print('Saving config to \"%s\"...' % filename, end=\"\")\n with io.open(filename, \"w\", encoding=\"utf-8\") as ini_file:\n ini_file.write(six.u(\"# Config file for Comet.ml\\n\"))\n ini_file.write(\n six.u(\n \"# For help see https://www.comet.ml/docs/python-sdk/getting-started/\\n\"\n )\n )\n last_section = None\n for section, setting in sorted(\n [key.rsplit(\".\", 1) for key in self.config_map.keys()]\n ):\n key = \"%s.%s\" % (section, setting)\n key_arg = \"%s_%s\" % (section, setting)\n if key_arg in kwargs:\n value = kwargs[key_arg]\n del kwargs[key_arg]\n elif key_arg.upper() in kwargs:\n value = kwargs[key_arg.upper()]\n del kwargs[key_arg.upper()]\n else:\n value = self[key]\n if len(kwargs) != 0:\n raise ValueError(\n \"'%s' is not a valid config key\" % list(kwargs.keys())[0]\n )\n if \".\" in section:\n section = section.replace(\".\", \"_\")\n if value is None:\n value = \"...\"\n default_value = self.config_map[key].get(\"default\", None)\n LOGGER.debug(\"default value for %s is %s\", key, default_value)\n if value == default_value or value == \"...\":\n # It is a default value\n # Only save it, if save_all is True:\n if save_all:\n if section != last_section:\n if section is not None:\n ini_file.write(six.u(\"\\n\")) # break between sections\n ini_file.write(six.u(\"[%s]\\n\" % section))\n last_section = section\n if isinstance(value, list):\n value = \",\".join(value)\n ini_file.write(six.u(\"# %s = %s\\n\" % (setting, value)))\n else:\n # Not a default value; write it out:\n if section != last_section:\n if section is not None:\n ini_file.write(six.u(\"\\n\")) # break between sections\n ini_file.write(six.u(\"[%s]\\n\" % section))\n last_section = section\n if isinstance(value, list):\n value = \",\".join([str(v) for v in value])\n ini_file.write(six.u(\"%s = %s\\n\" % (setting, value)))\n print(\" done!\")\n\n def get_config_origin(self, name):\n # type: (str) -> Optional[str]\n splitted = name.split(\".\")\n\n for env in self.manager.envs:\n value = env.get(splitted[-1], namespace=splitted[:-1])\n\n if value != NO_VALUE:\n return env\n\n return None\n\n\nCONFIG_MAP = {\n \"comet.disable_auto_logging\": {\"type\": int, \"default\": 0},\n \"comet.api_key\": {\"type\": str},\n \"comet.rest_api_key\": {\"type\": str},\n \"comet.offline_directory\": {\"type\": str},\n \"comet.git_directory\": {\"type\": str},\n \"comet.offline_sampling_size\": {\"type\": int, \"default\": 15000},\n \"comet.url_override\": {\"type\": str, \"default\": \"https://www.comet.ml/clientlib/\"},\n \"comet.optimizer_url\": {\"type\": str, \"default\": \"https://optimizer.comet.ml\"},\n \"comet.ws_url_override\": {\"type\": str, \"default\": None},\n \"comet.predictor_url\": {\"type\": str, \"default\": \"https://predictor.comet.ml/\"},\n \"comet.experiment_key\": {\"type\": str},\n \"comet.project_name\": {\"type\": str},\n \"comet.workspace\": {\"type\": str},\n \"comet.display_summary_level\": {\"type\": int, \"default\": 1},\n # Logging\n \"comet.logging.file\": {\"type\": str},\n \"comet.logging.file_level\": {\"type\": str, \"default\": \"INFO\"},\n \"comet.logging.file_overwrite\": {\"type\": bool, \"default\": False},\n \"comet.logging.console\": {\"type\": str},\n \"comet.logging.metrics_ignore\": {\n \"type\": list,\n \"default\": \"keras:batch_size,keras:batch_batch\",\n },\n \"comet.logging.parameters_ignore\": {\n \"type\": list,\n \"default\": \"keras:verbose,keras:do_validation,keras:validation_steps\",\n },\n \"comet.logging.others_ignore\": {\"type\": list, \"default\": \"\"},\n \"comet.logging.env_blacklist\": {\n \"type\": list,\n \"default\": \"api_key,apikey,authorization,passwd,password,secret,token,comet\",\n },\n # Timeout, unit is seconds\n \"comet.timeout.cleaning\": {\"type\": int, \"default\": DEFAULT_STREAMER_MSG_TIMEOUT},\n \"comet.timeout.upload\": {\n \"type\": int,\n \"default\": ADDITIONAL_STREAMER_UPLOAD_TIMEOUT,\n },\n \"comet.timeout.http\": {\"type\": int, \"default\": 10},\n \"comet.timeout.api\": {\"type\": int, \"default\": 10},\n \"comet.timeout.file_upload\": {\"type\": int, \"default\": 900},\n \"comet.timeout.file_download\": {\"type\": int, \"default\": 600},\n \"comet.timeout.predictor\": {\"type\": int, \"default\": 60},\n # HTTP Allow header\n \"comet.allow_header.name\": {\"type\": str},\n \"comet.allow_header.value\": {\"type\": str},\n # Backend minimal rest V2 version\n \"comet.rest_v2_minimal_backend_version\": {\"type\": str, \"default\": \"1.2.78\"},\n # Feature flags\n \"comet.override_feature.sdk_http_logging\": {\n \"type\": bool\n }, # Leave feature toggle default to None\n \"comet.override_feature.use_http_messages\": {\n \"type\": bool\n }, # Leave feature toggle default to None\n \"comet.override_feature.sdk_log_env_variables\": {\n \"type\": bool\n }, # Leave feature toggle default to None\n # Experiment log controls:\n \"comet.auto_log.cli_arguments\": {\"type\": bool},\n \"comet.auto_log.code\": {\"type\": bool},\n \"comet.auto_log.disable\": {\"type\": bool},\n \"comet.auto_log.env_cpu\": {\"type\": bool},\n \"comet.auto_log.env_details\": {\"type\": bool},\n \"comet.auto_log.env_gpu\": {\"type\": bool},\n \"comet.auto_log.env_host\": {\"type\": bool},\n \"comet.auto_log.git_metadata\": {\"type\": bool},\n \"comet.auto_log.git_patch\": {\"type\": bool},\n \"comet.auto_log.graph\": {\"type\": bool},\n \"comet.auto_log.metrics\": {\"type\": bool},\n \"comet.auto_log.figures\": {\"type\": bool, \"default\": True},\n \"comet.auto_log.output_logger\": {\"type\": str},\n \"comet.auto_log.parameters\": {\"type\": bool},\n \"comet.auto_log.histogram_tensorboard\": {\"type\": bool, \"default\": False},\n \"comet.auto_log.histogram_epoch_rate\": {\"type\": int, \"default\": 1},\n \"comet.auto_log.histogram_weights\": {\"type\": bool, \"default\": False},\n \"comet.auto_log.histogram_gradients\": {\"type\": bool, \"default\": False},\n \"comet.auto_log.histogram_activations\": {\"type\": bool, \"default\": False},\n \"comet.keras.histogram_name_prefix\": {\n \"type\": str,\n \"default\": \"{layer_num:0{max_digits}d}\",\n },\n \"comet.keras.histogram_activation_index_list\": {\"type\": \"int_list\", \"default\": \"0\"},\n \"comet.keras.histogram_activation_layer_list\": {\"type\": list, \"default\": \"-1\"},\n \"comet.keras.histogram_batch_size\": {\"type\": int, \"default\": 1000},\n \"comet.keras.histogram_gradient_index_list\": {\"type\": \"int_list\", \"default\": \"0\"},\n \"comet.keras.histogram_gradient_layer_list\": {\"type\": list, \"default\": \"-1\"},\n \"comet.auto_log.metric_step_rate\": {\"type\": int, \"default\": 10},\n \"comet.auto_log.co2\": {\"type\": bool},\n \"comet.auto_log.tfma\": {\"type\": bool, \"default\": False},\n # Internals:\n \"comet.internal.reporting\": {\"type\": bool, \"default\": True},\n # Deprecated:\n \"comet.display_summary\": {\"type\": bool, \"default\": None},\n \"comet.auto_log.weights\": {\"type\": bool, \"default\": None},\n}\n\n\ndef get_config(setting=None):\n # type: (Any) -> Config\n \"\"\"\n Get a config or setting from the current config\n (os.environment or .env file).\n\n Note: this is not cached, so every time we call it, it\n re-reads the file. This makes these values always up to date\n at the expense of re-getting the data.\n \"\"\"\n cfg = Config(CONFIG_MAP)\n if setting is None:\n return cfg\n else:\n return cfg[setting]\n\n\ndef get_api_key(api_key, config):\n if api_key is None:\n return config[\"comet.api_key\"]\n else:\n return api_key\n\n\ndef get_display_summary_level(display_summary_level, config):\n if display_summary_level is None:\n return config[\"comet.display_summary_level\"]\n else:\n try:\n return int(display_summary_level)\n except Exception:\n LOGGER.warning(\n \"invalid display_summary_level %r; ignoring\", display_summary_level\n )\n return 1\n\n\ndef get_ws_url(ws_server_from_backend, config):\n \"\"\" Allow users to override the WS url from the backend using the usual\n config mechanism\n \"\"\"\n ws_server_from_config = config[\"comet.ws_url_override\"]\n if ws_server_from_config is None:\n return ws_server_from_backend\n else:\n return ws_server_from_config\n\n\ndef get_previous_experiment(previous_experiment, config):\n if previous_experiment is None:\n return config[\"comet.experiment_key\"]\n else:\n return previous_experiment\n\n\ndef save(directory=\"~/\", save_all=False, **settings):\n \"\"\"\n An easy way to create a config file.\n\n Args:\n directory: str (optional), location to save the\n .comet.config file. Typical values are \"~/\" (home)\n and \"./\" (current directory). Default is \"~/\"\n save_all: bool (optional). If True, will create\n entries for all items that are configurable\n with their defaults. Default is False\n settings: any valid setting and value\n\n Valid settings include:\n\n * api_key\n * disable_auto_logging\n * experiment_key\n * offline_directory\n * workspace\n * project_name\n * logging_console\n * logging_file\n * logging_file_level\n * logging_file_overwrite\n * timeout_cleaning\n * timeout_upload\n\n Examples:\n\n >>> import comet_ml\n >>> comet_ml.config.save(api_key=\"...\")\n >>> comet_ml.config.save(api_key=\"...\", directory=\"./\")\n \"\"\"\n cfg = get_config()\n subsections = cfg.get_subsections()\n for setting in settings:\n # Correct the keys:\n key = None\n for prefix in subsections:\n if setting.startswith(prefix + \"_\"):\n key = (\"comet.%s.\" % prefix) + setting[len(prefix) + 1 :]\n break\n if key is None:\n key = \"comet.\" + setting\n cfg[key] = settings[setting]\n cfg.save(directory, save_all=save_all)\n","sub_path":"venv/Lib/site-packages/comet_ml/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":26880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"523714455","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 ('members', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='communitymember',\n name='is_active',\n field=models.BooleanField(default=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='communitymember',\n name='username',\n field=models.CharField(default='testusername', unique=True, max_length=80),\n preserve_default=False,\n ),\n ]\n","sub_path":"neighborhoodnet/apps/members/migrations/0002_auto_20141110_1644.py","file_name":"0002_auto_20141110_1644.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"229558795","text":"# 45. 動詞の格パターンの抽出\n# 今回用いている文章をコーパスと見なし,日本語の述語が取りうる格を調査したい.\n# 動詞を述語,動詞に係っている文節の助詞を格と考え,述語と格をタブ区切り形式で出力せよ.\n# ただし,出力は以下の仕様を満たすようにせよ.\n# 動詞を含む文節において,最左の動詞の基本形を述語とする\n# 述語に係る助詞を格とする\n# 述語に係る助詞(文節)が複数あるときは,すべての助詞をスペース区切りで辞書順に並べる\n\nfrom knock41 import getdata\n\nif __name__ == \"__main__\":\n cabocha_file_path = \"ai.ja.split.txt.parsed\"\n document = getdata(cabocha_file_path)\n for sentence in document:\n for chunk in sentence:\n verb = \"\"\n for morph in chunk.morphs:\n if morph.pos == \"動詞\":\n verb = morph.base\n break # 最左のものを述語とするためにbreakする\n if verb == \"\":\n continue\n particles = []\n for src in chunk.srcs:\n for morph in sentence[src].morphs:\n if morph.pos == \"助詞\":\n particles.append(morph.base)\n particles = sorted(particles)\n particles = \" \".join(particles)\n print(f\"{verb}\\t{particles}\")","sub_path":"koyama/chapter05/knock45.py","file_name":"knock45.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"576193244","text":"from xml.dom import minidom\nimport os\nimport multiprocessing.dummy as mpd\nfrom functools import partial\nfrom collections import namedtuple\nimport glob\n\nfrom resize_images import main as ChangeImageSize\ndef ChangeXmlSize(filename, newHeight, newWidth):\n try:\n mydoc = minidom.parse(filename)\n except:\n print('empty file %s'% filename)\n return\n\n items = mydoc.getElementsByTagName('size')\n size_prop=items[0]\n ## GET_UPDATEe SIZE\n width_prop = size_prop.getElementsByTagName('width')[0]\n height_prop = size_prop.getElementsByTagName('height')[0]\n\n\n img_width = int(width_prop.firstChild.nodeValue)\n img_height = int(height_prop.firstChild.nodeValue)\n\n if(img_width==0 or img_height==0):\n print('bad size in %s'% filename)\n return\n\n width_prop.firstChild.nodeValue = str(newWidth)\n height_prop.firstChild.nodeValue = str(newHeight)\n items = mydoc.getElementsByTagName('object')\n \n\n for elem in items:\n bbox = elem.getElementsByTagName('bndbox')\n bbox=bbox[0]\n \n bbox.childNodes[ 1 ].firstChild.nodeValue = str(int( int(bbox.childNodes[ 1 ].firstChild.nodeValue) * newWidth/img_width))\n bbox.childNodes[ 3 ].firstChild.nodeValue = str(int( int(bbox.childNodes[ 3 ].firstChild.nodeValue) * newHeight/img_height))\n bbox.childNodes[ 5 ].firstChild.nodeValue = str(int( int(bbox.childNodes[ 5 ].firstChild.nodeValue) * newWidth/img_width))\n bbox.childNodes[ 7 ].firstChild.nodeValue = str(int( int(bbox.childNodes[ 7 ].firstChild.nodeValue) * newHeight/img_height))\n\n with open(filename, 'w') as out_file:\n mydoc.writexml(out_file)\n\ndef ChangeImageSizeWrapper(h, w, in_folder, out_folder):\n chngsize_args = namedtuple('Argument', 'raw_dir save_dir in_ext out_ext target_size')\n args = chngsize_args(in_folder, out_folder, \"jpg,png\", \"jpg\", f\"({w},{h})\")\n ChangeImageSize(args)\n\nif __name__ == \"__main__\":\n \n data_folder = \"data/VOC2007\"\n xml_folder = os.path.join(data_folder,'Annotations')\n in_folder = os.path.join(data_folder,\"JPEGImages_raw\")\n out_folder = os.path.join(data_folder,\"JPEGImages\")\n newHeight=400\n newWidth=1000\n\n\n #ChangeImageSizeWrapper(newHeight, newWidth, in_folder,out_folder)\n\n filenames = glob.glob(os.path.join(xml_folder, \"*.xml\" ) ) \n\n with mpd.Pool() as pool:\n pool.map(partial(ChangeXmlSize, newHeight=newHeight, newWidth=newWidth), filenames)","sub_path":"redo_xml.py","file_name":"redo_xml.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"585321007","text":"import os\r\nimport time\r\nimport shutil\r\nimport exifread\r\nfrom tkinter import messagebox as mb\r\nfrom PIL import Image as pimg\r\n\r\nclass Image():\r\n\r\n def __init__(self, directive, name):\r\n self.directive = directive\r\n self.name = name\r\n\r\n self.format = str()\r\n self.cdate = str()\r\n self.alldir = self.directive + '/' + self.name\r\n self.a = 0\r\n self.b = 0\r\n if not os.path.isdir(self.directive + '/' + self.name):\r\n self.getformat()\r\n self.getcdate()\r\n self.getab()\r\n\r\n def getformat(self):\r\n xi = -1\r\n while self.name[xi] != '.' and self.name:\r\n xi = xi-1\r\n self.format = self.name[xi:].lower()\r\n\r\n\r\n def getcdate(self):\r\n if self.format.lower() == '.jpg' or self.format.lower() == '.tiff' or self.format.lower() == '.jpeg':\r\n a = open(self.directive + '/' + self.name, 'rb')\r\n tags = exifread.process_file(a)\r\n print(tags)\r\n if 'Image DateTime' in tags:\r\n s = str(tags['Image DateTime'])\r\n else:\r\n s = '0000.00.00 00.00.00'\r\n else:\r\n a1 = time.ctime(os.path.getctime(self.directive +'/'+ self.name))\r\n s = a1[-4:] + ':'\r\n if a1[4:7] == 'Jan':\r\n s = s + '01.'\r\n elif a1[4:7] == 'Feb':\r\n s = s + '02.'\r\n elif a1[4:7] == 'Mar':\r\n s = s + '04.'\r\n elif a1[4:7] == 'Apr':\r\n s = s + '04.'\r\n elif a1[4:7] == 'May':\r\n s = s + '05.'\r\n elif a1[4:7] == 'Jun':\r\n s = s + '06.'\r\n elif a1[4:7] == 'Jul':\r\n s = s + '07.'\r\n elif a1[4:7] == 'Aug':\r\n s = s + '08.'\r\n elif a1[4:7] == 'Sep':\r\n s = s + '09:'\r\n elif a1[4:7] == 'Oct':\r\n s = s + '10:'\r\n elif a1[4:7] == 'Nov':\r\n s = s + '11:'\r\n elif a1[4:7] == 'Dec':\r\n s = s + '12:'\r\n s = s + a1[8:10] + ' ' + a1[11:19]\r\n for i in range(len(s)):\r\n if s[i] == ':':\r\n self.cdate = self.cdate + '.'\r\n else:\r\n self.cdate = self.cdate + s[i]\r\n def getab(self):\r\n im = pimg.open(self.directive + '/' + self.name)\r\n (self.a, self.b) = im.size\r\n im.close()\r\n\r\nglobal form\r\nform = ['.jpeg', '.jpg', '.png', '.bmp','.raw','.gif','.ico','.tiff']\r\n\r\ndef check_img(name):\r\n xi = -1\r\n while name[xi] != '.' and name:\r\n xi = xi - 1\r\n for i in range(8):\r\n if name[xi:].lower() == form[i]:\r\n return True\r\n\r\n\r\n\r\n# -----------------------Сортировка по дате(год-месяц-день-час)--------------------------------\r\ndef sort_date(dir, n, root, root1):\r\n files = os.listdir(dir)\r\n if n == 4:\r\n s = ' годам'\r\n elif n == 7:\r\n s = ' месяцам'\r\n elif n == 10:\r\n s = ' дням'\r\n elif n == 13:\r\n s = ' часам'\r\n \r\n if not (os.path.exists(dir + '/' + 'Сортировка по' + s)):\r\n os.mkdir(dir + '/' + 'Сортировка по' + s)\r\n dir1 = dir + '/' + 'Сортировка по' + s\r\n\r\n for x in files:\r\n if not os.path.isdir(dir + '/' + x):\r\n sort_date_move(dir + '/' + x, s, n, dir1)\r\n mb.showinfo('Выполнено', 'Каталогизация выполнена')\r\n root1.destroy()\r\n root.deiconify()\r\n\r\ndef sort_date_move(img, s, n, dir1):\r\n diri, namei = os.path.split(img)\r\n if check_img(namei) == True:\r\n img1 = Image(diri, namei)\r\n if os.path.exists(dir1 + '/' + img1.cdate[:n]):\r\n if not os.path.exists(dir1 + '/' + img1.cdate[:n] + '/' + img1.name):\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + img1.cdate[:n])\r\n else:\r\n os.remove(img1.directive + '/' + img1.name)\r\n else:\r\n os.mkdir(dir1 + '/' + img1.cdate[:n])\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + img1.cdate[:n])\r\n\r\n\r\n# ----------------Сортировка по формату---------------------------------------------------------------------\r\ndef sort_format(dir, root, root1):\r\n files = os.listdir(dir)\r\n os.chdir(dir)\r\n if not(os.path.exists(dir + '/' + 'Сортировка по формату')):\r\n os.mkdir('Сортировка по формату')\r\n dir1 = dir + '/' + 'Сортировка по формату'\r\n for x in files:\r\n if not os.path.isdir(dir + '/' + x):\r\n sort_format_move(dir + '/' + x, dir1)\r\n\r\n mb.showinfo('Выполнено', 'Каталогизация выполнена')\r\n root1.destroy()\r\n root.deiconify()\r\n\r\ndef sort_format_move(img, dir1):\r\n diri, namei = os.path.split(img)\r\n if check_img(namei) == True:\r\n img1 = Image(diri, namei)\r\n if img1.format == '.jpg' or img1.format == '.jpeg':\r\n if os.path.exists(dir1 + '/' + 'JPEG'):\r\n if not(os.path.exists(dir1 + '/' + 'JPEG' + '/' + img1.name)):\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'JPEG')\r\n else:\r\n os.remove(img1.directive + '/' + img1.name)\r\n else:\r\n os.mkdir(dir1 + '/' + 'JPEG')\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'JPEG')\r\n\r\n elif img1.format == '.png':\r\n if os.path.exists(dir1 + '/' + 'PNG'):\r\n if not(os.path.exists(dir1 + '/' + 'PNG' + '/' + img1.name)):\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'PNG')\r\n else:\r\n os.remove(img1.directive + '/' + img1.name)\r\n else:\r\n os.mkdir(dir1 + '/' + 'PNG')\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'PNG')\r\n\r\n elif img1.format == '.tiff':\r\n if os.path.exists(dir1 + '/' + 'TIFF'):\r\n if not(os.path.exists(dir1 + '/' + 'TIFF' + '/' + img1.name)):\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'TIFF')\r\n else:\r\n os.remove(img1.directive + '/' + img1.name)\r\n else:\r\n os.mkdir(dir1 + '/' + 'TIFF')\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'TIFF')\r\n\r\n elif img1.format == '.bmp':\r\n if os.path.exists(dir1 + '/' + 'BMP'):\r\n if not(os.path.exists(dir1 + '/' + 'BMP' + '/' + img1.name)):\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'BMP')\r\n else:\r\n os.remove(img1.directive + '/' + img1.name)\r\n else:\r\n os.mkdir(dir1 + '/' + 'BMP')\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'BMP')\r\n\r\n elif img1.format == '.ico':\r\n if os.path.exists(dir1 + '/' + 'ICO'):\r\n if not(os.path.exists(dir1 + '/' + 'ICO' + '/' + img1.name)):\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'ICO')\r\n else:\r\n os.remove(img1.directive + '/' + img1.name)\r\n else:\r\n os.mkdir(dir1 + '/' + 'ICO')\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'ICO')\r\n elif img1.format == '.raw':\r\n if os.path.exists(dir1 + '/' + 'RAW'):\r\n if not(os.path.exists(dir1 + '/' + 'RAW' + '/' + img1.name)):\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'RAW')\r\n else:\r\n os.remove(img1.directive + '/' + img1.name)\r\n else:\r\n os.mkdir(dir1 + '/' + 'RAW')\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'RAW')\r\n\r\n elif img1.format == '.gif':\r\n if os.path.exists(dir1 + '/' + 'GIF'):\r\n if not(os.path.exists(dir1 + '/' + 'GIF' + '/' + img1.name)):\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'GIF')\r\n else:\r\n os.remove(img1.directive + '/' + img1.name)\r\n else:\r\n os.mkdir(dir1 + '/' + 'GIF')\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + 'GIF')\r\n\r\n#--------------------Сортировка по разрешению---------------------------------\r\ndef sort_ab(dir, root, root1):\r\n files = os.listdir(dir)\r\n if not (os.path.exists(dir + '/' + 'Сортировка по разрешению')):\r\n os.mkdir(dir + '/' + 'Сортировка по разрешению')\r\n dir1 = dir + '/' + 'Сортировка по разрешению'\r\n\r\n for x in files:\r\n if not os.path.isdir(dir + '/' + x):\r\n sort_ab_move(dir + '/' + x, dir1)\r\n mb.showinfo('Выполнено', 'Каталогизация выполнена')\r\n root1.destroy()\r\n root.deiconify()\r\n\r\n\r\ndef sort_ab_move(img, dir1):\r\n diri, namei = os.path.split(img)\r\n if check_img(namei) == True:\r\n img1 = Image(diri, namei)\r\n if os.path.exists(dir1 + '/' + str(img1.a) + 'x' + str(img1.b)):\r\n if not os.path.exists(dir1 + '/' + str(img1.a) + 'x' + str(img1.b) + '/' + img1.name):\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + str(img1.a) + 'x' + str(img1.b))\r\n else:\r\n os.remove(img1.directive + '/' + img1.name)\r\n else:\r\n os.mkdir(dir1 + '/' + str(img1.a) + 'x' + str(img1.b))\r\n shutil.move(img1.directive + '/' + img1.name, dir1 + '/' + str(img1.a) + 'x' + str(img1.b))\r\n\r\n#--------------Сортировка по ориентации------------------------------------\r\ndef sort_orient(dir, root, root1):\r\n files = os.listdir(dir)\r\n if not (os.path.exists(dir + '/' + 'Сортировка по ориентации')):\r\n os.mkdir(dir + '/' + 'Сортировка по ориентации')\r\n dir1 = dir + '/' + 'Сортировка по ориентации'\r\n\r\n for x in files:\r\n if not os.path.isdir(dir + '/' + x):\r\n sort_orient_move(dir + '/' + x, dir1)\r\n mb.showinfo('Выполнено', 'Каталогизация выполнена')\r\n root1.destroy()\r\n root.deiconify()\r\n\r\n\r\ndef sort_orient_move(img, dir1):\r\n diri, namei = os.path.split(img)\r\n if check_img(namei) == True:\r\n img1 = Image(diri, namei)\r\n if img1.a>img1.b:\r\n s = 'Горизонтальная'\r\n elif img1.a0:\n print(\"Player 1 Wins!\")\n else:\n print(\"Player 2 Wins!\")\n \n\n\ndef main():\n if(len(sys.argv)) != 3:\n print(\"Usage: python3 GameDriver.py \")\n exit(1)\n game = GameDriver(sys.argv[1], sys.argv[2], 4, 4)\n game.run();\n return 0\n\n\nmain()\n","sub_path":"CS331-Assignment2/GameDriver.py","file_name":"GameDriver.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"256093175","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.colors as col\nimport math\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n#import string\n\nINTP_METHODS = [\"bilinear\", \"bicubic\"]\nCOLOR_SPECTRUMS = [\"rainbow\", \"gray\", \"BuGn\"]\nFILE_NAMES = [ \"aug_6_temp\",\"Aug-2016-meridional-current-181x189\", \"Aug-2016-potential-temperature-180x188\", \"Aug-2016-salinity-180x188\", \"Aug-2016-tropical-heat-potential-180x188\", \"Aug-2016-zonal-current-181x189\" ]\n\n\ncdict_gray = {'red': ((0.0, 0.0, 0.0),\n (1.0, 1.0, 1.0)),\n\n 'green': ((0.0, 0.0, 0.0),\n (1.0, 1.0, 1.0)),\n\n 'blue': ((0.0, 0.0, 0.0),\n (1.0, 1.0, 1.0))\n }\n\t\t\ncdict_BuGn = {'green': ((0.0, 0.0, 1.0),\n (1.0, 0.0, 0.0)),\n\n 'red': ((0.0, 0.0, 0.0),\n (1.0, 0.0, 0.0)),\n\n 'blue': ((0.0, 0.0, 0.0),\n (1.0, 1.0, 1.0))\n }\n\ncdict_rainbow = {'red': ((0.0, 0.0, 1.0),\n (0.2, 1.0, 1.0),\n\t\t\t\t (0.4, 0.0, 0.0),\n\t\t\t\t (0.6, 0.0, 0.0),\n\t\t\t\t (0.8, 0.0, 0.0),\n (1.0, 1.0, 0.0)),\n\n 'green': ((0.0, 0.0, 0.0),\n (0.2, 1.0, 1.0),\n\t\t\t\t (0.4, 1.0, 1.0),\n\t\t\t\t (0.6, 1.0, 1.0),\n\t\t\t\t (0.8, 0.0, 0.0),\n (1.0, 0.0, 1.0)),\n \n 'blue': ((0.0, 0.0, 0.0),\n (0.2, 0.0, 0.0),\n\t\t\t\t (0.4, 0.0, 0.0),\n\t\t\t\t (0.6, 1.0, 1.0),\n\t\t\t\t (0.8, 1.0, 1.0),\n (1.0, 1.0, 1.0)),\n }\n\t\t\n\t\t\nBAD_FLAG_KEY = \"BAD FLAG\"\nfolder_path = '../dataset'\nfile_name = FILE_NAMES[0]\nfile_path = folder_path + \"/\" + file_name + \".txt\"\n\ndef get_bad_flag( BAD_FLAG_KEY, file_path ):\n\tbad_flag = \"NA\"\n\tfile = open( file_path )\n\tfor line in file:\n\t\tif BAD_FLAG_KEY in line:\n\t\t\tflag = line.split(\":\")[1]\n\t\t\tbad_flag = flag.strip()\n\t\t\tbreak\n\tfile.close()\n\treturn bad_flag\n\t\ndef get_lines_to_skip( file_path ):\n\tbad_flag = \"NA\"\n\ti=0\n\tfile = open( file_path )\n\tfor line in file:\n\t\tsplit = line.split(\":\")\n\t\tif len(split) < 2 : \n\t\t\tbreak\n\t\ti = i + 1\n\tfile.close()\n\treturn i\n\ndef read_file( file_path, lines_to_skip, bad_flag ) :\n return pd.read_csv (file_path, skiprows=lines_to_skip, sep='\\t', na_values=[bad_flag])\n\ndef mask_array( array, mask_value ):\n\treturn np.ma.masked_equal(data, mask_value )\n\ndef format_latitudes( latitudes ):\n for i in range(len(latitudes)):\n if 'N' in latitudes[i]:\n latitudes[i] = float( str(latitudes[i]).replace(\"N\", \"\" ) )\n elif 'S' in latitudes[i] :\n latitudes[i] = float( \"-\" + str(latitudes[i]).replace(\"S\",\"\") )\n\ndef format_longitudes( longitudes ):\n for i in range(len(longitudes)):\n if 'E' in longitudes[i]:\n longitudes[i] = float( str(longitudes[i]).replace(\"E\",\"\") )\n elif 'W' in longitudes[i]:\n longitudes[i] = float( \"-\" + str(longitudes[i]).replace(\"W\",\"\") )\n\ndef perforn_bilinear_interpolation( array ):\n\tbint_arr = []\n\tfor i in range( len(array) - 1 ):\n\t\tbint_arr.append([])\n\t\tfor j in range( len(array[0]) - 1 ):\n\t\t\tx1 = i\n\t\t\ty1 = j\n\t\t\tx2 = i\n\t\t\ty2 = j+1\n\t\t\tx3 = i+1\n\t\t\ty3 = j\n\t\t\tx4 = i+1\n\t\t\ty4 = j+1\n\t\t\tf1 = data[x1][y1]\n\t\t\tf2 = data[x2][y2]\n\t\t\tf3 = data[x3][y3]\n\t\t\tf4 = data[x4][y4]\n\t\t\tx = i + 0.5\n\t\t\ty = j + 0.5\n\t\t\tif np.isnan(f1) or np.isnan(f2) or np.isnan(f3) or np.isnan(f4) :\n\t\t\t\tval = np.nan\n\t\t\telse:\n\t\t\t\tpoints = [ [x1,y1,f1], [x2,y2,f2], [x3,y3,f3], [x4,y4,f4] ]\n\t\t\t\tval = bili_intp_util( points, x, y )\n\t\t\tbint_arr[i].append( val )\n\treturn np.array(bint_arr)\n\t\ndef bili_intp_util( points, x, y ):\n points = sorted(points) # order points by x, then by y\n (x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = points\n\n if x1 != _x1 or x2 != _x2 or y1 != _y1 or y2 != _y2:\n raise ValueError('points do not form a rectangle')\n if not x1 <= x <= x2 or not y1 <= y <= y2:\n raise ValueError('(x, y) not within the rectangle')\n\n return (q11 * (x2 - x) * (y2 - y) +\n q21 * (x - x1) * (y2 - y) +\n q12 * (x2 - x) * (y - y1) +\n q22 * (x - x1) * (y - y1)\n ) / ((x2 - x1) * (y2 - y1) + 0.0)\n\t\ndef perform_task1( array, intp_method, cmap ):\n\n\t#array = np.transpose(array)\n\tarray = np.flipud(array)\n\tplt.imshow( array, cmap=cmap )\n\tplt.show()\n\ndef normalize_values( array ):\n\tmin = np.nanmin(array)\n\tmax = np.nanmax(array)\n\tif max == min :\n\t\treturn\n\tfor i in range( len(array) ):\n\t\tfor j in range( len(array[0]) ):\n\t\t\tarray[i][j] = (array[i][j] - min) / ( max - min )\n\ndef custom_color_map( c_name,c_dict ):\n\t#https://matplotlib.org/gallery/images_contours_and_fields/custom_cmap.html\n\treturn col.LinearSegmentedColormap( c_name, c_dict)\n\t\n\nbad_flag = get_bad_flag( BAD_FLAG_KEY, file_path )\nnum_lines_to_skip = get_lines_to_skip( file_path )\ndata = read_file( file_path, num_lines_to_skip, bad_flag )\n\n#extract longitudes\nlongitudes = np.array(data.columns.values)\n#get firts column key to extract latitudes\nfirst_cloumn_key = longitudes[0]\n#remove first element\nlongitudes = longitudes[1:]\n#extract latitudes\nlatitudes = np.array( data[first_cloumn_key] )\n#delete first clumn\ndata = data.drop(columns=first_cloumn_key)\n#convert data to numpy 2D array\ndata = np.array(data)\n#normalize data(all values between 0-1)\nnormalize_values( data )\n#do interpolation\ndata = perforn_bilinear_interpolation(data)\n#mask bad values\ndata = np.ma.masked_invalid( data )\n#format_latitudes\nformat_latitudes(latitudes)\nformat_longitudes(longitudes)\n\nperform_task1( data, INTP_METHODS[0],custom_color_map( \"BlueGreen\" ,cdict_gray) )\nwith open('your_file.txt', 'w') as f:\n for item in data:\n f.write(\"%s\\n\" % item)","sub_path":"assignment1/code/color_map.py","file_name":"color_map.py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"323366816","text":"from __future__ import print_function\r\nimport logger\r\nimport sqlite3\r\nimport bottle, json, time, sys, os, datetime, random\r\nfrom bottle import get,post,request,response,route,run,Bottle\r\nfrom rocket import Rocket\r\n\r\n# global variables\r\n# to print debug statements\r\nprint_debug = True\r\n# store generated id's based on request from pi\r\nid_given_to_pi = list()\r\n# store id's waiting to be registered from web\r\nconfirm_id_from_web = dict()\r\n# store the registered_pi's\r\nregistered_pi = dict()\r\n# maintain time of last access by pi\r\npi_last_connected = dict()\r\n# maintain the state of LED of connected pi's. By default it is \"off\"\r\npi_LED_state = dict()\r\n# logger for iotplatform\r\nplatform_log = logger.get_custom_logger(__name__, \"iotplatform.log\")\r\n# dict to store logger handles for devices\r\ndevice_log = dict()\r\n# end global variables\r\n\"\"\"\r\nThis class is used to decode json file.\r\nThe output can be either dictionary or list\r\n\"\"\"\r\nclass JsonDecode():\r\n @staticmethod\r\n def get_list(data):\r\n retval = []\r\n for item in data:\r\n if isinstance(item,unicode):\r\n item = item.encode('utf-8')\r\n elif isinstance(item, list):\r\n item = JsonDecode.get_list(item)\r\n elif isinstance(item, dict):\r\n item = JsonDecode.get_dict(item)\r\n retval.append(item)\r\n return retval\r\n\r\n @staticmethod\r\n def get_dict(data):\r\n retval = {}\r\n for key,value in data.iteritems():\r\n if isinstance(key,unicode):\r\n key = key.encode('utf-8')\r\n if isinstance(value,unicode):\r\n value = value.encode('utf-8')\r\n elif isinstance(value,list):\r\n value = JsonDecode.get_list(value)\r\n elif isinstance(value,dict):\r\n value = JsonDecode.get_dict(value)\r\n retval[key] = value\r\n return retval\r\n\r\n# bottle app initialization\r\napp = Bottle(__name__)\r\napp.debug = True\r\n\r\n# start bottle app REST API definitions\r\n\"\"\"\r\nEndpoint to connect to platform from pi\r\n\"\"\"\r\n@app.post('/connect/pi')\r\ndef connect_pi():\r\n global platform_log, device_log, registered_pi, pi_last_connected\r\n payload = json.loads(json.dumps(request.json), object_hook = JsonDecode.get_dict)\r\n pi_id = payload[\"DeviceId\"]\r\n email = payload[\"Email\"]\r\n if pi_id in registered_pi:\r\n if registered_pi[pi_id] != email:\r\n platform_log.error(\"Incorrect connection attempt from device ID: %s\", pi_id)\r\n return bottle.HTTPResponse(status = 404)\r\n elif registered_pi[pi_id] == email:\r\n now = datetime.datetime.now()\r\n pi_last_connected[pi_id] = now\r\n platform_log.info(\"Connected to Device ID: %s\", pi_id)\r\n device_log[pi_id].info(\"Connected to IoT Platform\")\r\n return bottle.HTTPResponse(status = 200)\r\n else:\r\n platform_log.error(\"Incorrect connection attempt from unregistered device using ID: %s\", pi_id)\r\n return bottle.HTTPResponse(status = 404)\r\n\r\n\"\"\"\r\nEndpoint to get device id for pi\r\n\"\"\"\r\n@app.get('/registerpi/get_pi_id')\r\ndef get_pi_id():\r\n global platform_log\r\n if print_debug:\r\n print(\"Request for ID received\")\r\n pi_id = generateID()\r\n id_given_to_pi.append(pi_id)\r\n platform_log.info('Generated PI ID: %s', pi_id)\r\n if print_debug:\r\n print(\"Generated ID: \",pi_id)\r\n print(\"id_given_to_pi ->\", id_given_to_pi)\r\n return {'pi_id' : pi_id}\r\n\r\n\"\"\"\r\nEndpoint to register device to platform from pi\r\n\"\"\"\r\n@app.post('/registerpi/registerdevice')\r\ndef register_pi_from_device():\r\n # need to complete implementation. Currently partial implementation\r\n global platform_log, device_log, registered_pi\r\n payload = json.loads(json.dumps(request.json), object_hook = JsonDecode.get_dict)\r\n if print_debug:\r\n print(\"ID received: \",payload[\"DeviceId\"])\r\n pi_id = payload[\"DeviceId\"]\r\n email = payload[\"Email\"]\r\n if print_debug:\r\n print(\"Request to register device ID: \",pi_id)\r\n if pi_id in registered_pi:\r\n if print_debug:\r\n print(\"PI already registered\")\r\n return bottle.HTTPResponse(status = 200)\r\n else:\r\n if pi_id not in id_given_to_pi:\r\n if print_debug:\r\n print(\"Incorrect ID from PI\")\r\n return bottle.HTTPResponse(status = 404)\r\n #setup pi last connected here\r\n if pi_id in id_given_to_pi:\r\n id_given_to_pi.remove(pi_id)\r\n confirm_id_from_web[pi_id] = email\r\n platform_log.info(\"Register request received from pi for ID: %s\", pi_id)\r\n if print_debug:\r\n print(\"Register request received from pi for ID: \",pi_id)\r\n return bottle.HTTPResponse(status = 200)\r\n\"\"\"\r\nEndpoint to register device to platform from web ui\r\n\"\"\"\r\n@app.get('/registerpi/get_pi_confirmation')\r\ndef get_pi_confirmation():\r\n # partial implementation. Need to implement this completely\r\n global platform_log, device_log, confirm_id_from_web, registered_pi, pi_LED_state\r\n if print_debug:\r\n print(request.params[\"pi_id\"])\r\n print(confirm_id_from_web)\r\n pi_id = str(request.params[\"pi_id\"]).split('|')[0]\r\n email = str(request.params[\"pi_id\"]).split('|')[1]\r\n location = str(request.params[\"pi_id\"]).split('|')[2]\r\n if pi_id in confirm_id_from_web:\r\n if confirm_id_from_web[pi_id] != email:\r\n platform_log.error('Wrong Email ID requested to register from front end. Incorrect Email ID: %s', email)\r\n if print_debug:\r\n print('Wrong Email ID requested to register from front end')\r\n return bottle.HTTPResponse(status = 404)\r\n\r\n del confirm_id_from_web[pi_id]\r\n registered_pi[pi_id] = email\r\n insert_device_details_in_db(pi_id, email, location)\r\n pi_LED_state[pi_id] = \"off\"\r\n platform_log.info(\"Device Successfully registered with ID: %s\", pi_id)\r\n device_log[pi_id] = logger.get_custom_logger(pi_id)\r\n device_log[pi_id].info('PI successfully registered.')\r\n if print_debug:\r\n print(\"PI successfully registered\")\r\n return bottle.HTTPResponse(status = 200)\r\n elif pi_id in registered_pi:\r\n if print_debug:\r\n print(\"PI already registered\")\r\n platform_log.error(\"WEB UI PI ID already registered before.\")\r\n return bottle.HTTPResponse(status = 403)\r\n else:\r\n platform_log.error('Wrong PI ID requested to register from front end. Incorrect pi ID: %s', pi_id)\r\n if print_debug:\r\n print('Wrong PI ID requested to register from front end')\r\n return bottle.HTTPResponse(status = 404)\r\n\"\"\"\r\nEndpoint to deregister pi from web ui\r\n\"\"\"\r\n@app.get('/deregisterpi')\r\ndef deregister_pi():\r\n global platform_log, device_log, registered_pi, pi_LED_state\r\n if print_debug:\r\n print(request.params[\"pi_id\"])\r\n pi_id = str(request.params[\"pi_id\"]).split('|')[0]\r\n if pi_id in registered_pi:\r\n del registered_pi[pi_id]\r\n delete_device_details_in_db(pi_id)\r\n else:\r\n bottle.HTTPResponse(status = 500)\r\n if pi_id in pi_LED_state:\r\n del pi_LED_state[pi_id]\r\n else:\r\n bottle.HTTPResponse(status = 500)\r\n platform_log.info(\"PI with ID: %s Successfully deregistered.\", pi_id)\r\n if pi_id in device_log:\r\n device_log[pi_id].info(\"PI deregistered.\")\r\n del device_log[pi_id]\r\n if pi_id in pi_last_connected:\r\n del pi_last_connected[pi_id]\r\n if print_debug:\r\n return bottle.HTTPResponse(status = 200)\r\n print(\"PI deregistered\")\r\n\r\n\"\"\"\r\nEndpoint to get light state from pi\r\n\"\"\"\r\n@app.get('/light/status')\r\ndef get_LED_status():\r\n global pi_LED_state, platform_log, device_log\r\n pi_id = request.params[\"DeviceId\"]\r\n if pi_id in pi_LED_state:\r\n led_state = pi_LED_state[pi_id]\r\n platform_log.info(\"Sending Light State %s to PI ID: %s\", led_state, pi_id)\r\n device_log[pi_id].info(\"Sending Light Status %s to device\", led_state)\r\n return {'light' : led_state}\r\n else:\r\n return bottle.HTTPResponse(status = 404)\r\n\r\n\"\"\"\r\nEndpoint to set light state from pi\r\n\"\"\"\r\n@app.post('/light/status')\r\ndef set_LED_status():\r\n global pi_LED_state, platform_log, device_log\r\n payload = json.loads(json.dumps(request.json), object_hook = JsonDecode.get_dict)\r\n if print_debug:\r\n print(payload)\r\n print(payload['light'])\r\n print(payload['pi_id'])\r\n led_state = payload['light']\r\n pi_id = payload['pi_id']\r\n if pi_id in pi_last_connected:\r\n now = datetime.datetime.now()\r\n last_time = pi_last_connected[pi_id]\r\n difference = now - last_time\r\n if int(difference) > 5 :\r\n platform_log.error(\"PI has not been connected to platform for more than 5 seconds. ID: %s\", pi_id)\r\n device_log[pi_id].error(\"PI has not been connected to platform for more than 5 seconds.\")\r\n return bottle.HTTPResponse(status = 404)\r\n pi_LED_state[pi_id] = led_state\r\n platform_log.info(\"Received Light State %s for PI ID: %s from WEB UI\", led_state, pi_id)\r\n device_log[pi_id].info('Received Light State %s from front end', led_state)\r\n return bottle.HTTPResponse(status = 200)\r\n\r\n\"\"\"\r\nEndpoint to get logs from pi.\r\n\"\"\"\r\n@app.get('/getlogs')\r\ndef get_log_ip():\r\n global logger, device_log\r\n if print_debug:\r\n print(request.params[\"pi_id\"])\r\n pi_id = str(request.params[\"pi_id\"]).split('|')[0]\r\n url = \"http://35.162.32.72/\" + str(pi_id) + '.log'\r\n platform_log.info(\"Got request for logs of device ID: %s\", pi_id)\r\n return bottle.HTTPResponse(url)\r\n\r\n\"\"\"\r\nEndpoint for getting IoT platform logs\r\n\"\"\"\r\n@app.get('/getlogsiot')\r\ndef get_logs_iot_ip():\r\n global logger\r\n if print_debug:\r\n print(request.params[\"email\"])\r\n platform_log.info(\"Got request for logs of IoT Platform\")\r\n url = \"http://35.162.32.72/iotplatform.log\"\r\n return bottle.HTTPResponse(url)\r\n# end bottle app REST API definitions\r\n# start regular functions\r\n\"\"\"\r\nThis function populates global variables\r\n\"\"\"\r\ndef get_registered_devices_from_db():\r\n global registered_pi\r\n conn = sqlite3.connect('devices.db')\r\n cur = conn.cursor()\r\n cur.execute(\"SELECT * FROM devices\")\r\n data = cur.fetchall()\r\n if len(data) == 0:\r\n conn.close()\r\n return\r\n elif len(data) > 0:\r\n for item in data:\r\n pi_id = str(item[0])\r\n email = str(item[1])\r\n registered_pi[pi_id] = email\r\n conn.close()\r\n return\r\n\"\"\"\r\nThis functions inserts pi details into database\r\n\"\"\"\r\ndef insert_device_details_in_db(pi_id, email, location):\r\n conn = sqlite3.connect('devices.db')\r\n cur = conn.cursor()\r\n cur.execute(\"insert into devices values (?, ?, ?)\", (pi_id, email, location))\r\n conn.commit()\r\n conn.close()\r\n return\r\n\r\n\"\"\"\r\nThis function deletes a row from database table\r\n\"\"\"\r\ndef delete_device_details_in_db(pi_id):\r\n conn = sqlite3.connect('devices.db')\r\n cur = conn.cursor()\r\n cur.execute(\"delete from devices where id = ?\",(pi_id,))\r\n conn.commit()\r\n conn.close()\r\n return\r\n\"\"\"\r\nThis function generates ID for pi\r\n\"\"\"\r\ndef generateID():\r\n generated_id = ''.join(random.choice('0123456789ABCDEF') for i in range(16))\r\n print(generated_id)\r\n while not ((generated_id not in id_given_to_pi) and (generated_id not in confirm_id_from_web) and (generated_id not in registered_pi)):\r\n generated_id = ''.join(random.choice('0123456789ABCDEF') for i in range(16))\r\n print(generated_id)\r\n return generated_id\r\n\r\n\"\"\"\r\nThis function deploys bottle app on Rocket server\r\n\"\"\"\r\ndef run_server():\r\n global platform_log\r\n if print_debug:\r\n print(\"Starting iotplatform\")\r\n server = Rocket(\r\n interfaces = ('0.0.0.0', 8005),\r\n method = 'wsgi',\r\n app_info = {'wsgi_app': app})\r\n server.start()\r\n platform_log.info(\"Started Server\")\r\n# end regular functions\r\n\r\n# code entry point\r\nif __name__ == \"__main__\" :\r\n get_registered_devices_from_db()\r\n run_server()\r\n","sub_path":"timepass/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":12124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"562345834","text":"#\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2007 Jared Crapo\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# pylint: disable=too-many-lines, too-many-public-methods\n\n\"\"\"\nMock up a Tomcat Manager application that behaves like tomcat version 8.0.x\n\"\"\"\n\nimport re\nfrom http.server import HTTPServer\nimport socket\nimport threading\n\nfrom tests.mock_server_nossl import MockRequestHandlerNoSSL\n\n\ndef requires_authorization(func):\n \"\"\"Decorator for methods which require authorization.\"\"\"\n\n def _requires_authorization(self, *args, **kwargs):\n if self.authorized():\n func(self, *args, **kwargs)\n\n return _requires_authorization\n\n\nclass MockRequestHandler80(MockRequestHandlerNoSSL):\n \"\"\"Handle HTTP Requests like Tomcat Manager 8.0.x\"\"\"\n\n SSL_PATTERN = re.compile(r\"^/manager/text/sslConnectorCiphers($|\\?.*$)\")\n\n # pylint: disable=too-many-branches, invalid-name\n @requires_authorization\n def do_GET(self):\n \"\"\"Handle all HTTP GET requests.\"\"\"\n # handle request based on path\n if re.search(self.TEXT_PATTERN, self.path):\n self.send_fail(\"Unknown command\")\n\n # the info commands\n elif re.search(self.LIST_PATTERN, self.path):\n self.get_list()\n elif re.search(self.SERVER_INFO_PATTERN, self.path):\n self.get_server_info()\n elif re.search(self.STATUS_PATTERN, self.path):\n self.get_status()\n elif re.search(self.VM_INFO_PATTERN, self.path):\n self.get_vm_info()\n elif re.search(self.SSL_PATTERN, self.path):\n self.get_ssl_connector_ciphers()\n elif re.search(self.THREAD_DUMP_PATTERN, self.path):\n self.get_thread_dump()\n elif re.search(self.RESOURCES_PATTERN, self.path):\n self.get_resources()\n elif re.search(self.FIND_LEAKERS_PATTERN, self.path):\n self.get_find_leakers()\n elif re.search(self.SESSIONS_PATTERN, self.path):\n self.get_sessions()\n\n # the action commands\n elif re.search(self.EXPIRE_PATTERN, self.path):\n self.get_expire()\n elif re.search(self.START_PATTERN, self.path):\n self.get_start()\n elif re.search(self.STOP_PATTERN, self.path):\n self.get_stop()\n elif re.search(self.RELOAD_PATTERN, self.path):\n self.get_reload()\n elif re.search(self.DEPLOY_PATTERN, self.path):\n self.get_deploy()\n elif re.search(self.UNDEPLOY_PATTERN, self.path):\n self.get_undeploy()\n\n # fail if we don't recognize the path\n else:\n self.send_fail(\"Unknown command\")\n\n def get_server_info(self):\n \"\"\"Send the server information.\"\"\"\n self.send_text(\n \"\"\"OK - Server info\nTomcat Version: Apache Tomcat/8.0.32 (Ubuntu)\nOS Name: Linux\nOS Version: 4.4.0-89-generic\nOS Architecture: amd64\nJVM Version: 1.8.0_131-8u131-b11-2ubuntu1.16.04.3-b11\nJVM Vendor: Oracle Corporation\"\"\"\n )\n\n def get_ssl_connector_ciphers(self):\n \"\"\"Send the SSL ciphers.\"\"\"\n self.send_text(\n \"\"\"OK - Connector / SSL Cipher information\nConnector[HTTP/1.1-8080]\n SSL is not enabled for this connector\"\"\"\n )\n\n\n###\n#\n#\n###\ndef start_mock_server_8_0(tms):\n \"\"\"Start a mock Tomcat Manager application\n\n :return: a tuple: (url, user, password) where the server is accessible\n \"\"\"\n # pylint: disable=unused-variable\n # go find an unused port\n sock = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM)\n sock.bind((\"localhost\", 0))\n address, port = sock.getsockname()\n sock.close()\n\n tms.url = \"http://localhost:{}/manager\".format(port)\n tms.user = MockRequestHandler80.USER\n tms.password = MockRequestHandler80.PASSWORD\n tms.cert = None\n tms.warfile = \"/path/to/server.war\"\n tms.contextfile = \"path/to/context.xml\"\n tms.connect_command = \"connect {} {} {}\".format(tms.url, tms.user, tms.password)\n\n mock_server = HTTPServer((\"localhost\", port), MockRequestHandler80)\n mock_server_thread = threading.Thread(target=mock_server.serve_forever)\n mock_server_thread.daemon = True\n mock_server_thread.start()\n\n return (mock_server, tms)\n","sub_path":"tests/mock_server_8_0.py","file_name":"mock_server_8_0.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"119693629","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\nfrom lama.modules import build_model_by_name\nfrom lama.utils import print_sentence_predictions, load_vocab\nimport lama.options as options\nimport lama.evaluation_metrics3 as evaluation_metrics\nimport jsonlines\nimport json\nfrom nltk.stem import PorterStemmer\n\n\ndef main(args):\n\n #all_results=dict()#list()\n all_results_list=list()\n\n if not args.text and not args.interactive:\n msg = \"ERROR: either you start LAMA eval_generation with the \" \\\n \"interactive option (--i) or you pass in input a piece of text (--t)\"\n raise ValueError(msg)\n\n\n print(\"Language Models: {}\".format(args.models_names))\n\n models = {}\n for lm in args.models_names:\n models[lm] = build_model_by_name(lm, args)\n\n vocab_subset = None\n if args.common_vocab_filename is not None:\n common_vocab = load_vocab(args.common_vocab_filename)\n print(\"common vocabulary size: {}\".format(len(common_vocab)))\n vocab_subset = [x for x in common_vocab]\n\n\n with open('lama/masked_claim_with_ID_on_dev_set.jsonl', \"r\", encoding=\"UTF-8\") as jsonl_file:\n\n file = list(jsonl_file)\n\n for e,jsonl_str in enumerate(file): # go over all the strings in the list\n\n get_dict = json.loads(jsonl_str) # load the string as dict\n\n for k,v in get_dict.items():\n\n text = v\n if args.split_sentence:\n import spacy\n # use spacy to tokenize input sentence\n nlp = spacy.load(args.spacy_model)\n tokens = nlp(text)\n #print(tokens)\n sentences = []\n for s in tokens.sents:\n print(\" - {}\".format(s))\n sentences.append(s.text)\n else:\n sentences = [text]\n\n if len(sentences) > 2:\n print(\"WARNING: only the first two sentences in the text will be considered!\")\n sentences = sentences[:2]\n print(\"\\n{}:\".format(model_name))\n for model_name, model in models.items():\n print(\"\\n{}:\".format(model_name))\n original_log_probs_list, [token_ids], [masked_indices] = model.get_batch_generation([sentences], try_cuda=False)\n\n\n index_list = None\n if vocab_subset is not None:\n # filter log_probs\n filter_logprob_indices, index_list = model.init_indices_for_filter_logprobs(vocab_subset)\n filtered_log_probs_list = model.filter_logprobs(original_log_probs_list, filter_logprob_indices)\n else:\n filtered_log_probs_list = original_log_probs_list\n\n # rank over the subset of the vocab (if defined) for the SINGLE masked tokens\n if masked_indices and len(masked_indices) > 0:\n inter_result = evaluation_metrics.get_ranking(filtered_log_probs_list[0], masked_indices, model.vocab, index_list=index_list)\n print(\"Progress: {}\".format(e), end='\\r')\n #all_results[k]=inter_result\n all_results_list.append(inter_result)\n # prediction and perplexity for the whole softmax\n # print_sentence_predictions(original_log_probs_list[0], token_ids, model.vocab, masked_indices=masked_indices)\n\n return (all_results_list)\n\nif __name__ == '__main__':\n parser = options.get_eval_generation_parser()\n args = options.parse_args(parser)\n final_results_list = main(args)\n\n with jsonlines.open('lama/bert_results_ios.jsonl',mode='w') as writer:\n writer.write_all(final_results_list)\n\n dev_set= list()\n with open('lama/output_after_Flair_and_BERT_checking_on_dev_set.jsonl', 'r', encoding='UTF-8') as jsonl_file2:\n file = list(jsonl_file2)\n\n for e,jsonl_str in enumerate(file): #go over all the strings in the list\n result = json.loads(jsonl_str) # load the string as dict\n dev_set.append(result)\n\n del file\n del result\n\n\n ps = PorterStemmer()\n\n counter = 0\n for e,d in enumerate(dev_set):\n\n selected_list = final_results_list[e]\n selected_list2 = [ps.stem(elm[0].lower()) for elm in selected_list]\n if ps.stem(d['entity']['mention'].lower()) in selected_list2:\n counter += 1\n\n print('Accuracy: {}%'.format(round((counter / len(final_results_list))*100)))\n","sub_path":"task1_2.py","file_name":"task1_2.py","file_ext":"py","file_size_in_byte":4738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"366738461","text":"\"\"\"Initial Database Setup\n\nRevision ID: 4e73d0b97781\nRevises: \nCreate Date: 2021-01-15 09:57:11.614864\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '4e73d0b97781'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('guilds',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=255), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('sorcerers',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=255), nullable=True),\n sa.Column('guild_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['guild_id'], ['guilds.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('sorcerers')\n op.drop_table('guilds')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/4e73d0b97781_initial_database_setup.py","file_name":"4e73d0b97781_initial_database_setup.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"189530459","text":"import requests\n\n\nfrom shakenfist.util import general as util_general\n\n\ndef fetch_remote_checksum(checksum_url):\n resp = requests.get(checksum_url,\n headers={'User-Agent': util_general.get_user_agent()})\n if resp.status_code != 200:\n return {}\n\n checksums = {}\n for line in resp.text.split('\\n'):\n elems = line.split()\n if len(elems) == 2:\n checksums[elems[1]] = elems[0]\n return checksums\n","sub_path":"shakenfist/image_resolver/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"607606076","text":"import random\nimport string\n\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth import logout\nfrom django.db.models import Q\nfrom django.db.models import Sum\nfrom django.http import HttpResponseRedirect\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, get_object_or_404\nimport math\n\n\nfrom .forms import PackageForm, DriverForm, UserForm\nfrom .models import Package, Driver\n\n\n# Add a package to the system\ndef create_package(request):\n if not request.user.is_authenticated():\n return render(request, 'logistics/login.html')\n else:\n # Empty form if request is GET\n form = PackageForm(request.POST or None)\n\n if form.is_valid():\n package = form.save(commit=False)\n # Store the user associated with the package\n package.user = request.user\n # Create a random 10 letter reference number including numbers\n package.reference_number = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))\n package.save()\n\n # Redirect to the index page when form successfully submitted\n return HttpResponseRedirect('/logistics/')\n\n context = {\"form\": form}\n return render(request, 'logistics/create_package.html', context)\n\n\n# Add a driver to the system\ndef create_driver(request, package_id):\n # Empty form if request is GET\n form = DriverForm(request.POST or None)\n package = get_object_or_404(Package, pk=package_id)\n\n if form.is_valid():\n driver = form.save(commit=False)\n driver.package = package\n driver.save()\n return render(request, 'logistics/detail.html', {'package': package})\n\n context = {'package': package, 'form': form}\n return render(request, 'logistics/create_driver.html', context)\n\n\n# Remove a package from the system\ndef delete_package(request, package_id):\n package = Package.objects.get(pk=package_id)\n package.delete()\n packages = Package.objects.filter(user=request.user)\n return render(request, 'logistics/index.html', {'packages': packages})\n\n\n# Remove a driver from the system\ndef delete_driver(request, package_id, driver_id):\n package = get_object_or_404(Package, pk=package_id)\n driver = Driver.objects.get(pk=driver_id)\n driver.delete()\n return render(request, 'logistics/detail.html', {'package': package})\n\n\n# View drivers assigned to a package\ndef detail(request, package_id):\n if not request.user.is_authenticated():\n return render(request, 'logistics/login.html')\n else:\n user = request.user\n package = get_object_or_404(Package, pk=package_id)\n return render(request, 'logistics/detail.html', {'package': package, 'user': user})\n\n\n# Driver assigns 'delivered' status\ndef status(request, driver_id):\n driver = get_object_or_404(Driver, pk=driver_id)\n try:\n # If a driver has been assigned\n if driver.is_status:\n driver.is_status = False\n # If a driver hasn't been assigned\n else:\n driver.is_status = True\n driver.save()\n except (KeyError, Driver.DoesNotExist):\n # Tick 'unselected'\n return JsonResponse({'success': False})\n else:\n # Tick 'selected'\n return JsonResponse({'success': True})\n\n\ndef status_package(request, package_id):\n package = get_object_or_404(Package, pk=package_id)\n try:\n # If a driver has been assigned\n if package.is_status:\n package.is_status = False\n # If a driver hasn't been assigned\n else:\n package.is_status = True\n package.save()\n except (KeyError, Package.DoesNotExist):\n # Tick 'unselected'\n return JsonResponse({'success': False})\n else:\n # Tick 'selected'\n return JsonResponse({'success': True})\n\n\n# First page the user sees after homepage, shows their packages\ndef index(request):\n if not request.user.is_authenticated():\n return render(request, 'logistics/login.html')\n else:\n # Get the user-specific packages\n packages = Package.objects.filter(user=request.user)\n driver_results = Driver.objects.all()\n\n query = request.GET.get(\"q\")\n if query:\n packages = packages.filter(\n Q(weight__icontains=query) |\n Q(reference_number__icontains=query)\n ).distinct()\n driver_results = driver_results.filter(\n Q(driver_name__icontains=query)\n ).distinct()\n return render(request, 'logistics/index.html', {\n 'packages': packages,\n 'drivers': driver_results,\n })\n else:\n return render(request, 'logistics/index.html', {'packages': packages})\n\n\n# Log the user out of the site\ndef logout_user(request):\n logout(request)\n # Empty form if request is GET\n form = UserForm(request.POST or None)\n context = {\"form\": form}\n return render(request, 'logistics/login.html', context)\n\n\n# Log the user in to the site\ndef login_user(request):\n if request.method == \"POST\":\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return HttpResponseRedirect('/logistics/')\n else:\n return render(request, 'logistics/login.html', {'error_message': 'Your account has been disabled'})\n else:\n return render(request, 'logistics/login.html', {'error_message': 'Invalid login'})\n\n return render(request, 'logistics/login.html')\n\n\n# Show the drivers who have transported the particular package\ndef drivers(request, filter_by):\n if not request.user.is_authenticated():\n return render(request, 'logistics/login.html')\n else:\n try:\n driver_ids = []\n # Loop through the user's packages\n for package in Package.objects.filter(user=request.user):\n # Loop through the drivers for the package\n for driver in package.driver_set.all():\n # Add the driver's ID to the list\n driver_ids.append(driver.pk)\n # Get all the driver objects for the users packages\n users_drivers = Driver.objects.filter(pk__in=driver_ids)\n\n if filter_by == 'statuss':\n users_drivers = users_drivers.filter(is_status=True)\n except Package.DoesNotExist:\n users_drivers = []\n return render(request, 'logistics/drivers.html', {\n 'driver_list': users_drivers,\n 'filter_by': filter_by,\n })\n\n\n# Display a dashboard of key statistics\ndef dashboard(request):\n # Largest demand the company can handle\n maximum_tolerable_demand = 50\n number_of_packages = Package.objects.all().count()\n # Current demand as a percentage of maximum tolerable demand\n demand_ratio = (number_of_packages / maximum_tolerable_demand) * 100\n\n # Number of packages delivered\n delivered = Package.objects.filter(driver__is_status=True).count()\n # Number of packages not delivered\n not_delivered = Package.objects.filter(driver__is_status=False).count()\n\n number_of_drivers = Driver.objects.all().count()\n # Number of packages per driver\n package_to_driver_ratio = round(number_of_packages / number_of_drivers, 2)\n\n total_weight = Package.objects.aggregate(Sum('weight'))['weight__sum']\n\n context = {'number_of_packages': number_of_packages, 'demand_ratio': demand_ratio, 'delivered': delivered,\n 'not_delivered': not_delivered, 'number_of_drivers': number_of_drivers,\n 'package_to_driver_ratio': package_to_driver_ratio, 'total_weight': total_weight}\n\n return render(request, 'logistics/dashboard.html', context)\n\n\ndef home(request):\n if not request.user.is_authenticated():\n return render(request, 'logistics/login.html')\n else:\n return render(request, 'logistics/home.html')\n\n\ndef see_all(request):\n if not request.user.is_authenticated():\n return render(request, 'logistics/login.html')\n else:\n packages = Package.objects.filter()\n driver_results = Driver.objects.all()\n query = request.GET.get(\"q\")\n if query:\n packages = packages.filter(\n Q(weight__icontains=query) |\n Q(reference_number__icontains=query)\n ).distinct()\n driver_results = driver_results.filter(\n Q(driver_name__icontains=query)\n ).distinct()\n return render(request, 'logistics/index.html', {\n 'packages': packages,\n 'drivers': driver_results,\n })\n else:\n return render(request, 'logistics/see_all.html', {'packages': packages})\n\n\n\n\n","sub_path":"logistics/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"492019522","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 ('grunt', '0005_message_verified'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Question',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('choices', models.ManyToManyField(related_name='word_questions', to='grunt.Message')),\n ],\n ),\n migrations.CreateModel(\n name='Response',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('question', models.ForeignKey(related_name='responses', to='words.Question')),\n ('selection', models.ForeignKey(related_name='word_responses', to='grunt.Message')),\n ],\n ),\n migrations.CreateModel(\n name='Survey',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(unique=True, max_length=30)),\n ('num_questions_per_player', models.IntegerField(default=10)),\n ],\n ),\n migrations.CreateModel(\n name='Word',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('text', models.CharField(max_length=60)),\n ('survey', models.ForeignKey(to='words.Survey')),\n ],\n ),\n migrations.AddField(\n model_name='question',\n name='survey',\n field=models.ForeignKey(related_name='questions', to='words.Survey'),\n ),\n migrations.AddField(\n model_name='question',\n name='word',\n field=models.ForeignKey(related_name='questions', to='words.Word'),\n ),\n ]\n","sub_path":"words/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"193262726","text":"class Solution(object):\n def matrixReshape(self, nums, r, c):\n \"\"\"\n :type nums: List[List[int]]\n :type r: int\n :type c: int\n :rtype: List[List[int]]\n \"\"\"\n res = []\n nums_r = len(nums)\n if nums_r == 0:\n return res\n nums_c = len(nums[0])\n if nums_r * nums_c < r * c:\n return nums\n for i in range(0, r):\n res.append([0] * c)\n for j in range(0, c):\n idx = c * i + j\n res[i][j] = nums[idx / nums_c][idx % nums_c]\n return res","sub_path":"ReshapeTheMatrix/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"541822555","text":"import skvideo.io\nimport numpy as np\nimport argparse\nimport os\nimport re\n\n'''\nConverts avi files to uint8 grayscale numpy arrays\nof shape (#Frames, Height, Width)\n\n@author Meekail Zain\n'''\nparser = argparse.ArgumentParser(description='array2vid')\nparser.add_argument('--source', type=str, default='', metavar='s',help='Source of video')\nparser.add_argument('--dest', type=str, default='', metavar='d',help='Destination of numpy array')\nargs = parser.parse_args()\n\nassert args.source != '','Please specify video directory'\n\nfor subdir, dirs, files in os.walk(args.source):\n for file in files:\n if file[-4:]=='.avi':\n location=os.path.join(subdir, file)\n print(location)\n destName=args.dest+file[:-4]\n destName = re.sub('[^0-9a-zA-Z/-]+', '_', destName)\n print(destName)\n if not os.path.exists(destName+'.npy'):\n videodata = skvideo.io.vread(location)\n videodata=videodata[:,:,:,0]\n print(videodata.shape)\n np.save(destName,videodata)\n","sub_path":"VTP/utils/vid2array.py","file_name":"vid2array.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"325777293","text":"from django.shortcuts import render, redirect, reverse\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom .models import Problem, Question\nfrom PIL import Image,ImageDraw,ImageFont\nimport random ,io\n\nfrom django.core.cache import cache\n\ndef checklogin(fun):\n def check(request, *args):\n # 利用cookie获取信息\n # username = request.COOKIES.get('username')\n # 利用session获取信息\n username = request.session.get('username')\n if username:\n return fun(request, *args)\n else:\n return redirect(reverse('polls:login'))\n\n return check\n\n\n# Create your views here.\n\n@checklogin\ndef index(request):\n # username = request.COOKIES.get(\"username\")\n # if username:\n problems = Problem.objects.all()\n # 利用\n # username = request.COOKIES.get('username')\n username = request.session.get('username')\n return render(request, \"task1/index.html\", locals())\n # else:\n # return redirect(reverse('polls:login'))\n\n\n@checklogin\ndef choice(request, id):\n problems = Problem.objects.get(pk=id)\n if request.method == \"GET\":\n return render(request, 'task1/detail.html', locals())\n elif request.method == \"POST\":\n # num = problems.question_set\n choiceid = request.POST.get(\"choice\")\n choices = Question.objects.get(pk=choiceid)\n choices.num += 1\n choices.save()\n # print(locals())\n # return render(request,'task1/number.html',locals())\n return redirect(reverse(\"polls:number\", args=(id,)))\n\n\n@checklogin\ndef number(request, id):\n problems = Problem.objects.get(pk=id)\n return render(request, 'task1/number.html', locals())\n\n\ndef login(request):\n if request.method == \"GET\":\n return render(request, 'task1/login.html', {})\n elif request.method == \"POST\":\n # 检测用户密码是否对应\n # 1、登录成功需存储cookie\n # response = redirect(reverse('polls:index'))\n # response.set_cookie('username',request.POST.get('username'))\n # return response\n # 2、使用session存储信息\n verifycode = request.POST.get(\"verify\")\n print(\"+++++++\")\n print(cache.get(\"verify\"))\n if verifycode == cache.get(\"verify\"):\n request.session['username'] = request.POST.get('username')\n return redirect(reverse('polls:index'))\n else:\n return HttpResponse(\"登录错误\")\n\ndef logout(request):\n # 利用cookie删除信息\n # 1、\n # request.COOKIES.pop('username')\n # 2、\n # res = redirect(reverse('polls:index'))\n # res.delete_cookie('username')\n # return res\n # 利用session删除信息\n request.session.flush()\n return redirect(reverse('polls:login'))\n\n\ndef verify(request):\n # 定义变量,用于画面的背景色、宽、高\n bgcolor = (random.randrange(20,100), random.randrange(20,100), random.randrange(20,100))\n width = 100\n heigth = 25\n # 创建画面对象\n im = Image.new('RGB',(width,heigth),bgcolor)\n # 创建画笔对象\n draw = ImageDraw.Draw(im)\n # 调用画笔的point()函数绘制噪点\n for i in range(0, 100):\n xy = (random.randrange(0, width), random.randrange(0, heigth))\n fill = (random.randrange(0, 255), 255, random.randrange(0, 255))\n draw.point(xy, fill=fill)\n # 定义验证码的备选值\n str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'\n # 随机选取4个值作为验证码\n rand_str = ''\n for i in range(0, 4):\n rand_str += str1[random.randrange(0, len(str1))]\n\n cache.set(\"verify\",rand_str)\n # 构造字体对象\n font = ImageFont.truetype('calibrib.ttf', 23)\n\n fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))\n # 绘制4个字\n draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)\n draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)\n draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)\n draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)\n # 释放画笔\n del draw\n request.session['verifycode'] = rand_str\n f = io.BytesIO()\n im.save(f,'png')\n # 将内存中的图片数据返回给客户端,MIME类型为图片png\n return HttpResponse(f.getvalue(), 'image/png')\n","sub_path":"task1/polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"535082803","text":"# -*- coding: utf-8 -*-\n\"\"\"\n util.py\n 工具类\n\"\"\"\nimport time\nimport re\nimport struct\nimport socket\n\n\ndef split_ips(str):\n \"\"\"\n 分割参数中的ip\n :param str:\n :return:\n \"\"\"\n if str == '':\n return\n else:\n return str.split('-')\n\n\ndef check_ips_valid(ip):\n \"\"\"\n 校验ip是否合法\n :param ip:\n :return:\n \"\"\"\n if ip == '':\n return False\n else:\n ips = ip.split('.')\n if len(ips) != 4:\n return False\n else:\n return True\n\n\ndef check_ip_same_segment(ip1, ip2):\n \"\"\"\n 校验两个ip是不是同一个网段\n :param ip1:\n :param ip2:\n :return:\n \"\"\"\n ips1 = ip1.split('.')\n ips2 = ip2.split('.')\n if ips1[0] != ips2[0] or ips1[1] != ips2[1] or ips1[2] != ips2[2]:\n return False\n else:\n return True\n\n\ndef ip2int(ip):\n return struct.unpack(\"!I\", socket.inet_aton(ip))[0]\n\n\ndef int2ip(int_ip):\n return socket.inet_ntoa(struct.pack('!I', int_ip))\n\n\ndef parse_ip_range(ips):\n match = re.match(r\"(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})-(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$\", ips)\n\n if match is None:\n raise Exception('解析ip格式出现异常')\n\n ip_list = match.groups()\n start_ip_int = ip2int(ip_list[0])\n end_ip_int = ip2int(ip_list[1])\n if start_ip_int > end_ip_int:\n raise Exception(\"ip的范围异常\")\n\n return start_ip_int, end_ip_int\n\n\ndef save_log_file(filename, text):\n \"\"\"\n 写入文件\n :param filename:\n :param text:\n :return:\n \"\"\"\n localtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n with open(filename, 'a', encoding='utf-8') as f:\n f.write(f'{str(localtime)} : {text} \\n')\n","sub_path":"week03/task01/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"629895927","text":"class Solution:\n def canFinish(self, n: int, a: List[List[int]]) -> bool:\n novisit = 0\n visit = 1\n visited = 2\n \n def dfs(course):\n if state[course] == visit:\n return True\n if state[course] == visited:\n return False\n state[course] = visit\n \n for j in g[course]:\n if dfs(j):\n return True\n state[course] = visited\n return False\n g = collections.defaultdict(list)\n \n for k, v in a:\n g[k].append(v)\n \n state = [novisit for i in range(n)]\n \n return all(dfs(i)==False for i in range(n))\n","sub_path":"Course Schedule.py","file_name":"Course Schedule.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"126511741","text":"import pandas as pd\nimport numpy as np\n\ncolnames = ['DISTRICT','FUND','FUNCTION','OBJECT','FIN_UNIT','PROGRAM_INTENT','FUNDYEAR','ACTAMT','DTUPDATE']\nactual = {}\n\nfor i in range(7,19):\n if i<10:\n actual.update({i:'/Users/vincentcarse/Desktop/Thesis/Texas_Education/Formatted_Data/ISD_Financial_Reports/Actual/Actual'+str(0)+str(i)+'/ACTUAL_'+str(200)+str(i)+'F.TXT'})\n else:\n actual.update({i:'/Users/vincentcarse/Desktop/Thesis/Texas_Education/Formatted_Data/ISD_Financial_Reports/Actual/Actual'+str(i)+'/ACTUAL_'+str(20)+str(i)+'F.TXT'})\n\nfor i in actual:\n actual[i] = pd.read_csv(actual[i], names = colnames, dtype = str)\n actual[i]['CAMPUS'] = (actual[i]['DISTRICT']+actual[i]['FIN_UNIT'])\n print(str(i)+' is done importing.')\n\ndef spending_extractor(file, object, prog_intent,columns):\n df = file[(file['OBJECT']==str(object))&(file['PROGRAM_INTENT']==str(prog_intent))][columns]\n df.index = range(len(df.index))\n return(df)\n\ndef spending_extractor_simple(file, object,columns):\n df = file[file['OBJECT']==str(object)][columns]\n df.index = range(len(df.index))\n return(df)\n\ndef format_finances(data):\n store = []\n for i in data:\n data[i].index = data[i]['CAMPUS'].values\n data[i] = data[i].drop('CAMPUS',axis=1)\n data[i] = data[i].rename(columns={'ACTAMT':i})\n store.append(data[i])\n data = pd.concat(store, join='outer',axis=1,sort=True)\n return(data)\n\ndef group_duplicates(data,col1,col2):\n df = pd.DataFrame()\n file=data.copy()\n file[col2] = file[col2].astype(int)\n df[col2] = file.groupby(col1)[col2].sum()\n df[col1] = file.groupby(col1)[col2].sum().index\n df[col2] = df[col2].astype(int)\n df.index = range(len(df[col2].values))\n return(df)\n\ndef add_finances(data1, data2, name):\n data2.index = data2['CAMPUS'].values\n data1[name] = data2['ACTAMT']\n return(data1)\n\ndef dict_updater(data1,data2,name,obj,prog_intent,simple=False):\n if simple:\n data1.update({name:spending_extractor_simple(data2,obj,['ACTAMT','CAMPUS'])})\n data1.update({name:group_duplicates(data1[name],'CAMPUS','ACTAMT')})\n else:\n data1.update({name:spending_extractor(data2,obj,prog_intent,['ACTAMT','CAMPUS'])})\n data1.update({name:group_duplicates(data1[name],'CAMPUS','ACTAMT')})\n\ndef finance_creator(source):\n files = {}\n dict_updater(files,source,'general_wages',6119,11)\n dict_updater(files,source,'athletics_wages',6119,91)\n dict_updater(files,source,'gifted_wages',6119,21)\n dict_updater(files,source,'accelerated_wages',6119,24)\n dict_updater(files,source,'disability_wages',6119,23)\n dict_updater(files,source,'billingual_wages',6119,25)\n dict_updater(files,source,'tax_rev',5711,00)\n dict_updater(files,source,'bond_interest',6521,11,True)\n dict_updater(files,source,'debt_interest',6523,91,True)\n dict_updater(files,source,'rent',5743,21,True)\n dict_updater(files,source,'athletics',5752,24,True)\n dict_updater(files,source,'chap_41_?',6224,24,True)\n dict_updater(files,source,'per_capita_ASF',5811,23,True)\n dict_updater(files,source,'foundational_school',5812,25,True)\n dict_updater(files,source,'school_lunch',5922,11,True)\n dict_updater(files,source,'bond_principal',6511,91,True)\n dict_updater(files,source,'prof_services',6219,21,True)\n dict_updater(files,source,'utilities',6259,24,True)\n dict_updater(files,source,'USDA_donations',6344,23,True)\n dict_updater(files,source,'overtime',6121,25,True)\n dict_updater(files,source,'land_purchase',6619,25,True)\n finances = format_finances(files)\n return(finances)\n\ncleaned_actual = {}\nfor i in actual:\n cleaned_actual[i] = finance_creator(actual[i])\n print(str(i)+' is done formatting.')\n\nfor i in cleaned_actual:\n cleaned_actual[i].to_csv('/Users/vincentcarse/Desktop/Thesis/Texas_Education/Regression/formatted_actual/actual'+str(i)+'.csv')\n\nactual_total = pd.DataFrame()\nfor i in cleaned_actual:\n for j in cleaned_actual[i]:\n actual_total[str(j)+str(i)] = cleaned_actual[i][j]\n\nactual_total.to_csv('/Users/vincentcarse/Desktop/Thesis/Texas_Education/Regression/formatted_actual/actual_total.csv')\n\n\n#having trouble with the naming\n\nactual_total[actual_total['chap_41_?17'].notna()]['chap_41_?17']\n\n#\n","sub_path":"Data_Wranglers/spending_aggregator copy.py","file_name":"spending_aggregator copy.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"381329138","text":"#!/usr/bin/env python\nu\"\"\"\nregress_grace_maps.py\nWritten by Tyler Sutterley (10/2020)\n\nReads in GRACE/GRACE-FO spatial files from grace_spatial_maps.py and\n fits a regression model at each grid point\n\nCALLING SEQUENCE:\n python regress_grace_maps.py --start 4 --end 175 --order 2 parameter_file\n\nCOMMAND LINE OPTIONS:\n -P X, --np X: Run in parallel with X number of processes\n -S X, --start X: starting GRACE month for time series regression\n -E X, --end X: ending GRACE month for time series regression\n --order X: regression fit polynomial order\n --cycles X: regression fit cyclical terms\n -M X, --mode X: permissions mode of the output files\n -V, --verbose: verbose output of processing run\n -l, --log: output log file for each job\n\nSYSTEM ARGUMENTS README:\n program is run as:\n python regress_grace_maps.py parameter_file\n\n As python is base 0, sys.argv[0] is equal to regress_grace_maps.py\n (which is useful in some applications, but not for this program)\n\n For this program, the system arguments are parameter files\n The program reads the parameter file, which is separated by column as:\n Column 1: parameter name (such as LMAX)\n Column 2: parameter (e.g. 60)\n Column 3: comments (which are discarded)\n The parameters are stored in a python dictionary (variables indexed by keys)\n the keys are the parameter name (for LMAX: parameters['LMAX'] == 60)\n\nINPUTS:\n parameter file containing specific variables for the analysis\n\nPYTHON DEPENDENCIES:\n numpy: Scientific Computing Tools For Python (https://numpy.org)\n scipy: Scientific Tools for Python (https://docs.scipy.org/doc/)\n netCDF4: netCDF4: Python interface to the netCDF C library\n h5py: Python interface for Hierarchal Data Format 5 (HDF5)\n (https://h5py.org)\n\nPROGRAM DEPENDENCIES:\n tsregress.py: calculates trend coefficients using least-squares\n tsamplitude.py: calculates the amplitude and phase of a harmonic function\n spatial.py: spatial data class for reading, writing and processing data\n ncdf_read.py: reads input spatial data from netCDF4 files\n hdf5_read.py: reads input spatial data from HDF5 files\n ncdf_write.py: writes output spatial data to netCDF4\n hdf5_write.py: writes output spatial data to HDF5\n\nUPDATE HISTORY:\n Updated 10/2020: use argparse to set command line parameters\n Updated 06/2020: using spatial data class for input and output operations\n Updated 01/2020: output seasonal amplitude and phase\n Updated 10/2019: changing Y/N flags to True/False\n Updated 01/2019: include 161-day S2 tidal aliasing terms in regression\n Updated 12/2018: added parallel processing with multiprocessing\n Updated 11/2018: using future division for python3 compatibility\n Updated 06/2018: using python3 compatible octal and input\n can run for different sets of months using the --start and --end options\n can run for different fit types using the --fit option\n use output_data wrapper function for writing data to file\n Updated 04/2018: changed the names of the output log files\n Updated 03/2018: added option --mode to set the output file permissions\n added option for output in pascals (UNITS=5)\n Updated 06/2016: using __future__ print function, MMAX for LMAX != MMAX\n Updated 06/2015: added output_files for log files\n Written 09/2013\n\"\"\"\nfrom __future__ import print_function, division\n\nimport sys\nimport os\nimport time\nimport argparse\nimport traceback\nimport numpy as np\nimport multiprocessing\n\nfrom gravity_toolkit.tsregress import tsregress\nfrom gravity_toolkit.tsamplitude import tsamplitude\nfrom gravity_toolkit.spatial import spatial\n\n#-- PURPOSE: keep track of multiprocessing threads\ndef info(title):\n print(os.path.basename(sys.argv[0]))\n print(title)\n print('module name: {0}'.format(__name__))\n if hasattr(os, 'getppid'):\n print('parent process: {0:d}'.format(os.getppid()))\n print('process id: {0:d}'.format(os.getpid()))\n\n#-- program module to run with specified parameters\ndef regress_grace_maps(parameters, ORDER=None, CYCLES=None,\n VERBOSE=False, MODE=0o775):\n #-- convert parameters into variables\n #-- Data processing center\n PROC = parameters['PROC']\n #-- Data Release\n DREL = parameters['DREL']\n #-- GRACE/GRACE-FO dataset\n DSET = parameters['DSET']\n #-- GRACE/GRACE-FO months\n START_MON = np.int(parameters['START'])\n END_MON = np.int(parameters['END'])\n MISSING = np.array(parameters['MISSING'].split(','),dtype=np.int)\n months = sorted(set(np.arange(START_MON,END_MON+1)) - set(MISSING))\n nmon = len(months)\n #-- maximum degree and order\n LMAX = np.int(parameters['LMAX'])\n if (parameters['MMAX'].title() == 'None'):\n MMAX = np.copy(LMAX)\n else:\n MMAX = np.int(parameters['MMAX'])\n #-- Glacial Isostatic Adjustment file to read\n GIA = parameters['GIA'] if (parameters['GIA'].title() != 'None') else None\n GIA_FILE = os.path.expanduser(parameters['GIA_FILE'])\n #-- remove a set of spherical harmonics from the GRACE data\n REDISTRIBUTE_REMOVED = parameters['REDISTRIBUTE_REMOVED'] in ('Y','y')\n #-- smoothing radius\n RAD = np.int(parameters['RAD'])\n #-- destriped coefficients\n DESTRIPE = parameters['DESTRIPE'] in ('Y','y')\n #-- output spatial units\n UNITS = np.int(parameters['UNITS'])\n #-- output degree spacing\n #-- can enter dlon and dlat as [dlon,dlat] or a single value\n DDEG = np.squeeze(np.array(parameters['DDEG'].split(','),dtype='f'))\n #-- output degree interval (0:360, 90:-90) or (degree spacing/2)\n INTERVAL = np.int(parameters['INTERVAL'])\n #-- input/output data format (ascii, netCDF4, HDF5)\n DATAFORM = parameters['DATAFORM']\n #-- output directory and base filename\n DIRECTORY = os.path.expanduser(parameters['DIRECTORY'])\n FILENAME = parameters['FILENAME']\n #-- output filename suffix\n suffix = dict(ascii='txt', netCDF4='nc', HDF5='H5')[DATAFORM]\n\n #-- flag for spherical harmonic order\n order_str = 'M{0:d}'.format(MMAX) if (MMAX != LMAX) else ''\n #-- Calculating the Gaussian smoothing for radius RAD\n gw_str = '_r{0:0.0f}km'.format(RAD) if (RAD != 0) else ''\n #-- destriped GRACE/GRACE-FO coefficients\n ds_str = '_FL' if DESTRIPE else ''\n #-- distributing removed mass uniformly over ocean\n ocean_str = '_OCN' if REDISTRIBUTE_REMOVED else ''\n #-- input and output spatial units\n unit_list = ['cmwe', 'mmGH', 'mmCU', u'\\u03BCGal', 'mbar']\n unit_name = ['Equivalent Water Thickness', 'Geoid Height',\n 'Elastic Crustal Uplift', 'Gravitational Undulation',\n 'Equivalent Surface Pressure']\n\n #-- input file format\n input_format = '{0}{1}_L{2:d}{3}{4}{5}_{6:03d}.{7}'\n #-- output file format\n output_format = '{0}{1}_L{2:d}{3}{4}{5}_{6}{7}_{8:03d}-{9:03d}.{10}'\n\n #-- Output Degree Spacing\n dlon,dlat = (DDEG,DDEG) if (np.ndim(DDEG) == 0) else (DDEG[0],DDEG[1])\n #-- Output Degree Interval\n if (INTERVAL == 1):\n #-- (-180:180,90:-90)\n nlon = np.int((360.0/dlon)+1.0)\n nlat = np.int((180.0/dlat)+1.0)\n elif (INTERVAL == 2):\n #-- (Degree spacing)/2\n nlon = np.int(360.0/dlon)\n nlat = np.int(180.0/dlat)\n\n #-- Setting output parameters for each fit type\n coef_str = ['x{0:d}'.format(o) for o in range(ORDER+1)]\n unit_suffix = [' yr^{0:d}'.format(-o) if o else '' for o in range(ORDER+1)]\n if (ORDER == 0):#-- Mean\n unit_longname = ['Mean']\n elif (ORDER == 1):#-- Trend\n unit_longname = ['Constant','Trend']\n elif (ORDER == 2):#-- Quadratic\n unit_longname = ['Constant','Linear','Quadratic']\n #-- filename strings for cyclical terms\n cyclic_str = {}\n cyclic_str['SEMI'] = ['SS','SC']\n cyclic_str['ANN'] = ['AS','AC']\n cyclic_str['S2'] = ['S2S','S2C']\n #-- unit longnames for cyclical terms\n cyclic_longname = {}\n cyclic_longname['SEMI'] = ['Semi-Annual Sine', 'Semi-Annual Cosine']\n cyclic_longname['ANN'] = ['Annual Sine', 'Annual Cosine']\n cyclic_longname['S2'] = ['S2 Tidal Alias Sine', 'S2 Tidal Alias Cosine']\n amp_str = []\n for i,c in enumerate(CYCLES):\n if (c == 0.5):\n flag = 'SEMI'\n elif (c == 1.0):\n flag = 'ANN'\n elif (c == (161.0/365.25)):\n flag = 'S2'\n coef_str.extend(cyclic_str[flag])\n unit_longname.extend(cyclic_longname[flag])\n unit_suffix.extend(['',''])\n amp_str.append(flag)\n\n #-- input data spatial object\n spatial_list = []\n for t,grace_month in enumerate(months):\n #-- input GRACE/GRACE-FO spatial file\n fi = input_format.format(FILENAME,unit_list[UNITS-1],LMAX,\n order_str,gw_str,ds_str,grace_month,suffix)\n #-- read GRACE/GRACE-FO spatial file\n if (DATAFORM == 'ascii'):\n dinput = spatial(spacing=[dlon,dlat],nlon=nlon,\n nlat=nlat).from_ascii(os.path.join(DIRECTORY,fi))\n elif (DATAFORM == 'netCDF4'):\n #-- netcdf (.nc)\n dinput = spatial().from_netCDF4(os.path.join(DIRECTORY,fi))\n elif (DATAFORM == 'HDF5'):\n #-- HDF5 (.H5)\n dinput = spatial().from_HDF5(os.path.join(DIRECTORY,fi))\n #-- append to spatial list\n dinput.month[:] = grace_month\n nlat,nlon = dinput.shape\n spatial_list.append(dinput)\n\n #-- concatenate list to single spatial object\n grid = spatial().from_list(spatial_list)\n spatial_list = None\n\n #-- Fitting seasonal components\n ncomp = len(coef_str)\n ncycles = 2*len(CYCLES)\n\n #-- Allocating memory for output variables\n out = dinput.zeros_like()\n out.data = np.zeros((nlat,nlon,ncomp))\n out.error = np.zeros((nlat,nlon,ncomp))\n out.mask = np.ones((nlat,nlon,ncomp),dtype=np.bool)\n #-- Fit Significance\n FS = {}\n #-- SSE: Sum of Squares Error\n #-- AIC: Akaike information criterion\n #-- BIC: Bayesian information criterion\n #-- R2Adj: Adjusted Coefficient of Determination\n for key in ['SSE','AIC','BIC','R2Adj']:\n FS[key] = dinput.zeros_like()\n\n #-- valid values for ocean function\n #-- calculate the regression coefficients and fit significance\n for i in range(nlat):\n for j in range(nlon):\n #-- Calculating the regression coefficients\n tsbeta = tsregress(grid.time, grid.data[i,j,:],\n ORDER=ORDER, CYCLES=CYCLES, CONF=0.95)\n #-- save regression components\n for k in range(0, ncomp):\n out.data[i,j,k] = tsbeta['beta'][k]\n out.error[i,j,k] = tsbeta['error'][k]\n out.mask[i,j,k] = False\n #-- Fit significance terms\n #-- Degrees of Freedom\n nu = tsbeta['DOF']\n #-- Converting Mean Square Error to Sum of Squares Error\n FS['SSE'].data[i,j] = tsbeta['MSE']*nu\n FS['AIC'].data[i,j] = tsbeta['AIC']\n FS['BIC'].data[i,j] = tsbeta['BIC']\n FS['R2Adj'].data[i,j] = tsbeta['R2Adj']\n\n #-- list of output files\n output_files = []\n #-- Output spatial files\n for i in range(0,ncomp):\n #-- output spatial file name\n f1 = output_format.format(FILENAME,unit_list[UNITS-1],LMAX,order_str,\n gw_str,ds_str,coef_str[i],'',START_MON,END_MON,suffix)\n f2 = output_format.format(FILENAME,unit_list[UNITS-1],LMAX,order_str,\n gw_str,ds_str,coef_str[i],'_ERROR',START_MON,END_MON,suffix)\n #-- full attributes\n UNITS_TITLE = '{0}{1}'.format(unit_list[UNITS-1],unit_suffix[i])\n LONGNAME = unit_name[UNITS-1]\n FILE_TITLE = 'GRACE/GRACE-FO_Spatial_Data_{0}'.format(unit_longname[i])\n #-- output regression fit to file\n output = out.index(i, date=False)\n output_data(output, FILENAME=os.path.join(DIRECTORY,f1),\n DATAFORM=DATAFORM, UNITS=UNITS_TITLE, LONGNAME=LONGNAME,\n TITLE=FILE_TITLE, VERBOSE=VERBOSE, MODE=MODE)\n output_data(output, FILENAME=os.path.join(DIRECTORY,f2),\n DATAFORM=DATAFORM, UNITS=UNITS_TITLE, LONGNAME=LONGNAME,\n TITLE=FILE_TITLE, KEY='error', VERBOSE=VERBOSE, MODE=MODE)\n #-- add output files to list object\n output_files.append(os.path.join(DIRECTORY,f1))\n output_files.append(os.path.join(DIRECTORY,f2))\n\n #-- if fitting coefficients with cyclical components\n if (ncycles > 0):\n #-- output spatial titles for amplitudes\n amp_title = {'ANN':'Annual Amplitude','SEMI':'Semi-Annual Amplitude',\n 'S2':'S2 Tidal Alias Amplitude'}\n ph_title = {'ANN':'Annual Phase','SEMI':'Semi-Annual Phase',\n 'S2':'S2 Tidal Alias Phase'}\n\n #-- output amplitude and phase of cyclical components\n for i,flag in enumerate(amp_str):\n #-- Indice pointing to the cyclical components\n j = 1 + ORDER + 2*i\n #-- Allocating memory for output amplitude and phase\n amp = dinput.zeros_like()\n ph = dinput.zeros_like()\n #-- calculating amplitude and phase of spatial field\n amp.data,ph.data = tsamplitude(out.data[:,:,j],out.data[:,:,j+1])\n #-- convert phase from -180:180 to 0:360\n ii,jj = np.nonzero(ph.data < 0)\n ph.data[ii,jj] += 360.0\n #-- Amplitude Error\n comp1 = out.error[:,:,j]*out.data[:,:,j]/amp.data\n comp2 = out.error[:,:,j+1]*out.data[:,:,j+1]/amp.data\n amp.error = np.sqrt(comp1**2 + comp2**2)\n #-- Phase Error (degrees)\n comp1 = out.error[:,:,j]*out.data[:,:,j+1]/(amp.data**2)\n comp2 = out.error[:,:,j+1]*out.data[:,:,j]/(amp.data**2)\n ph.error = (180.0/np.pi)*np.sqrt(comp1**2 + comp2**2)\n\n #-- output file names for amplitude, phase and errors\n f3 = output_format.format(FILENAME,unit_list[UNITS-1],LMAX,order_str,\n gw_str,ds_str,flag,'',START_MON,END_MON,suffix)\n f4 = output_format.format(FILENAME,unit_list[UNITS-1],LMAX,order_str,\n gw_str,ds_str,flag,'_PHASE',START_MON,END_MON,suffix)\n #-- output spatial error file name\n f5 = output_format.format(FILENAME,unit_list[UNITS-1],LMAX,order_str,\n gw_str,ds_str,flag,'_ERROR',START_MON,END_MON,suffix)\n f6 = output_format.format(FILENAME,unit_list[UNITS-1],LMAX,order_str,\n gw_str,ds_str,flag,'_PHASE_ERROR',START_MON,END_MON,suffix)\n #-- full attributes\n AMP_UNITS = unit_list[UNITS-1]\n PH_UNITS = 'degrees'\n LONGNAME = unit_name[UNITS-1]\n AMP_TITLE = 'GRACE/GRACE-FO_Spatial_Data_{0}'.format(amp_title[flag])\n PH_TITLE = 'GRACE/GRACE-FO_Spatial_Data_{0}'.format(ph_title[flag])\n #-- Output seasonal amplitude and phase to files\n output_data(amp, FILENAME=os.path.join(DIRECTORY,f3),\n DATAFORM=DATAFORM, UNITS=AMP_UNITS, LONGNAME=LONGNAME,\n TITLE=AMP_TITLE, VERBOSE=VERBOSE, MODE=MODE)\n output_data(ph, FILENAME=os.path.join(DIRECTORY,f4),\n DATAFORM=DATAFORM, UNITS=PH_UNITS, LONGNAME='Phase',\n TITLE=PH_TITLE, VERBOSE=VERBOSE, MODE=MODE)\n #-- Output seasonal amplitude and phase error to files\n output_data(amp, FILENAME=os.path.join(DIRECTORY,f5),\n DATAFORM=DATAFORM, UNITS=AMP_UNITS, LONGNAME=LONGNAME,\n TITLE=AMP_TITLE, KEY='error', VERBOSE=VERBOSE, MODE=MODE)\n output_data(ph, FILENAME=os.path.join(DIRECTORY,f6),\n DATAFORM=DATAFORM, UNITS=PH_UNITS, LONGNAME='Phase',\n TITLE=PH_TITLE, KEY='error', VERBOSE=VERBOSE, MODE=MODE)\n #-- add output files to list object\n output_files.append(os.path.join(DIRECTORY,f3))\n output_files.append(os.path.join(DIRECTORY,f4))\n output_files.append(os.path.join(DIRECTORY,f5))\n output_files.append(os.path.join(DIRECTORY,f6))\n\n #-- Output fit significance\n signif_longname = {'SSE':'Sum of Squares Error',\n 'AIC':'Akaike information criterion',\n 'BIC':'Bayesian information criterion',\n 'R2Adj':'Adjusted Coefficient of Determination'}\n #-- for each fit significance term\n for key,fs in FS.items():\n #-- output file names for fit significance\n signif_str = '{0}_'.format(key)\n f7 = output_format.format(FILENAME,unit_list[UNITS-1],LMAX,order_str,\n gw_str,ds_str,signif_str,coef_str[ORDER],START_MON,END_MON,suffix)\n #-- full attributes\n LONGNAME = signif_longname[key]\n #-- output fit significance to file\n output_data(fs, FILENAME=os.path.join(DIRECTORY,f7),\n DATAFORM=DATAFORM, UNITS=key, LONGNAME=LONGNAME,\n TITLE=nu, VERBOSE=VERBOSE, MODE=MODE)\n #-- add output files to list object\n output_files.append(os.path.join(DIRECTORY,f7))\n\n #-- return the list of output files\n return output_files\n\n#-- PURPOSE: wrapper function for outputting data to file\ndef output_data(data, FILENAME=None, KEY='data', DATAFORM=None,\n UNITS=None, LONGNAME=None, TITLE=None, VERBOSE=False, MODE=0o775):\n output = data.copy()\n setattr(output,'data',getattr(data,KEY))\n if (DATAFORM == 'ascii'):\n #-- ascii (.txt)\n output.to_ascii(FILENAME,date=False,verbose=VERBOSE)\n elif (DATAFORM == 'netCDF4'):\n #-- netcdf (.nc)\n output.to_netCDF4(FILENAME,date=False,verbose=VERBOSE,\n units=UNITS,longname=LONGNAME,title=TITLE)\n elif (DATAFORM == 'HDF5'):\n #-- HDF5 (.H5)\n output.to_HDF5(FILENAME,date=False,verbose=VERBOSE,\n units=UNITS,longname=LONGNAME,title=TITLE)\n #-- change the permissions mode of the output file\n os.chmod(FILENAME, MODE)\n\n#-- PURPOSE: print a file log for the GRACE/GRACE-FO regression\n#-- lists: the parameter file, the parameters and the output files\ndef output_log_file(parameters,output_files):\n #-- format: GRACE_processing_run_2002-04-01_PID-70335.log\n args = (time.strftime('%Y-%m-%d',time.localtime()), os.getpid())\n LOGFILE = 'GRACE_processing_run_{0}_PID-{1:d}.log'.format(*args)\n DIRECTORY = os.path.expanduser(parameters['DIRECTORY'])\n #-- create a unique log and open the log file\n fid = create_unique_logfile(os.path.join(DIRECTORY,LOGFILE))\n #-- check if run from entering parameters or from parameter files\n if parameters['PARAMETER_FILE'] is not None:\n #-- print parameter file on top\n print('PARAMETER FILE:\\n{0}\\n\\nPARAMETERS:'.format(\n os.path.abspath(parameters['PARAMETER_FILE'])), file=fid)\n else:\n print('PARAMETERS:', file=fid)\n #-- print parameter values sorted alphabetically\n for p in sorted(list(set(parameters.keys())-set(['PARAMETER_FILE']))):\n print('{0}: {1}'.format(p, parameters[p]), file=fid)\n #-- print output files\n print('\\n\\nOUTPUT FILES:', file=fid)\n for f in output_files:\n print('{0}'.format(f), file=fid)\n #-- close the log file\n fid.close()\n\n#-- PURPOSE: print a error file log for the GRACE/GRACE-FO regression\n#-- lists: the parameter file, the parameters and the error\ndef output_error_log_file(parameters):\n #-- format: GRACE_processing_failed_run_2002-04-01_PID-70335.log\n args = (time.strftime('%Y-%m-%d',time.localtime()), os.getpid())\n LOGFILE = 'GRACE_processing_failed_run_{0}_PID-{1:d}.log'.format(*args)\n DIRECTORY = os.path.expanduser(parameters['DIRECTORY'])\n #-- create a unique log and open the log file\n fid = create_unique_logfile(os.path.join(DIRECTORY,LOGFILE))\n #-- check if run from entering parameters or from parameter files\n if parameters['PARAMETER_FILE'] is not None:\n #-- print parameter file on top\n print('PARAMETER FILE:\\n{0}\\n\\nPARAMETERS:'.format(\n os.path.abspath(parameters['PARAMETER_FILE'])), file=fid)\n else:\n print('PARAMETERS:', file=fid)\n #-- print parameter values sorted alphabetically\n for p in sorted(list(set(parameters.keys())-set(['PARAMETER_FILE']))):\n print('{0}: {1}'.format(p, parameters[p]), file=fid)\n #-- print traceback error\n print('\\n\\nTRACEBACK ERROR:', file=fid)\n traceback.print_exc(file=fid)\n #-- close the log file\n fid.close()\n\n#-- PURPOSE: open a unique log file adding a numerical instance if existing\ndef create_unique_logfile(filename):\n #-- split filename into fileBasename and fileExtension\n fileBasename, fileExtension = os.path.splitext(filename)\n #-- create counter to add to the end of the filename if existing\n counter = 1\n while counter:\n try:\n #-- open file descriptor only if the file doesn't exist\n fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_RDWR)\n except OSError:\n pass\n else:\n return os.fdopen(fd, 'w+')\n #-- new filename adds counter the between fileBasename and fileExtension\n filename = '{0}_{1:d}{2}'.format(fileBasename, counter, fileExtension)\n counter += 1\n\n#-- PURPOSE: define the analysis\ndef define_analysis(parameter_file,START,END,ORDER=None,CYCLES=None,\n VERBOSE=False,LOG=False,MODE=0o775):\n #-- keep track of progress\n info(os.path.basename(parameter_file))\n\n #-- variable with parameter definitions\n parameters = {}\n parameters['PARAMETER_FILE'] = parameter_file\n #-- Opening parameter file and assigning file ID number (fid)\n fid = open(os.path.expanduser(parameter_file), 'r')\n #-- for each line in the file will extract the parameter (name and value)\n for fileline in fid:\n #-- Splitting the input line between parameter name and value\n part = fileline.split()\n #-- filling the parameter definition variable\n parameters[part[0]] = part[1]\n #-- close the parameter file\n fid.close()\n\n #-- can change the date range from the defaults (change parameters for logs)\n parameters['START'] = np.copy(START) if START else parameters['START']\n parameters['END'] = np.copy(END) if END else parameters['END']\n #-- set regression fit type as parameter for logs\n parameters['ORDER'] = '{0:d}'.format(ORDER)\n parameters['CYCLES'] = ','.join(['{0:4f}'.format(c) for c in CYCLES])\n #-- try to run the program with listed parameters\n try:\n #-- run GRACE/GRACE-FO spatial regression program with parameters\n output_files = regress_grace_maps(parameters,ORDER=ORDER,\n CYCLES=CYCLES,VERBOSE=VERBOSE,MODE=MODE)\n except:\n #-- if there has been an error exception\n #-- print the type, value, and stack trace of the\n #-- current exception being handled\n print('process id {0:d} failed'.format(os.getpid()))\n traceback.print_exc()\n if LOG:#-- write failed job completion log file\n output_error_log_file(parameters)\n else:\n if LOG:#-- write successful job completion log file\n output_log_file(parameters,output_files)\n\n#-- This is the main part of the program that calls the individual modules\n#-- If no parameter file is listed as an argument: will exit with an error\ndef main():\n #-- Read the system arguments listed after the program\n parser = argparse.ArgumentParser(\n description=\"\"\"Reads in GRACE/GRACE-FO spatial files and calculates the\n trends at each grid point following an input regression model\n \"\"\"\n )\n #-- command line parameters\n parser.add_argument('parameters',\n type=lambda p: os.path.abspath(os.path.expanduser(p)), nargs='+',\n help='Parameter files containing specific variables for each analysis')\n #-- number of processes to run in parallel\n parser.add_argument('--np','-P',\n metavar='PROCESSES', type=int, default=0,\n help='Number of processes to run in parallel')\n #-- start and end years for regression\n parser.add_argument('--start','-S',\n type=int,\n help='Starting GRACE/GRACE_FO month for time series regression')\n parser.add_argument('--end','-E',\n type=int,\n help='Ending GRACE/GRACE_FO month for time series regression')\n #-- regression parameters\n #-- 0: mean\n #-- 1: trend\n #-- 2: acceleration\n parser.add_argument('--order','-o',\n type=int, default=2,\n help='Regression fit polynomial order')\n #-- regression fit cyclical terms\n parser.add_argument('--cycle','-c',\n type=float, default=[0.5,1.0,161.0/365.25], nargs='+',\n help='Regression fit cyclical terms')\n #-- verbose output\n parser.add_argument('--verbose','-V',\n default=False, action='store_true',\n help='Verbose output of run')\n #-- Output log file for each job in forms\n #-- GRACE_processing_run_2002-04-01_PID-00000.log\n #-- GRACE_processing_failed_run_2002-04-01_PID-00000.log\n parser.add_argument('--log','-l',\n default=False, action='store_true',\n help='Output log file for each job')\n #-- permissions mode of the local directories and files (number in octal)\n parser.add_argument('--mode','-M',\n type=lambda x: int(x,base=8), default=0o775,\n help='permissions mode of output files')\n args = parser.parse_args()\n\n #-- use parameter files from system arguments listed after the program.\n if (args.np == 0):\n #-- run directly as series if PROCESSES = 0\n for f in args.parameters:\n define_analysis(f,args.start,args.end,\n ORDER=args.order,CYCLES=args.cycle,VERBOSE=args.verbose,\n LOG=args.log,MODE=args.mode)\n else:\n #-- run in parallel with multiprocessing Pool\n pool = multiprocessing.Pool(processes=args.np)\n #-- for each parameter file\n for f in args.parameters:\n kwds=dict(ORDER=args.order,CYCLES=args.cycle,\n VERBOSE=args.verbose,LOG=args.log,MODE=args.mode)\n pool.apply_async(define_analysis,args=(f,args.start,args.end),\n kwds=kwds)\n #-- start multiprocessing jobs\n #-- close the pool\n #-- prevents more tasks from being submitted to the pool\n pool.close()\n #-- exit the completed processes\n pool.join()\n\n#-- run main program\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/regress_grace_maps.py","file_name":"regress_grace_maps.py","file_ext":"py","file_size_in_byte":26357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"538522990","text":"\"\"\"\n===================\nMap Window Examples\n===================\nagent maps the function func from its single input stream to its\nsingle output stream.\n \nThis example demonstrates how to use :function:`filter_element` in \nagent_types/op.py on streams.\n\"\"\"\nimport sys\nimport os\nsys.path.append(os.path.abspath(\"../../IoTPy/\"))\nsys.path.append(os.path.abspath(\"../../IoTPy/helper_functions\"))\nsys.path.append(os.path.abspath(\"../../IoTPy/core\"))\nsys.path.append(os.path.abspath(\"../../IoTPy/agent_types\"))\n\nfrom stream import Stream, StreamArray\nfrom stream import _no_value, _multivalue\nfrom check_agent_parameter_types import *\nfrom recent_values import recent_values\nfrom op import map_window\n\n# In the following examples, x is a stream that is an input stream of\n# the agents. \nx = Stream('x')\n\n#---------------------------------------------------------------- \n# Example with no state and no additional parameters\n#----------------------------------------------------------------\ns = Stream()\nmap_window(func=sum, in_stream=x, out_stream=s, \n window_size=2, step_size=10)\n# out_stream[j] = \\\n# func(in_stream[j*step_size : j*step_size + window_size])\n# for all j.\n# So:\n# s[j] = x[10*j] + x[10*j+1], for all j\n\n#---------------------------------------------------------------- \n# Example with state and no additional parameters\n#----------------------------------------------------------------\nthis_list = range(10)\ndef comp(this_list, state):\n # Current state is sum_of_previous_list\n # Next state will be sum(this_list)\n # return next element of output stream, next state\n next_state = sum(this_list)\n next_output_element = sum(this_list) > state\n return next_output_element, next_state\nc = Stream()\nmap_window(func=comp, in_stream=x, out_stream=c, \n state=0, window_size=10, step_size=20)\n# The initial state is 0\n# The initial value of this_list is x[:window_size]\n# The zeroth element of the output stream is:\n# func(x[:window_size], state)\n# c[0] = sum(x[:10]) > 0 because 0 is the initial state\n# c[j] = sum(x[20*j:20*j+10]) > sum(x[20*(j-1):20*(j-1)+10])\n\n#---------------------------------------------------------------- \n# Example with no state and additional parameters\n#----------------------------------------------------------------\n# The additional parameter is threshold\ndef thresh(in_stream_window, threshold):\n return sum(in_stream_window) > threshold\nt = Stream()\nmap_window(func=thresh, in_stream=x, out_stream=t, window_size=10,\n step_size=20, threshold=5) \n# For all j, : t[j] is True if and only if sum(x[20*j : 20*j+10]) > 5.\n#\n# Note: You can use any names as arguments in the\n# definition of func, as in:\n# def thresh(v, s): return sum(v) > w\n\n#---------------------------------------------------------------- \n# Example with state and additional parameters\n#----------------------------------------------------------------\ndef maxes(in_stream_window, state, parameter):\n next_output_element = sum(in_stream_window) > parameter * state\n next_state = max(state, sum(in_stream_window))\n return (next_output_element, next_state)\nm = Stream()\nmap_window(func=maxes, in_stream=x, out_stream=m, state=0,\n window_size=20, step_size=10, parameter=0.5)\n# in_stream_window on step j is x[10*j : 10*j + 20]\n# state[j] = max(state[j-1], sum(x[10*j : 10*j + 20]))\n# m[j] = sum(x[10*j : 10*j + 20]) > 0.5 * state[j]\n","sub_path":"examples/op/map_window_examples.py","file_name":"map_window_examples.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"563150066","text":"import numpy\nfrom tensorflow import keras\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nimport matplotlib.pyplot as plt\n\ndataset1 = numpy.loadtxt('data/demo53_datasets.csv', delimiter=',', skiprows=1)\nprint(type(dataset1), dataset1.shape)\n\ninputList = dataset1[:, 0:8]\nresultList = dataset1[:, 8]\nprint(inputList.shape)\nprint(resultList.shape)\n\nmodel = Sequential()\nprint(type(model))\nmodel.add(Dense(20, input_dim=8, activation='relu'))\nmodel.add(Dense(10, activation='relu'))\nmodel.add(Dense(3, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\nopt = keras.optimizers.Adam(learning_rate=0.01)\nmodel.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])\nprint(model.summary())\nhistory = model.fit(inputList, resultList, validation_split=0.1, epochs=200, batch_size=20)\n\nplt.plot(history.history['val_loss'])\nplt.plot(history.history['loss'])\nplt.legend(['val_loss','loss'])\nplt.show()\n\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.legend(['accuracy','val_accuracy'])\nplt.show()","sub_path":"demo53_copy.py","file_name":"demo53_copy.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"178825236","text":"from django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.sites.models import Site\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\n\nfrom spreedly.models import Plan, Subscription\nfrom spreedly.pyspreedly.api import Client\nfrom spreedly import signals\nimport spreedly.settings as spreedly_settings\n\ndef sync_plans():\n '''\n Sync subscription plans with Spreedly API\n '''\n client = Client(settings.SPREEDLY_AUTH_TOKEN, settings.SPREEDLY_SITE_NAME)\n \n for plan in client.get_plans():\n p, created = Plan.objects.get_or_create(speedly_id=plan['speedly_id'])\n \n changed = False\n for k, v in plan.items():\n if hasattr(p, k) and not getattr(p, k) == v:\n setattr(p, k, v)\n changed = True\n if changed:\n p.save()\n\ndef get_subscription(user):\n client = Client(settings.SPREEDLY_AUTH_TOKEN, settings.SPREEDLY_SITE_NAME)\n data = client.get_info(user.id)\n \n subscription, created = Subscription.objects.get_or_create(\n user=user\n )\n for k, v in data.items():\n if hasattr(subscription, k):\n setattr(subscription, k, v)\n subscription.save()\n signals.subscription_update.send(sender=subscription, user=user)\n return subscription\n\ndef check_trial_eligibility(plan, user):\n if plan.plan_type != 'free_trial':\n return False\n try:\n # make sure the user is trial eligable (they don't have a subscription yet, or they are trial_elegible)\n not_allowed = Subscription.objects.get(user=user, trial_elegible=False)\n return False\n except Subscription.DoesNotExist:\n return True\n\ndef start_free_trial(plan, user):\n if check_trial_eligibility(plan, user):\n client = Client(settings.SPREEDLY_AUTH_TOKEN, settings.SPREEDLY_SITE_NAME)\n client.get_or_create_subscriber(user.id, user.username)\n client.subscribe(user.id, plan.pk, trial=True)\n get_subscription(user)\n return True\n else:\n return False\n\ndef return_url(plan_pk, user, trial=False):\n url = 'http://%s%s' % (spreedly_settings.SPREEDLY_SITE_URL, reverse('spreedly_return', args=[user.id, plan_pk]))\n if trial:\n url = url + '?trial=true'\n return url\n\ndef subscription_url(plan, user):\n return 'https://spreedly.com/%(site_name)s/subscribers/%(user_id)s/subscribe/%(plan_id)s/%(user_email)s?email=%(user_email)s&return_url=%(return_url)s' % {\n 'site_name': settings.SPREEDLY_SITE_NAME,\n 'plan_id': plan.pk,\n 'user_id': user.id,\n 'user_username': user.username,\n 'user_email': user.email,\n 'return_url': return_url(plan.pk, user)\n }\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"286258349","text":"input = [line.strip() for line in open(\"../Inputs/day06\", \"r\")]\n\ndef getSwarmAfterDays(days):\n swarmAgeDistribution = [0 for i in range(9)]\n\n for fish in input[0].split(','):\n swarmAgeDistribution[int(fish)] += 1\n\n for day in range(days):\n reproductiveFishCount = swarmAgeDistribution[0]\n for ageCounter in range(1,9):\n swarmAgeDistribution[ageCounter - 1] = swarmAgeDistribution[ageCounter]\n swarmAgeDistribution[8] = reproductiveFishCount\n swarmAgeDistribution[6] += reproductiveFishCount\n\n return sum(swarmAgeDistribution)\n\nprint(\"2021 Day 6, Part 1: \" + str(getSwarmAfterDays(80)))\nprint(\"2021 Day 6, Part 2: \" + str(getSwarmAfterDays(256)))\n","sub_path":"2021/AoC2021Day06/AoC2021Day06.py","file_name":"AoC2021Day06.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"346614854","text":"import itertools\r\n\r\nfrom autofit.tools.util import get_class\r\nfrom .identifier import Identifier\r\n\r\n\r\nclass ModelObject:\r\n _ids = itertools.count()\r\n\r\n def __init__(self):\r\n self.id = next(self._ids)\r\n\r\n @property\r\n def component_number(self):\r\n return self.id\r\n\r\n def __hash__(self):\r\n return self.id\r\n\r\n def __eq__(self, other):\r\n try:\r\n return self.id == other.id\r\n except AttributeError:\r\n return False\r\n\r\n @property\r\n def identifier(self):\r\n return str(Identifier(self))\r\n\r\n @staticmethod\r\n def from_dict(d):\r\n \"\"\"\r\n Recursively parse a dictionary returning the model, collection or\r\n instance that is represents.\r\n\r\n Parameters\r\n ----------\r\n d\r\n A dictionary representation of some object\r\n\r\n Returns\r\n -------\r\n An instance\r\n \"\"\"\r\n from autofit.mapper.prior_model.abstract import AbstractPriorModel\r\n from autofit.mapper.prior_model.collection import CollectionPriorModel\r\n from autofit.mapper.prior_model.prior_model import PriorModel\r\n from autofit.mapper.prior.prior import Prior\r\n from autofit.mapper.prior.prior import TuplePrior\r\n\r\n if not isinstance(\r\n d, dict\r\n ):\r\n return d\r\n\r\n type_ = d[\"type\"]\r\n\r\n if type_ == \"model\":\r\n instance = PriorModel(\r\n get_class(\r\n d.pop(\"class_path\")\r\n )\r\n )\r\n elif type_ == \"collection\":\r\n instance = CollectionPriorModel()\r\n elif type_ == \"instance\":\r\n cls = get_class(\r\n d.pop(\"class_path\")\r\n )\r\n instance = object.__new__(cls)\r\n elif type_ == \"tuple_prior\":\r\n instance = TuplePrior()\r\n else:\r\n return Prior.from_dict(d)\r\n\r\n d.pop(\"type\")\r\n\r\n for key, value in d.items():\r\n setattr(\r\n instance,\r\n key,\r\n AbstractPriorModel.from_dict(value)\r\n )\r\n return instance\r\n\r\n @property\r\n def dict(self) -> dict:\r\n \"\"\"\r\n A dictionary representation of this object\r\n \"\"\"\r\n from autofit.mapper.prior_model.abstract import AbstractPriorModel\r\n from autofit.mapper.prior_model.collection import CollectionPriorModel\r\n from autofit.mapper.prior_model.prior_model import PriorModel\r\n from autofit.mapper.prior.prior import TuplePrior\r\n\r\n if isinstance(\r\n self,\r\n CollectionPriorModel\r\n ):\r\n type_ = \"collection\"\r\n elif isinstance(\r\n self,\r\n AbstractPriorModel\r\n ) and self.prior_count == 0:\r\n type_ = \"instance\"\r\n elif isinstance(\r\n self,\r\n PriorModel\r\n ):\r\n type_ = \"model\"\r\n elif isinstance(\r\n self,\r\n TuplePrior\r\n ):\r\n type_ = \"tuple_prior\"\r\n else:\r\n raise AssertionError(\r\n f\"{self.__class__.__name__} cannot be serialised to dict\"\r\n )\r\n\r\n dict_ = {\r\n \"type\": type_\r\n }\r\n\r\n for key, value in self._dict.items():\r\n try:\r\n if not isinstance(\r\n value, ModelObject\r\n ):\r\n value = AbstractPriorModel.from_instance(\r\n value\r\n )\r\n value = value.dict\r\n except AttributeError:\r\n pass\r\n dict_[key] = value\r\n return dict_\r\n\r\n @property\r\n def _dict(self):\r\n return {\r\n key: value\r\n for key, value in self.__dict__.items()\r\n if key not in (\"component_number\", \"item_number\", \"id\", \"cls\")\r\n and not key.startswith(\"_\")\r\n }\r\n","sub_path":"autofit/mapper/model_object.py","file_name":"model_object.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"612529528","text":"from datetime import timedelta, datetime, date\nfrom io import BytesIO\nfrom itertools import groupby\nfrom urllib.parse import quote\n\nimport math\nfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENT\nfrom docx.oxml import parse_xml\nfrom docx.oxml.ns import nsdecls\nfrom docx.shared import Mm, Pt\nfrom flask import request, jsonify, Response, send_file, make_response\nfrom flask.views import MethodView\nfrom sqlalchemy import union\nfrom sqlalchemy.sql.elements import literal_column\nfrom sqlalchemy.sql.functions import coalesce\nfrom wtforms import DateField, Form, BooleanField, StringField\nfrom wtforms.fields.html5 import IntegerField\n\nfrom back.base import app\nfrom back.consts import AFANASEVNA_AUDS, SMI_AUDS, POTOKS_AUDS\nfrom back.helpers import get_date_week_even, set_row_height, set_cell_border, set_vert_cell_direction, delete_paragraph, \\\n set_repeat_table_header\nfrom back.models import *\nfrom back.views.zaoch.mixins import HolidaysMixin\n\n\nclass ZaochAuditoryMapView(MethodView):\n def process_item(self, schedule_items):\n sem = g.settings.semester\n\n def process_para_item(p):\n konts = (p.konts or \"\").replace('(И,З)', '').replace('(И,О)', '').strip()\n\n if getattr(p, \"potoklist_semestr\"):\n year = date.today().year - 2000\n learn_year = p.potoklist_semestr // 2\n if sem == 1:\n year -= learn_year - 1\n else:\n year -= learn_year\n\n konts = \"{}-{}\".format(p.konts, year)\n\n return {\n 'konts': konts,\n 'hours': p.hours,\n }\n\n result = {\n \"{:%Y-%m-%d}\".format(dt): {\n para: [process_para_item(p) for p in para_items\n ] for para, para_items in groupby(items, lambda x: x.para)\n }\n for dt, items in groupby(schedule_items, lambda x: x.dt)\n }\n\n return {\n 'id': schedule_items[0].id,\n # 'raspis_id': schedule_items[0].id,\n 'title': schedule_items[0].title,\n 'schedule': result\n }\n\n def filter_by(self, sql_query, query, field_base):\n\n if query == 'afanasevna':\n sql_query = sql_query.filter(field_base.id.in_(AFANASEVNA_AUDS))\n elif query == 'potochki':\n sql_query = sql_query.filter(field_base.id.in_(POTOKS_AUDS))\n elif query.lower() == 'сми-':\n sql_query = sql_query.filter(field_base.id.in_(SMI_AUDS))\n else:\n sql_query = sql_query.filter(field_base.title.startswith(func.rtrim(query)))\n return sql_query\n\n def get_data(self, only_auds_ids=False):\n year = g.settings.year\n period = g.settings.period\n konts_info = Periods.query.filter_by(year=year, period=period).with_entities(\n func.min(Periods.period_start).label('min'),\n func.max(Periods.period_end).label('max'),\n ).first()\n\n query = request.args.get('query')\n data = {}\n\n if query:\n if g.settings.session_start:\n period_start = min(g.settings.session_start.date(), konts_info.min - timedelta(1))\n else:\n period_start = konts_info.min - timedelta(1)\n\n if g.settings.session_end:\n period_end = max(g.settings.session_end.date(), konts_info.max + timedelta(1))\n else:\n period_end = konts_info.max + timedelta(1)\n\n if only_auds_ids:\n entities = []\n else:\n entities = [\n func.rtrim(Auditory.title).label('title'),\n func.rtrim(coalesce(Potoklist.title, Kontkurs.title)).label(\"konts\"),\n RaspisZaoch.para.label(\"para\"),\n RaspisZaoch.dt.label(\"dt\"),\n RaspisZaoch.hours.label(\"hours\"),\n Potoklist.semestr.label(\"potoklist_semestr\"),\n ]\n\n query_aud = Auditory.query \\\n .outerjoin(RaspisZaoch, RaspisZaoch.aud == Auditory.id) \\\n .outerjoin(Kontkurs, Kontkurs.id == RaspisZaoch.kont_id) \\\n .outerjoin(Potoklist, Potoklist.op == RaspisZaoch.op_id) \\\n .filter(RaspisZaoch.dt.between(period_start, period_end)) \\\n .with_entities(RaspisZaoch.aud.label(\"id\"), *entities) \\\n .distinct()\n\n query_aud2 = Auditory.query \\\n .outerjoin(RaspisZaoch, RaspisZaoch.aud2 == Auditory.id) \\\n .outerjoin(Kontkurs, Kontkurs.id == RaspisZaoch.kont_id) \\\n .outerjoin(Potoklist, Potoklist.op == RaspisZaoch.op_id) \\\n .filter(RaspisZaoch.dt.between(period_start, period_end)) \\\n .with_entities(RaspisZaoch.aud2.label(\"id\"), *entities) \\\n .distinct()\n\n if only_auds_ids:\n entities = []\n else:\n entities = [\n func.rtrim(Auditory.title).label('title'),\n (case([\n (AudActions.action == 1, \"Экзамен \"),\n (AudActions.action == 2, \"ГЭК \"),\n (AudActions.action == 3, \"МРЦПК \"),\n (AudActions.action == 4, \"Консультация \"),\n (AudActions.action == 5, \"Консультация заочники \"),\n ]) + func.rtrim(func.isnull(Kontkurs.title, \"\")) + \" \" + func.rtrim(\n func.isnull(Teacher.name, \"\"))).label(\"konts\"),\n AudActions.para.label(\"para\"),\n AudActions.date.label('dt'),\n (AudActions.para_count * 2).label(\"hours\"),\n literal_column(\"NULL\").label(\"potoklist_semestr\")\n ]\n\n query_aud3 = AudActions.query \\\n .outerjoin(Auditory, Auditory.id == AudActions.aud) \\\n .outerjoin(Kontkurs, Kontkurs.id == AudActions.kont) \\\n .outerjoin(Teacher, Teacher.id == AudActions.prep_id) \\\n .filter(AudActions.date.between(period_start, period_end)) \\\n .with_entities(Auditory.id.label(\"id\"), *entities)\n\n squery = query_aud.union(query_aud2, query_aud3).subquery()\n squery = self.filter_by(db.session.query(squery), query, squery.c)\n\n if only_auds_ids:\n data = [i.id for i in squery]\n else:\n squery = squery.order_by(\"title\", \"id\", \"dt\", \"para\")\n for aud_id, items in groupby(squery, lambda x: x.id):\n data[aud_id] = self.process_item(list(items))\n return data\n\n def get(self):\n data = self.get_data()\n return jsonify(data)\n\n\nclass ZaochAuditoryMapDocxView(HolidaysMixin, ZaochAuditoryMapView):\n PAIR_HOURS = {\n 1: \"8\",\n 2: \"10\",\n 3: \"11\",\n 4: \"13\",\n 5: \"15\",\n 6: \"17\",\n 7: \"18\",\n 8: \"20\",\n }\n\n class InnerForm(Form):\n date_start = DateField(format=\"%d.%m.%Y\")\n date_end = DateField(format=\"%d.%m.%Y\")\n with_holidays = BooleanField(default=False)\n with_sunday = BooleanField(default=False)\n query = StringField(default=\"\")\n onlyOccupied = BooleanField(default=False)\n max_auditories_per_page = IntegerField(default=14)\n\n def get_auditories(self, form):\n if form.data['onlyOccupied']:\n auditories_all = Auditory.query.filter(Auditory.id.in_(self.get_data(only_auds_ids=True)))\n else:\n auditories_all = self.filter_by(Auditory.query, query=form.data['query'], field_base=Auditory)\n\n auditories_all = list(auditories_all.order_by(Auditory.title))\n return auditories_all\n\n def get(self):\n data = self.get_data()\n\n form = self.InnerForm(request.args)\n\n def keys_to_str(keys):\n keys = [i for i in keys if i >= 1 and i <= 8]\n if max(keys) != min(keys) and max(keys) - min(keys) == len(keys) - 1:\n return \"{}-{}\".format(min(keys), max(keys))\n return \",\".join(map(str, keys))\n\n if form.validate():\n from docx import Document\n\n document = Document(\"back/templates/audGridA32.docx\")\n delete_paragraph(document.paragraphs[0])\n\n name = form.data['query']\n if name == 'afanasevna':\n name = \"Т.А. Дмитриенко\"\n elif name == 'potochki':\n name = \"Поточки\"\n else:\n name = name.replace(\"-\", \"\")\n section = document.sections[0]\n r = section.header.paragraphs[0].runs[0]\n r.text = name\n\n days = (form.data['date_end'] - form.data['date_start']).days\n holidays = [d.date() if isinstance(d, datetime) else d for d in self.get_holidays()]\n dates = []\n for i, delta in enumerate(range(days + 1)):\n dt = form.data['date_start'] + timedelta(delta)\n if (form.data['with_holidays'] or dt not in holidays) and (\n form.data['with_sunday'] or dt.isoweekday() != 7):\n dates.append(dt)\n\n auditories_per_page = form.data['max_auditories_per_page']\n offset = 2\n width = Mm(14.8 * 17)\n\n auditories_all = self.get_auditories(form)\n\n pages_count = math.ceil(len(auditories_all) / auditories_per_page)\n auditories_per_page = math.ceil(len(auditories_all) / pages_count)\n cell_width = width / auditories_per_page\n pages = math.ceil(len(auditories_all) / auditories_per_page)\n for page_index in range(pages):\n\n table = document.add_table(1, auditories_per_page + offset)\n table.style = 'Table Grid'\n set_repeat_table_header(table.rows[0])\n table.columns[0].width = Mm(4.8)\n table.columns[1].width = Mm(9.5)\n\n auditories = auditories_all[page_index * auditories_per_page: (page_index + 1) * auditories_per_page]\n\n cells = list(table.rows[0].cells)\n cells[0].width = Mm(4.8)\n cells[1].width = Mm(9.5)\n for index, aud in enumerate(auditories):\n cell = cells[index + offset]\n cell.width = cell_width\n p = cell.paragraphs[0]\n r = p.add_run(\"{}\".format(aud.title))\n p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n p.vertical_alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n r.font.size = Pt(8)\n\n last_week_even = get_date_week_even(dates[0])\n last_week_even_index = 1\n\n for dt_index, dt in enumerate(dates):\n dt_key = \"{:%Y-%m-%d}\".format(dt)\n row = table.add_row()\n cells = list(row.cells)\n set_row_height(row, str(420))\n week_even = get_date_week_even(dt)\n\n week_day = {1: \"пн\", 2: 'вт', 3: 'ср', 4: 'чт', 5: 'пт', 6: 'сб', 7: 'вс'}.get(dt.isoweekday())\n week = dt.isocalendar()[1]\n week_changed = False\n\n if last_week_even != week_even:\n # week changed\n table.cell(last_week_even_index, 0).merge(table.cell(dt_index, 0))\n cell = table.cell(last_week_even_index, 0)\n cell.text = \"нечетная\" if week_even == 1 else 'четная'\n\n week_changed = True\n if last_week_even_index > 1:\n set_cell_border(cell, top={\"sz\": 24, \"val\": \"single\", \"color\": \"#000000\"})\n\n p = cell.paragraphs[0]\n p.runs[0].font_size = Pt(9)\n p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n p.vertical_alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n set_vert_cell_direction(cell)\n last_week_even = week_even\n last_week_even_index = dt_index + 1\n\n cell = cells[offset - 1]\n p = cell.paragraphs[0]\n r = p.add_run(\"{}{}\".format(week_day, '\\n'))\n r.font.size = Pt(8)\n r = p.add_run(\"{:%d.%#m}\".format(dt))\n r.font.size = Pt(8)\n p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n p.vertical_alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n\n if week_changed:\n set_cell_border(cell, top={\"sz\": 24, \"val\": \"single\", \"color\": \"#000000\"})\n\n for index, aud in enumerate(auditories):\n schedule = data.get(aud.id, {}).get('schedule', {}).get(dt_key)\n cell = cells[index + offset]\n if schedule:\n\n pairs = []\n pairs_keys = sorted(schedule.keys())\n previous_key = pairs_keys[0]\n previous_value = \", \".join([i['konts'] for i in schedule[previous_key]])\n previous_hours = 2\n last_keys = []\n for key in pairs_keys:\n value = \", \".join([i['konts'] for i in schedule[key]])\n hours = max([i['hours'] for i in schedule[key]])\n if value != previous_value:\n for x in range(previous_hours // 2 - 1):\n last_keys.append(previous_key + x + 1)\n pairs.append(\"{}: {}\".format(keys_to_str(last_keys), previous_value))\n last_keys = []\n previous_hours = hours\n previous_value = value\n previous_key = key\n last_keys.append(key)\n\n if last_keys:\n hours = max([i['hours'] for i in schedule[previous_key]])\n value = \", \".join([i['konts'] for i in schedule[previous_key]])\n for x in range(hours // 2 - 1):\n last_keys.append(previous_key + x + 1)\n pairs.append(\"{}: {}\".format(keys_to_str(last_keys), value))\n\n shading_elm = parse_xml(r''.format(nsdecls('w')))\n cell._tc.get_or_add_tcPr().append(shading_elm)\n\n p = cell.paragraphs[0]\n p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n p.vertical_alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n r = p.add_run(\"\\n\".join(pairs))\n r.font.size = Pt(7)\n\n if week_changed:\n set_cell_border(cell, top={\"sz\": 24, \"val\": \"single\", \"color\": \"#000000\"})\n\n if dt_index > last_week_even_index:\n table.cell(last_week_even_index, 0).merge(table.cell(dt_index + 1, 0))\n cell = table.cell(last_week_even_index, 0)\n cell.text = \"нечетная\" if week_even != 1 else 'четная'\n p = cell.paragraphs[0]\n p.runs[0].font_size = Pt(9)\n p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n p.vertical_alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n set_vert_cell_direction(cell)\n if last_week_even_index > 1:\n set_cell_border(cell, top={\"sz\": 24, \"val\": \"single\", \"color\": \"#000000\"})\n\n if page_index < pages - 1:\n document.add_page_break()\n\n fp = BytesIO()\n document.save(fp)\n fp.seek(0)\n\n response = make_response(send_file(fp, mimetype=\"docx\"))\n response.headers[\"Content-Disposition\"] = \\\n \"attachment;\" \\\n \"filename*=UTF-8''{utf_filename}\".format(\n utf_filename=quote(\n (form.data['query'].replace(\"-\", \"\") + \".docx\").encode('utf-8')\n )\n )\n\n return response\n\n return Response(status=404)\n\n\nclass GetAudGridDatesView(HolidaysMixin, MethodView):\n page_margin = 10\n page_height = 420\n page_width = 297\n\n class InnerForm(Form):\n date_start = DateField(format=\"%d.%m.%Y\")\n date_end = DateField(format=\"%d.%m.%Y\")\n with_holidays = BooleanField()\n with_sunday = BooleanField()\n pairs_per_day = IntegerField(default=1)\n empty = BooleanField()\n half = BooleanField()\n\n def add_table(self, document, form):\n date_cell_width = 10\n aud_cell_width = 14\n groups_count = 4\n pairs_per_day = form.data['pairs_per_day']\n\n table = document.tables[0]\n\n days = (form.data['date_end'] - form.data['date_start']).days\n holidays = [d.date() if isinstance(d, datetime) else d for d in self.get_holidays()]\n dates = []\n for i, delta in enumerate(range(days + 1)):\n dt = form.data['date_start'] + timedelta(delta)\n if (form.data['with_holidays'] or dt not in holidays) and (\n form.data['with_sunday'] or dt.isoweekday() != 7):\n dates.append(dt)\n\n last_week_even = get_date_week_even(dates[0])\n last_week_even_index = 0\n last_col_index = 0\n for index, dt in enumerate(dates):\n week_day = {1: \"пн\", 2: 'вт', 3: 'ср', 4: 'чт', 5: 'пт', 6: 'сб', 7: 'вс'}.get(dt.isoweekday())\n week = dt.isocalendar()[1]\n\n col_index = index // 27 * 2\n row_index = index % 27\n\n cell = table.cell(row_index, col_index + 1)\n p = cell.paragraphs[0]\n r = p.add_run(\"{}{}\".format(week_day, '\\n'))\n r.font.size = Pt(9)\n r = p.add_run(\"{:%d.%#m}\".format(dt))\n r.font.size = Pt(9)\n p.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT\n\n cell = table.cell(row_index, col_index)\n week_even = get_date_week_even(dt)\n cell.text = \"нечетная\" if week_even != 1 else 'четная'\n p = cell.paragraphs[0]\n p.runs[0].font_size = Pt(9)\n\n if last_week_even != week_even or last_col_index != col_index:\n if last_col_index != col_index:\n row_index = 27\n table.cell(last_week_even_index, last_col_index).merge(table.cell(row_index - 1, last_col_index))\n last_week_even = week_even\n last_week_even_index = row_index\n last_col_index = col_index\n\n def get(self):\n form = self.InnerForm(request.args)\n\n if form.validate():\n from docx import Document\n\n document = Document(\"back/templates/aud_grid_dates_A4.docx\")\n\n self.add_table(document, form)\n\n fp = BytesIO()\n document.save(fp)\n fp.seek(0)\n\n return send_file(\n fp,\n mimetype=\"docx\"\n )\n return jsonify({\n \"errors\": form.errors\n })\n\n\nclass FreeAuditoriesView(MethodView):\n def get(self):\n conditions = []\n conditions_zaoch = []\n conditions_aud_actions = []\n dates_pairs = request.args.get('dates', '').split(',')\n check_day_raspis = request.args.get('check_day_raspis') == 'true'\n\n for date_pair in dates_pairs:\n date_txt, para = date_pair.split(':')\n dt = datetime.strptime(date_txt, \"%Y-%m-%d\")\n\n para = int(para)\n\n even = get_date_week_even(dt)\n\n conditions_aud_actions.append(\n and_(\n AudActions.date == dt,\n or_(\n AudActions.para == para,\n and_(AudActions.para_count > 1, AudActions.para == para - 1),\n and_(AudActions.para_count > 2, AudActions.para == para - 2),\n ),\n )\n )\n\n if check_day_raspis and g.settings.daily_start <= dt <= g.settings.daily_end:\n if even == 0:\n week_condition = Raspis.day - 1 == dt.weekday()\n else:\n week_condition = Raspis.day - 8 == dt.weekday()\n\n conditions.append(\n and_(\n Raspis.para == para,\n or_(and_(Raspis.everyweek == 2, Raspis.day - 1 == dt.weekday()),\n and_(Raspis.everyweek == 1, week_condition))\n )\n )\n conditions_zaoch.append(\n and_(\n or_(\n RaspisZaoch.para == para,\n and_(RaspisZaoch.hours > 2, RaspisZaoch.para == para - 1),\n and_(RaspisZaoch.hours > 4, RaspisZaoch.para == para - 2),\n ),\n RaspisZaoch.dt == dt,\n )\n )\n\n exclude_ids_queries = []\n\n exclude_ids_queries.append(\n RaspisZaoch.query.filter(or_(*conditions_zaoch)).with_entities(RaspisZaoch.aud)\n )\n\n exclude_ids_queries.append(\n AudActions.query.filter(or_(*conditions_aud_actions)).with_entities(AudActions.aud)\n )\n\n if check_day_raspis and conditions:\n exclude_ids_day = Raspis.query.join(Raspnagr, Raspnagr.id == Raspis.raspnagr_id)\\\n .filter(and_(Raspnagr.sem == g.settings.semester, or_(*conditions))).with_entities(Raspis.aud_id)\n exclude_ids_queries.append(exclude_ids_day)\n\n exclude_ids = union(*exclude_ids_queries)\n\n query = Auditory.query.filter(\n ~Auditory.id.in_(exclude_ids)\n ).outerjoin(Korpus) \\\n .with_entities(Auditory.id, Auditory.title, Auditory.maxstud, Korpus.title.label('korpus')) \\\n .order_by(Auditory.title)\n\n auditories = [{\n 'value': a.id,\n 'label': \"{} ({} чел.)\".format(a.title.strip(), a.maxstud),\n 'size': a.maxstud,\n 'korpus': a.korpus.strip() if a.korpus else '',\n } for a in query]\n return jsonify({\n 'auditories': auditories\n })\n\n\nclass AuditoryOccupationAt(MethodView):\n def get(self):\n dates_pairs = request.args.get('dates', '').split(',')\n\n auds = Auditory.query.order_by(Auditory.title).all()\n auds = {i.id: {\n 'id': i.id,\n 'title': i.title.strip(),\n 'maxstud': i.maxstud,\n 'occupation': {}\n } for i in auds}\n\n for date_pair in dates_pairs:\n date_txt, para = date_pair.split(':')\n dt = datetime.strptime(date_txt, \"%Y-%m-%d\")\n\n even = get_date_week_even(dt)\n\n para = int(para)\n\n if g.settings.daily_start <= dt <= g.settings.daily_end:\n if even == 0:\n week_condition = Raspis.day - 1 == dt.weekday()\n else:\n week_condition = Raspis.day - 8 == dt.weekday()\n\n items = Raspis.query.filter(\n Raspis.para == para,\n or_(and_(Raspis.everyweek == 2, Raspis.day - 1 == dt.weekday()),\n and_(Raspis.everyweek == 1, week_condition))\n )\\\n .outerjoin(Raspnagr, Raspnagr.id == Raspis.raspnagr_id)\\\n .outerjoin(Kontkurs, Kontkurs.id == Raspnagr.kontkurs_id)\\\n .outerjoin(Kontgrp, Kontgrp.id == Raspnagr.kontgrp_id)\\\n .outerjoin(Potoklist, Potoklist.op == Raspnagr.op)\\\n .with_entities(\n Raspis.aud_id,\n Raspnagr.stud,\n func.coalesce(Potoklist.title, Kontgrp.title, Kontkurs.title).label(\"kont\")\n )\n\n for item in items:\n if item.aud_id in auds:\n arr = auds.setdefault(item.aud_id, {'occupation': {}})\n para_item = arr['occupation'].setdefault(para, {\n 'title': item.kont.replace(\"(И,О)\", \"\").strip(),\n 'stud': item.stud\n })\n\n return jsonify({\n 'auditories': sorted(auds.values(), key=lambda x: x['title'])\n })\n\n\n\n\n\napp.add_url_rule(\"/api/aud_grid_dates.docx\", view_func=GetAudGridDatesView.as_view(\"aud_grid_dates\"), methods=['GET'])\napp.add_url_rule(\"/api/auditories-schedule.json\",\n view_func=ZaochAuditoryMapView.as_view(\"auditories_map_schedule_json\"))\napp.add_url_rule(\"/api/auditories-schedule.docx\",\n view_func=ZaochAuditoryMapDocxView.as_view(\"auditories_map_schedule_docx\"))\napp.add_url_rule(\"/api/auditories-schedule\", view_func=ZaochAuditoryMapView.as_view(\"auditories_map_schedule\"))\napp.add_url_rule(\"/api/free-auditories/\", view_func=FreeAuditoriesView.as_view(\"free_auditories\"), methods=['GET'])\napp.add_url_rule(\"/api/auditory-occupation/\", view_func=AuditoryOccupationAt.as_view(\"auditory-occupation\"), methods=['GET'])\n","sub_path":"back/views/zaoch/auditories.py","file_name":"auditories.py","file_ext":"py","file_size_in_byte":25777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"415218989","text":"from django.conf import settings\nfrom django.utils.translation import gettext as _, get_language\n\n\nclass Page:\n def __init__(self, request):\n self.request = request\n\n def __call__(self, page):\n label, name = page\n\n return {\n 'label': label,\n 'name': name,\n 'current': self.name == name,\n }\n\n @property\n def name(self):\n return self.request.resolver_match.view_name\n\n\nclass ContextProcessor:\n @property\n def is_auth(self):\n return self.request.user.is_authenticated\n\n @property\n def full_path(self):\n return self.request.get_full_path()\n\n @property\n def lang(self):\n return get_language()\n\n @property\n def language_links(self):\n for code, label in settings.LANGUAGES:\n yield {\n 'code': code,\n 'label': label,\n 'current': code == self.lang,\n 'path': self.i18n_path(code),\n }\n\n @property\n def auth_pages(self):\n if self.is_auth:\n return [\n (_('Topics'), 'fpy:topic-list'),\n (_('Logout'), 'fpy:logout'),\n ]\n\n return [\n (_('Login'), 'fpy:login'),\n (_('Signup'), 'fpy:signup'),\n ]\n\n def i18n_path(self, code):\n return self.full_path.replace(self.lang, code, 1)\n\n def __call__(self, request):\n self.request = request\n\n return {\n 'language_links': self.language_links,\n 'pages': map(\n Page(request),\n [\n (_('Home'), 'site:home'),\n *self.auth_pages,\n ],\n ),\n 'json_context': {\n 'isAuthenticated': self.is_auth,\n 'availableLanguages': dict(settings.LANGUAGES),\n },\n }\n\n\ncontext_processor = ContextProcessor()\n","sub_path":"fpy/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"245053549","text":"#### insAnimation.py\n#### usage: pvbatch pvbatch insAnimation.py 1 ../examples/cnsTri2D/foo foo\n\n\n#### import the simple module from the paraview\nfrom paraview.simple import *\nimport glob \n#### disable automatic camera reset on 'Show'\nparaview.simple._DisableFirstRenderCameraReset()\n\nNdatasets = int(sys.argv[1])\ndatasetIn = sys.argv[2]\nimageFilesOut = sys.argv[3]\n\ndataset = range(0,Ndatasets)\ndatasetDisplay = range(0,Ndatasets)\nfor n in range(0,Ndatasets):\n\tNfiles = len(glob.glob(datasetIn+'_%04d_*.vtu' % n))\n\tfiles = range(0,Nfiles)\n\tfor m in range(0,Nfiles):\n\t\tfiles[m] = glob.glob(datasetIn+'_%04d_%04d.vtu' % (n,m))[0]\n\n\t# create a new 'XML Unstructured Grid Reader'\n\tdataset[n] = XMLUnstructuredGridReader(FileName=files)\n\tdataset[n].PointArrayStatus = ['Pressure', 'Divergence', 'Vorticity', 'Velocity']\n\n\t# set active source\n\t#SetActiveSource(dataset[n])\n\n# get animation scene\nanimationScene1 = GetAnimationScene()\n\n# update animation scene based on data timesteps\nanimationScene1.UpdateAnimationUsingDataTimeSteps()\n\n# create a new 'Group Datasets'\ngroupDatasets1 = GroupDatasets(Input=dataset)\n\n# get active view\nrenderView1 = GetActiveViewOrCreate('RenderView')\n# uncomment following to set a specific view size\n# renderView1.ViewSize = [1599, 803]\n\n# reset view to fit data\nrenderView1.ResetCamera()\n\n#changing interaction mode based on data extents\n# renderView1.InteractionMode = '2D'\n# renderView1.CameraPosition = [-0.39905500411987305, 0.0, 10000.0]\n# renderView1.CameraFocalPoint = [-0.39905500411987305, 0.0, 0.0]\n\n# # show data in view\ngroupDatasets1Display = Show(groupDatasets1, renderView1)\n# trace defaults for the display properties.\ngroupDatasets1Display.Representation = 'Surface'\ngroupDatasets1Display.ColorArrayName = [None, '']\ngroupDatasets1Display.OSPRayScaleArray = 'Divergence'\ngroupDatasets1Display.OSPRayScaleFunction = 'PiecewiseFunction'\ngroupDatasets1Display.SelectOrientationVectors = 'Divergence'\ngroupDatasets1Display.ScaleFactor = 1.8\ngroupDatasets1Display.SelectScaleArray = 'Divergence'\ngroupDatasets1Display.GlyphType = 'Arrow'\ngroupDatasets1Display.GlyphTableIndexArray = 'Divergence'\ngroupDatasets1Display.DataAxesGrid = 'GridAxesRepresentation'\ngroupDatasets1Display.PolarAxes = 'PolarAxesRepresentation'\ngroupDatasets1Display.ScalarOpacityUnitDistance = 0.1199621937768176\ngroupDatasets1Display.GaussianRadius = 0.9\ngroupDatasets1Display.SetScaleArray = ['POINTS', 'Divergence']\ngroupDatasets1Display.ScaleTransferFunction = 'PiecewiseFunction'\ngroupDatasets1Display.OpacityArray = ['POINTS', 'Divergence']\ngroupDatasets1Display.OpacityTransferFunction = 'PiecewiseFunction'\n\n# # hide data in view\n# #Hide(foo_0001_000, renderView1)\n\n# # hide data in view\n# #Hide(foo_0000_000, renderView1)\n\n# # update the view to ensure updated data information\nrenderView1.Update()\n\n# set scalar coloring\nColorBy(groupDatasets1Display, ('POINTS', 'Vorticity'))\n\n# Hide the scalar bar for this color map if no visible data is colored by it.\n#HideScalarBarIfNotNeeded(vtkBlockColorsLUT, renderView1)\n\n# rescale color and/or opacity maps used to include current data range\ngroupDatasets1Display.RescaleTransferFunctionToDataRange(True, False)\n\n# show color bar/color legend\n#groupDatasets1Display.SetScalarBarVisibility(renderView1, True)\n\n# get color transfer function/color map for 'Vorticity'\nvorticityLUT = GetColorTransferFunction('Vorticity')\n\n# Rescale transfer function\nvorticityLUT.RescaleTransferFunction(-4.0, 4.0)\n\n# get opacity transfer function/opacity map for 'Vorticity'\nvorticityPWF = GetOpacityTransferFunction('Vorticity')\n\n# Rescale transfer function\nvorticityPWF.RescaleTransferFunction(-4.0, 4.0)\n\n# Hide orientation axes\nrenderView1.OrientationAxesVisibility = 0\ngroupDatasets1Display.SetScalarBarVisibility(renderView1, False)\n\n# current camera placement for renderView1\nrenderView1.InteractionMode = '2D'\nrenderView1.CameraPosition = [3.8648142362157496, -0.12321016819782263, 25.0]\nrenderView1.CameraFocalPoint = [3.8648142362157496, -0.12321016819782263, 0.0]\nrenderView1.CameraParallelScale = 6.210760565455133\n\n# save animation\n#SaveAnimation(imageFilesOut+'.avi', renderView1, ImageResolution=[1596, 800], FrameRate=15, FrameWindow=[0, len(files)])\nSaveAnimation(imageFilesOut+'.png', renderView1, ImageResolution=[1855, 1163],\n FrameWindow=[0, 10])\n\n#### uncomment the following to render all views\n#RenderAllViews()\n# alternatively, if you want to write images, you can use SaveScreenshot(...).\n\n# save screenshot\n#SaveScreenshot(imageFilesOut+'.png', renderView1, ImageResolution=[1599, 803])","sub_path":"scripts/insAnimation.py","file_name":"insAnimation.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"44154403","text":"import bokeh.plotting as bk_plt\nimport bokeh.models as bk_models\nimport bokeh.layouts as bk_layouts\n\n\nclass OneTeam:\n\n def __init__(self, data):\n self.measures = data.measures\n self.schedule = data.schedule\n\n def callback_1t(self, attr, old, new):\n print('In callback for team:', new)\n self.layout.children[1] = self.plot_1t(new)\n\n def df_new_1t(self, team):\n df_matches = self.schedule[(self.schedule.team == team)]\n match_list = df_matches.match.unique()\n sorted_match = self.measures[self.measures.match.isin(match_list)]\n sorted_match = sorted_match[(sorted_match.team == team)]\n sorted_task = sorted_match[sorted_match.task.isin(['shootUpper',\n 'shootLower'])]\n grouped = sorted_task.groupby(['match', 'task'])\n grouped = grouped.sum()\n grouped = grouped.drop(columns=grouped.columns[1:5])\n df_unstacked = grouped.unstack()\n df_unstacked.columns = df_unstacked.columns.droplevel()\n df_fil = df_unstacked.fillna(0)\n return df_fil\n\n def plot_1t(self, team):\n self.cds = bk_models.ColumnDataSource(self.df_new_1t(team))\n col_names = self.cds.column_names\n tasks = col_names[1:3]\n matches = self.cds.data['match']\n plt_title = \"Team \" + team\n colors = ['#30678D', '#FDE724']\n self.pcplot = bk_plt.figure(x_range=matches, plot_height=250,\n title=plt_title, tools=\"hover\", tooltips=\"$name: @$name\")\n self.pcplot.vbar_stack(tasks, x='match', width=0.4,\n source=self.cds, color=colors,\n legend_label=[\" \" + x for x in tasks])\n return self.pcplot\n\n def list_teams(self):\n return list(self.schedule.team.unique())\n\n def layout_1t(self, team):\n plot_1t = self.plot_1t(team)\n team_sel = bk_models.Select(title='Team', options=self.list_teams())\n team_sel.on_change('value', self.callback_1t)\n self.layout = bk_layouts.row(team_sel, plot_1t)\n return self.layout\n\n def panel(self, team):\n layout = self.layout_1t(team)\n return bk_models.Panel(child=layout, title='One Team Charts')\n","sub_path":"viewer_app/oneteam_pc.py","file_name":"oneteam_pc.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"630057775","text":"#!/usr/bin/env python\n\n\"\"\"List the locations of accessible sequence regions in a FASTA file.\n\nInaccessible regions, e.g. telomeres and centromeres, are masked out with N in\nthe reference genome sequence; this script scans those to identify the\ncoordinates of the accessible regions (those between the long spans of N's).\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nfrom builtins import next, zip\n\nimport itertools\nimport logging\n\nimport numpy as np\n\nfrom cnvlib.ngfrills import parse_regions\n\n\ndef log_this(chrom, run_start, run_end):\n \"\"\"Log a coordinate range, then return it as a tuple.\"\"\"\n logging.info(\"\\tAccessible region %s:%d-%d (size %d)\",\n chrom, run_start, run_end, run_end - run_start)\n return (chrom, run_start, run_end)\n\n\ndef get_regions(fasta_fname):\n \"\"\"Find accessible sequence regions (those not masked out with 'N').\"\"\"\n with open(fasta_fname) as infile:\n chrom = cursor = run_start = None\n for line in infile:\n if line.startswith('>'):\n # Emit the last chromosome's last run, if any\n if run_start is not None:\n yield log_this(chrom, run_start, cursor)\n # Start new chromosome\n chrom = line.split(None, 1)[0][1:]\n run_start = None\n cursor = 0\n logging.info(\"%s: Scanning for accessible regions\", chrom)\n else:\n line = line.rstrip()\n if 'N' in line:\n if all(c == 'N' for c in line):\n # Shortcut if the line is all N chars\n if run_start is not None:\n yield log_this(chrom, run_start, cursor)\n run_start = None\n else:\n # Slow route: line is a mix of N and non-N chars\n line_chars = np.array(line, dtype='c')\n n_indices = np.where(line_chars == 'N')[0]\n # Emit the first block of non-N chars, if any\n if run_start is not None:\n yield log_this(chrom, run_start, cursor + n_indices[0])\n elif n_indices[0] != 0:\n yield log_this(chrom, cursor, cursor + n_indices[0])\n # Emit any short intermediate blocks\n gap_mask = np.diff(n_indices) > 1\n if gap_mask.any():\n ok_starts = n_indices[gap_mask] + 1 + cursor\n ok_ends = n_indices[1:][gap_mask] + cursor\n for start, end in zip(ok_starts, ok_ends):\n yield log_this(chrom, start, end)\n # Account for any tailing non-N chars\n if n_indices[-1] + 1 < len(line_chars):\n run_start = cursor + n_indices[-1] + 1\n else:\n run_start = None\n else:\n if run_start is None:\n # Start of a new run of non-N characters\n run_start = cursor\n cursor += len(line)\n # Emit the last run if it's accessible (i.e. not a telomere)\n if run_start is not None:\n yield log_this(chrom, run_start, cursor)\n\n\ndef group_regions_by_chromosome(rows):\n \"\"\"Iterate through BED3 rows: (chrom, BED3-rows-in-this-chrom)\"\"\"\n for chrom, rows in itertools.groupby(rows, lambda bed3: bed3[0]):\n yield chrom, [(start, end) for _chrom, start, end in rows]\n\n\ndef join_regions(regions, min_gap_size):\n \"\"\"Filter regions, joining those separated by small gaps.\"\"\"\n for chrom, coords in group_regions_by_chromosome(regions):\n logging.info(\"%s: Joining over small gaps\", chrom)\n coords = iter(coords)\n prev_start, prev_end = next(coords)\n for start, end in coords:\n gap = start - prev_end\n assert gap > 0, (\"Impossible gap between %s %d-%d and %d-%d (=%d)\"\n % (chrom, prev_start, prev_end, start, end, gap))\n if gap < min_gap_size:\n # Join with the previous region\n logging.info(\"\\tJoining %s %d-%d and %d-%d (gap size %d)\",\n chrom, prev_start, prev_end, start, end, gap)\n prev_end = end\n else:\n # Keep the gap; emit the previous region as-is\n logging.info(\"\\tKeeping gap %s:%d-%d (size %d)\",\n chrom, prev_end, start, gap)\n yield (chrom, prev_start, prev_end)\n prev_start, prev_end = start, end\n yield (chrom, prev_start, prev_end)\n\n\ndef exclude_regions(bed_fname, access_rows):\n ex_by_chrom = dict(group_regions_by_chromosome(\n parse_regions(bed_fname, coord_only=True)))\n if len(ex_by_chrom) == 0:\n # Nothing to exclude -> emit the input regions unmodified\n for row in access_rows:\n yield row\n else:\n # Check if each input region overlaps an excluded region\n for chrom, a_rows in group_regions_by_chromosome(access_rows):\n if chrom in ex_by_chrom:\n logging.info(\"%s: Subtracting excluded regions\", chrom)\n exclude_rows = iter(ex_by_chrom[chrom])\n ex_start, ex_end = next_or_inf(exclude_rows)\n for a_start, a_end in a_rows:\n for row in exclude_in_region(exclude_rows, chrom, a_start,\n a_end, ex_start, ex_end):\n yield row\n else:\n logging.info(\"%s: No excluded regions\", chrom)\n for a_start, a_end in a_rows:\n yield (chrom, a_start, a_end)\n\n\ndef exclude_in_region(exclude_rows, chrom, a_start, a_end, ex_start, ex_end):\n \"\"\"Take region exclusions from an iterable and apply, perhaps recursively.\n\n Returns an iterable (usually length 1) of two tuples:\n (accessible chromosome, start, end)\n (current exclusion start, end)\n \"\"\"\n # If we've leapfrogged the excluded area, catch up\n while ex_end <= a_start:\n ex_start, ex_end = next_or_inf(exclude_rows)\n if a_end <= ex_start:\n # Excluded area does not overlap this one\n yield (chrom, a_start, a_end)\n else:\n # Excluded area overlaps this one -> trim this region\n logging.info(\"\\tExclusion %s:%d-%d overlaps accessible region %d-%d\",\n chrom, ex_start, ex_end, a_start, a_end)\n if ex_start <= a_start:\n if ex_end < a_end:\n # Exclusion covers this region's left (start) edge only\n for row in exclude_in_region(exclude_rows, chrom, ex_end, a_end,\n ex_start, ex_end):\n yield row\n # Otherwise: Exclusion covers the whole region\n else:\n yield (chrom, a_start, ex_start)\n if ex_end < a_end:\n # Exclusion is in the middle of this region\n for row in exclude_in_region(exclude_rows, chrom, ex_end,\n a_end, ex_start, ex_end):\n yield row\n # Otherwise: Exclusion covers this region's right (end) edge only\n\n\ndef next_or_inf(iterable):\n try:\n return next(iterable)\n except StopIteration:\n return float(\"Inf\"), float(\"Inf\")\n\n","sub_path":"cnvlib/access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":7587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"5655134","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Initial migration\n\nRevision ID: 464e951dc3b8\nRevises: None\nCreate Date: 2014-08-05 17:41:34.470183\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '464e951dc3b8'\ndown_revision = None\n\nfrom alembic import op # noqa: E402\nimport sqlalchemy as sa # noqa: E402\n\n\ndef upgrade():\n op.create_table(\n 'states',\n sa.Column('name', sa.String(length=255), nullable=False),\n sa.Column('state', sa.BigInteger(), nullable=False),\n sa.Column('s_metadata', sa.Text(), nullable=True),\n sa.PrimaryKeyConstraint('name'))\n op.create_table(\n 'modules_state',\n sa.Column('name', sa.String(length=255), nullable=False),\n sa.Column('state', sa.Boolean(), nullable=False),\n sa.PrimaryKeyConstraint('name'))\n","sub_path":"cloudkitty/db/sqlalchemy/alembic/versions/464e951dc3b8_initial_migration.py","file_name":"464e951dc3b8_initial_migration.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"628723262","text":"class Solution:\n # @param A, a list of integers\n # @return an integer\n def jump(self, A):\n step = 0\n end = len(A) - 1\n while end > 0:\n for pos in range(end):\n if pos + A[pos] >= end:\n end = pos\n step += 1\n \n return step \n","sub_path":"src/main/python/lc/jump_game_2.py","file_name":"jump_game_2.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"128346221","text":"import json as j\nimport os\nimport random\nimport pandas as pd\nimport json\nimport xml.etree.cElementTree as e\n\npath = '/content/drive/MyDrive/객체탐지/json_label'\nfile_list = os.listdir(path)\nimage_file_list_py = [file for file in file_list if file.endswith('.json')] \nimage_file_list_py.sort()\nimage_file_list_py\n\nfor i in range(len(image_file_list_py)):\n\n with open(\"/content/drive/MyDrive/객체탐지/json_label/\"+image_file_list_py[i]) as json_format_file:\n d = j.load(json_format_file)\n \n r = e.Element(\"annotation\")\n\n e.SubElement(r,\"folder\").text = \"testpart\"\n e.SubElement(r,\"filename\").text = d[0]['image']\n for w in d[0][\"annotations\"]:\n object = e.SubElement(r,\"object\")\n e.SubElement(object,\"name\").text = \"error\"\n bndbox = e.SubElement(object,\"bndbox\")\n e.SubElement(bndbox,\"xmin\").text=str(w[\"coordinates\"][\"x\"])\n e.SubElement(bndbox,\"ymin\").text=str(w[\"coordinates\"][\"y\"])\n e.SubElement(bndbox,\"xmax\").text=str(w[\"coordinates\"][\"width\"])\n e.SubElement(bndbox,\"ymax\").text=str(w[\"coordinates\"][\"height\"])\n\n a=e.ElementTree(r)\n\n image_file_list_py2 = image_file_list_py[i].split(\".\")[0]\n\n print(image_file_list_py[i])\n\n a.write(\"/content/drive/MyDrive/json/\" + image_file_list_py2)\n","sub_path":"Convert json file to xml file.py","file_name":"Convert json file to xml file.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"647864461","text":"# http://tutorial.djangogirls.org/en/installation/ # reference\n# install python2.7\n## virtualenv -p /usr/bin/python2.7 ./virtual_env/venv\n# pip install django\n# pip install gspread\n# pip install gdata or download the package into the path Downloads/gdata/gdata-python-client-master/ sudo ./setup.py install\n# https://pythonhosted.org/gdata/installation.html\n# pip install psycopg2\n# pip install --upgrade oauth2client\n\n################### django-sheets get the google sheet contents to show up like a table\n#### https://django-sheets.readthedocs.org/en/latest/usage.html \n# pip install django-sheets\n# Add sheets to INSTALLED_APPS in settings.py:\n''' \nINSTALLED_APPS = (\n ...\n 'sheets',\n ...\n)\n'''\n#!/usr/bin/python\n\nimport gdata.docs.service\nfrom gdata.spreadsheets.client import SpreadsheetsClient\nimport gdata.gauth\n\n\n# Create a client class which will make HTTP requests with Google Docs server.\nclient = gdata.docs.service.DocsService()\n# Authenticate using your Google Docs email address and password.\n\nclient.Download('https://docs.google.com/spreadsheets/d/1mu9CVYUIi81Ntag5eIEzJEUV8RmWT_V0DCzmh9lqwAs/edit#gid=1489986476','/Users/yiweisun/Downloads/gdata/iah1_metadata_2016')\ndocuments_feed = client.GetDocumentListFeed()\n\n\n################################################################################ from https://gist.github.com/egor83/4634422#file-google_spreadsheets-py\n'''\nclient = gdata.spreadsheets.client.SpreadsheetsClient()\n\ntoken = GetAuthSubUrl()\ntoken.authorize(client)\n\nsps = client.GetSpreadsheets()\nprint len(sps.entry) # shows how many spreadsheets you have\n\nsprd_key = '1ZPIYJtaPNIEpT_rvvR3WfKvXYx1_p2vZtHycCPUUaJg' # a certain key\nwss = client.GetWorksheets(sprd_key) # get a list of all worksheets in this spreadsheet, to look around for info in a debugger\nws = client.GetWorksheet(sprd_key, 'od6') # get the first worksheet in a spreadsheet; seems 'od6' is always used as a WS ID of the first worksheet\ndef GetAuthSubUrl():\n next = 'http://www.example.com/myapp.py'\n scopes = ['http://docs.google.com/feeds/', 'https://docs.google.com/feeds/']\n secure = False # set secure=True to request a secure AuthSub token\n session = True\n return gdata.gauth.generate_auth_sub_url(next, scopes, secure=secure, session=session)\n\nprint '
Login to your Google account' % GetAuthSubUrl()\n'''\n######################################### to get the googlesheet contents method succeed...\n\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n\nscope = ['https://spreadsheets.google.com/feeds']\npath_to_json = '/Users/yiweisun/Downloads/GoogleSheetTest-d112a30fe1a8.json'\ncredentials = ServiceAccountCredentials.from_json_keyfile_name(path_to_json, scope)\ngc = gspread.authorize(credentials)\n\n#wks = gc.open(\"iah1_metadata_2016\").sheet1 #gspread.exceptions.SpreadsheetNotFound\n#wks = gc.open(\"iah1_metadata_2016\") #gspread.exceptions.SpreadsheetNotFound\n#inDjango, method\n##### gspread http://www.indjango.com/access-google-sheets-in-python-using-gspread/\n\n\nsh = gc.open_by_url('https://docs.google.com/spreadsheets/d/1mu9CVYUIi81Ntag5eIEzJEUV8RmWT_V0DCzmh9lqwAs/edit#gid=1489986476')\n\nsh1 = gc.open_by_url('https://docs.google.com/spreadsheets/d/1ZPIYJtaPNIEpT_rvvR3WfKvXYx1_p2vZtHycCPUUaJg/edit#gid=2130071960')\nsh1 = gc.open_by_key('1ZPIYJtaPNIEpT_rvvR3WfKvXYx1_p2vZtHycCPUUaJg')\n##### gspread http://www.indjango.com/access-google-sheets-in-python-using-gspread/\n#worksheet = sh.get_worksheet(4)\nworksheet=sh1.worksheet('data_collector')\nworksheet_list = sh.worksheets()\n# worksheet_list\nvalues_list = worksheet.row_values(1)\nvalues_list_2 = worksheet.row_values(2)\nvalues_list_3 = worksheet.row_values(3)\n\nworksheet_1 = sh1.get_worksheet(4)\nworksheet_list_1 = sh.worksheets()\nworksheet_list_1\n# before to do the openall(), you have to share the documents with the client email that in the downloaded json file. for example, scenic-setup-128014@appspot.gserviceaccount.com, which \n# is NOT the gmail email account. \nsh_all = gc.openall()\n#######################################step 1 from http://heinrichhartmann.com/2015/05/17/Using-the-Google-Drive-Spreadsheet-API.html\n","sub_path":"googleSheetIntoDB/test_GoogleSheetReading.py","file_name":"test_GoogleSheetReading.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"411360285","text":"\"\"\"\nThis file works with Stripe, our payment api.\n\"\"\"\n\nfrom settings import *\nfrom essentials import *\n\nfrom messaging import *\n\nimport stripe\n\n\n\n\"\"\"\nSends the user a link to checkout.\n\"\"\"\ndef checkout(msg):\n \n stripe.api_key = STRIPE_API_KEY\n product_id = STRIPE_PRODUCT_ID\n\n #if this is the demo number then use development credentials even if in deployment\n if msg.to == \"+12676276054\":\n product_id = STRIPE_TEST_PRODUCT_ID\n stripe.api_key = STRIPE_TEST_API_KEY\n\n #creates a checkout session with stripe api\n session = stripe.checkout.Session.create(\n payment_method_types = ['card'],\n line_items=[{\n \n 'price_data': {\n 'unit_amount': subtotal(msg)+tax(msg),\n 'currency': 'usd',\n 'product': product_id,\n },\n 'quantity': 1,\n }],\n mode='payment',\n success_url='https://dashboard.autoordersystems.com/success/',\n cancel_url='https://dashboard.autoordersystems.com/failure/',\n )\n\n #stores the unique id\n OPC.update_one(current_order(msg), {\"$set\":{\"payment_intent\":session.payment_intent}})\n\n #craft response\n resp = \"Here is your link to checkout. Your order will be processed once you pay. \\n\\nhttps://dashboard.autoordersystems.com/checkout/{id}\".format(id=session.id)\n if msg.to == \"+12676276054\":\n resp += \"\\n\\nDEMO: Use 4242 4242 4242 4242 as the credit card number. Type in anything for the rest of the information.\"\n\n return send_message(resp)","sub_path":"payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"226213523","text":"from util.Functions import *\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s')\nlogger = logging.getLogger(__name__)\n\n\nappname=\"10_LEAPFROG_1D\"\n\nfn = Functions()\nnorm, err = fn.initialize_arrays(2)\n\n\nlogger.info(\"Starting {} =======================\".format(appname))\n\nu = fn.get_gaussian()\nu0 = fn.get_gaussian(ctype=\"1D\")\n\nfn.pre_plot(1)\nfn.plot([[fn.x_val,u],\"u(x,T=0)\"])\n\n\nfor i,n in enumerate(pr.distance):\n un= fn.leapfrog(u0,u,\"1D\")\n norm = fn.add_to_array(\"norm\",un,norm)\n if i in pr.selected_entries_1D.keys():\n if i in pr.error_entries: err= fn.add_to_array(\"err\",un,err)\n fn.plot([[fn.x_val,un],\"u(x,T={})\".format(str(pr.selected_entries_1D[i]))])\n u0= u\n u= un\nlogger.info(\"Performed {} iterations for Leapfrog 1D and norm.\".format(str(i)))\n\nfn.post_plot(appname,\"x\",\"u\",\"Leapfrog 1D Method\",\"out\")\n\nfn.pre_plot(2)\nfn.plot([[pr.distance,norm],\"\"])\nfn.post_plot(appname,\"t\",\"L2 Norm\",\"L2 Norm with Leapfrog 1D Method\",\"norm\")\n\nfn.pre_plot(3)\nfn.plot([[list(pr.error_entries.values()),err,'o-'],\"\"])\nfn.post_plot(appname,\"t\",\"Error of L2 Norm\",\"Norma l2 per errore della soluzione con metodo Leapfrog 1D\",\"normerror\")\n\nlogger.info(\"======================= {} END\".format(appname))","sub_path":"pde/1DLEAPFROG.py","file_name":"1DLEAPFROG.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"311332038","text":"# -*- coding: utf-8 -*-\n#wallhaven爬取\nimport os\nfrom urllib.parse import urlencode\nimport time\nimport random\nimport requests\nfrom lxml import etree\n\n# NSFW分类请登录网址F12抓取Cookie,在此处填写!!!!\ncookie = [\"\"]\n \ndef GetHeaders(): \n if len(cookie[0])>0:\n headers = {\n \"cookie\":cookie[0],\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5)\\AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36\"\n }\n else :\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5)\\AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36\"\n }\n return headers\n\n#定义创建文件路径函数,将下载的文件存储到该路径\ndef CreatePath(filepath):\n if not os.path.exists(filepath):\n os.makedirs(filepath)\n\n#定义获取url函数,这里是通过urlencode方法把url的各个部分拼接起来的,拼接起来的url\n#像是这样的:https://wallhaven.cc/search?q=girls&categories=111&purity=110&sorting=toplist&order=desc \ndef GetUrl(keyword,category,purity):\n params = {\n 'q': keyword,\n 'categories': category,\n 'purity': purity,#\\100\\010\\110\n 'sorting': 'favorites', #relevance\\random\\date_added\\views\\favorites\\toplist\\toplist-beta\n 'topRange':'1y', #1y\\6M\\3M\\1w\\3d\\1d\n 'order':'desc'#,\n #'page':1\n }\n base_url='https://wallhaven.cc/search?'\n url=base_url + urlencode(params)\n print(url)\n return url\n\n#获取查找到的图片数\ndef GetPictureNum(url):\n allpic=\" \"\n try:\n html = requests.get(url, headers= GetHeaders()) \n if 200 == html.status_code:\n selector = etree.HTML(html.text) \n pageInfo = selector.xpath('//header[@class=\"listing-header\"]/h1[1]/text()')#提取出文本\n string = str(pageInfo[0])#图片数是文本中的第一个\n numlist = list(filter(str.isdigit,string)) #有些数字是这样的,11,123,所以需要整理。\n for item in numlist:\n allpic+=item\n totalPicNum=int(allpic) #把拼接起来的字符串进行整数化\n return totalPicNum\n except requests.ConnectionError:\n return None\n \n#获取图片链接\ndef GetLinks(url,number):\n urls=url+'&page='+str(number)\n try:\n html=requests.get(urls, headers= GetHeaders())\n selector=etree.HTML(html.text)\n PicLink=selector.xpath('//a[@class=\"preview\"]/@href')#这里寻找图片的链接地址,以求得到图片编号\n except Exception as e:\n print('Error',e.args)\n return PicLink \n \n#下载函数 \ndef Download(filepath,url):\n picStr = url.replace('https://wallhaven.cc/w/','') #python3 replace\n picJpg = filepath+'wallhaven-'+picStr+'.jpg'\n picPng = filepath+'wallhaven-'+picStr+'.png'\n\n if os.path.exists(picJpg)|os.path.exists(picPng):\n return\n #此函数用于图片下载。其中参数url是形如:https://wallhaven.cc/w/eyyoj8 的网址\n #因为wallheaven上只有两种格式的图片,分别是png和jpg,所以设置两种最终地址HtmlJpg和HtmlPng,通过status_code来进行判断,状态码为200时请求成功。\n \n #print(picStr)\n HtmlJpg='https://w.wallhaven.cc/full/'+ picStr[0:2] +'/wallhaven-' + picStr +'.jpg'\n HtmlPng='https://w.wallhaven.cc/full/'+ picStr[0:2] +'/wallhaven-' + picStr +'.png'\n \n try:\n pic=requests.get(HtmlJpg,headers= GetHeaders())\n if 200== pic.status_code:\n pic_path= picJpg \n else:\n pic= requests.get(HtmlPng,headers= GetHeaders())\n if 200== pic.status_code:\n pic_path= picPng\n else:\n print(\"Downloaded error:\",picStr)\n return\n with open(pic_path,'wb') as f:\n f.write(pic.content)\n f.close()\n print(\"Downloaded image:\",picStr) \n except Exception as e:\n print(repr(e)) \n \n#主函数\ndef main():\n\n filepath = ('/wallpaper/Pictures/')#存储路径。\n\n keyword = input('请输入关键词:')\n category = input('请输入图片分类,Gneral,Anime,People三种,如果你想要只想选择Anime,就键入010,如果全选就键入111,以此类推:')\n purity = input('请输入权限分类,SFW,Sketchy,NSFW三种,如果你想要只想选择Sketchy,就键入010,如果全选就键入111(NSFW分类需cookie)),以此类推:')\n\n CreatePath(filepath) #创建保存路径\n url = GetUrl(keyword,category,purity) #获取url\n \n PicNum = GetPictureNum(url)#总图片数\n pageNum = int(PicNum/24+1) #求出总页面数\n print(\"We found:\"+format(PicNum)+\" images,\"+format(pageNum)+\" pages.\")\n\n \n pageInput = input(\"请输入你想要爬的图片的开始页【每页24张】:\")\n pageStart = int(pageInput)\n \n for i in range(pageStart,pageNum):\n PicUrl=GetLinks(url,i+1)\n for item in PicUrl:\n #print(item)\n Download(filepath,item)\n \n # 打开一个文件\n fo = open(\"page.txt\", \"w+\",encoding='utf-8')\n fo.write(\"page\"+ str(i) +\":\"+item+\"\\n\")\n # 关闭打开的文件\n fo.close()\n time.sleep(random.uniform(0,5)) #这里是让爬虫在下载完一张图片后休息一下,防被侦查到是爬虫从而引发反爬虫机制。\n time.sleep(random.uniform(10,20)) #这里是让爬虫在下载完一张图片后休息一下,防被侦查到是爬虫从而引发反爬虫机制。 \n\n\nif __name__ == '__main__':\n main()","sub_path":"wallhaven1.1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"352380918","text":"# Copyright 2019 QuantRocket 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\nimport pandas as pd\nfrom moonshot import MoonshotML\nfrom moonshot.commission import PerShareCommission\nfrom quantrocket.fundamental import get_sharadar_fundamentals_reindexed_like\nfrom quantrocket import get_prices\nfrom quantrocket.master import get_securities_reindexed_like\n\nclass USStockCommission(PerShareCommission):\n BROKER_COMMISSION_PER_SHARE = 0.005\n\nclass TheKitchenSinkML(MoonshotML):\n\n CODE = \"kitchensink-ml\"\n DB = \"sharadar-us-stk-1d\"\n DB_FIELDS = [\"Close\", \"Volume\"]\n BENCHMARK_DB = \"market-1d\"\n SPY_SID = \"FIBBG000BDTBL9\"\n VIX_SID = \"IB13455763\"\n TRIN_SID = \"IB26718743\"\n BENCHMARK = SPY_SID\n DOLLAR_VOLUME_TOP_N_PCT = 60\n DOLLAR_VOLUME_WINDOW = 90\n MODEL = None\n LOOKBACK_WINDOW = 252\n COMMISSION_CLASS = USStockCommission\n\n def prices_to_features(self, prices: pd.DataFrame):\n\n closes = prices.loc[\"Close\"]\n\n features = {}\n\n print(\"adding fundamental features\")\n self.add_fundamental_features(prices, features)\n print(\"adding quality features\")\n self.add_quality_features(prices, features)\n\n print(\"adding price and volume features\")\n self.add_price_and_volume_features(prices, features)\n print(\"adding techical indicator features\")\n self.add_technical_indicator_features(prices, features)\n print(\"adding securities master features\")\n self.add_securities_master_features(prices, features)\n print(\"adding market features\")\n self.add_market_features(prices, features)\n\n # Target to predict: next week return\n one_week_returns = (closes - closes.shift(5)) / closes.shift(5).where(closes.shift(5) > 0)\n targets = one_week_returns.shift(-5)\n\n return features, targets\n\n def add_fundamental_features(self, prices: pd.DataFrame, features: dict[str, pd.DataFrame]):\n \"\"\"\n Fundamental features:\n\n - Enterprise multiple\n - various quarterly values and ratios\n - various trailing-twelve month values and ratios\n \"\"\"\n\n closes = prices.loc[\"Close\"]\n\n # enterprise multiple\n fundamentals = get_sharadar_fundamentals_reindexed_like(\n closes,\n fields=[\"EVEBIT\", \"EBIT\"],\n dimension=\"ART\")\n enterprise_multiples = fundamentals.loc[\"EVEBIT\"]\n ebits = fundamentals.loc[\"EBIT\"]\n # Ignore negative earnings\n enterprise_multiples = enterprise_multiples.where(ebits > 0)\n features[\"enterprise_multiples_ranks\"] = enterprise_multiples.rank(axis=1, pct=True).fillna(0.5)\n\n # Query quarterly fundamentals\n fundamentals = get_sharadar_fundamentals_reindexed_like(\n closes,\n dimension=\"ARQ\", # As-reported quarterly reports\n fields=[\n \"CURRENTRATIO\", # Current ratio\n \"DE\", # Debt to Equity Ratio\n \"PB\", # Price to Book Value\n \"TBVPS\", # Tangible Asset Book Value per Share\n \"MARKETCAP\",\n ])\n\n for field in fundamentals.index.get_level_values(\"Field\").unique():\n features[\"{}_ranks\".format(field)] = fundamentals.loc[field].rank(axis=1, pct=True).fillna(0.5)\n\n # Query trailing-twelve-month fundamentals\n fundamentals = get_sharadar_fundamentals_reindexed_like(\n closes,\n dimension=\"ART\", # As-reported trailing-twelve-month reports\n fields=[\n \"ASSETTURNOVER\", # Asset Turnover\n \"EBITDAMARGIN\", # EBITDA Margin\n \"EQUITYAVG\", # Average Equity\n \"GROSSMARGIN\", # Gross Margin\n \"NETMARGIN\", # Profit Margin\n \"PAYOUTRATIO\", # Payout Ratio\n \"PE\", # Price Earnings Damodaran Method\n \"PE1\", # Price to Earnings Ratio\n \"PS\", # Price Sales (Damodaran Method)\n \"PS1\", # Price to Sales Ratio\n \"ROA\", # Return on Average Assets\n \"ROE\", # Return on Average Equity\n \"ROS\", # Return on Sales\n ])\n\n for field in fundamentals.index.get_level_values(\"Field\").unique():\n features[\"{}_ranks\".format(field)] = fundamentals.loc[field].rank(axis=1, pct=True).fillna(0.5)\n\n def add_quality_features(self, prices: pd.DataFrame, features: dict[str, pd.DataFrame]):\n \"\"\"\n Adds quality features, based on the Piotroski F-score.\n \"\"\"\n closes = prices.loc[\"Close\"]\n\n # Step 1: query relevant indicators\n fundamentals = get_sharadar_fundamentals_reindexed_like(\n closes,\n dimension=\"ART\", # As-reported TTM reports\n fields=[\n \"ROA\", # Return on assets\n \"ASSETS\", # Total Assets\n \"NCFO\", # Net Cash Flow from Operations\n \"DE\", # Debt to Equity Ratio\n \"CURRENTRATIO\", # Current ratio\n \"SHARESWA\", # Outstanding shares\n \"GROSSMARGIN\", # Gross margin\n \"ASSETTURNOVER\", # Asset turnover\n ])\n return_on_assets = fundamentals.loc[\"ROA\"]\n total_assets = fundamentals.loc[\"ASSETS\"]\n operating_cash_flows = fundamentals.loc[\"NCFO\"]\n leverages = fundamentals.loc[\"DE\"]\n current_ratios = fundamentals.loc[\"CURRENTRATIO\"]\n shares_out = fundamentals.loc[\"SHARESWA\"]\n gross_margins = fundamentals.loc[\"GROSSMARGIN\"]\n asset_turnovers = fundamentals.loc[\"ASSETTURNOVER\"]\n\n # Step 2: many Piotroski F-score components compare current to previous\n # values, so get DataFrames of previous values\n\n # Step 2.a: get a boolean mask of the first day of each newly reported fiscal\n # period\n fundamentals = get_sharadar_fundamentals_reindexed_like(\n closes,\n dimension=\"ARQ\", # As-reported quarterly reports\n fields=[\n \"REPORTPERIOD\"\n ])\n fiscal_periods = fundamentals.loc[\"REPORTPERIOD\"]\n are_new_fiscal_periods = fiscal_periods != fiscal_periods.shift()\n\n periods_ago = 4\n\n # this function will be applied sid by sid and returns a Series of\n # earlier fundamentals\n def n_periods_ago(fundamentals_for_sid):\n sid = fundamentals_for_sid.name\n # remove all rows except for new fiscal periods\n new_period_fundamentals = fundamentals_for_sid.where(are_new_fiscal_periods[sid]).dropna()\n # Shift the desired number of periods\n earlier_fundamentals = new_period_fundamentals.shift(periods_ago)\n # Reindex and forward-fill to restore original shape\n earlier_fundamentals = earlier_fundamentals.reindex(fundamentals_for_sid.index, method=\"ffill\")\n return earlier_fundamentals\n\n previous_return_on_assets = return_on_assets.apply(n_periods_ago)\n previous_leverages = leverages.apply(n_periods_ago)\n previous_current_ratios = current_ratios.apply(n_periods_ago)\n previous_shares_out = shares_out.apply(n_periods_ago)\n previous_gross_margins = gross_margins.apply(n_periods_ago)\n previous_asset_turnovers = asset_turnovers.apply(n_periods_ago)\n\n # Step 3: calculate F-Score components; each resulting component is a DataFrame\n # of booleans\n have_positive_return_on_assets = return_on_assets > 0\n have_positive_operating_cash_flows = operating_cash_flows > 0\n have_increasing_return_on_assets = return_on_assets > previous_return_on_assets\n total_assets = total_assets.where(total_assets > 0) # avoid DivisionByZero errors\n have_more_cash_flow_than_incomes = operating_cash_flows / total_assets > return_on_assets\n have_decreasing_leverages = leverages < previous_leverages\n have_increasing_current_ratios = current_ratios > previous_current_ratios\n have_no_new_shares = shares_out <= previous_shares_out\n have_increasing_gross_margins = gross_margins > previous_gross_margins\n have_increasing_asset_turnovers = asset_turnovers > previous_asset_turnovers\n\n # Save each boolean F score component as a feature\n features[\"have_positive_return_on_assets\"] = have_positive_return_on_assets.astype(int)\n features[\"have_positive_operating_cash_flows\"] = have_positive_operating_cash_flows.astype(int)\n features[\"have_increasing_return_on_assets\"] = have_increasing_return_on_assets.astype(int)\n features[\"have_more_cash_flow_than_incomes\"] = have_more_cash_flow_than_incomes.astype(int)\n features[\"have_decreasing_leverages\"] = have_decreasing_leverages.astype(int)\n features[\"have_increasing_current_ratios\"] = have_increasing_current_ratios.astype(int)\n features[\"have_no_new_shares\"] = have_no_new_shares.astype(int)\n features[\"have_increasing_gross_margins\"] = have_increasing_gross_margins.astype(int)\n features[\"have_increasing_asset_turnovers\"] = have_increasing_asset_turnovers.astype(int)\n\n # Sum the components to get the F-Score and saves the ranks as a feature\n f_scores = (\n have_positive_return_on_assets.astype(int)\n + have_positive_operating_cash_flows.astype(int)\n + have_increasing_return_on_assets.astype(int)\n + have_more_cash_flow_than_incomes.astype(int)\n + have_decreasing_leverages.astype(int)\n + have_increasing_current_ratios.astype(int)\n + have_no_new_shares.astype(int)\n + have_increasing_gross_margins.astype(int)\n + have_increasing_asset_turnovers.astype(int)\n )\n features[\"f_score_ranks\"] = f_scores.rank(axis=1, pct=True).fillna(0.5)\n\n def add_price_and_volume_features(self, prices: pd.DataFrame, features: dict[str, pd.DataFrame]):\n \"\"\"\n Price and volume features, or features derived from price and volume:\n\n - return ranks\n - price level\n - dollar volume rank\n - volatility ranks\n - volatility spikes\n - volume spikes\n \"\"\"\n closes = prices.loc[\"Close\"]\n\n # yearly, monthly, weekly, 2-day, daily returns ranks\n one_year_returns = (closes.shift(22) - closes.shift(252)) / closes.shift(252) # exclude most recent month, per classic momentum\n one_month_returns = (closes - closes.shift(22)) / closes.shift(22)\n one_week_returns = (closes - closes.shift(5)) / closes.shift(5)\n two_day_returns = (closes - closes.shift(2)) / closes.shift(2)\n one_day_returns = closes.pct_change()\n features[\"1yr_returns_ranks\"] = one_year_returns.rank(axis=1, pct=True).fillna(0.5)\n features[\"1mo_returns_ranks\"] = one_month_returns.rank(axis=1, pct=True).fillna(0.5)\n features[\"1wk_returns_ranks\"] = one_week_returns.rank(axis=1, pct=True).fillna(0.5)\n features[\"2d_returns_ranks\"] = two_day_returns.rank(axis=1, pct=True).fillna(0.5)\n features[\"1d_returns_ranks\"] = one_day_returns.rank(axis=1, pct=True).fillna(0.5)\n\n # whether returns were positive\n features[\"last_1year_was_positive\"] = (one_year_returns > 0).astype(int)\n features[\"last_1month_was_positive\"] = (one_month_returns > 0).astype(int)\n features[\"last_1week_was_positive\"] = (one_week_returns > 0).astype(int)\n features[\"last_2day_was_positive\"] = (two_day_returns > 0).astype(int)\n features[\"last_1day_was_positive\"] = (one_day_returns > 0).astype(int)\n\n # price level\n features[\"price_below_10\"] = closes < 10\n features[\"price_below_2\"] = closes < 2\n\n # dollar volume ranks\n volumes = prices.loc[\"Volume\"]\n avg_dollar_volumes = (closes * volumes).rolling(63).mean()\n features[\"dollar_volume_ranks\"] = avg_dollar_volumes.rank(axis=1, ascending=True, pct=True).fillna(0.5)\n\n # quarterly volatility ranks\n quarterly_stds = closes.pct_change().rolling(window=63).std()\n features[\"quaterly_std_ranks\"] = quarterly_stds.rank(axis=1, pct=True).fillna(0.5)\n\n # volatility spikes\n volatility_1d_vs_quarter = closes.pct_change().abs() / quarterly_stds.where(quarterly_stds > 0)\n features[\"2std_volatility_spike\"] = (volatility_1d_vs_quarter >= 2).astype(int)\n features[\"volatility_spike_ranks\"] = volatility_1d_vs_quarter.rank(axis=1, pct=True).fillna(0.5)\n\n # volume spike\n avg_volumes = volumes.rolling(window=63).mean()\n volume_1d_vs_quarter = volumes / avg_volumes.where(avg_volumes > 0)\n features[\"2x_volume_spike\"] = (volume_1d_vs_quarter >= 2).astype(int)\n features[\"volume_spike_ranks\"] = volume_1d_vs_quarter.rank(axis=1, pct=True).fillna(0.5)\n\n def add_technical_indicator_features(self, prices: pd.DataFrame, features: dict[str, pd.DataFrame]):\n \"\"\"\n Various technical indicators:\n\n - Bollinger bands\n - RSI\n - Stochastic oscillator\n - Money Flow Index\n \"\"\"\n closes = prices.loc[\"Close\"]\n\n # relative position within Bollinger Bands (0 = at or below lower band, 1 = at or above upper band)\n mavgs = closes.rolling(20).mean()\n stds = closes.rolling(20).std()\n upper_bands = mavgs + (stds * 2)\n lower_bands = mavgs - (stds * 2)\n # Winsorize at upper and lower bands\n winsorized_closes = closes.where(closes > lower_bands, lower_bands).where(closes < upper_bands, upper_bands)\n features[\"close_vs_bbands\"] = (winsorized_closes - lower_bands) / (winsorized_closes - lower_bands)\n\n # RSI (0-1)\n returns = closes.diff()\n avg_gains = returns.where(returns > 0).rolling(window=14, min_periods=1).mean()\n avg_losses = returns.where(returns < 0).abs().rolling(window=14, min_periods=1).mean()\n relative_strengths = avg_gains / avg_losses.where(avg_losses != 0)\n features[\"RSI\"] = 1 - (1 / (1 + relative_strengths.fillna(0.5)))\n\n # Stochastic oscillator (0-1)\n highest_highs = closes.rolling(window=14).max()\n lowest_lows = closes.rolling(window=14).min()\n features[\"stochastic\"] = (closes - lowest_lows) / (highest_highs - lowest_lows)\n\n # Money flow (similar to RSI but volume-weighted) (0-1)\n money_flows = closes * prices.loc[\"Volume\"]\n positive_money_flows = money_flows.where(returns > 0).rolling(window=14, min_periods=1).sum()\n negative_money_flows = money_flows.where(returns < 0).rolling(window=14, min_periods=1).sum()\n money_flow_ratios = positive_money_flows / negative_money_flows.where(negative_money_flows > 0)\n features[\"money_flow\"] = 1 - (1 / (1 + money_flow_ratios.fillna(0.5)))\n\n def add_securities_master_features(self, prices: pd.DataFrame, features: dict[str, pd.DataFrame]):\n \"\"\"\n Features from the securities master:\n\n - ADR?\n - sector\n \"\"\"\n closes = prices.loc[\"Close\"]\n\n securities = get_securities_reindexed_like(closes, fields=[\"sharadar_Category\", \"sharadar_Sector\"])\n\n # Is it an ADR?\n categories = securities.loc[\"sharadar_Category\"]\n unique_categories = categories.iloc[0].unique()\n # this dataset includes several ADR classifications, all of which start with \"ADR \"\n features[\"are_adrs\"] = categories.isin([cat for cat in unique_categories if cat.startswith(\"ADR \")]).astype(int)\n\n # Which sector? (sectors must be one-hot encoded - see usage guide for more)\n sectors = securities.loc[\"sharadar_Sector\"]\n for sector in sectors.stack().unique():\n features[\"sector_{}\".format(sector)] = (sectors == sector).astype(int)\n\n def add_market_features(self, prices: pd.DataFrame, features: dict[str, pd.DataFrame]):\n \"\"\"\n Market price, volatility, and breadth, some of which are queried from a\n database and some of which are calculated from the Sharadar data:\n\n - whether S&P 500 is above or below its 200-day moving average\n - where VIX falls within the range of 12 - 30\n - where 10-day NYSE TRIN falls within the range of 0.5 to 2\n - McClellan oscillator\n - Hindenburg Omen\n \"\"\"\n closes = prices.loc[\"Close\"]\n\n # Get prices for SPY, VIX, TRIN-NYSE\n market_prices = get_prices(self.BENCHMARK_DB,\n fields=\"Close\",\n start_date=closes.index.min(),\n end_date=closes.index.max())\n market_closes = market_prices.loc[\"Close\"]\n\n # Is S&P above its 200-day?\n spy_closes = market_closes[self.SPY_SID]\n spy_200d_mavg = spy_closes.rolling(200).mean()\n spy_above_200d = (spy_closes > spy_200d_mavg).astype(int)\n # Must reindex like closes in case indexes differ\n spy_above_200d = spy_above_200d.reindex(closes.index, method=\"ffill\")\n features[\"spy_above_200d\"] = closes.apply(lambda x: spy_above_200d)\n\n # VIX and TRIN don't go back as far as Sharadar data, so we may need a filler DataFrame\n fillers = pd.DataFrame(0.5, index=closes.index, columns=closes.columns)\n\n # Where does VIX fall within the range of 12-30?\n try:\n vix = market_closes[self.VIX_SID]\n except KeyError:\n features[\"vix\"] = fillers\n else:\n vix_high = 30\n vix_low = 12\n # Winsorize VIX\n vix = vix.where(vix > vix_low, vix_low).where(vix < vix_high, vix_high)\n vix_as_pct = (vix - vix_low) / (vix_high - vix_low)\n vix_as_pct = vix_as_pct.reindex(closes.index, method=\"ffill\")\n features[\"vix\"] = closes.apply(lambda x: vix_as_pct).fillna(0.5)\n\n # Where does NYSE TRIN fall within the range of 0.5-2?\n try:\n trin = market_closes[self.TRIN_SID]\n except KeyError:\n features[\"trin\"] = fillers\n else:\n trin = trin.rolling(window=10).mean()\n trin_high = 2\n trin_low = 0.5\n # Winsorize TRIN\n trin = trin.where(trin > trin_low, trin_low).where(trin < trin_high, trin_high)\n trin_as_pct = (trin - trin_low) / (trin_high - trin_low)\n trin_as_pct = trin_as_pct.reindex(closes.index, method=\"ffill\")\n features[\"trin\"] = closes.apply(lambda x: trin_as_pct).fillna(0.5)\n\n # McClellan oscillator\n total_issues = closes.count(axis=1)\n returns = closes.pct_change()\n advances = returns.where(returns > 0).count(axis=1)\n declines = returns.where(returns < 0).count(axis=1)\n net_advances = advances - declines\n pct_net_advances = net_advances / total_issues\n ema_19 = pct_net_advances.ewm(span=19).mean()\n ema_39 = pct_net_advances.ewm(span=39).mean()\n mcclellan_oscillator = (ema_19 - ema_39) * 10\n # Winsorize at 50 and -50\n mcclellan_oscillator = mcclellan_oscillator.where(mcclellan_oscillator < 50, 50).where(mcclellan_oscillator > -50, -50)\n features[\"mcclellan_oscillator\"] = closes.apply(lambda x: mcclellan_oscillator).fillna(0)\n\n # Hindenburg omen (and new 52-week highs/lows)\n one_year_highs = closes.rolling(window=252).max()\n one_year_lows = closes.rolling(window=252).min()\n new_one_year_highs = (closes > one_year_highs.shift()).astype(int)\n new_one_year_lows = (closes < one_year_lows.shift()).astype(int)\n features[\"new_one_year_highs\"] = new_one_year_highs\n features[\"new_one_year_lows\"] = new_one_year_lows\n pct_one_year_highs = new_one_year_highs.sum(axis=1) / total_issues\n pct_one_year_lows = new_one_year_lows.sum(axis=1) / total_issues\n hindenburg_omens = (pct_one_year_highs > 0.028) & (pct_one_year_lows > 0.028) & (spy_closes > spy_closes.shift(50))\n # Omen lasts for 30 days\n hindenburg_omens = hindenburg_omens.where(hindenburg_omens).fillna(method=\"ffill\", limit=30).fillna(False).astype(int)\n hindenburg_omens = hindenburg_omens.reindex(closes.index, method=\"ffill\")\n features[\"hindenburg_omens\"] = closes.apply(lambda x: hindenburg_omens)\n\n def predictions_to_signals(self, predictions: pd.DataFrame, prices: pd.DataFrame):\n closes = prices.loc[\"Close\"]\n volumes = prices.loc[\"Volume\"]\n avg_dollar_volumes = (closes * volumes).rolling(self.DOLLAR_VOLUME_WINDOW).mean()\n dollar_volume_ranks = avg_dollar_volumes.rank(axis=1, ascending=False, pct=True)\n have_adequate_dollar_volumes = dollar_volume_ranks <= (self.DOLLAR_VOLUME_TOP_N_PCT/100)\n\n # Save the predictions and prices so we can analyze them\n self.save_to_results(\"Prediction\", predictions)\n self.save_to_results(\"Close\", closes)\n self.save_to_results(\"Volume\", volumes)\n\n # Buy (sell) stocks with best (worst) predicted return\n have_best_predictions = predictions.where(have_adequate_dollar_volumes).rank(ascending=False, axis=1) <= 10\n have_worst_predictions = predictions.where(have_adequate_dollar_volumes).rank(ascending=True, axis=1) <= 10\n signals = have_best_predictions.astype(int).where(have_best_predictions, -have_worst_predictions.astype(int).where(have_worst_predictions, 0))\n return signals\n\n def signals_to_target_weights(self, signals: pd.DataFrame, prices: pd.DataFrame):\n # Allocate equal weights\n daily_signal_counts = signals.abs().sum(axis=1)\n weights = signals.div(daily_signal_counts, axis=0).fillna(0)\n\n # Rebalance weekly\n # Resample daily to weekly, taking the first day's signal\n # For pandas offset aliases, see https://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases\n weights = weights.resample(\"W\").first()\n # Reindex back to daily and fill forward\n weights = weights.reindex(prices.loc[\"Close\"].index, method=\"ffill\")\n\n return weights\n\n def target_weights_to_positions(self, weights: pd.DataFrame, prices: pd.DataFrame):\n # Enter the position the day after the signal\n return weights.shift()\n\n def positions_to_gross_returns(self, positions: pd.DataFrame, prices: pd.DataFrame):\n\n closes = prices.loc[\"Close\"]\n gross_returns = closes.pct_change() * positions.shift()\n return gross_returns\n","sub_path":"kitchensink_ml/kitchensink_ml.py","file_name":"kitchensink_ml.py","file_ext":"py","file_size_in_byte":22912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"76862296","text":"#AWS_Restart\n#Ghanaian Names Days Of The Week\n#Daniel Nii Amu Dodoo\n\ndaysOfWeek = []\n\nday_1 = input(\"Enter the first day of the week:\")\ndaysOfWeek.append(day_1.capitalize())\nprint(daysOfWeek)\n\nday_2 = input(\"Enter the second day of the week:\")\nif day_1 == day_2:\n day_2 = input(\"Enter the second day of the week again!:\")\ndaysOfWeek.append(day_2.capitalize())\nprint(daysOfWeek)\n\nday_3 = input(\"Enter the third day of the week:\")\nif day_3 == daysOfWeek:\n day_3 = input(\"Enter the second day of the week again!:\")\ndaysOfWeek.append(day_3.capitalize())\nprint(daysOfWeek)\n\nday_4 = input(\"Enter the fourth day of the week:\")\nif day_4 == daysOfWeek:\n day_4 = input(\"Enter the fourth of the week again!:\")\ndaysOfWeek.append(day_4.capitalize())\nprint(daysOfWeek)\n\nday_5 = input(\"Enter the fifth day of the week:\")\nif day_5 == daysOfWeek:\n day_5 = input(\"Enter the fifth day of the week again!:\")\ndaysOfWeek.append(day_5.capitalize())\nprint(daysOfWeek)\n\nday_6 = input(\"Enter the sixth day of the week:\")\nif day_6 == daysOfWeek:\n day_6 = input(\"Enter the sixth day of the week again!:\")\ndaysOfWeek.append(day_6.capitalize())\nprint(daysOfWeek)\n\nday_7 = input(\"Enter the seventh day of the week:\")\nif day_7 == daysOfWeek:\n day_7 = input(\"Enter the seventh day of the week again!:\")\ndaysOfWeek.append(day_7.capitalize())\nprint(daysOfWeek)\n\nsex_Male_Female = input(\"Enter Your Sex, Male or Female:\")\nday_Born = input(\"Enter the day of the week you were born:\")\n\nif sex_Male_Female == \"Male\" and day_Born == \"Monday\":\n print(\"Kwadwo\")\nelif sex_Male_Female == \"Female\" and day_Born == \"Monday\":\n print(\"Ajua\")\n\nif sex_Male_Female == \"Male\" and day_Born == \"Tuesday\":\n print(\"Kwabena\")\n\nelif sex_Male_Female == \"Female\" and day_Born == \"Tuesday\":\n print(\"Abena\")\n\nif sex_Male_Female == \"Male\" and day_Born == \"Wednesday\":\n print(\"Kwaku\")\n\nelif sex_Male_Female == \"Female\" and day_Born == \"Wednesday\":\n print(\"Akua\")\n\nif sex_Male_Female == \"Male\" and day_Born == \"Thursday\":\n print(\"Yaw\")\n\nelif sex_Male_Female == \"Female\" and day_Born == \"Thursday\":\n print(\"Yaa\")\n\nif sex_Male_Female == \"Male\" and day_Born == \"Friday\":\n print(\"Kofi\")\n\nelif sex_Male_Female == \"Female\" and day_Born == \"Friday\":\n print(\"Afia\")\n\nif sex_Male_Female == \"Male\" and day_Born == \"Saturday\":\n print(\"Kwame\")\n\nelif sex_Male_Female == \"Female\" and day_Born == \"Saturday\":\n print(\"Ama\")\n\nif sex_Male_Female == \"Male\" and day_Born == \"Sunday\":\n print(\"Kwesi\")\n\nelif sex_Male_Female == \"Female\" and day_Born == \"Sunday\":\n print(\"Esi\")\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"loops_old.py","file_name":"loops_old.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"225614113","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Author: Luo-Songtao\n# Email: ryomawithlst@gmail/outlook.com\nfrom math import inf\nfrom copy import deepcopy\n\nthe_graph = [\n [0, 3, 8, inf, -4 ],\n [inf, 0, inf, 1, 7 ],\n [inf, 4, 0, inf, inf],\n [2, inf, -5, 0, inf],\n [inf, inf, inf, 6, 0 ]\n]\n\n\nclass GeneralPairsShortestPaths:\n \"\"\"一般的结点对最短路径算法\n \n 有向图上所有节点对最短路径问题可以使用动态规划算法:\n - 最短路径的结构:一条最短路径的所有子路径都是最短路径\n - 所有结点对最短路径问题的递归解:\n - 设 :math:`l^{(m)}_{ij}`为从i结点到j结点的至多包含m多条边的任意路径的最小权重,并用矩阵 :math:`L^{(m)}`存储。当m=0时,也就是i结点到j结点没有之间没有便,有两种情况,一种是i=j,( :math:`l^{(m)}_{ij}=0`),另一种是i和j不连通( :math:`l^{(m)}_{ij}=\\inf`)。且有:\n .. math:: l^{(m)}_{ij} = \\min (l^{(m-1)}_{ij}, \\min_{1\\le k \\le n} \\{l^{(m-1)}_{ik}+\\omega_{kj} \\} \n \n 这里我们默认有向图使用矩阵形式表示,只记录权重的矩阵记为 :math:`W`,其中:math:`\\omega_{ij}`表示边的权重\n \"\"\"\n @classmethod\n def extend_shortest_paths(cls, L, W, P=None):\n \"\"\"\n 根据 :math:`L^{m-1}` 计算 :math:`L^{(m)}`\n \n .. math:: l^{(m)}_{ij} = \\min (l^{(m-1)}_{ij}, \\min_{1\\le k \\le n} \\{l^{(m-1)}_{ik}+\\omega_{kj} \\}\n \n Args:\n L: 表示 :math:`L^{m-1}` 矩阵\n W: 表示 :math:`W` 矩阵,其中 :math:`\\omega_{ij}` 表示边的权重\n P: 表示 :math:`L^{m-1}` 的前驱子图矩阵,记录结点的前驱\n \"\"\"\n n = len(W)\n L_m = L\n for i in range(n):\n for j in range(n):\n for k in range(n):\n l_ij = min(L_m[i][j], L_m[i][k] + W[k][j])\n if l_ij != L_m[i][j]:\n L_m[i][j] = l_ij\n if P is not None:\n P[i][j] = k\n return L_m, P\n\n @classmethod\n def slow_pairs_shortest_paths(cls, W):\n \"\"\"较慢的计算版本\n \n 运算复杂度为 :math:`O(n^4)`\n \n Args:\n W: 表示 :math:`W` 矩阵,其中 :math:`\\omega_{ij}` 表示边的权重\n \n Retuens:\n L矩阵, P矩阵\n \n Example:\n >>> from pprint import pprint\n >>> pprint(the_graph)\n [[0, 3, 8, inf, -4],\n [inf, 0, inf, 1, 7],\n [inf, 4, 0, inf, inf],\n [2, inf, -5, 0, inf],\n [inf, inf, inf, 6, 0]]\n >>> L_m, P = GeneralPairsShortestPaths.slow_pairs_shortest_paths(the_graph)\n >>> pprint(L_m)\n [[0, 1, -3, 2, -4],\n [3, 0, -4, 1, -1],\n [7, 4, 0, 5, 3],\n [2, -1, -5, 0, -2],\n [8, 5, 1, 6, 0]]\n >>> pprint(P)\n [[None, 2, 3, 4, 0],\n [3, None, 3, 1, 0],\n [3, 2, None, 1, 0],\n [3, 2, 3, None, 0],\n [3, 2, 3, 4, None]]\n \"\"\"\n n = len(W)\n # 同时计算L_1的前驱子图\n P = []\n for i in range(n):\n P.append([])\n for v in W[i]:\n if v == inf or v == 0:\n P[i].append(None)\n else:\n P[i].append(i)\n\n L_1 = deepcopy(W)\n L_m = L_1\n for m in range(2, n): # 分别计算m=2,...,n-1的L矩阵\n L_m, P = cls.extend_shortest_paths(L_m, W, P)\n return L_m, P\n \n @classmethod\n def faster_pairs_shortest_paths(cls, W):\n \"\"\"较快的计算版本\n \n extend_shortest_paths方法的运算非常类似矩阵乘积的 :math:`O(n^3)`形式算法:\n .. math:: \n L^{(1)} &= W\n L^{(2)} &= L^{(1)} \\cdot W = W \\cdot W\n L^{(3)} &= L^{(2)} \\cdot W = W^2 \\cdot W\n L^{(4)} &= L^{(2)} \\cdot L^{(2)} = W^2 \\cdot W^2\n L^{(8)} &= L^{(4)} \\cdot L^{(4)} = W^4 \\cdot W^4\n \n 且注意当 :math:`m\\ge n-1`时::math:`L^{(m)} = L^{(n-1)}`\n \n 所以借助这样的关系式,可以使用重复平方的方法进行运算,使得运算时间复杂度从 :math:`O(n^4)`变为 :math:`O(n^3\\lg n)`\n \n Args:\n W: 表示 :math:`W` 矩阵,其中 :math:`\\omega_{ij}` 表示边的权重\n \n Example:\n >>> from pprint import pprint\n >>> pprint(the_graph)\n [[0, 3, 8, inf, -4],\n [inf, 0, inf, 1, 7],\n [inf, 4, 0, inf, inf],\n [2, inf, -5, 0, inf],\n [inf, inf, inf, 6, 0]]\n >>> L_m = GeneralPairsShortestPaths.faster_pairs_shortest_paths(the_graph)\n >>> pprint(L_m)\n [[0, 1, -3, 2, -4],\n [3, 0, -4, 1, -1],\n [7, 4, 0, 5, 3],\n [2, -1, -5, 0, -2],\n [8, 5, 1, 6, 0]]\n \"\"\"\n n = len(W)\n L_m = deepcopy(W)\n m = 1\n while m < n-1:\n L_m, _ = cls.extend_shortest_paths(L_m, L_m)\n m = 2*m\n return L_m\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n ","sub_path":"src/graphs/psp_basics.py","file_name":"psp_basics.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"322646242","text":"#!/usr/bin/env\tpython2.7\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nDT=np.array([0.5,1,1.5,2,2.5,3,3.5,4,4.5])\nt=np.array([0.07,0.10,0.13,0.18,0.24,0.32,0.45,1.01,1.36])\nplt.ylabel('$\\Delta T$')\nplt.xlabel('tiempo')\nplt.title('$Grafica \\Delta T \\ vs \\ tiempo \\ a \\ 0.3 \\ volts$')\nfor i in range(len(DT)):\n\tplt.text(t[i],DT[i], r'$\\Delta T=%2.2f \\ t=%2.2f$' % (DT[i], t[i]))\nplt.axis([0, 2, 0, 5])\nplt.plot(t,DT,'bo',t,DT,'k')\nplt.grid(True)\nplt.show()\n","sub_path":"TrabajoFinal/tubo210cm/6-DTvst/DTvst-0.3v.py","file_name":"DTvst-0.3v.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"402759844","text":"import pickle\nimport logging\n\nfrom collections import Iterable\nfrom redis import StrictRedis, ConnectionPool\nfrom mine.algorithm.models import \\\n (DecisionTree, PieGraph, ThreeDHistogram, Scatter)\nfrom .settings import REDIS\nfrom super_dash import jsonschema\n\nLOG = logging.getLogger(__name__)\n\n_REDIS_POOL = None\n\n\ndef init_redis(db=0):\n global _REDIS_POOL\n if not _REDIS_POOL:\n _REDIS_POOL = ConnectionPool(host=REDIS.get('host', 'localhost'),\n port=REDIS.get('port', 6379),\n db=db,\n password=REDIS.get('password'))\n redis = StrictRedis(connection_pool=_REDIS_POOL)\n return redis\n\n\ndef get_dataset_status(name):\n redis = init_redis()\n try:\n status = redis.get(name)\n except TimeoutError:\n LOG.info('redis连接超时')\n raise\n if status:\n return 'ok'\n else:\n LOG.info('未在redis中查询到%s数据集的状态' % name)\n return 'loading'\n\n\ndef get_user_info(user):\n user_info = {\n 'username': user.get_username(),\n 'email': user.email,\n 'password': None,\n 'photo_url': '/static/img/photo/%s' % user.photo.photo_url,\n 'message_nu': user.recv_msg.filter(type='message').count(),\n 'messages': [(message.date, message.msg,\n '/static/img/photo/%s' % message.sender.photo.photo_url)\n for message in user.recv_msg.filter(type='message')],\n 'alter_nu': user.recv_msg.filter(type='alter').count(),\n 'alters': [(message.date, message.msg, message.user.photo.photo_url)\n for message in user.recv_msg.filter(type='alter')],\n 'datasets': [{\n \"name\": item.name,\n \"file\": item.file,\n \"algorithm\": item.algorithm,\n \"config\": item.config,\n \"status\": get_dataset_status(item.name)}\n for item in user.dataset.all()\n ]\n }\n return user_info\n\n\ndef cache(key, value):\n redis = init_redis()\n redis.set(key, value)\n\n\ndef get_cache(key):\n redis = init_redis()\n return redis.get(key)\n\n\ndef cache_models(name, models):\n redis = init_redis()\n redis.set(name, pickle.dumps(models))\n\n\ndef get_models_cache(name):\n redis = init_redis()\n bin_model = redis.get(name)\n if not bin_model:\n return []\n return pickle.loads(bin_model)\n\n\ndef del_cache(name):\n redis = init_redis()\n redis.delete(name)\n\n\ndef get_training_result(name):\n models = get_models_cache(name)\n if isinstance(models, dict):\n LOG.warning(models.get('exp_stk'))\n return models\n if not isinstance(models, Iterable):\n raise Exception(\"Unknown exception\")\n res = {}\n for item in models:\n if isinstance(item, DecisionTree):\n if 'decision_tree' not in res:\n res.setdefault('decision_tree', [])\n res.get('decision_tree').append(item.to_json_able())\n elif isinstance(item, PieGraph):\n if 'pie_graphs' not in res:\n res.setdefault('pie_graphs', [])\n res['pie_graphs'].append(item.to_json_able())\n elif isinstance(item, ThreeDHistogram):\n if 'threeD_histogram' not in res:\n res.setdefault('threeD_histogram', [])\n res.get('threeD_histogram').append(item.to_json_able())\n elif isinstance(item, Scatter):\n if 'scatter' not in res:\n res.setdefault('scatter', [])\n res.get('scatter').append(item.to_json_able())\n return res\n\n\ndef get_schema(name):\n try:\n schema = getattr(jsonschema, name.replace('.', '_'))\n except AttributeError:\n return None\n return schema\n","sub_path":"super_dash/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"274666927","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\nfrom django.db.models import Count, Sum\nfrom django.views.decorators.cache import cache_page, never_cache\nfrom django.contrib.auth.decorators import login_required\nfrom core.models import Member, Post, Comment\nfrom itertools import chain\nfrom random import sample\nfrom haystack.query import SearchQuerySet\nfrom haystack.views import SearchView\nfrom hashids import Hashids\n\n\n@cache_page(60 * 5)\ndef login_page(request):\n top_15_posters = Member.objects.annotate(\n num_posts=Count('post')).order_by('-num_posts')[:50]\n top_15_commentors = Member.objects.annotate(\n num_comments=Count('comment')).order_by('-num_comments')[:50]\n\n context = {\n \"hall_of_fame\": sample(\n list(chain(top_15_posters, top_15_commentors)), 100),\n }\n return render(request, 'login.html', context)\n\n\n# @login_required\n# @cache_page(60 * 60)\ndef stats_page(request):\n posts_by_hours = Post.objects.extra({\n \"hour\": \"extract('hour' from created_time at time zone 'UZT')\"\n }).values(\"hour\").order_by(\"-hour\").annotate(num_posts=Count(\"id\"))\n posts_by_hours_daytime = [{'hour': x['hour'], 'num_posts': x['num_posts'] } for x in posts_by_hours[11:]]\n del posts_by_hours_daytime[-1]\n posts_by_hours_nighttime = [{'hour': x['hour'], 'num_posts': x['num_posts'] } for x in posts_by_hours[:11]]\n posts_by_hours_nighttime.insert(0, {'hour': posts_by_hours.last()['hour'], 'num_posts': posts_by_hours.last()['num_posts']})\n\n comments_by_hours = Comment.objects.extra({\n \"hour\": \"extract('hour' from created_time at time zone 'UZT')\"\n }).values(\"hour\").order_by(\"-hour\").annotate(num_comments=Count(\"id\"))\n comments_by_hours_daytime = [{'hour': x['hour'], 'num_comments': x['num_comments'] } for x in comments_by_hours[11:]]\n del comments_by_hours_daytime[-1]\n comments_by_hours_nighttime = [{'hour': x['hour'], 'num_comments': x['num_comments'] } for x in comments_by_hours[:11]]\n comments_by_hours_nighttime.insert(0, {'hour': comments_by_hours.last()['hour'], 'num_comments': comments_by_hours.last()['num_comments']})\n\n posts_by_weekdays = Post.objects.extra({\n \"weekday\": \"EXTRACT('dow' FROM created_time AT TIME ZONE 'UZT')\"\n }).values(\"weekday\").order_by(\"weekday\").annotate(num_posts=Count(\"id\"))\n comments_by_weekdays = Comment.objects.extra({\n \"weekday\": \"EXTRACT('dow' FROM created_time AT TIME ZONE 'UZT')\"\n }).values(\"weekday\").order_by(\"weekday\").annotate(num_comments=Count(\"id\"))\n posts_by_months = Post.objects.extra({\n \"month\": \"EXTRACT('month' FROM created_time AT TIME ZONE 'UZT')\"\n }).values(\"month\").order_by(\"month\").annotate(num_posts=Count(\"id\"))\n comments_by_months = Comment.objects.extra({\n \"month\": \"EXTRACT('month' FROM created_time AT TIME ZONE 'UZT')\"\n }).values(\"month\").order_by(\"month\").annotate(num_comments=Count(\"id\"))\n\n context = {\n \"posts_by_hours_daytime\": posts_by_hours_daytime,\n \"posts_by_hours_nighttime\": posts_by_hours_nighttime,\n \"comments_by_hours_daytime\": comments_by_hours_daytime,\n \"comments_by_hours_nighttime\": comments_by_hours_nighttime,\n \"posts_by_weekdays\": posts_by_weekdays,\n \"comments_by_weekdays\": comments_by_weekdays,\n \"posts_by_months\": posts_by_months,\n \"comments_by_months\": comments_by_months,\n \"total_posts\": Post.objects.count(),\n \"total_comments\": Comment.objects.count(),\n \"next\": request.GET.get('next')\n }\n\n return render(request, 'pages/stats_time.html', context)\n\n\n# @login_required\n# @cache_page(60 * 60)\ndef members_page(request):\n total_members = Member.objects.count()\n top_posters = Member.objects.annotate(\n num_posts=Count('post')).order_by('-num_posts')[:10]\n top_commentors = Member.objects.annotate(\n num_comments=Count('comment')).order_by('-num_comments')[:10]\n top_liked_posters = Post.objects.annotate(\n creator_times=Count('creator__name', distinct=True)).order_by('-likes')[:10]\n top_liked_commentors = Comment.objects.annotate(\n creator_times=Count('creator__name', distinct=True)).order_by('-likes')[:10]\n\n context = {\n \"total_members\": total_members,\n \"top_posters\": top_posters,\n \"top_commentors\": top_commentors,\n \"top_liked_posters\": top_liked_posters,\n \"top_liked_commentors\": top_liked_commentors,\n \"next\": request.GET.get('next')\n }\n\n return render(request, 'pages/members.html', context)\n\n\n# @login_required\n# @cache_page(60 * 5)\ndef posts_page(request):\n daily_posts = Post.objects.extra({\n \"day\": \"date_trunc('day', created_time)\"\n }).values('day').order_by('day').annotate(num_posts=Count('id'))\n\n context = {\n \"total_posts\": Post.objects.count(),\n \"daily_posts\": daily_posts,\n \"next\": request.GET.get('next')\n }\n return render(request, 'pages/posts.html', context)\n\n\n# @login_required\n# @cache_page(60 * 5)\ndef comments_page(request):\n\n context = {\n \"total_comments\": Comment.objects.count(),\n \"next\": request.GET.get('next')\n }\n return render(request, 'pages/comments.html', context)\n\n\nclass TarjimonSearchView(SearchView):\n \n def get_context_data(self, *args, **kwargs):\n context = super(TarjimonSearchView, self).get_context_data(*args, **kwargs)\n return context\n\n\n# @login_required\n# @cache_page(60 * 5)\ndef subscribe_page(request):\n context = {\"next\": request.GET.get('next')}\n return render(request, 'pages/subscribe.html', context)\n\n\n# @login_required\n# @cache_page(60 * 5)\ndef about_page(request):\n context = {\"next\": request.GET.get('next')}\n return render(request, 'pages/about.html', context)\n\ndef go_to_link(request, hashid):\n hashids = Hashids(salt='tarjimonlar')\n realid = hashids.decode(hashid)[0]\n url = 'https://fb.com/{objid}'.format(objid=realid)\n return HttpResponseRedirect(url)\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"487456977","text":"#!/usr/bin/python2\n# -*- coding: utf-8 -*-\n\n# News plugin\n\nimport os\n\nclass News:\n def __init__(self, options, env):\n self.id = options['id']\n self.durration = options['durration']\n self.type = options['type']\n self.news = options['news']\n self.news_durration = options['news_durration']\n\n self.outdir = env['outdir']\n\n def get_html(self):\n return {\n 'content': \n ''.join(['

' \n + news_page[0] +\n '

'\n + news_page[1] +\n '
' for news_page in self.news]),\n 'durration': self.durration,\n 'id': self.id,\n 'class': [\"news\", \"full\"],\n 'type': self.type,\n 'logo': \"fa-bullhorn\",\n 'custom_data_tags': {\n 'news-durration': self.news_durration,\n },\n }\n\n @staticmethod\n def get_js():\n with open(os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"news.js\"), \"r\") as f:\n return f.read()\n\n @staticmethod\n def get_css():\n with open(os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"news.css\"), \"r\") as f:\n return f.read()\n\n def get_type(self):\n return self.type\n","sub_path":"generator/plugins/news/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"69055563","text":"nx = [0, 1, 0, -1] # 동 북 서 남\r\nny = [1, 0, -1, 0] # 동 북 서 남\r\n\r\nvisited = [[0 for i in range(7)] for j in range(7)]\r\nL = []\r\nfor i in range(7):\r\n L.append(list(map(int, input().split())))\r\n\r\ndef dfs(x, y, answer):\r\n count = 0\r\n \r\n if x < 0 or x > 6 or y < 0 or y > 6:\r\n return False\r\n\r\n if visited[x][y] == 0 and L[x][y] == answer: #방문 하지 않은 행과 열\r\n visited[x][y] = 1\r\n count += 1\r\n \r\n for i in range(4):\r\n count += dfs(x+nx[i], y+ny[i], answer)\r\n\r\n return count\r\n\r\nresult = 0\r\n\r\nfor i in range(7):\r\n for j in range(7):\r\n ans = L[i][j]\r\n c = dfs(i, j, ans)\r\n if c >= 3:\r\n result += 1\r\nprint(result)\r\n","sub_path":"CodeUp/hyung_seop/2605.py","file_name":"2605.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"223232293","text":"\nfrom JumpScale import j\n\nfrom ActionDecorator import ActionDecorator\nclass actionrun(ActionDecorator):\n def __init__(self,*args,**kwargs):\n ActionDecorator.__init__(self,*args,**kwargs)\n self.selfobjCode=\"cuisine=j.tools.cuisine.getFromId('$id');selfobj=cuisine.ufw\"\n\nbase=j.tools.cuisine.getBaseClass()\nclass CuisineUFW(base):\n\n def __init__(self, executor, cuisine):\n self.executor = executor\n self.cuisine = cuisine\n self._ufw_allow = {}\n self._ufw_deny = {}\n self._ufw_enabled = None\n\n @property\n def ufw_enabled(self):\n if not self._ufw_enabled:\n if not self.cuisine.core.isMac:\n if self.cuisine.bash.cmdGetPath(\"ufw\", die=False) == False:\n self.cuisine.package.install(\"ufw\")\n self.cuisine.bash.cmdGetPath(\"ufw\")\n self._ufw_enabled = not \"inactive\" in self.cuisine.core.run(\"ufw status\")[1]\n return self._ufw_enabled\n\n @actionrun(action=True)\n def ufw_enable(self):\n if not self.ufw_enabled:\n if not self.cuisine.core.isMac:\n if self.executor.type != 'local':\n self.cuisine.core.run(\"ufw allow %s\" % self.executor.port)\n self.cuisine.core.run(\"echo \\\"y\\\" | ufw enable\")\n self._ufw_enabled = True\n return True\n\n @property\n def ufw_rules_allow(self):\n if self.cuisine.core.isMac:\n return {}\n if self._ufw_allow == {}:\n self._ufw_status()\n return self._ufw_allow\n\n @property\n def ufw_rules_deny(self):\n if self.cuisine.core.isMac:\n return {}\n if self._ufw_deny == {}:\n self._ufw_status()\n return self._ufw_deny\n\n def _ufw_status(self):\n self.ufw_enable()\n _, out, _ = self.cuisine.core.run(\"ufw status\", action=True, force=True)\n for line in out.splitlines():\n if line.find(\"(v6)\") != -1:\n continue\n if line.find(\"ALLOW \") != -1:\n ip = line.split(\" \", 1)[0]\n self._ufw_allow[ip] = \"*\"\n if line.find(\"DENY \") != -1:\n ip = line.split(\" \", 1)[0]\n self._ufw_deny[ip] = \"*\"\n\n @actionrun(action=True)\n def allowIncoming(self, port, protocol='tcp'):\n if self.cuisine.core.isMac:\n return\n self.ufw_enable()\n self.cuisine.core.run(\"ufw allow %s/%s\" % (port, protocol))\n\n @actionrun(action=True)\n def denyIncoming(self, port):\n if self.cuisine.core.isMac:\n return\n\n self.ufw_enable()\n self.cuisine.core.run(\"ufw deny %s\" % port)\n\n @actionrun(action=True,force=True)\n def flush(self):\n C = \"\"\"\n ufw disable\n iptables --flush\n iptables --delete-chain\n iptables --table nat --flush\n iptables --table filter --flush\n iptables --table nat --delete-chain\n iptables --table filter --delete-chain\n \"\"\"\n self.cuisine.core.run_script(C)\n\n def show(self):\n a = self.ufw_rules_allow\n b = self.ufw_rules_deny\n print(\"ALLOW\")\n print(a)\n print(\"DENY\")\n print(b)\n\n # print(self.cuisine.core.run(\"iptables -t nat -nvL\"))\n","sub_path":"lib/JumpScale/tools/cuisine/CuisineUFW.py","file_name":"CuisineUFW.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"466305592","text":"# Displaying the sum of all the digits entered by the user and reversing the digit\nnum = int(input(\"Enter any number: \"))\nsum=0\nreverse = 0\nwhile(num>0):\n\tlength = len(str(num))-1\n\ta = num%10;\n\tsum = sum+a\n\treverse = reverse+a*10**length\n\tnum = num//10\nprint(sum)\t\nprint(reverse)","sub_path":"Day5/sumOfDigit.py","file_name":"sumOfDigit.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"546705963","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nfrom zas.app import views\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n\n # do stron html\n url(r'^$', views.index, name='index'),\n url(r'^search', views.search, name='search'),\n url(r'^contact', views.contact, name='contact'),\n #url(r'^signup', views.signup, name='signup'),\n url(r'^signin', views.signin, name='signin'),\n url(r'^statistics', views.statistics, name='statistics'),\n url(r'^signout', views.signout, name='signout'),\n #url(r'^user/(?P[0-9]*)', views.user_details, name='user_details'),\n\n #url(r'^message/(?P[0-9]*)/delete', views.delete_message,\n # name='delete_message'),\n #url(r'^message/(?P[0-9]*)/edit', views.edit_message,\n # name='edit_message'),\n)\n","sub_path":"weblayer/src/zas/zas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"174641207","text":"#Plotting thermister stuff\n#max huggins\n#1/30/19\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#define data arrays\ntime_data = []\nvelocity_data = []\n\n#read in data\nlines = np.loadtxt('g_Constant.txt', delimiter=',')\nfor line in lines:\n time_data.append(line[0])\n velocity_data.append(line[1])\n\n#make plot\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\n\n#make an xy scatter plot\nplt.scatter(time_data,velocity_data,color='r', label = 'data', s =1)\n\nax.set_xlabel('Time (s)')\nax.set_ylabel('Velocity')\nax.set_title('Velocity vs Time')\nplt.legend(loc = 'best')\n\n\n#save it\nplt.savefig('GravitationalConstant.png')\n","sub_path":"uControllers/IR Sensor/Making plots with IR Sensor.py","file_name":"Making plots with IR Sensor.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"133433695","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\n#assigning elements to different lists\nlist1=[1,2,3,4]\nlist2=[]\nfor i in range(len(list1)):\n list2.append(list1[i])\n\n \n\n\n# In[8]:\n\n\n#accessing elements from a tuple\ntuple = (\"virat\",\"mahendra\",\"rohit\")\nfor x in tuple:\n print(x)\n\n\n# In[ ]:\n\n\n#deleting different dictionary elements\ndict = {\"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964}\nprint(\"elements of dictionary :\"+ str(dict))\nprint(\"For deleting mango, put 0\")\nprint(\"For deleting mango, put 1\")\nprint(\"For deleting mango, put 2\")\nx = int(input(\"Put your option : \"))\nif x==0:\n dict.pop(\"brand\")\n print(dict)\nelif x==1:\n dict.pop(\"model\")\n print(dict)\nelif x==2:\n dict.pop(\"year\")\n print(dict)\nelse:\n print(\"your option is incorrect\")\n print(\"try again\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Assignment 2.py","file_name":"Assignment 2.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"148348468","text":"class Consts():\n def __init__(self):\n self.DATA_DIR = 'braille_uncropped'\n self.MIXED = False\n self.EPOCHS = 20\n self.TRAIN_BATCH_SIZE = 104\n self.VALIDATE_BATCH_SIZE = 26\n self.IMAGE_SHAPE = (240,240)\n self.ALL_DATA = ['braille_cropped', 'braille_uncropped']\n\n\n ","sub_path":"consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"461763887","text":"\"\"\"\nUtility functions for Langevin regression\n\nJared Callaham (2020)\n\"\"\"\n\nimport numpy as np\nfrom time import time\nfrom scipy.optimize import minimize\n\n# Return a single expression from a list of expressions and coefficients\n# Note this will give a SymPy expression and not a function\ndef sindy_model(Xi, expr_list):\n return sum([Xi[i]*expr_list[i] for i in range(len(expr_list))])\n\n\ndef ntrapz(I, dx):\n if isinstance(dx, int) or isinstance(dx, float) or len(dx)==1:\n return np.trapz(I, dx=dx, axis=0)\n else:\n return np.trapz( ntrapz(I, dx[1:]), dx=dx[0])\n \n\ndef kl_divergence(p_in, q_in, dx=1, tol=None):\n \"\"\"\n Approximate Kullback-Leibler divergence for arbitrary dimensionality\n \"\"\"\n if tol==None:\n tol = max( min(p_in.flatten()), min(q_in.flatten()))\n q = q_in.copy()\n p = p_in.copy()\n q[q bins[i]) * (Y[:-1] < bins[i+1]) )[0]\n\n if len(mask) > 0:\n f_KM[i] = np.mean(dY[mask]) # Conditional average ~ drift\n a_KM[i] = 0.5*np.mean(dY2[mask]) # Conditional variance ~ diffusion\n\n # Estimate error by variance of samples in the bin\n a_KM[i] = 0.5*np.mean(dY2[mask]) # Conditional average\n a_err[i] = np.std(dY2[mask])/np.sqrt(len(mask))\n\n else:\n f_KM[i] = np.nan\n f_err[i] = np.nan\n a_KM[i] = np.nan\n a_err[i] = np.nan\n \n return f_KM, a_KM, f_err, a_err\n\n\n# Return optimal coefficients for finite-time correctio\ndef AFP_opt(cost, params):\n ### RUN OPTIMIZATION PROBLEM\n start_time = time()\n Xi0 = params[\"Xi0\"]\n\n is_complex = np.iscomplex(Xi0[0])\n \n if is_complex:\n Xi0 = np.concatenate((np.real(Xi0), np.imag(Xi0))) # Split vector in two for complex\n opt_fun = lambda Xi: cost(Xi[:len(Xi)//2] + 1j*Xi[len(Xi)//2:], params)\n\n else:\n opt_fun = lambda Xi: cost(Xi, params)\n\n res = minimize(opt_fun, Xi0, method='nelder-mead',\n options={'disp': False, 'maxfev':int(1e4)})\n print('%%%% Optimization time: {0} seconds, Cost: {1} %%%%'.format(time() - start_time, res.fun) )\n \n # Return coefficients and cost function\n if is_complex:\n # Return to complex number\n return res.x[:len(res.x)//2] + 1j*res.x[len(res.x)//2:], res.fun\n else:\n return res.x, res.fun\n\n\n \ndef SSR_loop(opt_fun, params):\n \"\"\"\n Stepwise sparse regression: general function for a given optimization problem\n opt_fun should take the parameters and return coefficients and cost\n\n Requires a list of drift and diffusion expressions,\n (although these are just passed to the opt_fun)\n \"\"\"\n \n # Lists of candidate expressions... coefficients are optimized\n f_expr, s_expr = params['f_expr'].copy(), params['s_expr'].copy() \n lib_f, lib_s = params['lib_f'].copy(), params['lib_s'].copy()\n Xi0 = params['Xi0'].copy()\n \n m = len(f_expr) + len(s_expr)\n \n Xi = np.zeros((m, m-1), dtype=Xi0.dtype) # Output results\n V = np.zeros((m-1)) # Cost at each step\n \n # Full regression problem as baseline\n Xi[:, 0], V[0] = opt_fun(params)\n \n # Start with all candidates\n active = np.array([i for i in range(m)])\n \n # Iterate and threshold\n for k in range(1, m-1):\n # Loop through remaining terms and find the one that increases the cost function the least\n min_idx = -1\n V[k] = 1e8\n for j in range(len(active)):\n tmp_active = active.copy()\n tmp_active = np.delete(tmp_active, j) # Try deleting this term\n \n # Break off masks for drift/diffusion\n f_active = tmp_active[tmp_active < len(f_expr)]\n s_active = tmp_active[tmp_active >= len(f_expr)] - len(f_expr)\n print(f_active)\n print(s_active)\n \n print(f_expr[f_active], s_expr[s_active])\n params['f_expr'] = f_expr[f_active]\n params['s_expr'] = s_expr[s_active]\n params['lib_f'] = lib_f[:, f_active]\n params['lib_s'] = lib_s[:, s_active]\n params['Xi0'] = Xi0[tmp_active]\n \n # Ensure that there is at least one drift and diffusion term left\n if len(s_active) > 0 and len(f_active) > 0:\n tmp_Xi, tmp_V = opt_fun(params)\n\n # Keep minimum cost\n if tmp_V < V[k]:\n # Ensure that there is at least one drift and diffusion term left\n #if (IS_DRIFT and len(f_active)>1) or (not IS_DRIFT and len(a_active)>1):\n min_idx = j\n V[k] = tmp_V\n min_Xi = tmp_Xi\n \n print(\"Cost: {0}\".format(V[k]))\n # Delete least important term\n active = np.delete(active, min_idx) # Remove inactive index\n Xi0[active] = min_Xi # Re-initialize with best results from previous\n Xi[active, k] = min_Xi\n print(Xi[:, k])\n \n return Xi, V\n\ndef cost(Xi, params):\n \"\"\"\n Least-squares cost function for optimization\n This version is only good in 1D, but could be extended pretty easily\n Xi - current coefficient estimates\n param - inputs to optimization problem: grid points, list of candidate expressions, regularizations\n W, f_KM, a_KM, x_pts, y_pts, x_msh, y_msh, f_expr, a_expr, l1_reg, l2_reg, kl_reg, p_hist, etc\n \"\"\"\n \n # Unpack parameters\n W = params['W'] # Optimization weights\n \n # Kramers-Moyal coefficients\n f_KM, a_KM = params['f_KM'].flatten(), params['a_KM'].flatten()\n \n fp, afp = params['fp'], params['afp'] # Fokker-Planck solvers\n lib_f, lib_s = params['lib_f'], params['lib_s']\n N = params['N']\n \n # Construct parameterized drift and diffusion functions from libraries and current coefficients\n f_vals = lib_f @ Xi[:lib_f.shape[1]]\n a_vals = 0.5*(lib_s @ Xi[lib_f.shape[1]:])**2\n \n # Solve AFP equation to find finite-time corrected drift/diffusion\n # corresponding to the current parameters Xi\n afp.precompute_operator(np.reshape(f_vals, N), np.reshape(a_vals, N))\n f_tau, a_tau = afp.solve(params['tau'])\n \n # Histogram points without data have NaN values in K-M average - ignore these in the average\n mask = np.nonzero(np.isfinite(f_KM))[0]\n V = np.sum(W[0, mask]*abs(f_tau[mask] - f_KM[mask])**2) \\\n + np.sum(W[1, mask]*abs(a_tau[mask] - a_KM[mask])**2)\n \n # Include PDF constraint via Kullbeck-Leibler divergence regularization\n if params['kl_reg'] > 0:\n p_hist = params['p_hist'] # Empirical PDF\n p_est = fp.solve(f_vals, a_vals) # Solve Fokker-Planck equation for steady-state PDF\n kl = utils.kl_divergence(p_hist, p_est, dx=fp.dx, tol=1e-6)\n kl = max(0, kl) # Numerical integration can occasionally produce small negative values\n V += params['kl_reg']*kl\n return V\n\n\n# 1D Markov test\ndef markov_test(X, lag, N=32, L=2):\n # Lagged time series\n X1 = X[:-2*lag:lag]\n X2 = X[lag:-lag:lag]\n X3 = X[2*lag::lag]\n \n # Two-time joint pdfs\n bins = np.linspace(-L, L, N+1)\n dx = bins[1]-bins[0]\n p12, _, _ = np.histogram2d(X1, X2, bins=[bins, bins], density=True)\n p23, _, _ = np.histogram2d(X2, X3, bins=[bins, bins], density=True)\n p2, _ = np.histogram(X2, bins=bins, density=True)\n p2[p2<1e-4] = 1e-4\n \n # Conditional PDF (Markov assumption)\n pcond_23 = p23.copy()\n for j in range(pcond_23.shape[1]):\n pcond_23[:, j] = pcond_23[:, j]/p2\n \n # Three-time PDFs\n p123, _ = np.histogramdd(np.array([X1, X2, X3]).T, bins=np.array([bins, bins, bins]), density=True)\n p123_markov = np.einsum('ij,jk->ijk',p12, pcond_23)\n \n # Chi^2 value\n #return utils.ntrapz( (p123 - p123_markov)**2, [dx, dx, dx] )/(np.var(p123.flatten()) + np.var(p123_markov.flatten()))\n return kl_divergence(p123, p123_markov, dx=[dx, dx, dx], tol=1e-6)\n\n\n\n### FAST AUTOCORRELATION FUNCTION\n# From https://dfm.io/posts/autocorr/\n\ndef next_pow_two(n):\n i = 1\n while i < n:\n i = i << 1\n return i\n\ndef autocorr_func_1d(x, norm=True):\n x = np.atleast_1d(x)\n if len(x.shape) != 1:\n raise ValueError(\"invalid dimensions for 1D autocorrelation function\")\n n = next_pow_two(len(x))\n\n # Compute the FFT and then (from that) the auto-correlation function\n f = np.fft.fft(x - np.mean(x), n=2*n)\n acf = np.fft.ifft(f * np.conjugate(f))[:len(x)].real\n acf /= 4*n\n \n # Optionally normalize\n if norm:\n acf /= acf[0]\n\n return acf","sub_path":".ipynb_checkpoints/utils-checkpoint.py","file_name":"utils-checkpoint.py","file_ext":"py","file_size_in_byte":9144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"598805976","text":"\"\"\"\nprices.py - Phenny Magic: The Gathering Price Lookup Module\nA module for the IRC Bot Phenny that allows a user to get the TCG Player\nprices for cards.\n\nAuthor: John Cleaver\n\nLicense: BSD 3 Clause\n\"\"\"\nimport urllib\nimport xml.etree.ElementTree as ET\nfrom collections import OrderedDict\nimport string\n\npartner_key = \"MTGIRC\" #This is the partner code assigned with you TCGPlayer API account.\nsecret_api_url = \"\" #This is the URL that the TCGPlayer Rep assigns you for API access.\ntcg_player_url = secret_api_url + \"pk=\" + partner_key + \"&s=\" + \"&p=\"\n\n\ndef price(phenny, input):\n \"\"\"Gets the TCG Player Prices for a specified card.\"\"\"\n card_dict = parse_tcg_player_xml(get_tcg_price(input.group(2)))\n if not card_dict:\n phenny.say(input.nick + \": I don't recognize that card name.\")\n return\n output_string = input.nick + \": \" + string.capwords(input.group(2))\n for key, val in card_dict.items():\n output_string += \" | \" + key + \": \" + val\n\n phenny.say(output_string)\n\nprice.commands = ['price']\nprice.priority = 'medium'\nprice.example = '.price Black Lotus'\n\n\ndef get_tcg_price(card_name):\n \"\"\" Makes the API call and returns the resultsing XML. \"\"\"\n url = tcg_player_url + card_name\n xml_return = urllib.urlopen(url)\n\n return xml_return\n\n\ndef parse_tcg_player_xml(xml):\n \"\"\" Converts the XML response from the API into an ordered dict. \"\"\"\n tree = ET.parse(xml)\n root = tree.getroot()\n\n if not root:\n return None\n\n card = OrderedDict([('Hi', root[0][1].text),\n ('Low', root[0][2].text),\n ('Avg', root[0][3].text),\n ('Link', root[0][4].text)])\n\n return card\n","sub_path":"price.py","file_name":"price.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"342246894","text":"# pylint: disable=missing-docstring\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom guardian.models import GroupObjectPermission, UserObjectPermission\nfrom guardian.shortcuts import assign_perm\n\nfrom resolwe.flow.models import Collection, Process\nfrom resolwe.permissions.utils import copy_permissions\nfrom resolwe.test import TestCase\n\n\nclass UtilsTestCase(TestCase):\n def setUp(self):\n super(UtilsTestCase, self).setUp()\n\n self.src_process = Process.objects.create(name='Source process', contributor=self.contributor)\n self.dst_process = Process.objects.create(name='Destination process', contributor=self.contributor)\n\n self.collection = Collection.objects.create(name='Test collection', contributor=self.contributor)\n\n def test_copy_permissions(self):\n assign_perm('view_process', self.contributor, self.src_process)\n assign_perm('view_process', self.group, self.src_process)\n\n copy_permissions(self.src_process, self.dst_process)\n\n self.assertEqual(GroupObjectPermission.objects.count(), 2)\n self.assertEqual(UserObjectPermission.objects.count(), 2)\n\n self.assertTrue(self.contributor.has_perm('flow.view_process', self.dst_process))\n # User inherites permission from group\n self.assertTrue(self.user.has_perm('flow.view_process', self.dst_process))\n\n def test_copy_perms_wrong_ctype(self):\n with self.assertRaises(AssertionError):\n copy_permissions(self.src_process, self.collection)\n","sub_path":"resolwe/permissions/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"48775009","text":"\"\"\"\nFile rgf_gen Docstring.\n\"\"\"\nimport os\nimport re\nfrom math import ceil\nfrom openpyxl import load_workbook\nfrom noise_wires_gen import (\n gen_dac_mgr_wires,\n gen_adc_mgr_wires\n)\n\ndef rgf_gen():\n \"\"\"\n Function rgf_gen Docstring.\n \"\"\"\n gen_tx_mgr_wires()\n\n dir_path = os.path.dirname(os.path.realpath(__file__))\n excel_reg_file = 'Noise Project Register Mapping 0V94.xlsx'\n excel_work_book = load_workbook(os.sep.join([dir_path, excel_reg_file]), data_only=True)\n selected_sheet = 'Detailed List'\n # sheet_names = excel_work_book.sheetnames\n excel_work_sheet = excel_work_book[selected_sheet]\n\n settings_starting_row = 2\n settings_cols = {\n 'title' : 'C',\n 'identifier' : 'E',\n 'wordSize' : 'L',\n 'regMaxSize' : 'M'\n }\n\n regs_start_row = 3\n sel_cols = {\n 'regOffset' : 'A',\n 'fieldPosition' : 'B',\n 'regIdentifier' : 'E',\n 'regAccessLevel' : 'G',\n 'regType' : 'H',\n 'fieldRstVal' : 'I',\n 'regRstMask' : 'J',\n 'regNum' : 'N',\n 'fieldDest' : 'O'\n }\n\n rgf_f_fields = dict()\n\n rgf_f_settings = {\n 'prefix' : '{',\n 'suffix' : '}',\n 'fileName' : 'register',\n 'fileExt' : '.v',\n 'projName' : 'Noise_Project',\n 'commentTag' : '//'\n }\n\n sizes_dictionary = {\n 'bytes' : 8,\n 'addr' : 10\n }\n\n io_types = {\n 'I' : 'input',\n 'O' : 'output',\n 'IO' : 'inout',\n 'owire' : 'output'\n }\n\n # Prepare Data\n doc_last_row = excel_work_sheet.max_row\n\n # Read Register Excel Settings\n for setting_entry in settings_cols:\n rgf_f_settings[setting_entry] = excel_work_sheet[settings_cols[setting_entry] + str(settings_starting_row)].value\n\n word_size = re.findall(r'[^\\W\\d_]+|\\d+', rgf_f_settings['wordSize'])\n rgf_f_settings['wordSize'] = int(word_size[0]) * sizes_dictionary[word_size[1]]\n sizes_dictionary['word'] = rgf_f_settings['wordSize']\n rgf_f_settings['regMaxSize'] = sizes_dictionary[rgf_f_settings['regMaxSize']]\n\n registers = dict()\n for row in range(regs_start_row, doc_last_row+1):\n reg_type = excel_work_sheet[sel_cols['regType'] + str(row)].value\n reg_name = excel_work_sheet[sel_cols['regIdentifier'] + str(row)].value\n if row is regs_start_row and reg_type != 'register':\n print('Error: Not a register on first row')\n break\n elif reg_type == 'register':\n last_reg = reg_name\n registers[last_reg] = {\n 'regAddr' : int(excel_work_sheet[sel_cols['regOffset'] + str(row)].value, 16),\n 'regNum' : excel_work_sheet[sel_cols['regNum'] + str(row)].value\n }\n registers[last_reg]['fields'] = dict()\n elif reg_type == 'configuration':\n field_pos_info = excel_work_sheet[sel_cols['fieldPosition'] + str(row)].value.strip(' []').split(':')\n field_pos_info = list(map(int, field_pos_info))\n\n # print(field_pos_info)\n field_pos_info = list(map(int, field_pos_info))\n if len(field_pos_info) <= 1:\n field_start_bit = field_pos_info[0]\n field_stop_bit = field_pos_info[0]\n field_width = 1\n else:\n field_start_bit = min((field_pos_info))\n field_stop_bit = max(field_pos_info)\n field_width = field_stop_bit - field_start_bit + 1\n\n field_destination = excel_work_sheet[sel_cols['fieldDest'] + str(row)].value\n\n registers[last_reg]['fields'][reg_name] = {\n 'name' : reg_name,\n 'accessLevel' : excel_work_sheet[sel_cols['regAccessLevel'] + str(row)].value,\n # 'fieldPosition' : excel_work_sheet[sel_cols['fieldPosition'] + str(row)].value,\n 'fieldRstVal' : excel_work_sheet[sel_cols['fieldRstVal'] + str(row)].value,\n 'fieldStartBit' : field_start_bit,\n 'fieldStopBit' : field_stop_bit,\n 'fieldWidth' : field_width,\n 'fieldDest' : field_destination\n }\n\n print(registers)\n return\n\n reg_static_io = {\n 'clk' : ['I', 0],\n 'rst_n' : ['I', 0],\n 'reg_wr_flag' : ['I', 0],\n 'reg_rd_flag' : ['I', 0],\n\n 'reg_rw_addr_i' : ['I', sizes_dictionary['addr']],\n 'reg_wr_data_i' : ['I', rgf_f_settings['regMaxSize']],\n\n 'reg_rd_data_o' : ['owire', rgf_f_settings['regMaxSize']],\n 'tx_mgr_regs' : ['owire', 1120],\n 'pg_regs' : ['owire', 160]\n }\n\n # print(registers)\n black_box_port_inst_list = []\n black_box_port_io_inst_list = []\n black_box_port_wire_list = []\n black_box_port_output_list = []\n black_box_port_output_inst_list = []\n black_box_port_list = []\n black_box_port_io_wire_list = []\n black_box_port_io_output_list = []\n black_box_port_io_list = []\n rgf_f_fields['ioList'] = []\n rgf_f_fields['portList'] = []\n static_io_list = []\n reg_ports_list = []\n for static_io in reg_static_io:\n static_io_list.append(static_io)\n if reg_static_io[static_io][1] is not 0:\n port_str = '[' + str((reg_static_io[static_io][1]-1)) + ':0] '\n else:\n port_str = ''\n\n if reg_static_io[static_io][0] == 'O':\n port_type = 'reg '\n elif reg_static_io[static_io][0] == 'I':\n port_type = ''\n else:\n port_type = ''\n reg_ports_list.append(\n io_types[reg_static_io[static_io][0]]\n + ' ' + port_type + port_str + static_io + ','\n )\n rgf_f_fields['ioList'].append(static_io)\n\n black_box_port_inst_list.append(\n '.' + static_io + '(' + static_io + ')'\n )\n black_box_port_wire_list.append(\n 'wire ' + port_str + static_io + ';'\n )\n rgf_f_fields['portList'].append(str('\\n' + ' '*4).join(reg_ports_list))\n\n # Registers Read FSM\n file_name = os.sep.join([dir_path, 'register_read_fsm_template.txt'])\n file_handler = open(file_name, 'r', newline='\\n')\n\n # Read Template\n reg_fsm_text = file_handler.read()\n file_handler.close()\n\n rgf_f_fsm = {}\n rgf_f_fsm['regFsmRdFlag'] = 'reg_rd_flag'\n rgf_f_fsm['regFsmAddr'] = 'reg_rw_addr_i'\n rgf_f_fsm['regOutBus'] = 'reg_rd_data_o'\n rgf_f_fsm['regTmpOutBus'] = 'reg_rd_data_comb'\n rgf_f_fsm['regOutBusRstVal'] = '{REG_DATA_WIDTH{1\\'b0}}'\n\n param_static_io = []\n param_static_io.append('localparam REG_ADDR_WIDTH = ' + str(sizes_dictionary['addr']) + ';')\n param_static_io.append('localparam REG_DATA_WIDTH = ' + str(rgf_f_settings['regMaxSize']) + ';')\n param_static_io = '\\n'.join(param_static_io)\n rgf_f_fields['paramList'] = []\n rgf_f_fields['paramList'].append(param_static_io)\n\n rgf_f_fsm['regCases'] = []\n rgf_f_fields['instList'] = []\n\n reg_param_list = []\n reg_param_list.append(\n rgf_f_settings['commentTag'] + ' Register Addresses: '\n )\n\n\n for register in registers:\n reg_ports_list = []\n reg_fsm_case = []\n reg_wr_proc = []\n reg_wr_proc_rst_list = []\n reg_wr_proc_wr_list = []\n reg_param_list.append(\n 'parameter ' + register + '_ADDR = ' + str(sizes_dictionary['addr'])\n + '\\'d' + str(registers[register]['regAddr']) + ';')\n\n reg_ports_list.append(\n ' '*4 + rgf_f_settings['commentTag'] + ' Register: ' + register + ' Fields Ports'\n )\n\n reg_fsm_case.append(register + '_ADDR : begin')\n\n reg_wr_proc.append(\n rgf_f_settings['commentTag'] + ' Register: ' + register + ' Writing Proccess\\n' +\n 'always @(posedge clk or negedge rst_n)\\n' +\n ' '*4 + 'if (!rst_n) begin\\n'\n )\n\n reg_wr_proc_wr_list.append(\n ' '*8 + 'if(reg_wr_flag && reg_rw_addr_i == ' + register + '_ADDR) begin\\n'\n )\n\n for reg_field in registers[register]['fields']:\n if registers[register]['fields'][reg_field]['fieldDest'] == 'Analog':\n registers[register]['fields'][reg_field]['name'] = reg_field\n else:\n registers[register]['fields'][reg_field]['name'] = 'reg_' + register.lower() + '_' + reg_field\n if registers[register]['fields'][reg_field]['fieldDest'] == 'Digital':\n black_box_port_inst_list.append(\n '.' + registers[register]['fields'][reg_field]['name'] +\n '(' + registers[register]['fields'][reg_field]['name'] + ')'\n )\n elif registers[register]['fields'][reg_field]['fieldDest'] == 'IO':\n black_box_port_io_inst_list.append(\n '.' + registers[register]['fields'][reg_field]['name'] +\n '(' + registers[register]['fields'][reg_field]['name'] + ')'\n )\n\n rgf_f_fields['ioList'].append(registers[register]['fields'][reg_field]['name'])\n\n port_str = []\n\n if registers[register]['fields'][reg_field]['accessLevel'] == 'R/W':\n port_str.append('output reg')\n elif registers[register]['fields'][reg_field]['accessLevel'] == 'R':\n port_str.append('input')\n else:\n print('Error: Un-supported access level')\n return\n\n if registers[register]['fields'][reg_field]['fieldWidth'] is not 1:\n port_reg_boundries = '[' + str((registers[register]['fields'][reg_field]['fieldStopBit']) - registers[register]['fields'][reg_field]['fieldStartBit']) +':0] '\n port_str.append(\n '[' +\n str((registers[register]['fields'][reg_field]['fieldStopBit']) -\n registers[register]['fields'][reg_field]['fieldStartBit']) +\n ':0]'\n )\n\n reg_fsm_case.append(\n ' '*4 + rgf_f_fsm['regTmpOutBus'] + '[' +\n str((registers[register]['fields'][reg_field]['fieldStopBit'])) +\n ':' +\n str(registers[register]['fields'][reg_field]['fieldStartBit']) +\n '] = ' + registers[register]['fields'][reg_field]['name'] + ';'\n )\n else:\n port_reg_boundries = ''\n reg_fsm_case.append(\n ' '*4 + rgf_f_fsm['regTmpOutBus'] + '[' +\n str(registers[register]['fields'][reg_field]['fieldStartBit']) +\n '] = ' + registers[register]['fields'][reg_field]['name'] + ';'\n )\n\n port_reg_str = port_reg_boundries + registers[register]['fields'][reg_field]['name'] + ';'\n if registers[register]['fields'][reg_field]['fieldDest'] == 'Digital':\n black_box_port_wire_list.append(\n 'wire ' + port_reg_str\n )\n elif registers[register]['fields'][reg_field]['fieldDest'] == 'Analog':\n black_box_port_output_list.append(\n 'output ' + port_reg_str\n )\n black_box_port_output_inst_list.append(\n '.' +\n registers[register]['fields'][reg_field]['name'] +\n '(' + registers[register]['fields'][reg_field]['name'] +\n ')'\n )\n black_box_port_list.append(\n ' '*4 + registers[register]['fields'][reg_field]['name']\n )\n elif registers[register]['fields'][reg_field]['fieldDest'] == 'IO':\n black_box_port_io_wire_list.append(\n 'wire ' + port_reg_str\n )\n black_box_port_io_output_list.append(\n 'output ' + port_reg_str\n )\n black_box_port_io_list.append(\n ' '*4 + registers[register]['fields'][reg_field]['name']\n )\n else:\n print('Error: Unrecognized field Destination')\n\n if registers[register]['fields'][reg_field]['accessLevel'] == 'R/W':\n rst_val = int(registers[register]['fields'][reg_field]['fieldRstVal'], 16)\n if rst_val is 0:\n rst_val_width = int(ceil(registers[register]['fields'][reg_field]['fieldWidth']/4))\n rst_val = str(registers[register]['fields'][reg_field]['fieldWidth']) + '\\'h' + rst_val_width*'0'\n else:\n rst_val = registers[register]['fields'][reg_field]['fieldRstVal'][2:]\n rst_val = str(registers[register]['fields'][reg_field]['fieldWidth']) + '\\'h' + rst_val\n\n reg_wr_proc_rst_list.append(\n ' '*8 + registers[register]['fields'][reg_field]['name'] +\n ' <= ' + rst_val + ';\\n'\n )\n\n reg_wr_proc_wr_list.append(\n ' '*12 + registers[register]['fields'][reg_field]['name'] + ' <= reg_wr_data_i[' +\n str((registers[register]['fields'][reg_field]['fieldStopBit'])) +\n ':' +\n str(registers[register]['fields'][reg_field]['fieldStartBit']) +\n '];\\n'\n )\n\n port_str.append(registers[register]['fields'][reg_field]['name'] + ',')\n\n reg_ports_list.append(' '.join(port_str))\n\n reg_wr_proc_rst_list.append(\n ' '*4 + 'end'\n )\n\n reg_wr_proc_wr_list.append(\n ' '*8 + 'end'\n )\n\n reg_fsm_case.append('end')\n\n reg_ports_list = str('\\n' + ' '*4).join(reg_ports_list)\n rgf_f_fields['portList'].append(reg_ports_list)\n\n rgf_f_fsm['regCases'].append(str('\\n'+' '*12).join(reg_fsm_case))\n\n reg_wr_proc.append(''.join(reg_wr_proc_rst_list))\n reg_wr_proc.append('\\n' + ' '*4 + 'else\\n')\n reg_wr_proc.append(''.join(reg_wr_proc_wr_list))\n\n reg_wr_proc = ''.join(reg_wr_proc)\n rgf_f_fields['instList'].append(reg_wr_proc)\n\n reg_param_list = '\\n'.join(reg_param_list)\n rgf_f_fsm['regCases'].append('default : ' + rgf_f_fsm['regTmpOutBus'] + ' = {REG_DATA_WIDTH{1\\'b0}};')\n rgf_f_fsm['regCases'] = str('\\n\\n'+' '*12).join(rgf_f_fsm['regCases'])\n\n # Populate Data Into Reg-FSM Template\n for key, val in rgf_f_fsm.items():\n reg_fsm_text = reg_fsm_text.replace(\n rgf_f_settings['prefix'] + key + rgf_f_settings['suffix'],\n val\n )\n rgf_f_fields['instList'].append(reg_fsm_text)\n\n rgf_f_fields['instList'] = '\\n\\n'.join(rgf_f_fields['instList'])\n\n rgf_f_fields['paramList'].append(reg_param_list)\n rgf_f_fields['paramList'] = '\\n\\n'.join(rgf_f_fields['paramList'])\n\n rgf_f_fields['ioList'] = '\\n\\n'.join(rgf_f_fields['portList'])[0:-1]\n\n rgf_f_fields['portList'] = ''\n rgf_f_fields['varList'] = 'reg [REG_DATA_WIDTH-1:0] reg_rd_data_comb;'\n\n file_name = os.sep.join([dir_path, 'reg_ant_sg.txt'])\n file_handler = open(file_name, 'r', newline='\\n')\n\n # Read Template\n rgf_f_fields['varList'] = rgf_f_fields['varList'] + '\\n\\n' + file_handler.read()\n file_handler.close()\n\n file_name = os.sep.join([dir_path, 'verilog_file_header.txt'])\n file_handler = open(file_name, 'r', newline='\\n')\n\n # Read Template\n text = file_handler.read()\n file_handler.close()\n\n # Read & Parse Excel Document\n black_box_port_inst_list = rgf_f_settings['commentTag'] + 'Start Of Register Instance:\\n' + str(',\\n' + ' '*4).join(black_box_port_inst_list)\n black_box_port_io_inst_list = rgf_f_settings['commentTag'] + ' IO outputs Port Inst:\\n' + str(',\\n' + ' '*4).join(black_box_port_io_inst_list)\n black_box_port_io_output_list = rgf_f_settings['commentTag'] + ' IO outputs:\\n' + '\\n'.join(black_box_port_io_output_list)\n black_box_port_output_list = rgf_f_settings['commentTag'] + ' Analog Outputs:\\n' + '\\n'.join(black_box_port_output_list)\n black_box_port_output_inst_list = rgf_f_settings['commentTag'] + ' Analog Outputs Inst List:\\n' + str(',\\n' + ' '*4).join(black_box_port_output_inst_list)\n black_box_port_io_wire_list = rgf_f_settings['commentTag'] + ' IO Varaibles Declaration:\\n' + '\\n'.join(black_box_port_io_wire_list)\n black_box_port_wire_list = rgf_f_settings['commentTag'] + ' Registers Varaibles Declaration:\\n' + '\\n'.join(black_box_port_wire_list)\n black_box_port_io_list = ' '*4 + rgf_f_settings['commentTag'] + ' Registers Outputs(IO):\\n' + ',\\n'.join(black_box_port_io_list) + ','\n black_box_port_list = ' '*4 + rgf_f_settings['commentTag'] + ' Registers Outputs(Analog):\\n' + ',\\n'.join(black_box_port_list)\n\n black_box_inst_txt = []\n black_box_inst_txt.append(black_box_port_inst_list)\n black_box_inst_txt.append(black_box_port_io_inst_list)\n black_box_inst_txt.append(black_box_port_io_output_list)\n black_box_inst_txt.append(black_box_port_output_list)\n black_box_inst_txt.append(black_box_port_output_inst_list)\n black_box_inst_txt.append(black_box_port_io_wire_list)\n black_box_inst_txt.append(black_box_port_wire_list)\n black_box_inst_txt.append(black_box_port_io_list)\n black_box_inst_txt.append(black_box_port_list)\n\n black_box_inst_txt = '\\n\\n\\n'.join(black_box_inst_txt)\n file_name = os.sep.join([dir_path, 'blackbox_inst.txt'])\n file_handler = open(file_name, 'w', newline='\\n')\n\n # Read Template\n file_handler.write(black_box_inst_txt)\n file_handler.close()\n\n rgf_f_fields['fileName'] = rgf_f_settings['fileName'] + rgf_f_settings['fileExt']\n rgf_f_fields['fileDescription'] = rgf_f_settings['projName'] + ' Auto Generated Registers'\n rgf_f_fields['moduleName'] = rgf_f_settings['fileName']\n\n # Populate Data Into Template\n for key, val in rgf_f_fields.items():\n text = text.replace(\n rgf_f_settings['prefix'] + key + rgf_f_settings['suffix'],\n val\n )\n\n file_name = os.sep.join(\n [dir_path, 'register.v']\n )\n file_handler = open(file_name, 'w', newline='\\n')\n\n file_handler.write(text)\n\n file_handler.close()\n\nif __name__ == '__main__':\n rgf_gen()\n","sub_path":"Book/scripts/rgf_gen.py","file_name":"rgf_gen.py","file_ext":"py","file_size_in_byte":18237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"604226651","text":"import logging\n\n# create log with 'spam_application'\nlogger = logging.getLogger(\"OnStudy\")\nlogger.setLevel(logging.INFO)\n\n# create formatter and add it to the handlers\nformatter = logging.Formatter(\n \"%(asctime)s - %(name)s::%(funcName)s::%(lineno)d\"\n \"- %(levelname)s - %(message)s\"\n)\n\n# create console handler\nconsoleHandler = logging.StreamHandler()\nconsoleHandler.setLevel(logging.INFO)\nconsoleHandler.setFormatter(formatter)\n\n# allows to add only one instance of file handler and stream handler\nif logger.handlers:\n for handler in logger.handlers:\n # add the handlers to the log\n # makes sure no duplicate handlers are added\n\n if not isinstance(handler, logging.StreamHandler):\n logger.addHandler(consoleHandler)\n print('added stream handler')\nelse:\n logger.addHandler(consoleHandler)\n print('added handler for the first time')","sub_path":"OnStudy/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"533170468","text":"# coding=utf-8\nimport pandas\nimport numpy as np\nimport scipy\nimport statsmodels.api as sm\nimport traceback\nimport logging\n\nimport math\nimport random\n\nfrom time import time\nfrom msgpack import unpackb, packb\nfrom redis import StrictRedis\nfrom scipy import stats\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.cluster import KMeans\n\nfrom settings import (\n ALGORITHMS,\n CONSENSUS,\n FULL_DURATION,\n MAX_TOLERABLE_BOREDOM,\n MIN_TOLERABLE_LENGTH,\n STALE_PERIOD,\n REDIS_SOCKET_PATH,\n ENABLE_SECOND_ORDER,\n BOREDOM_SET_SIZE,\n K_MEANS_CLUSTER,\n VERTEX_WEIGHT_ETA,\n VERTEX_THRESHOLD,\n ANOMALY_COLUMN,\n ANOMALY_PATH,\n CSHL_NUM,\n CSHL_PATH,\n)\n\nfrom algorithm_exceptions import *\n\nlogger = logging.getLogger(\"AnalyzerLog\")\nredis_conn = StrictRedis(unix_socket_path=REDIS_SOCKET_PATH)\nvertex_centers = np.zeros((1, 1))\nvertex_avg_score = -1\ncshl_weight = [-1.35455734e-01, -5.44036064e-04, -1.35455734e-01, -5.44036064e-04,\n -1.35455734e-01, -1.35455734e-01, -5.44036064e-04, -1.35455734e-01,\n -5.44036064e-04, -1.35455734e-01, -5.44036064e-04, -5.44036064e-04,\n -1.67484694e+00, 1.04843752e+00, 6.61651030e-01, 4.13469487e-08,\n 1.78945321e-01, -3.60150391e-01, 1.21850659e-01, 4.61800469e-01,\n -1.00200490e-01, -1.33467708e-06, 9.32745829e-19, 4.21863030e-09,\n -3.36662454e-10, -8.90717918e-06, -4.42558069e-05, -2.87667856e-09]\n\n\"\"\"\nThis is no man's land. Do anything you want in here,\nas long as you return a boolean that determines whether the input\ntimeseries is anomalous or not.\n\nTo add an algorithm, define it here, and add its name to settings.ALGORITHMS.\n\"\"\"\n\n\ndef vertex_score(timeseries):\n \"\"\"\n A timeseries is anomalous if vertex score in hypergraph is greater than average score of observed anomalous vertex.\n :return: True or False\n \"\"\"\n if vertex_centers.shape[0] <= 1:\n update_vertex_param()\n timeseries = np.array(timeseries)\n test_data = timeseries[:, 1:]\n test_data = (test_data - np.min(test_data, axis=0)) / (np.max(test_data, axis=0) - np.min(test_data, axis=0))\n test_data = np.nan_to_num(test_data)\n score = calculate_vertex_score(test_data, vertex_centers)\n if np.sum(score[score > vertex_avg_score]) > VERTEX_THRESHOLD:\n return True\n return False\n\n\ndef cshl_detect(timeseries):\n timeseries = np.delete(np.array(timeseries), [0,1,2,15], axis=1)\n abnormal_num = 0\n for i in range(timeseries.shape[0]):\n zeta = np.dot(timeseries[i], cshl_weight)\n if zeta < 0:\n abnormal_num = abnormal_num + 1\n if abnormal_num >= CSHL_NUM:\n return True\n return False\n\n\ndef update_vertex_param():\n \"\"\"\n Read observed abnormal data and update cluster centers\n \"\"\"\n global vertex_centers\n global vertex_avg_score\n origin_data = pandas.read_csv(ANOMALY_PATH).values\n abnormal = origin_data[:, 3:]\n abnormal = (abnormal - np.min(abnormal, axis=0)) / (np.max(abnormal, axis=0) - np.min(abnormal, axis=0))\n abnormal = np.nan_to_num(abnormal)\n k_means = KMeans(n_clusters=K_MEANS_CLUSTER)\n k_means.fit_predict(abnormal)\n vertex_centers = k_means.cluster_centers_\n vertex_avg_score = np.mean(calculate_vertex_score(abnormal, vertex_centers))\n\n\ndef calculate_vertex_score(samples, center):\n \"\"\"\n we use similarity score and isolation score to initialize vertex weight\n according to their correlations\n\n :param samples: all the samples\n :param center: abnormal cluster center\n :return: total score of samples\n \"\"\"\n clf = IsolationForest()\n clf.fit(samples)\n num = samples.shape[0]\n IS = (0.5 - clf.decision_function(samples)).reshape((num, 1))\n distance = np.array(np.min(euclidean_distances(samples, center), axis=1))\n dis_min = np.min(distance)\n dis_max = np.max(distance)\n distance = (distance - dis_min) / (dis_max - dis_min)\n SS = np.exp(-distance).reshape((num, 1))\n TS = VERTEX_WEIGHT_ETA * IS + (1-VERTEX_WEIGHT_ETA) * SS\n return TS\n\n\ndef euclidean_distances(A, B):\n \"\"\"\n Euclidean distance between matrix A and B\n\n :param A: np array\n :param B: np array\n :return: np array\n \"\"\"\n BT = B.transpose()\n vec_prod = np.dot(A, BT)\n SqA = A**2\n sumSqA = np.matrix(np.sum(SqA, axis=1))\n sumSqAEx = np.tile(sumSqA.transpose(), (1, vec_prod.shape[1]))\n SqB = B**2\n sumSqB = np.sum(SqB, axis=1)\n sumSqBEx = np.tile(sumSqB, (vec_prod.shape[0], 1))\n SqED = sumSqBEx + sumSqAEx - 2*vec_prod\n SqED[SqED < 0] = 0.0\n ED = np.sqrt(SqED)\n return ED\n\n\ndef tail_avg(timeseries):\n \"\"\"\n This is a utility function used to calculate the average of the last three\n datapoints in the series as a measure, instead of just the last datapoint.\n It reduces noise, but it also reduces sensitivity and increases the delay\n to detection.\n \"\"\"\n timeseries = np.array(timeseries)\n timeseries = timeseries[:, 1:]\n try:\n t = (timeseries[-1] + timeseries[-2] + timeseries[-3]) / 3\n return t\n except IndexError:\n return timeseries[-1]\n\n\ndef update_cshl():\n global cshl_weight\n csv_data = pandas.read_csv(CSHL_PATH, header=None)\n csv_data.drop([1, 2, 15], axis=1, inplace=True)\n csv_data.drop_duplicates()\n\n normal_data = csv_data[csv_data[0] == 0]\n abnormal_data = csv_data[csv_data[0] == 1]\n measure_data = np.vstack((normal_data, abnormal_data))\n measure_label = measure_data[:, 0]\n measure_label[measure_label == 0] = -1\n\n measure_data = measure_data[:, 1:]\n measure_data = (measure_data - np.min(measure_data, axis=0)) / (\n np.max(measure_data, axis=0) - np.min(measure_data, axis=0))\n measure_data = np.nan_to_num(measure_data)\n\n cshl_weight = hpconstruct(measure_data, measure_label, 5)\n\n\ndef hpconstruct(x, y, k):\n \"\"\"\n construct hypergraph and interative process\n :param x: np array, train and test set\n :param y: np array, cost for each sample\n :param k: value, kNN\n :return: evaluation criteria\n \"\"\"\n length = len(x)\n h = np.zeros((length, length))\n dvlist = []\n delist = []\n totaldis = 0.0\n alpha = 0.05\n\n wm = np.eye(length)\n wm = (1.0 / length) * wm\n # initialize W\n\n for xi in range(length):\n diffMat = np.tile(x[xi], (length, 1)) - x # 求inX与训练集各个实例的差\n sqDiffMat = diffMat ** 2\n sqDistances = sqDiffMat.sum(axis=1)\n distances = sqDistances ** 0.5 # 求欧式距离\n sortedDistIndicies = distances.argsort() # 取排序的索引,用于排label\n for i in range(k):\n index = sortedDistIndicies[i + 1]\n h[index][xi] = distances[index]\n totaldis += distances.sum()\n avedis = totaldis / (length ** 2 - length)\n for xi in range(length):\n for yi in range(length):\n if h[xi][yi]:\n h[xi][yi] = math.exp(((h[xi][yi] / avedis) ** 2) / (-alpha))\n h[xi][xi] = 1\n # initialize H,横坐标代表点,纵坐标代表边(中心点为序号)\n\n for xi in range(length):\n vertextmp = 0\n for yi in range(length):\n vertextmp += wm[yi][yi] * h[xi][yi]\n dvlist.append(vertextmp)\n dv = np.diag(dvlist)\n # initialize Dv\n\n for xi in range(length):\n edgetmp = 0\n for yi in range(length):\n edgetmp += h[yi][xi]\n delist.append(edgetmp)\n de = np.diag(delist)\n # initialize De\n\n di = []\n # y = np.array([])\n for i in range(length):\n if y[i] == 1:\n di.append(1)\n elif y[i] == -1:\n di.append(1)\n else:\n di.append(0)\n v = np.diag(di)\n # initialize Υ\n\n for i in range(length):\n dv[i][i] = 1 / (math.sqrt(dv[i][i]))\n # de[i][i] = 1 / de[i][i]\n # calculate power of Dv and De\n de = np.linalg.inv(de)\n mu = 1\n lamb = 1\n\n xt = np.transpose(x)\n first = np.dot(v, v)\n first = np.dot(xt, first)\n first = np.dot(first, x)\n third = np.dot(xt, v)\n third = np.dot(third, y)\n second = mu * xt\n # initialize fixed part of ω\n\n count = 0\n threshold = 0.000001\n opt = [0]\n u = np.eye(x.shape[1])\n\n while True:\n deltaleft = np.dot(dv, h)\n deltaright = np.dot(de, np.transpose(h))\n deltaright = np.dot(deltaright, dv)\n deltai = np.eye(length)\n # left and right part of Δ\n\n delta = np.dot(deltaleft, wm)\n delta = np.dot(delta, deltaright)\n delta = deltai - delta\n # first delta\n\n w = np.dot(second, delta)\n w = np.dot(w, x)\n w = first + w\n w = w + 1.0 * u\n w = np.linalg.inv(w)\n w = np.dot(w, third)\n # first w\n\n test = 0.1 * 1.0 / (2 * w ** 2)\n np.fill_diagonal(u, test)\n # update u\n\n xw = np.dot(x, w)\n tmp = xw - y\n tmp = np.dot(v, tmp)\n remp = np.linalg.norm(tmp, ord=2) ** 2\n omega = np.dot(np.transpose(xw), delta)\n omega = np.dot(omega, xw)\n kesai = np.linalg.norm(wm) ** 2\n opttmp = remp + mu * omega + lamb * kesai\n opt.append(opttmp)\n # first optimization\n\n count += 1\n if count > 2 and opt[count - 1] - opt[count] < threshold:\n break\n # judge\n\n caplambda = np.dot(np.transpose(xw), dv)\n caplambda = np.dot(caplambda, h)\n # first Λ\n\n yita_tmp = mu * caplambda\n yita_tmp = np.dot(yita_tmp, de)\n yita_tmp = np.dot(yita_tmp, np.transpose(caplambda))\n yita = (yita_tmp - 2 * lamb) / length\n # first η\n\n w_tmp = mu * np.transpose(caplambda)\n w_tmp = np.dot(w_tmp, caplambda)\n wm = (0.5 / lamb) * (np.dot(w_tmp, de) - yita * deltai)\n # second W\n\n dvlist = []\n for xi in range(length):\n vertextmp = 0\n for yi in range(length):\n vertextmp += wm[yi][yi] * h[xi][yi]\n dvlist.append(vertextmp)\n dv = np.diag(dvlist)\n for i in range(length):\n dv[i][i] = 1 / (math.sqrt(dv[i][i]))\n # initialize Dv\n # iteration\n\n return w\n\n\ndef grubbs(timeseries):\n \"\"\"\n A timeseries is anomalous if the Z score is greater than the Grubb's score.\n \"\"\"\n\n series = scipy.array([x[1] for x in timeseries])\n stdDev = scipy.std(series)\n mean = np.mean(series)\n tail_average = tail_avg(timeseries)\n z_score = (tail_average - mean) / stdDev\n len_series = len(series)\n threshold = scipy.stats.t.isf(.05 / (2 * len_series), len_series - 2)\n threshold_squared = threshold * threshold\n grubbs_score = ((len_series - 1) / np.sqrt(len_series)) * np.sqrt(threshold_squared / (len_series - 2 + threshold_squared))\n\n return z_score > grubbs_score\n\n\ndef first_hour_average(timeseries):\n \"\"\"\n Calcuate the simple average over one hour, FULL_DURATION seconds ago.\n A timeseries is anomalous if the average of the last three datapoints\n are outside of three standard deviations of this value.\n \"\"\"\n timeseries = np.array(timeseries)\n last_hour_threshold = time() - (FULL_DURATION - 3600)\n series = timeseries[timeseries[:, 0] < last_hour_threshold]\n if series.shape[0] == 0:\n return False\n series = series[:, 1:]\n mean = np.mean(series, axis=0)\n stdDev = np.std(series, axis=0)\n t = tail_avg(timeseries)\n\n return np.sum(abs(t - mean) > 3 * stdDev) > ANOMALY_COLUMN\n\n\ndef stddev_from_average(timeseries):\n \"\"\"\n A timeseries is anomalous if the absolute value of the average of the latest\n three datapoint minus the moving average is greater than three standard\n deviations of the average. This does not exponentially weight the MA and so\n is better for detecting anomalies with respect to the entire series.\n \"\"\"\n timeseries = np.array(timeseries)\n series = timeseries[:, 1]\n mean = np.mean(series, axis=0)\n stdDev = np.std(series, axis=0)\n t = tail_avg(timeseries)\n\n return np.sum(abs(t - mean) > 3 * stdDev) > ANOMALY_COLUMN\n\n\ndef least_squares(timeseries):\n \"\"\"\n A timeseries is anomalous if the average of the last three datapoints\n on a projected least squares model is greater than three sigma.\n \"\"\"\n\n x = np.array([t[0] for t in timeseries])\n y = np.array([t[1] for t in timeseries])\n A = np.vstack([x, np.ones(len(x))]).T\n results = np.linalg.lstsq(A, y)\n residual = results[1]\n m, c = np.linalg.lstsq(A, y)[0]\n errors = []\n for i, value in enumerate(y):\n projected = m * x[i] + c\n error = value - projected\n errors.append(error)\n\n if len(errors) < 3:\n return False\n\n std_dev = scipy.std(errors)\n t = (errors[-1] + errors[-2] + errors[-3]) / 3\n\n return abs(t) > std_dev * 3 and round(std_dev) != 0 and round(t) != 0\n\n\ndef histogram_bins(timeseries):\n \"\"\"\n A timeseries is anomalous if the average of the last three datapoints falls\n into a histogram bin with less than 20 other datapoints (you'll need to tweak\n that number depending on your data)\n\n Returns: the size of the bin which contains the tail_avg. Smaller bin size\n means more anomalous.\n \"\"\"\n\n series = scipy.array([x[1] for x in timeseries])\n t = tail_avg(timeseries)\n h = np.histogram(series, bins=15)\n bins = h[1]\n for index, bin_size in enumerate(h[0]):\n if bin_size <= 20:\n # Is it in the first bin?\n if index == 0:\n if t <= bins[0]:\n return True\n # Is it in the current bin?\n elif t >= bins[index] and t < bins[index + 1]:\n return True\n\n return False\n\n\ndef ks_test(timeseries):\n \"\"\"\n A timeseries is anomalous if 2 sample Kolmogorov-Smirnov test indicates\n that data distribution for last 10 minutes is different from last hour.\n It produces false positives on non-stationary series so Augmented\n Dickey-Fuller test applied to check for stationarity.\n \"\"\"\n\n hour_ago = time() - 3600\n ten_minutes_ago = time() - 600\n reference = scipy.array([x[1] for x in timeseries if x[0] >= hour_ago and x[0] < ten_minutes_ago])\n probe = scipy.array([x[1] for x in timeseries if x[0] >= ten_minutes_ago])\n\n if reference.size < 20 or probe.size < 20:\n return False\n\n ks_d, ks_p_value = scipy.stats.ks_2samp(reference, probe)\n\n if ks_p_value < 0.05 and ks_d > 0.5:\n adf = sm.tsa.stattools.adfuller(reference, 10)\n if adf[1] < 0.05:\n return True\n\n return False\n\n\ndef is_anomalously_anomalous(metric_name, ensemble, datapoint):\n \"\"\"\n This method runs a meta-analysis on the metric to determine whether the\n metric has a past history of triggering. TODO: weight intervals based on datapoint\n \"\"\"\n # We want the datapoint to avoid triggering twice on the same data\n new_trigger = [time(), datapoint]\n\n # Get the old history\n raw_trigger_history = redis_conn.get('trigger_history.' + metric_name)\n if not raw_trigger_history:\n redis_conn.set('trigger_history.' + metric_name, packb([(time(), datapoint)]))\n return True\n\n trigger_history = unpackb(raw_trigger_history)\n\n # Are we (probably) triggering on the same data?\n if (new_trigger[1] == trigger_history[-1][1] and\n new_trigger[0] - trigger_history[-1][0] <= 300):\n return False\n\n # Update the history\n trigger_history.append(new_trigger)\n redis_conn.set('trigger_history.' + metric_name, packb(trigger_history))\n\n # Should we surface the anomaly?\n trigger_times = [x[0] for x in trigger_history]\n intervals = [\n trigger_times[i + 1] - trigger_times[i]\n for i, v in enumerate(trigger_times)\n if (i + 1) < len(trigger_times)\n ]\n\n series = pandas.Series(intervals)\n mean = series.mean()\n stdDev = series.std()\n\n return abs(intervals[-1] - mean) > 3 * stdDev\n\n\ndef run_selected_algorithm(timeseries, metric_name):\n \"\"\"\n Filter timeseries and run selected algorithm.\n \"\"\"\n # Get rid of short series\n if len(timeseries) < MIN_TOLERABLE_LENGTH:\n raise TooShort()\n\n # Get rid of stale series\n if time() - timeseries[-1][0] > STALE_PERIOD:\n raise Stale()\n\n # Get rid of boring series\n if len(set(item[1] for item in timeseries[-MAX_TOLERABLE_BOREDOM:])) == BOREDOM_SET_SIZE:\n raise Boring()\n\n try:\n ensemble = [globals()[algorithm](timeseries) for algorithm in ALGORITHMS]\n threshold = len(ensemble) - CONSENSUS\n if ensemble.count(False) <= threshold:\n # if ENABLE_SECOND_ORDER:\n # if is_anomalously_anomalous(metric_name, ensemble, timeseries[-1]):\n # return True, ensemble, timeseries[-1]\n # else:\n # return True, ensemble, timeseries[-1]\n return True, ensemble, timeseries[-1]\n return False, ensemble, timeseries[-1]\n except:\n logging.error(\"Algorithm error: \" + traceback.format_exc())\n return False, [], 1\n","sub_path":"src/analyzer/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":16990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"165923829","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config.from_object('config')\ndb = SQLAlchemy(app)\n\nimport logging\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\n\nfrom app import views, models\nfrom config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT\n\nif not app.debug:\n import logging\n from logging.handlers import SMTPHandler, RotatingFileHandler\n\n #sending errors via email\n mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), 'noreply@birdfly.com',\n ADMINS, 'ESL Podcast failuer')\n mail_handler.setLevel(logging.DEBUG)\n app.logger.addHandler(mail_handler)\n\n #logging to a file\n file_handler = RotatingFileHandler('tmp/eslpod.log', 'a', 1*1024*1024, 10)\n file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s '\n '[in %(pathname)s:%(lineno)d]'))\n app.logger.setLevel(logging.INFO)\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n app.logger.info('ESL Podcast startup')","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"67682414","text":"import math\ndef receptive_field(n, layers, position):\n \"\"\"\n Parameters\n ----------\n n: int, input size\n layers: array of triplets: (k,s,p)\n k: kernel size\n s: stride\n p: padding\n \n Returns\n -------\n n: output size\n j: jump size\n r: size of receptive field\n start: center position of the receptive field of the first output feature\n \"\"\"\n\n r = 1\n j = 1\n start = 0.5\n for k, s, p in layers:\n n = math.floor( (n - k + p)/s ) + 1\n r = r + (k-1)*j\n start = start + ( (k-1)/2 - p)*j\n j = j*s\n print(int(n), j, r, start)\n\n #return int(n), j, r, start\n x1 = (position[0]+1)*start\n y1 = (position[1]+1)*start\n\n x2 = (position[2]+1)*start\n y2 = (position[3]+1)*start\n print('Position : ',int(x1-r//2), int(y1-r//2), int(x2+r//2)-1, int(y2+r//2)-1)\n\n\n# Example:\nlayers = [\n (3, 2, 0), # k, s, p\n (3, 2, 0),\n # (1, 4, 0), # maxpool\n # (16, 8, 8),\n # (16, 8, 8),\n]\nreceptive_field(32, layers, [0,0,2,2])\n#> (0, 4096, 8796, -640.5)","sub_path":"receptive/receptive_field.py","file_name":"receptive_field.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"650398878","text":"\"\"\"\n --Monika Sawicka s1097259 bin 2c--\n -- 29.01.2017--\n\"\"\"\n\nfrom os import path\nimport io\nimport random\nimport datetime\n\n\ndef datum():\n \"\"\"\n Deze functie slaat de huidige datum op in een variable.\n :return: date\n \"\"\"\n date = datetime.date.today()\n return date\n\n\ndef file_controleren(path_to_check):\n \"\"\"\n Deze functie controleert of het bestand bestaat.\n :param path_to_check: bestands path en naam\n :return tuple\n \"\"\"\n if not path.isfile(path_to_check):\n return False, 'Het bestand \\'{}\\' bestaat niet. Download ' \\\n 'het bestand en probeer het openieuw.\\n' \\\n 'Het spel wordt afgesloten.' \\\n .format(path_to_check)\n return True, ''\n\n\ndef voeding_bestand_inlezen():\n \"\"\"\n Deze functie leest het voeding bestand tot een dictionary.\n :return: dictionary\n \"\"\"\n voeding_dict = {}\n with open(\"voeding.txt\", 'r') as f:\n for line in f:\n items = line.strip('\\n').split(':')\n key, values = items[0], items[1]\n voeding_dict[key] = values\n return voeding_dict\n\n\ndef plaatjes_bestand_inlezen():\n \"\"\"\n Deze functie leest het bestand met tamagotchi plaatjes tot een\n lijst.\n :return: lijst\n \"\"\"\n plaatjes_lijst = []\n with io.open(\"pet_pictures.txt\", encoding='utf-8') as f:\n for line in f:\n items = line.split(';')\n items.remove(items[0])\n plaatjes_lijst.append(items)\n return plaatjes_lijst\n\n\ndef input_voeding_controleren(voeding, voeding_dict):\n \"\"\"\n Deze functie controleert of ingevoerde voedings naam nog niet in de\n bestaande voedings lijst is en haalt alle vreemde tekens van het\n woord uit.\n :param voeding: ingevoerde woord\n :param voeding_dict: dictionary met alle bestaande voeding namen\n :return tuple: melding: bericht dat gebruiker krijgt van het\n programma, waarde: markeert voeding met o of g, v_woord: aangepaste\n woord.\n \"\"\"\n v_woord = ''\n for letter in voeding:\n if letter.isalpha():\n v_woord += letter\n if v_woord in voeding_dict:\n melding = \"Deze voeding soort komt al voor in de lijst.\\n\"\n return melding, '', ''\n elif len(v_woord) < 3 or len(v_woord) > 38:\n melding = (\"\\nUw woord is: \" + v_woord + \". \\nDeze woord niet \"\n \"toegevoegd tot het \"\n \"lijst.\\nHet woord moet \"\n \"langer dan 3 en korter \"\n \"dan 38 letters zijn.\\n\")\n return melding, '', ''\n else:\n v_woord = v_woord\n waarde = input_waarde_controleren()\n return '', waarde, v_woord\n\n\ndef input_waarde_controleren():\n \"\"\"\n Deze functie controleert of ingevoerde voeding waarte is correct.\n :return: voeding waarde\n \"\"\"\n herhalen = True\n waarde = str(input('\\nIs deze voeding gezond (g) '\n 'of ongezond (o)?'))\n while herhalen:\n if waarde != \"g\" and waarde != \"o\":\n waarde = str(input(\n \"\\nIs deze voeding gezond (g) of \"\n \"ongezond (o)?\"))\n else:\n return waarde\n\n\ndef voeding_toevoegen(voeding, voeding_dict, waarde):\n \"\"\"\n Deze functie controleert of ingevoerde voeding en zijn waarde al te\n vinden zijn in bestaande voeding dictionary. Als niet wordt de\n voeding als een key tot dictionary toegevoed en waarde als zijn\n value.\n :param voeding: ingevorde voeding naam\n :param voeding_dict: voeding dictionary\n :param waarde: ingevoerde voeding waarde\n :return: string - bericht voor de gebruiker\n \"\"\"\n if voeding not in voeding_dict:\n voeding_dict[voeding] = waarde\n voeding_lijst = []\n for a in voeding_dict:\n voeding_lijst.append(a + ':' + voeding_dict[a])\n voeding_lijst.sort(key=lambda x: (len(x), x))\n w_file = open('voeding.txt', 'w')\n w_file.write('\\n'.join(voeding_lijst))\n w_file.close()\n melding = ('Het voeding soort ' + voeding + ' is toegevoegd tot het '\n 'voeding lijst.')\n return melding\n else:\n melding = 'Dit woord komt al voor in deze lijst.'\n return melding\n\n\ndef leeftijden(beurt):\n \"\"\"\n Deze functie bepaald een waarde, die later gebruikt wordt in het\n keuze van de plaatjes.\n :param beurt: beurt nr\n :return: integer\n \"\"\"\n if beurt in range(0, 7):\n return 0\n elif beurt in range(7, 14):\n return 6\n elif beurt in range(14, 21):\n return 12\n elif beurt in range(21, 25):\n return 17\n\n\ndef volwassen(v_totaal, v_plaatjes):\n \"\"\"\n Deze functie bepaald welke plaatje moet worden gebruikt als\n Tamagotchi volwassen wordt.\n :param v_totaal: totale waarde van alle statussen\n :param v_plaatjes: lijst van lijsten met Tamagotchi plaatjes\n :return: lijst van gekozen plaatje\n \"\"\"\n if v_totaal in range(0, 6):\n return v_plaatjes[25]\n if v_totaal in range(6, 10):\n return v_plaatjes[26]\n if v_totaal in range(10, 14):\n return v_plaatjes[27]\n if v_totaal in range(14, 18):\n return v_plaatjes[28]\n if v_totaal > 17:\n return v_plaatjes[29]\n\n\ndef plaatje_kiezen(p_beurt, p_honger, p_afval, p_geluk, p_plaatjes,\n p_totaal, p_ranking_lijst, p_speller_naam, p_taam_naam,\n p_kopje, p_bericht, p_leeftijd):\n \"\"\"\n Deze functie\n :param p_leeftijd: leeftijd waarde voor plaatjes\n :param p_beurt: aantal beurten\n :param p_honger: aantal honger punten\n :param p_afval: aantal afval punten\n :param p_geluk: aantal geluk punten\n :param p_plaatjes: lijst van plaatjes lijsten\n :param p_totaal: totaal van alle statussen\n :param p_ranking_lijst: ranking lijst uit het bestand\n :param p_speller_naam: speler naam\n :param p_taam_naam: tamagotchi naam\n :param p_kopje: eerste rij van het ranking uit het bestand\n :param p_bericht: melding om te weergeven\n :return: string met het lay out van het scherm met updated waardes\n en plaatje, boolean, afhankelijk van het staats - lege string of\n ranking melding, afhankelijk van het staats - lege string of\n updated ranking string\n \"\"\"\n if p_totaal < 6 and p_beurt < 25:\n return plaatjes_layout(p_beurt, p_afval, p_geluk,\n p_taam_naam, p_honger, p_bericht,\n p_plaatjes[1 + p_leeftijd]), True, '', ''\n elif p_totaal in range(6, 10) and p_beurt < 25:\n return plaatjes_layout(p_beurt, p_afval, p_geluk,\n p_taam_naam, p_honger, p_bericht,\n p_plaatjes[2 + p_leeftijd]), True, '', ''\n elif p_totaal in range(10, 14) and p_honger < 13 and p_afval < 13 and \\\n p_geluk < 12 and p_beurt < 25:\n return plaatjes_layout(p_beurt, p_afval, p_geluk,\n p_taam_naam, p_honger, p_bericht,\n p_plaatjes[3 + p_leeftijd]), True, '', ''\n elif p_totaal in range(14, 18) and p_honger < 13 and p_afval < 13 and \\\n p_geluk < 13 and p_beurt < 25:\n return plaatjes_layout(p_beurt, p_afval, p_geluk,\n p_taam_naam, p_honger, p_bericht,\n p_plaatjes[4 + p_leeftijd]), True, '', ''\n elif p_totaal > 17 and p_honger < 13 and p_afval < 13 and \\\n p_geluk < 13 and p_beurt < 25:\n return plaatjes_layout(p_beurt, p_afval, p_geluk,\n p_taam_naam, p_honger, p_bericht,\n p_plaatjes[5 + p_leeftijd]), True, '', ''\n else:\n scherm, spelen, ranking_bericht, rank = game_over(p_honger,\n p_ranking_lijst,\n p_speller_naam,\n p_taam_naam,\n p_beurt, p_totaal,\n p_afval, p_geluk,\n p_plaatjes,\n p_leeftijd, p_kopje)\n return scherm, spelen, ranking_bericht, rank\n\n\ndef game_over(g_honger, g_ranking_lijst, g_speller_naam, g_t_naam,\n g_beurt, g_totaal, g_afval, g_geluk, g_plaatjes,\n g_leeftijd, g_kopje):\n \"\"\"\n Deze functie bepaald welke plaatje woord getoond in het gevaal\n van te gohe statussen en eindingt het spel.\n :param g_honger: honger punten\n :param g_ranking_lijst: ranking lijst uit de bedstand\n :param g_speller_naam: speler naam\n :param g_t_naam: Tamagotchi naam\n :param g_beurt: aantal beurten\n :param g_totaal: totaal alle statussen\n :param g_afval: aantal afval punten\n :param g_geluk: aantal geluk punten\n :param g_plaatjes: lijst van plaatjes lijsten\n :param g_leeftijd: leeftijd waarde\n :param g_kopje: eerste regel van ranking bestand\n :return: string voor het scherm layout, boolean, string met\n melding voor de gebruiker,string met updated ranking layout\n \"\"\"\n if g_honger >= 13:\n rank_voor_wegschrijven, rank_bericht = ranking_vullen(\n g_ranking_lijst, g_speller_naam,\n g_t_naam,\n g_beurt, g_totaal)\n ranking_wegschrijven(rank_voor_wegschrijven, g_kopje)\n scherm = plaatjes_layout(g_beurt, g_afval, g_geluk,\n g_t_naam, g_honger,\n 'Je moet de Tamagotchi wel eten geven...',\n g_plaatjes[6 + g_leeftijd])\n rank = ranking_layout()\n return scherm, False, rank_bericht, rank\n elif g_afval >= 13:\n rank_voor_wegschrijven, rank_bericht = ranking_vullen(\n g_ranking_lijst, g_speller_naam,\n g_t_naam,\n g_beurt, g_totaal)\n ranking_wegschrijven(rank_voor_wegschrijven, g_kopje)\n scherm = plaatjes_layout(g_beurt, g_afval, g_geluk,\n g_t_naam, g_honger, 'Ik ga weg, '\n 'er is teveel rommel!',\n g_plaatjes[30])\n rank = ranking_layout()\n return scherm, False, rank_bericht, rank\n elif g_geluk >= 13:\n rank_voor_wegschrijven, rank_bericht = ranking_vullen(\n g_ranking_lijst, g_speller_naam,\n g_t_naam,\n g_beurt, g_totaal)\n ranking_wegschrijven(rank_voor_wegschrijven, g_kopje)\n scherm = plaatjes_layout(g_beurt, g_afval, g_geluk,\n g_t_naam, g_honger, 'Varwel, ik heb er meer'\n ' van verwacht!',\n g_plaatjes[30])\n rank = ranking_layout()\n return scherm, False, rank_bericht, rank\n elif g_beurt == 25:\n rank_voor_wegschrijven, rank_bericht = ranking_vullen(\n g_ranking_lijst, g_speller_naam,\n g_t_naam,\n g_beurt, g_totaal)\n ranking_wegschrijven(rank_voor_wegschrijven, g_kopje)\n plaatje = volwassen(g_totaal, g_plaatjes)\n scherm = plaatjes_layout(g_beurt, g_afval, g_geluk,\n g_t_naam, g_honger,\n '{}{}{}'.format('Hoera ', g_t_naam,\n ' is volwassen!'), plaatje)\n rank = ranking_layout()\n return scherm, False, rank_bericht, rank\n\n\ndef padding(woord, lengte):\n \"\"\"\n Deze functie plakt spaties aan de strings zodat ze verwachte lengte\n hebben.\n :param woord: string om aan te passen\n :param lengte: vewarchtte lengte\n :return:\n \"\"\"\n return woord + (' ' * (lengte - len(woord)))\n\n\ndef plaatjes_layout(beurt, afval, ongelukkig, naam, honger,\n bericht, plaatje):\n \"\"\"\n Deze functie maakt en update string voor het lay out van het spel\n scherm.\n :param beurt: aantal beurten\n :param afval: aantal afval punnten\n :param ongelukkig: aantal geluk punnten\n :param naam: Tamagotchi naam\n :param honger: aantal honger punnten\n :param bericht: string met melding voor het gebruiker\n :param plaatje: lijst van plaatje\n :return: string met updated layout\n \"\"\"\n space = 20 * '\\n'\n naam = padding(\"Naam: \" + naam, 20)\n beurtje = padding('Leeftijd: ' + str(beurt), 20)\n afval = padding(\"Afval: \" + (afval * '*'), 20)\n hongerig = padding(\"Hongerig: \" + (honger * '*'), 20)\n ongelukkig = padding(\"Ongelukkig: \" + (ongelukkig * ('*')), 20)\n scherm = \"{}\\n\" \\\n \"{:^70}\\n\" \\\n \"{}\\n\" \\\n \"{}{}{}\\n\" \\\n \"{}{}{}\\n\" \\\n \"{}{}{}\\n\" \\\n \"{}\\n\" \\\n \"{:^69}\\n\" \\\n \"{:^69}\\n\" \\\n \"{:^79}\\n\" \\\n \"{:^69}\\n\".format(\n space,\n bericht,\n naam,\n beurtje, \" \" * (60 - (len(beurtje) + len(plaatje[0]))),\n padding(plaatje[0], 20),\n afval, \" \" * (60 - (len(afval) + len(plaatje[0]))),\n padding(plaatje[1], 20),\n hongerig, \" \" * (60 - (len(hongerig) + len(plaatje[0]))),\n padding(plaatje[2], 20),\n ongelukkig,\n \"1. Geef eten\",\n \"2. Verschoon\",\n \"3. Speel een spelletje\",\n \"4. Afsluiten\")\n\n return scherm\n\n\ndef voeding_lijsten(voeding):\n \"\"\"\n Deze functie doorzoekt het voeding dictionary aan de hand van de\n waarde van de voeding en voegt gezonde en ongezonde voeding tot\n behorende lijsten.\n :param voeding: voeding dictionary\n :return: lijsten voor gezonde van strings voor ongezonde voeding\n \"\"\"\n gezond = []\n ongezond = []\n for eten in voeding:\n if voeding[eten] == 'g':\n gezond.append(eten)\n else:\n ongezond.append(eten)\n return gezond, ongezond\n\n\ndef eten_kiezen(voeding, naam):\n \"\"\"\n Deze functie kiest random gezonde en ongezonde voeding items en\n heeft gebruiker de keuze.\n :param voeding: voeding dictionary\n :param naam: Tamagotchi naam\n :return: string voor input\n \"\"\"\n\n gezond, ongezond = voeding_lijsten(voeding)\n opties = \"Wat geef je \" + naam + \" te eten?\\n1.\" + \\\n random.choice(gezond) + \"\\n2.\" + random.choice(ongezond) + \\\n \"\\n3.Niks.\\n\\nMaak een keuze:\\n\"\n return opties\n\n\ndef gezond_eten_geven(afval, ongelukkig, honger):\n \"\"\"\n Deze functie update eten, honger en geluk statussen in het geval\n van het gebruiker's keuze voor gezonde eten. Statusen woorden\n updated afhankelijk van huidige staat.\n :param afval: aantal afval punten\n :param ongelukkig: aantal geluks punten\n :param honger: aantal honger punten\n :return: updatetd status van honger, afval, geluk, string voor\n het melding\n \"\"\"\n if honger < 13 and afval < 13 and ongelukkig < 13 and honger \\\n > 0:\n honger -= 2\n if honger < 0:\n honger = 0\n afval += 1\n ongelukkig = ongelukkig\n return honger, afval, ongelukkig, 'Nomnom'\n elif honger < 13 and afval < 13 and ongelukkig < 13 \\\n and honger < 1:\n honger = 0\n ongelukkig += 1\n afval = afval\n return honger, afval, ongelukkig, 'Ik heb geen honger!'\n\n\ndef ongezond_eten_geven(afval, ongelukkig, honger):\n \"\"\"\n Deze functie update eten, honger en geluk statussen in het geval\n van het gebruiker's keuze voor ongezonde eten. Statusen woorden\n updated afhankelijk van huidige staat.\n :param afval: aantal afval punten\n :param ongelukkig: aantal geluks punten\n :param honger: aantal honger punten\n :return: updatetd status van honger, afval, geluk, string voor\n het melding\n \"\"\"\n if honger < 13 and afval < 13 and ongelukkig < 13 and honger \\\n > 0:\n honger -= 1\n if honger < 0:\n honger = 0\n afval += 3\n ongelukkig -= 1\n if ongelukkig < 0:\n ongelukkig = 0\n return honger, afval, ongelukkig, 'Nomnomnom!'\n elif honger < 13 and honger < 1 and afval < 13 and ongelukkig < \\\n 13:\n honger = 0\n ongelukkig += 1\n afval = afval\n return honger, afval, ongelukkig, 'Ik heb geen honger!'\n\n\ndef geen_eten_geven(afval, ongelukkig, honger):\n \"\"\"\n Deze functie update eten, honger en geluk statussen in het geval\n van het gebruiker's keuze voor geen eten geven. Statusen woorden\n updated afhankelijk van huidige staat.\n :param afval: aantal afval punten\n :param ongelukkig: aantal geluks punten\n :param honger: aantal honger punten\n :return: updatetd status van honger, afval, geluk, string voor\n het melding\n \"\"\"\n if honger < 13 and afval < 13 and ongelukkig < 13 and honger \\\n > 0:\n honger += 1\n afval = afval\n ongelukkig += 1\n return honger, afval, ongelukkig, 'Maar ik heb honger!'\n\n elif honger < 13 and afval < 13 and ongelukkig < 13 \\\n and honger < 1:\n honger += 1\n ongelukkig += 0\n afval = afval\n return honger, afval, ongelukkig, 'Ik krijg hier wel trek ' \\\n 'van!'\n\n\ndef verschonen(afval, ongelukkig, honger):\n \"\"\"\n Deze functie update eten, honger en geluk statussen in het geval\n van het gebruiker's keuze voor verschonen van Tamagotchi. Statusen\n woorden\n updated afhankelijk van huidige staat.\n :param afval: aantal afval punten\n :param ongelukkig: aantal geluks punten\n :param honger: aantal honger punten\n :return: updatetd status van honger, afval, geluk, string voor\n het melding\n \"\"\"\n if honger < 13 and afval < 13 and ongelukkig < 13 and afval \\\n > 0:\n honger += 1\n afval -= 2\n if afval < 0:\n afval = 0\n ongelukkig += 1\n return honger, afval, ongelukkig, 'Fris en fruitig!'\n elif honger < 13 and afval < 13 and ongelukkig < 13 and afval \\\n < 1:\n honger += 1\n afval = afval\n ongelukkig += 2\n return honger, afval, ongelukkig, 'Grmpf, het is al schoon!'\n\n\ndef kop_of_munt(km_input, honger, ongelukkig, t_naam, naam):\n \"\"\"\n Deze functie update eten, honger en geluk statussen in het geval\n van het gebruiker's keuze voor spelen met Tamagotchi in 'Kop of\n munt'. Statusen woorden updated afhankelijk van huidige staat.\n :param km_input: keuze van gebruiker voor kop of munt\n :param honger: aantal honger punten\n :param ongelukkig: aantal geluks punten\n :param t_naam: Tamagotchi naam\n :param naam: speler naam\n :return: updatetd status van honger, geluk, string voor het melding\n \"\"\"\n penny = ['kop', 'munt']\n side = random.choice(penny)\n if penny[int(km_input) - 1] != side:\n honger += 1\n ongelukkig -= 2\n if ongelukkig < 0:\n ongelukkig = 0\n return honger, ongelukkig, 'Uitslag: ' + side.capitalize() + '. ' + \\\n t_naam.capitalize() + ' heeft gewonnen!'\n else:\n honger += 1\n ongelukkig += 2\n return honger, ongelukkig, 'Uitslag: ' + side.capitalize() + '. ' + \\\n naam.capitalize() + ' heeft gewonnen!'\n\n\ndef steen_schaar_papier(ssp_keuze, honger, geluk, afval):\n \"\"\"\n Deze functie update eten, honger en geluk statussen in het geval\n van het gebruiker's keuze voor spelen met Tamagotchi in 'Steen,\n schaar of papier'. Statusen woorden updated afhankelijk van huidige\n staat.\n :param ssp_keuze: keuze van gebruiker tussen steen, papier en schaar\n :param honger: aantal honger punten\n :param geluk: aantal geluks punten\n :param afval: aantal afval punten\n :return: updatetd status van honger, afval, geluk, string voor\n het melding\n \"\"\"\n ssp = ['steen', 'papier', 'schaar']\n tref = random.choice(ssp)\n if ssp[int(ssp_keuze) - 1] == tref:\n return honger, afval, geluk, 'Gelijkspel, allebei ' + tref + '.'\n elif (tref == 'steen' and ssp[int(ssp_keuze) - 1] == 'papier') \\\n or (tref == 'schaar' and ssp[int(ssp_keuze) - 1] == 'steen') \\\n or (tref == 'papier' and ssp[int(ssp_keuze) - 1] == 'schaar'):\n\n return honger + 1, afval + 1, geluk + 2, 'Jij wint, ' + ssp[int(\n ssp_keuze) - 1] + ' verslaat ' + tref + '.'\n else:\n geluk -= 2\n if geluk < 1:\n geluk = 0\n return honger + 1, afval + 1, geluk, 'Jij verliest, ' \\\n '' + tref + ' ' \\\n 'verslaat ' + \\\n ssp[int(ssp_keuze) - 1] + '.'\n\n\ndef punten_tellen(p_beurten, p_totaal_staat):\n \"\"\"\n Deze functie berekent de score voor de ranking.\n :param p_beurten: aantal beurten\n :param p_totaal_staat: cumulatieve staat\n :return: eindscore\n \"\"\"\n p_totaal_score = 0\n p_totaal_score += p_totaal_staat\n p_eindscore = (900 - p_totaal_score) * p_beurten\n return p_eindscore\n\n\ndef rankinglijst_maken():\n \"\"\"\n Deze Functie leest een ranking file tot de lijst.\n :return: ranking lijst\n \"\"\"\n ranking_file = open('ranking.txt', 'r')\n lijst_ranking = []\n inhoud_bestand = ranking_file.read().splitlines()\n for rij in inhoud_bestand:\n lijst_ranking.append(rij.split(';'))\n ranking_file.close()\n return lijst_ranking\n\n\ndef ranking_vullen(r_leeg_lijst, r_speller_naam,\n r_taam_naam,\n r_beurten, r_totaal_staat):\n \"\"\"\n Deze functie maakt een lijst met nieuwe scores en voegt het aan\n de bestande rankinglijst. Vervolgens sorteert rankinglijst en\n bepaalt of nieuwe scores in de ranking komen.\n :param r_leeg_lijst: rankinglijst van de bestand\n :param r_speller_naam: speler naam\n :param r_taam_naam: Tamagotchi naam\n :param r_beurten: aantal beurten\n :param r_totaal_staat: cumulatieve staat\n :return: updated rankinglijst, string met melding voor de gebruiker\n \"\"\"\n r_punten = punten_tellen(r_beurten,\n r_totaal_staat)\n r_datum = datum()\n r_leeg_lijst.append(['', str(r_datum), str(r_speller_naam),\n str(r_taam_naam),\n str(r_beurten), str(r_punten)])\n r_leeg_lijst.sort(key=lambda itemrij: int(itemrij[5]),\n reverse=True)\n positie = 1\n for item, value in enumerate(r_leeg_lijst):\n r_leeg_lijst[item][0] = str(positie)\n positie += 1\n r_lijst = r_leeg_lijst[0:10]\n # lijst_positie, item_positie = positie_vinden(r_lijst, r_punten)\n r_bericht = ''\n # rank_positie = r_lijst[lijst_positie][0]\n if r_punten <= int(r_lijst[9][5]):\n # rank_positie = r_lijst[lijst_positie][0]\n r_bericht = 'Eindscore: ' + str(r_punten) + '\\nHelaas, ' \\\n 'jouw ' \\\n 'score is niet hoog ' \\\n 'genoeg voor de ' \\\n 'ranglijst.\\n\\n'\n\n r_bericht = 'Eindscore: ' + str(r_punten) # + '\\nDaarmee kom je op\n # positie ' + str(rank_positie) + ' in de ranking.\\n\\n'\n\n return r_lijst, r_bericht\n\n\ndef positie_vinden(pv_lijst, pv_punten):\n \"\"\"\n Deze haalt het positie van de speler uit de raninglijst\n :param pv_lijst: updated rankinglijst\n :param pv_punten: gescoorde punten\n :return: lijst index\n \"\"\"\n for i, lst in enumerate(pv_lijst):\n for j, positie in enumerate(lst):\n if positie == str(pv_punten):\n return i, j\n\n\ndef ranking_wegschrijven(r_ranking, r_kopje):\n \"\"\"\n Functiebeschrijving: Deze Functie schrijf een rankinglijst tot een\n file.\n :param r_kopje: eerste regel uit het ranking file\n :param r_ranking: lijst met ranking\n \"\"\"\n file = open('ranking.txt', 'w')\n\n r_schrijfbaar = []\n\n for item in r_ranking:\n r_schrijfbaar.append(';'.join(item))\n\n r_schrijfbaar.insert(0, ';'.join(r_kopje))\n\n file.write('\\n'.join(r_schrijfbaar))\n file.close()\n\n\ndef ranking_layout():\n \"\"\"\n Functiebeschrijving: Deze Functie opent een ranking file, schrijft het\n file tot de lijst, vervolgens converteert het lijst tot een string in\n aangegeven format.\n :return: string met ranking\n \"\"\"\n r_ranking = open('ranking.txt', 'r')\n lijst_ranking = []\n inhoud_bestand = r_ranking.read().splitlines()\n for rij in inhoud_bestand:\n lijst_ranking.append(rij.split(';'))\n r_ranking.close()\n print(lijst_ranking)\n teller = 0\n r_ranking_string = ''\n for rij in lijst_ranking:\n r_ranking_string += '{:<10}{:<20}{:<10}{:<10}{:<10}{:<15}\\n'.format(\n [rij[0], teller][teller > 0], rij[1], rij[2], rij[3], rij[4],\n rij[5])\n teller += 1\n return r_ranking_string\n\n\ndef main():\n if not file_controleren('voeding.txt')[0]:\n print(file_controleren('voeding.txt')[1])\n exit()\n\n if not file_controleren('ranking.txt')[0]:\n print(file_controleren('ranking.txt')[1])\n exit()\n if not file_controleren('pet_pictures.txt')[0]:\n print(file_controleren('pet_pictures.txt')[1])\n exit()\n dict_voeding = voeding_bestand_inlezen()\n ranking_lijst = rankinglijst_maken()\n kopje = ranking_lijst[0]\n leeg_ranking = ranking_lijst[1:]\n plaatjes = plaatjes_bestand_inlezen()\n speler_naam = str(input(\"Wat is je naam? \"))\n naam_check = False\n while not naam_check:\n if len(speler_naam) < 1:\n speler_naam = str(input(\"Wat is je naam? \")).lower()\n elif not speler_naam.isalpha():\n speler_naam = str(input(\"Wat is je naam? \")).lower()\n else:\n print(\"Welkom \" + speler_naam + \"!!\\n\")\n naam_check = True\n menu_eind = False\n while not menu_eind:\n main_keuze = str(input(\"Wat wil je doen?\\n\"\n \"1. Voeding toevoegen\\n\"\n \"2. Tamagotchi spelen\\n\"\n \"3. De ranking bekijken\\n\"\n \"4. Afsluiten\\n\\nMaak een keuze: \\n\"))\n if main_keuze.isdigit() and (main_keuze == \"1\"):\n input_voeding = str(input(\"\\nVoer voedeing in (voorbeeld:\"\n \" wortel, snikers.spitskool, \"\n \"etc.)\"\n \": \"))\n melding, waarde, voeding = input_voeding_controleren(\n input_voeding,\n dict_voeding)\n print(melding)\n\n voeding_toevoegen(voeding, dict_voeding, waarde)\n\n elif main_keuze.isdigit() and main_keuze == \"2\":\n t_naam = str(input('Hoera, er is een nieuwe Tamagotchi '\n 'geboren!\\nHmm, hoe zullen we '\n 'hem/haar noemen?\\n\\nVoer een '\n 'naam in: ')).capitalize()\n naam_check = False\n while not naam_check:\n if len(t_naam) < 1:\n t_naam = str(input(\"De naam kan alleen \"\n \"letters bewaren. \"\n \"Voer een naam in: \"\n \"\")).capitalize()\n elif not t_naam.isalpha():\n t_naam = str(input(\"De naam kan alleen \"\n \"letters bewaren. Voer een \"\n \"naam in: \")).capitalize()\n else:\n naam_check = True\n beurt = 0\n afval = random.randint(0, 4)\n hongerig = random.randint(0, 4)\n ongelukkig = random.randint(0, 4)\n plaatje = plaatjes[1]\n scherm = plaatjes_layout(beurt, afval, ongelukkig,\n t_naam,\n hongerig, 'Succes met spelen!', plaatje)\n print(scherm)\n spelen = True\n leeftijd = leeftijden(beurt)\n while spelen:\n in_spel_keuze = str(input(\"Kies een optie:\\n\"))\n\n if in_spel_keuze.isdigit() and in_spel_keuze == '1':\n beurt += 1\n stop_eten_menu = False\n while not stop_eten_menu:\n eten_keuze = str(input(eten_kiezen(\n dict_voeding,\n t_naam)))\n if eten_keuze.isdigit() and eten_keuze == \\\n '1':\n hongerig, afval, ongelukkig, bericht = \\\n gezond_eten_geven(afval, ongelukkig,\n hongerig)\n totaal = hongerig + afval + ongelukkig\n scherm, spelen, rank_bericht, rank = \\\n plaatje_kiezen(beurt, hongerig, afval,\n ongelukkig, plaatjes, totaal,\n leeg_ranking, speler_naam,\n t_naam, kopje, bericht,\n leeftijd)\n stop_eten_menu = True\n if spelen:\n print(scherm)\n else:\n print(scherm + '\\n' +\n rank_bericht + rank + '\\n')\n elif eten_keuze.isdigit() and eten_keuze == \\\n '2':\n hongerig, afval, ongelukkig, bericht = \\\n ongezond_eten_geven(afval, ongelukkig,\n hongerig)\n totaal = hongerig + afval + ongelukkig\n scherm, spelen, rank_bericht, rank = \\\n plaatje_kiezen(beurt, hongerig, afval,\n ongelukkig, plaatjes, totaal,\n leeg_ranking, speler_naam,\n t_naam, kopje, bericht,\n leeftijd)\n stop_eten_menu = True\n if spelen:\n print(scherm)\n else:\n print(scherm + '\\n' +\n rank_bericht + rank + '\\n')\n\n elif eten_keuze.isdigit() and eten_keuze == \\\n '3':\n hongerig, afval, ongelukkig, bericht = \\\n geen_eten_geven(afval,\n ongelukkig, hongerig)\n totaal = hongerig + afval + ongelukkig\n scherm, spelen, rank_bericht, rank = \\\n plaatje_kiezen(\n beurt,\n hongerig, afval, ongelukkig,\n plaatjes,\n totaal, leeg_ranking, speler_naam,\n t_naam, kopje, bericht, leeftijd)\n stop_eten_menu = True\n if spelen:\n print(scherm)\n else:\n print(scherm + '\\n' + rank_bericht + rank +\n '\\n')\n\n else:\n print('Kies een nummer tussen 1 en 3.\\n')\n stop_eten_menu = False\n\n elif in_spel_keuze.isdigit() and in_spel_keuze == '2':\n beurt += 1\n hongerig, afval, ongelukkig, bericht = \\\n verschonen(afval,\n ongelukkig, hongerig)\n totaal = hongerig + afval + ongelukkig\n scherm, spelen, rank_bericht, rank = plaatje_kiezen(\n beurt,\n hongerig, afval, ongelukkig, plaatjes,\n totaal, leeg_ranking, speler_naam,\n t_naam, kopje, bericht, leeftijd)\n if spelen:\n print(scherm)\n else:\n print(\n scherm + '\\n' + rank_bericht + rank + '\\n')\n elif in_spel_keuze.isdigit() and in_spel_keuze == '3':\n beurt += 1\n spelletjes_menu = True\n while spelletjes_menu:\n spelletjes_keuze = str(\n input('Welke spel wil je '\n 'spelen?\\n1. Kop of '\n 'munt.\\n2. Steen, papier, '\n 'schaar.\\n3. Toch maar '\n 'niet.\\n\\nMaak een keuze:'))\n if spelletjes_keuze.isdigit() and \\\n spelletjes_keuze == '1':\n wrong_input = True\n while wrong_input:\n kop_munt_input = input('{:^70}\\n'\n '{:^65}\\n'\n '{:^65}\\n\\n'\n '{}'.format(\n 'Kop '\n 'of '\n 'munt?',\n '1. Kop',\n '2. Munt',\n 'Maak een keuze'\n ))\n if kop_munt_input == '1' or \\\n kop_munt_input == '2':\n hongerig, ongelukkig, bericht = \\\n kop_of_munt(\n kop_munt_input, hongerig,\n ongelukkig,\n t_naam, speler_naam)\n totaal = hongerig + afval + \\\n ongelukkig\n scherm, spelen, \\\n rank_bericht, rank = \\\n plaatje_kiezen(\n beurt,\n hongerig, afval,\n ongelukkig,\n plaatjes,\n totaal, leeg_ranking,\n speler_naam,\n t_naam, kopje, bericht, leeftijd)\n if spelen:\n print(scherm)\n else:\n print(\n scherm + '\\n' + rank_bericht +\n rank + '\\n')\n wrong_input = False\n spelletjes_menu = False\n\n else:\n print('Kies een nummer tussen 1 '\n 'en 2.')\n elif spelletjes_keuze.isdigit() and \\\n spelletjes_keuze == '2':\n spelletjes_menu = False\n ssp_menu = True\n while ssp_menu:\n ssp_keuze = input('{:^70}\\n'\n '{:^65}\\n'\n '{:^65}\\n'\n '{:^65}\\n\\n'\n '{}'\n .format(\n 'Steen,'\n 'papier of schaar?',\n '1. Steen',\n '2. Papier',\n '3. Schaar',\n 'Maak een keuze'\n ))\n if ssp_keuze == '1' or ssp_keuze \\\n == '2' or ssp_keuze == '3':\n hongerig, \\\n afval, \\\n ongelukkig, \\\n bericht = steen_schaar_papier(\n ssp_keuze, hongerig,\n ongelukkig, afval)\n totaal = hongerig + afval + \\\n ongelukkig\n print(hongerig)\n scherm, spelen, \\\n rank_bericht, rank = \\\n plaatje_kiezen(\n beurt, hongerig, afval,\n ongelukkig, plaatjes,\n totaal, leeg_ranking,\n speler_naam, t_naam, kopje,\n bericht, leeftijd)\n if spelen:\n print(scherm)\n else:\n print(\n scherm + '\\n' + rank_bericht +\n rank + '\\n')\n ssp_menu = False\n else:\n print('Kies een nummer tussen 1 '\n 'en 3.')\n ssp_menu = True\n elif spelletjes_keuze.isdigit() and \\\n spelletjes_keuze == '3':\n hongerig += 1\n ongelukkig += 2\n totaal = hongerig + afval + ongelukkig\n scherm, spelen, rank_bericht, rank = \\\n plaatje_kiezen(\n beurt,\n hongerig, afval, ongelukkig,\n plaatjes,\n totaal, leeg_ranking, speler_naam,\n t_naam, kopje, 'Jammer.', leeftijd)\n spelletjes_menu = False\n if spelen:\n print(scherm)\n else:\n print(scherm + '\\n' + rank_bericht + rank +\n '\\n')\n else:\n print('Kies een '\n 'nummer tussen 1 en '\n '3.')\n\n elif in_spel_keuze.isdigit() and in_spel_keuze == '4':\n print('Tot volgende keer!')\n spelen = False\n else:\n totaal = hongerig + afval + ongelukkig\n scherm, spelen, rank_bericht, rank = plaatje_kiezen(\n beurt,\n hongerig, afval, ongelukkig, plaatjes,\n totaal, leeg_ranking, speler_naam,\n t_naam, kopje, ' Kies '\n 'een nummer tussen 1 en'\n ' 4', leeftijd)\n if spelen:\n print(scherm)\n else:\n print(scherm + '\\n' + rank_bericht +\n rank + '\\n')\n elif main_keuze.isdigit() and main_keuze == \"3\":\n print(ranking_layout())\n elif main_keuze.isdigit() and main_keuze == \"4\":\n print(\"Bedankt voor het spelen, tot de voglende keer.\")\n menu_eind = True\n else:\n print('Geen geldige optie. Kies een nummer tussen 1 '\n 'en 4\\n')\n\n","sub_path":"Tamagotchis.py","file_name":"Tamagotchis.py","file_ext":"py","file_size_in_byte":41042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"147665850","text":"\"\"\"Server.\"\"\"\n# pylint: disable-msg=C0103\n# pylint: disable-msg=E1101\n# pylint: disable-msg=E0632\n\nimport threading\nimport numpy as np\nimport zmq\nimport msgpack\nimport msgpack_numpy\nimport config\nfrom env.gobang import Game\nfrom pprint import pprint\nmsgpack_numpy.patch()\n\n\nclass Server(threading.Thread):\n \"\"\"Server.\"\"\"\n\n def __init__(self, server_id, player1_id, player2_id):\n super().__init__()\n self.g = [Game() for i in range(config.GAMEPARALELL)]\n self.server_id = server_id\n seats = [player1_id, player2_id]\n self.seats = [[\n bytes('%s-%d' % (seats[i % 2], i), 'utf8'),\n bytes('%s-%d' % (seats[1 - i % 2], i), 'utf8')\n ] for i in range(config.GAMEPARALELL)]\n self.socket = None\n self.statistics = {\n player1_id: {k: 0\n for k in 'BWJE'},\n player2_id: {k: 0\n for k in 'BWJE'},\n }\n\n def _buildsocket(self):\n context = zmq.Context()\n self.socket = context.socket(zmq.ROUTER)\n self.socket.bind('ipc://./tmp/server_%s' % self.server_id)\n for _ in range(2 * config.GAMEPARALELL):\n self._recv()\n print(\"%s FINISH build socket\" % self.server_id)\n\n def _send_state(self, gid, result):\n \"\"\"\n state: t(or BWJE), black, white\n \"\"\"\n pid = self.g[gid].t % 2\n if result == 'P':\n state = (self.g[gid].t, str(self.g[gid].black), str(\n self.g[gid].white))\n self.socket.send_multipart(\n [self.seats[gid][pid],\n msgpack.dumps(state)])\n elif result in 'BWJE':\n state = (result, str(self.g[gid].black), str(self.g[gid].white))\n self.socket.send_multipart(\n [self.seats[gid][0], msgpack.dumps(state)])\n self.socket.send_multipart(\n [self.seats[gid][1], msgpack.dumps(state)])\n player = '-'.join(self.seats[gid][1\n - pid].decode().split('-')[:-1])\n self.statistics[player][result] += 1\n self._new_game(gid)\n self._send_state(gid, 'P')\n if gid == 0:\n pprint(self.statistics)\n else:\n raise RuntimeError(\"Invalid result %s\" % result)\n\n def _recv(self):\n _, content = self.socket.recv_multipart()\n return msgpack.loads(content)\n\n def _new_game(self, gid):\n self.seats[gid] = self.seats[gid][::-1]\n self.g[gid].newround()\n\n def _run_infinite_round(self):\n for gid in range(config.GAMEPARALELL):\n self._new_game(gid)\n self._send_state(gid, 'P')\n\n while True:\n x, y, gid = self._recv()\n result = self.g[gid].add(x, y)\n if self.g[gid].t > config.GAMELENGTH:\n result = 'E'\n self._send_state(gid, result)\n\n def run(self):\n np.random.seed()\n self._buildsocket()\n self._run_infinite_round()\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"env/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"42228403","text":"# import the necessary packages\nfrom imutils.video import VideoStream\nfrom imutils.video import FPS\nimport numpy as np\nimport argparse\nimport imutils\nimport time\nimport cv2\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\n\n# argument to use the tensorflow or caffe model\nap.add_argument(\"--method\", default = \"caffe\")\n\n#args = vars(ap.parse_args())\n#ap.add_argument(\"-p\", \"--prototxt\", required=True,\n#\thelp=\"path to Caffe 'deploy' prototxt file\")\n#ap.add_argument(\"-m\", \"--model\", required=True,\n#\thelp=\"path to Caffe pre-trained model\")\nap.add_argument(\"-c\", \"--confidence\", type=float, default=0.6,\n\thelp=\"minimum probability to filter weak detections\")\nargs = ap.parse_args()\n#args = vars(ap.parse_args())\n\n# LOAD MODEL\nprint(\"[INFO] loading model...\")\nprint(args.method)\nprint(type(args.method))\n\n# Check argument for caffe or tensorflow, then use selected model\nif args.method == 'tensorflow-mobilenet':\n \n # Mobile net SSD from Tensorflow\n prtxt = \"ssd_mobilenet_v1_coco_11_06_2017/ssd_mobilenet_v1_coco.pbtxt\"\n model = \"ssd_mobilenet_v1_coco_11_06_2017/frozen_inference_graph.pb\"\n \n # Load the model\n net = cv2.dnn.readNetFromTensorflow(model, prtxt)\n \n # initialize list of classes for the tensorflow coco model\n CLASSES = { 0: 'background',\n 1: 'person', 2: 'bicycle', 3: 'car', 4: 'motorcycle', 5: 'airplane', 6: 'bus',\n 7: 'train', 8: 'truck', 9: 'boat', 10: 'traffic light', 11: 'fire hydrant',\n 13: 'stop sign', 14: 'parking meter', 15: 'bench', 16: 'bird', 17: 'cat',\n 18: 'dog', 19: 'horse', 20: 'sheep', 21: 'cow', 22: 'elephant', 23: 'bear',\n 24: 'zebra', 25: 'giraffe', 27: 'backpack', 28: 'umbrella', 31: 'handbag',\n 32: 'tie', 33: 'suitcase', 34: 'frisbee', 35: 'skis', 36: 'snowboard',\n 37: 'sports ball', 38: 'kite', 39: 'baseball bat', 40: 'baseball glove',\n 41: 'skateboard', 42: 'surfboard', 43: 'tennis racket', 44: 'bottle',\n 46: 'wine glass', 47: 'cup', 48: 'fork', 49: 'knife', 50: 'spoon',\n 51: 'bowl', 52: 'banana', 53: 'apple', 54: 'sandwich', 55: 'orange',\n 56: 'broccoli', 57: 'carrot', 58: 'hot dog', 59: 'pizza', 60: 'donut',\n 61: 'cake', 62: 'chair', 63: 'couch', 64: 'potted plant', 65: 'bed',\n 67: 'dining table', 70: 'toilet', 72: 'tv', 73: 'laptop', 74: 'mouse',\n 75: 'remote', 76: 'keyboard', 77: 'cell phone', 78: 'microwave', 79: 'oven',\n 80: 'toaster', 81: 'sink', 82: 'refrigerator', 84: 'book', 85: 'clock',\n 86: 'vase', 87: 'scissors', 88: 'teddy bear', 89: 'hair drier', 90: 'toothbrush' }\n \n\n# Incpetion tensorflow model\nelif args.method == 'tensorflow-inception':\n \n # Inception SSD from Tensorflow\n prtxt = \"ssd_inception_v2_coco_2017_11_17/graphFile.pbtxt\"\n model = \"ssd_inception_v2_coco_2017_11_17/frozen_inference_graph.pb\"\n \n # Load the model\n net = cv2.dnn.readNetFromTensorflow(model, prtxt)\n \n # initialize list of classes for the tensorflow coco model\n CLASSES = { 0: 'background',\n 1: 'person', 2: 'bicycle', 3: 'car', 4: 'motorcycle', 5: 'airplane', 6: 'bus',\n 7: 'train', 8: 'truck', 9: 'boat', 10: 'traffic light', 11: 'fire hydrant',\n 13: 'stop sign', 14: 'parking meter', 15: 'bench', 16: 'bird', 17: 'cat',\n 18: 'dog', 19: 'horse', 20: 'sheep', 21: 'cow', 22: 'elephant', 23: 'bear',\n 24: 'zebra', 25: 'giraffe', 27: 'backpack', 28: 'umbrella', 31: 'handbag',\n 32: 'tie', 33: 'suitcase', 34: 'frisbee', 35: 'skis', 36: 'snowboard',\n 37: 'sports ball', 38: 'kite', 39: 'baseball bat', 40: 'baseball glove',\n 41: 'skateboard', 42: 'surfboard', 43: 'tennis racket', 44: 'bottle',\n 46: 'wine glass', 47: 'cup', 48: 'fork', 49: 'knife', 50: 'spoon',\n 51: 'bowl', 52: 'banana', 53: 'apple', 54: 'sandwich', 55: 'orange',\n 56: 'broccoli', 57: 'carrot', 58: 'hot dog', 59: 'pizza', 60: 'donut',\n 61: 'cake', 62: 'chair', 63: 'couch', 64: 'potted plant', 65: 'bed',\n 67: 'dining table', 70: 'toilet', 72: 'tv', 73: 'laptop', 74: 'mouse',\n 75: 'remote', 76: 'keyboard', 77: 'cell phone', 78: 'microwave', 79: 'oven',\n 80: 'toaster', 81: 'sink', 82: 'refrigerator', 84: 'book', 85: 'clock',\n 86: 'vase', 87: 'scissors', 88: 'teddy bear', 89: 'hair drier', 90: 'toothbrush' }\n\nelse:\n # Mobile net SSD Model from Caffe\n prtxt = 'MobileNetSSD_deploy.prototxt.txt'\n model = 'MobileNetSSD_deploy.caffemodel' \n \n # initialize the list of class labels MobileNet SSD was trained to\n # detect with the caffe model.\n CLASSES = [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\",\n\t\"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\",\n\t\"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\",\n\t\"sofa\", \"train\", \"tvmonitor\"]\n \n # Load the Model\n net = cv2.dnn.readNetFromCaffe(prtxt, model)\n\n# Randomize some colors for each class\nCOLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))\n\n#Confidence threshold\nconf = .75\n\n# load our serialized model from disk\n#net = cv2.dnn.readNetFromCaffe(args[\"prototxt\"], args[\"model\"])\n \n# initialize the video stream, allow the cammera sensor to warmup,\n# and initialize the FPS counter\nprint(\"[INFO] starting video stream...\")\nvs = VideoStream(src=0).start()\ntime.sleep(2.0)\nfps = FPS().start()\n\n# loop over the frames from the video stream\nwhile True:\n\t# grab the frame from the threaded video stream and resize it\n\t# to have a maximum width of 400 pixels\n frame = vs.read()\n frame = imutils.resize(frame, width=800)\n \n\t# grab the frame dimensions and convert it to a blob\n (h, w) = frame.shape[:2]\n blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),\n\t\t0.007843, (300, 300), 127.5)\n \n\t# pass the blob through the network and obtain the detections and\n\t# predictions\n net.setInput(blob)\n detections = net.forward() \n \n # list for persons, dont want person box inside another\n personsFound = []\n confHigh = 0\n \n # WHether to draw box or not\n drawBox = True\n\n \n\n\t# loop over the detections\n for i in np.arange(0, detections.shape[2]):\n\t\t# extract the confidence (i.e., probability) associated with\n\t\t# the prediction\n confidence = detections[0, 0, i, 2]\n \n\t\t# filter out weak detections by ensuring the `confidence` is\n\t\t# greater than the minimum confidence\n if confidence > conf: #args[\"confidence\"]:\n \n\t\t\t# extract the index of the class label from the\n\t\t\t# `detections`, then compute the (x, y)-coordinates of\n\t\t\t# the bounding box for the object\n idx = int(detections[0, 0, i, 1])\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n \n # persons checker\n if CLASSES[idx] == 'person':\n if i == 0:\n personsFound.append([startX, startY, endX, endY])\n else:\n if startX > personsFound[0][0] and endX < personsFound[0][2]:\n drawBox = False\n \n \n if drawBox == True:\n # draw the prediction on the frame\n label = \"{}: {:.2f}%\".format(CLASSES[idx],\n \t\t\t\tconfidence * 100)\n cv2.rectangle(frame, (startX, startY), (endX, endY),\n \t\t\t\tCOLORS[idx], 2)\n y = startY - 15 if startY - 15 > 15 else startY + 15\n cv2.putText(frame, label, (startX, y),\n \t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)\n\n\t# show the output frame\n cv2.imshow(\"Frame\", frame)\n key = cv2.waitKey(1) & 0xFF\n \n\t# if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n \n\t# update the FPS counter\n fps.update()\n\n# stop the timer and display FPS information\nfps.stop()\nprint(\"[INFO] elapsed time: {:.2f}\".format(fps.elapsed()))\nprint(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n \n# do a bit of cleanup\ncv2.destroyAllWindows()\nvs.stop()\n","sub_path":"detectWebcam.py","file_name":"detectWebcam.py","file_ext":"py","file_size_in_byte":8129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"73840064","text":"from django.shortcuts import render\nfrom django.views.generic import View\nfrom user_profile.models import User\nfrom models import Tweet\n# Create your views here.\n\nclass Index(View):\n\tdef get(self, request):\n\t\tparams = {}\n\t\tparams['name'] = \"Django\"\n\t\treturn render(request, 'base.html', params)\n\nclass Profile(View):\n\t\"\"\"\n\tUser profile reachable from /user/ URL\n\t\"\"\"\n\t\n\tdef get(self, request, username):\n\t\tparams = dict()\n\t\tuser = User.objects.get(username=username)\n\t\ttweets = Tweet.objects.filter(user=user)\n\t\tparams[\"tweets\"] = tweets\n\t\tparams[\"user\"] = user\n\t\treturn render(request, 'profile.html', params)\n\n\n\n","sub_path":"mytweets/tweets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"453931435","text":"from flask import g, Flask, request, session as flask_session\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom .models import Base, User\nfrom .fixtures import load_fixture_data\n\nfrom oso import Oso\nfrom sqlalchemy_oso import authorized_sessionmaker, register_models\nfrom sqlalchemy_oso.roles2 import OsoRoles\n\n\ndef create_app(db_path=None, load_fixtures=False):\n from . import routes\n\n # init engine and session\n if db_path:\n engine = create_engine(db_path)\n else:\n engine = create_engine(\"sqlite:///roles.db\")\n\n # init app\n app = Flask(__name__)\n app.secret_key = b\"ball outside of the school\"\n app.register_blueprint(routes.bp)\n\n # init basic session factory\n Session = sessionmaker(bind=engine)\n\n # init oso\n oso = init_oso(app, Session)\n\n # init authorized session factory\n AuthorizedSession = authorized_sessionmaker(\n bind=engine,\n get_oso=lambda: oso,\n get_user=lambda: g.current_user,\n get_action=lambda: g.current_action,\n )\n\n # https://github.com/osohq/oso/blob/70965f2277d7167c38d3641140e6e97dec78e3bf/languages/python/sqlalchemy-oso/tests/test_roles2.py#L106-L107\n Base.metadata.create_all(engine)\n\n # https://github.com/osohq/oso/blob/70965f2277d7167c38d3641140e6e97dec78e3bf/languages/python/sqlalchemy-oso/tests/test_roles2.py#L110-L112\n # docs: begin-configure\n app.roles.synchronize_data()\n # docs: end-configure\n\n # optionally load fixture data\n if load_fixtures:\n session = Session()\n load_fixture_data(session, app.roles)\n session.close()\n\n @app.before_request\n def set_current_user_and_session():\n flask_session.permanent = True\n\n # docs: begin-authn\n session = Session()\n if \"current_user\" not in g:\n if \"current_user_id\" in flask_session:\n user_id = flask_session.get(\"current_user_id\")\n user = session.query(User).filter_by(id=user_id).one_or_none()\n if user is None:\n flask_session.pop(\"current_user_id\")\n g.current_user = user\n else:\n g.current_user = None\n\n # Set basic (non-auth) session for this request\n g.basic_session = session\n # docs: end-authn\n\n # Set action for this request\n if request.endpoint:\n actions = {\n \"routes.org_role_index\": \"read_role\",\n \"routes.org_role_create\": \"create_role\",\n \"routes.org_role_update\": \"update_role\",\n \"routes.org_role_delete\": \"delete_role\",\n \"routes.repo_create\": \"create_repo\",\n \"routes.issue_create\": \"create_issue\",\n }\n g.current_action = actions.get(request.endpoint, \"read\")\n else:\n g.current_action = None\n\n # Set auth session for this request\n g.auth_session = AuthorizedSession()\n\n @app.after_request\n def add_cors_headers(res):\n res.headers.add(\"Access-Control-Allow-Origin\", \"http://localhost:3000\")\n res.headers.add(\"Access-Control-Allow-Headers\", \"Accept,Content-Type\")\n res.headers.add(\"Access-Control-Allow-Methods\", \"DELETE,GET,OPTIONS,PATCH,POST\")\n res.headers.add(\"Access-Control-Allow-Credentials\", \"true\")\n return res\n\n @app.after_request\n def close_sessions(res):\n g.basic_session.close()\n g.auth_session.close()\n return res\n\n return app\n\n\n# docs: begin-init-oso\ndef init_oso(app, Session: sessionmaker):\n # Initialize oso instance\n oso = Oso()\n\n # Register authorization data\n register_models(oso, Base)\n roles = OsoRoles(oso, Base, User, Session)\n\n # Load authorization policy.\n oso.load_file(\"app/authorization.polar\")\n\n # Attach Oso and OsoRoles instances to Flask application.\n app.oso = oso\n app.roles = roles\n\n return oso\n # docs: end-init-oso\n","sub_path":"backend/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"200137764","text":"#!/usr/bin/env python3\n\"\"\"\nrandomreddit.py - return a random reddit url from a subreddit's frontpage\nauthor: andreim \n\"\"\"\n\nimport web\nimport re\nimport json\nfrom tools import GrumbleError\nfrom random import choice\n\n\ndef randomreddit(phenny, input):\n\n subreddit = input.group(2)\n if not subreddit:\n phenny.say(\".random - get a random link from the subreddit's frontpage\")\n return\n \n if not re.match('^[A-Za-z0-9_-]*$',subreddit):\n phenny.say(input.nick + \": bad subreddit format.\")\n return\n\n\n url = \"http://www.reddit.com/r/\" + subreddit + \"/.json\"\n try:\n resp = web.get(url)\n except:\n try:\n resp = web.get(url)\n except:\n try:\n resp = web.get(url)\n except:\n raise GrumbleError('Reddit or subreddit unreachable.')\n \n try:\n reddit = json.loads(resp)\n post = choice(reddit['data']['children'])\n except:\n raise GrumbleError('Error parsing response from Reddit.')\n\n nsfw = False\n if post['data']['over_18']:\n nsfw = True\n \n if nsfw:\n phenny.reply(\"!!NSFW!! \" + post['data']['url'] + \" (\" + post['data']['title'] + \") !!NSFW!!\")\n else:\n phenny.reply(post['data']['url'] + \" (\" + post['data']['title'] + \")\")\n\nrandomreddit.commands = ['random']\nrandomreddit.priority = 'medium'\nrandomreddit.thread = False\n","sub_path":"modules/randomreddit.py","file_name":"randomreddit.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"475558054","text":"\"\"\"\nContains any twitter specific functionality related to channels.\n\"\"\"\nfrom datetime import datetime\nfrom collections import defaultdict\nfrom solariat.utils.lang.helper import LingualToken, is_token_lang_adopted\nfrom solariat_bottle.db.language import MultilanguageChannelMixin\n\nfrom solariat_bottle.settings import get_var, LOGGER, AppException\n\nfrom solariat.db import fields\nfrom solariat_bottle.db.auth import Document\nfrom solariat_bottle.db.group import Group\nfrom solariat.db.abstract import Index, SonDocument\nfrom solariat_bottle.db.channel.base import (\n needs_postfilter_sync,\n Channel, ChannelManager, ServiceChannel,\n create_outbound_post, CHANNEL_ID_URL_MAP\n)\n\n\nclass TwitterConfigurationException(AppException):\n pass\n\n\ndef get_sync_usernames_list(username_list):\n \"\"\"\n For a list of twitter usernames, make sure that we have both pairs of\n @handle / handle even if for some reason user added only one or another.\n \"\"\"\n full_usernames = username_list[:]\n for handle in username_list:\n if handle.startswith('@'):\n if handle[1:] not in full_usernames:\n full_usernames.append(handle[1:])\n elif '@' + handle not in full_usernames:\n full_usernames.append('@' + handle)\n return full_usernames\n\n\ndef get_twitter_outbound_channel(user, channel):\n '''\n Get the outbound channel based on user access, channel configuration, and as\n a last resort, channel configurations\n '''\n from solariat_bottle.utils.post import get_service_channel\n\n # If for any reason we try to get the dispatch channel for\n # a dispatch channel, and user has edit perms, we can just use same channel.\n if isinstance(channel, EnterpriseTwitterChannel) and channel.can_edit(user):\n return channel\n # The configured channel is only necessary, or correct, if this is no service\n # channel, or if there is a service channel with multiple candidates\n configured_channel = user.get_outbound_channel(channel.platform)\n\n sc = get_service_channel(channel)\n if sc:\n if sc.dispatch_channel:\n return sc.dispatch_channel\n\n candidates = EnterpriseTwitterChannel.objects.find_by_user(user, account=channel.account, status='Active')[:]\n # Case insensitive filter for match with user names\n usernames_lowercase = [n.lower() if not n.startswith('@') else n[1:] for n in sc.usernames]\n candidates = [c for c in candidates if c.is_authenticated and (c.twitter_handle.lower() in usernames_lowercase or\n not usernames_lowercase)]\n # If there are no candidates for the service channel, then do not return anything.\n if candidates == []:\n return None\n\n # If exactly 1, return it\n if len(candidates) == 1:\n return candidates[0]\n\n # If more than one, we bring in the configured channel if we have one to disambiguate\n if configured_channel and configured_channel in candidates:\n return configured_channel\n\n # Otherwise, return nothing. We have no solid way to disambiguate\n raise TwitterConfigurationException(\n \"Sorry! There is a configuration error. \"\n \"You have 2 or more reply channels configured.\"\n \"Please set up a default reply channel in Settings on the Default Channels page.\"\n )\n\n # We only have the configured channel, no candidates based on sc, it could be None, which is OK\n return configured_channel\n\n\nclass EnterpriseTwitterChannelManager(ChannelManager):\n \"\"\"\n Specific manager for a ETC. Makes sure we track the twitter handle\n on channel creation.\n \"\"\"\n def create_by_user(self, user, **kw):\n from solariat_bottle.db.tracking import PostFilterStream\n channel = super(EnterpriseTwitterChannelManager, self).create_by_user(user, **kw)\n twitter_handle = kw.get('twitter_handle')\n if twitter_handle:\n stream = PostFilterStream.get()\n stream.track('USER_NAME', [twitter_handle], [channel])\n\n return channel\n\n\nclass TwitterChannel(Channel):\n \"Channel with twitter specific information for crawler\"\n\n # monitored twitter users.\n # THIS SHOULD BE DEPRECATED. WILL NOT SCALE\n twitter_usernames = fields.ListField(fields.StringField())\n\n # twitter credentials for replying\n access_token_key = fields.EncryptedField(\n fields.StringField(),\n allow_db_plain_text=True)\n access_token_secret = fields.EncryptedField(\n fields.StringField(),\n allow_db_plain_text=True)\n\n review_outbound = fields.BooleanField(default=False, db_field='ro')\n review_team = fields.ReferenceField(Group, db_field='rg')\n\n @property\n def is_authenticated(self):\n ''' Over-ride in derived classes. '''\n return self.access_token_key and self.access_token_secret\n\n @property\n def type_id(self):\n return 8\n\n @property\n def type_name(self):\n return \"Twitter\"\n\n @property\n def platform(self):\n return \"Twitter\"\n\n @property\n def is_dispatchable(self):\n return True\n\n def get_outbound_channel(self, user):\n return get_twitter_outbound_channel(user, self)\n\n def has_direct_messages(self, conversation, contact = None):\n \"\"\"\n If any post from this conversation that is not replied is a direct message,\n that this conversation still has open direct messages, and any reply will be\n as a direct message.\n\n :param conversation: the conversation we are checking for direct messages\n :param contact: if provided, will only check for open direct messages from this contact.\n \"\"\"\n posts = conversation.query_posts()\n for post in posts:\n if (post.get_post_status(self) == 'actual' and post.message_type == 'direct'\n and (contact is None or post.user_profile.user_name == contact)):\n return True\n return False\n\n def send_message(self, dry_run, creative, post, user, direct_message=None):\n # self.sync_contacts(post.user_profile)\n from solariat_bottle.tasks.twitter import tw_normal_reply, tw_direct_reply\n\n is_dm = False # Assume this is not a DM\n if direct_message is not None:\n # If we specifically passed the fact that we want a direct message, use DM\n # Otherwise decide based on post type\n is_dm = direct_message\n else:\n if post.message_type == 'direct':\n is_dm = True\n if not is_dm:\n status = \"@%s %s\" % (post.user_profile.user_name, creative)\n else:\n status = creative\n\n if len(status) > 140:\n msg = (\n 'Sorry, you have exceeded your 140 character limit by %d characters. '\n 'Please correct your reply and try again.'\n ) % (len(status) - 140)\n raise AppException(msg)\n\n status_id = post.native_id\n\n # Update the engagement history\n post.user_profile.update_history(self)\n\n LOGGER.debug(\"For current message, direct message flag is %s\", is_dm)\n if not dry_run and not get_var('ON_TEST'):\n if is_dm:\n tw_direct_reply.ignore(\n self,\n status=status,\n screen_name=post.user_profile.user_name\n )\n else:\n tw_normal_reply.ignore(\n self,\n status = status,\n status_id = status_id,\n post = post\n )\n else:\n create_outbound_post(user, self, creative, post)\n\n LOGGER.debug(\n \"Sent '%s' to %s using %s\", creative, post.user_profile.user_name, self.title\n )\n\n def share_post(self, post, user, dry_run=False):\n # self.sync_contacts(post.user_profile)\n\n from solariat_bottle.tasks.twitter import tw_share_post\n\n post_content = post.plaintext_content\n status_id = post.native_id\n\n if dry_run is False and not get_var('ON_TEST') and get_var('APP_MODE') == 'prod':\n tw_share_post.ignore(self,\n status_id=status_id,\n screen_name=post.user_profile.user_name)\n else:\n create_outbound_post(user, self, \"RT: %s\" % post_content, post)\n\n LOGGER.debug(\"Retweet '%s' using %s\", post_content, self)\n\n def has_private_access(self, sender_handle, recipient_handle):\n return self._dm_access_check(recipient_handle)\n\n def _dm_access_check(self, twitter_handle):\n \"\"\"\n Check if a channels should actually have permissions to a direct message.\n\n :param sender_handle: the twitter handle for the sender of a message.\n :param recipient_handle: the twitter handle for the recipient of a message.\n \"\"\"\n\n if not self.account:\n LOGGER.info(\"Channel %s rejected because no account.\", self.title)\n return False\n\n outbounds = self.account.get_outbounds_for_handle(twitter_handle)\n if not outbounds:\n LOGGER.info(\"Channel %s rejected because no outbound channel is set for the handle %s.\" % (self.title,\n twitter_handle))\n return False\n\n # Go through all the outbounds and see if there is any valid for this inbound channel\n for outbound_channel in outbounds:\n LOGGER.info(\"Validating %s against outbound %s.\", self.title, outbound_channel.title)\n checks_passed = True\n\n if not outbound_channel:\n # There is no outbound channel configured for twitter.\n # At this point no channel from the account should have access.\n LOGGER.info(\"Channel %s rejected because no outbound channel is set.\", self.title)\n checks_passed = False\n\n if outbound_channel.status != 'Active' or outbound_channel.twitter_handle != twitter_handle:\n # Another reason why a channel might not have acces is if twitter\n # outbound channel is no longer active or if it's active for another\n # handle.\n LOGGER.info(\n \"Expected active outbound: %s with handle %s but got: (%s, %s)\",\n outbound_channel.title,\n twitter_handle,\n outbound_channel.status,\n outbound_channel.twitter_handle\n )\n checks_passed = False\n\n if not set(self.acl).intersection(set(outbound_channel.acl)):\n LOGGER.info(\"Channel %s rejected due to acl conflicts.\", self.title)\n LOGGER.info(\n \"ACL for %s: %s, while ACL for %s: %s\",\n self.title, set(self.acl),\n outbound_channel.title, set(outbound_channel.acl)\n )\n checks_passed = False\n if checks_passed: return True\n return False\n\n def get_service_channel(self):\n return None\n\n def list_outbound_channels(self, user):\n return EnterpriseTwitterChannel.objects.find_by_user(user,\n account=self.account,\n twitter_handle__in=self.usernames)\n\n def patch_user(self, user):\n from solariat_bottle.db.user_profiles.social_profile import TwitterProfile\n # TODO: [gsejop] Why do we need to create dummy Agent/UserProfiles\n # when User instance has no user_profile?\n up = TwitterProfile()\n up.save()\n AgentProfile = user.account.get_agent_profile_class()\n ap = AgentProfile(account_id=self.account.id)\n ap.save()\n #ap.add_profile(up)\n user.user_profile = up\n user.save()\n\n\nclass EnterpriseTwitterChannel(TwitterChannel):\n \"Channel with twitter specific information for tracking\"\n manager = EnterpriseTwitterChannelManager\n\n twitter_handle = fields.StringField(default='')\n twitter_handle_data = fields.DictField()\n status_update = fields.DateTimeField(db_field='st',\n default=datetime.utcnow())\n\n followers_count = fields.NumField(default=0, db_field='fc')\n friends_count = fields.NumField(default=0, db_field='frc')\n\n is_inbound = fields.BooleanField(db_field='in', default=False)\n\n def get_twitter_profile(self):\n if not self.is_authenticated:\n return None\n\n def fetch_api_me():\n from solariat_bottle.utils.tweet import TwitterApiWrapper, JSONParser\n\n api = TwitterApiWrapper.init_with_channel(self, parser=JSONParser())\n return api.me()\n\n token_hash = hash(\"%s%s\" % (\n self.access_token_key,\n self.access_token_secret)) & (1 << 8)\n data = dict(self.twitter_handle_data or {})\n if data and 'hash' in data and 'profile' in data and data['hash'] == token_hash:\n res = data['profile']\n else:\n api_me_json = fetch_api_me()\n data = {'hash': token_hash, 'profile': api_me_json}\n self.update(twitter_handle_data=data,\n twitter_handle=api_me_json['screen_name'])\n res = api_me_json\n return res\n\n @property\n def twitter_handle_id(self):\n if get_var('ON_TEST') and not self.twitter_handle_data:\n return self.twitter_handle\n\n profile_data = self.get_twitter_profile()\n if profile_data:\n return profile_data['id_str']\n\n @property\n def type_name(self):\n return \"Enterprise Twitter\"\n\n @property\n def type_id(self):\n return 1\n\n @property\n def is_dispatch_channel(self):\n return True\n\n @property\n def initial_status(self):\n return 'Active'\n\n def on_suspend(self):\n self.update(status='Suspended',\n status_update=datetime.utcnow().replace(microsecond=0))\n\n def tracked_entities(self):\n if self.status not in {'Active', 'Interim'}:\n return []\n return [('USER_NAME', [self.twitter_handle], self, ['en'])]\n\n def pre_save(self):\n \"Track/untrack twitter_handle\"\n from solariat_bottle.db.tracking import PostFilterStream\n\n stream = PostFilterStream.get()\n stream.untrack_channel(self)\n if self.twitter_handle and self.status != 'Archived':\n stream.track('USER_NAME', [self.twitter_handle], [self])\n\n def save(self, pre_save=True):\n if pre_save:\n self.pre_save()\n super(EnterpriseTwitterChannel, self).save()\n\n def save_by_user(self, user, **kw):\n if self.can_edit(user):\n self.pre_save()\n super(EnterpriseTwitterChannel, self).save_by_user(user, **kw)\n\n def follow_user(self, user_profile, silent_ex=False):\n \"\"\"\n For the given user profile, first do the actual twitter follow\n then also update the user profile object locally so we can quickly\n get the required status.\n\n If :param silent_ex: is set to true, any exception from twitter call\n is ignored. (e.g. autofollow on DM creation).\n \"\"\"\n from solariat_bottle.tasks.twitter import tw_follow\n tw_follow(channel=self,\n user_profile=user_profile,\n silent_ex=silent_ex)\n\n self.update(inc__friends_count=1)\n\n def unfollow_user(self, user_profile, silent_ex=False):\n \"\"\"\n For the given user profile, first do the actual twitter unfollow\n then also update the user profile object locally so we can quickly\n get the required status.\n\n If :param silent_ex: is set to true, any exception from twitter call\n is ignored. (e.g. autofollow on DM creation).\n \"\"\"\n from solariat_bottle.tasks.twitter import tw_unfollow\n tw_unfollow(channel=self,\n user_profile=user_profile,\n silent_ex=silent_ex)\n\n self.update(inc__friends_count=-1)\n\n def get_attached_service_channels(self):\n service_channel = self.get_service_channel()\n return service_channel and [service_channel] or []\n\n def get_service_channel(self):\n channel = self.get_user_tracking_channel()\n if channel:\n channel = TwitterServiceChannel.objects.find_one(outbound=channel.id)\n return channel\n\n def get_user_tracking_channel(self):\n\n if self.twitter_handle is None:\n return None\n\n # candidates = UserTrackingChannel.objects.find(usernames__in=get_sync_usernames_list([self.twitter_handle]),\n # account=self.account)[:]\n\n # case-insensitive lookup for service channel\n from solariat_bottle.db.tracking import PostFilterEntry, TrackingNLP\n\n usernames_list = get_sync_usernames_list([self.twitter_handle])\n usernames_list = map(TrackingNLP.normalize_kwd, usernames_list)\n candidate_channel_ids = set()\n for pfe in PostFilterEntry.objects.coll.find(\n {PostFilterEntry.F.entry: {'$in': usernames_list}},\n fields=[PostFilterEntry.F.channels]):\n chs = pfe[PostFilterEntry.F.channels]\n if not isinstance(chs, (list, tuple)):\n chs = [chs]\n for ch in chs:\n if hasattr(ch, 'id'):\n candidate_channel_ids.add(ch.id)\n else:\n candidate_channel_ids.add(ch)\n\n candidates = UserTrackingChannel.objects(id__in=candidate_channel_ids,\n account=self.account)[:]\n if candidates:\n if len(candidates) == 1:\n return candidates[0]\n else:\n LOGGER.warning(\n \"We have multiple candidates for service channel matching for enterprise channel %s\" % self)\n return None\n LOGGER.warning(\n \"No service channel candidates were found for outbound channel %s. \"\n \"Some outbound channel filtering might not work.\",\n self.title\n )\n return None\n\n def get_outbound_channel(self, user):\n return self\n\n\nclass TwitterTestDispatchChannel(EnterpriseTwitterChannel):\n '''Used for testing purposes, and defined here so the class is available'''\n _auth_flag = fields.BooleanField(default=True)\n\n @property\n def is_authenticated(self):\n return self._auth_flag\n\n\nclass FollowerTrackingChannel(Channel):\n \"\"\"\n A channel that follows a list of twitter usernames.\n \"\"\"\n twitter_handles = fields.ListField(fields.StringField())\n status_update = fields.DateTimeField(db_field='st',\n default=datetime.utcnow())\n\n tracking_mode = fields.StringField(\n default='Passive', choices=('Active', 'Passive'))\n\n @property\n def is_dispatchable(self):\n return False\n\n @property\n def type_name(self):\n return \"Follower Tracking\"\n\n @property\n def type_id(self):\n return 1\n\n def get_outbound_channel(self, user):\n return get_twitter_outbound_channel(user, self)\n\n def get_status(self):\n statuses = FollowerTrackingStatus.objects(channel=self.id)\n return [st.to_dict() for st in statuses]\n\n def on_active(self):\n\n self.status = 'Active'\n self.status_update = datetime.utcnow().replace(microsecond=0)\n self.update(set__status=self.status,\n set__status_update=self.status_update)\n\n from solariat_bottle.tasks.twitter import tw_count, tw_scan_followers\n\n for fts in FollowerTrackingStatus.objects.find(channel=self.id):\n tw_count.ignore(fts, params=('followers_count',))\n tw_scan_followers.ignore(fts, self.status_update)\n\n def on_suspend(self):\n\n self.status = 'Suspended'\n self.status_update = datetime.utcnow().replace(microsecond=0)\n self.update(set__status=self.status,\n set__status_update=self.status_update)\n\n from solariat_bottle.tasks.twitter import tw_drop_followers\n\n tw_drop_followers.ignore(self)\n\n @property\n def usernames(self):\n return get_sync_usernames_list(self.twitter_handles)\n\n def add_username(self, username):\n\n if not username in self.twitter_handles:\n\n self.update(addToSet__twitter_handles=username)\n\n fts = FollowerTrackingStatus.objects.get_or_create(\n channel=self.id,\n twitter_handle=username)\n\n from solariat_bottle.tasks.twitter import tw_count, tw_scan_followers\n\n tw_count.ignore(fts, params=('followers_count',))\n tw_scan_followers.ignore(fts, self.status_update)\n\n def del_username(self, username):\n\n if username in self.twitter_handles:\n\n self.update(pull__twitter_handles=username)\n\n fts = FollowerTrackingStatus.objects.get(\n channel=self.id,\n twitter_handle=username)\n\n from solariat_bottle.tasks.twitter import tw_drop_followers\n\n tw_drop_followers.ignore(fts)\n\n def has_private_access(self, sender_handle, recipient_handle):\n if not (self.is_service or self.is_inbound):\n twitter_handle = sender_handle\n else:\n twitter_handle = recipient_handle\n return (self.parent_channel and\n TwitterServiceChannel.objects.get(self.parent_channel)._dm_access_check(twitter_handle))\n\n\nclass FollowerTrackingStatus(Document):\n channel = fields.ObjectIdField(db_field='cl')\n twitter_handle = fields.StringField(db_field='th')\n followers_count = fields.NumField(default=0, db_field='fc')\n followers_synced = fields.NumField(default=0, db_field='fs')\n sync_status = fields.StringField(default='idle', db_field='sy',\n choices=('idle', 'sync'))\n\n indexes = [Index(('channel', 'twitter_handle'), unique=True)]\n\n\nclass UserTrackingChannel(Channel, MultilanguageChannelMixin):\n \" Tracks a list of datasift usernames \"\n\n usernames = fields.ListField(fields.StringField())\n\n @property\n def requires_interim_status(self):\n return True\n\n def mentions(self, post):\n ''' Get all the mentions based on user name configuration'''\n from solariat_bottle.utils.post import normalize_screen_name\n from solariat_bottle.utils.tracking import TrackingNLP\n usernames = map(normalize_screen_name, self.usernames)\n return list(set(TrackingNLP.extract_mentions(post)) & set(usernames))\n\n def addressees(self, post):\n '''Get all the mentions in the beginning.'''\n mentions = self.mentions(post)\n results = set()\n for term in post.plaintext_content.lower().split():\n if term in mentions:\n results.add(term)\n else:\n break\n return list(results)\n\n def on_suspend(self):\n super(UserTrackingChannel, self).on_suspend()\n\n from solariat_bottle.db.tracking import PostFilterStream\n stream = PostFilterStream.get()\n stream.untrack_channel(self)\n\n def on_active(self):\n super(UserTrackingChannel, self).on_active()\n\n from solariat_bottle.db.tracking import PostFilterStream\n stream = PostFilterStream.get()\n stream.track('USER_NAME', self.usernames, [self], langs=self.langs)\n\n def get_outbound_channel(self, user):\n return get_twitter_outbound_channel(user, self)\n\n def add_username(self, username):\n \" add username \"\n # self.sync_contacts(user=username, platform='Twitter')\n\n from solariat_bottle.db.tracking import PostFilterStream\n\n _usernames = set(self.usernames)\n _usernames.add(username)\n self.usernames = list(_usernames)\n\n self.update(addToSet__usernames=username)\n\n if self.status in {'Active', 'Interim'}:\n stream = PostFilterStream.get()\n stream.track('USER_NAME', [username], [self], langs=self.langs)\n\n def del_username(self, username):\n \" del username \"\n\n from solariat_bottle.db.tracking import PostFilterStream\n\n _usernames = set(self.usernames)\n _usernames.discard(username)\n self.usernames = list(_usernames)\n\n self.update(pull__usernames=username)\n stream = PostFilterStream.get()\n stream.untrack('USER_NAME', [username], [self], langs=self.langs)\n\n @property\n def platform(self):\n\n return \"Twitter\"\n\n def has_private_access(self, sender_handle, recipient_handle):\n if not (self.is_service or self.is_inbound):\n twitter_handle = sender_handle\n else:\n twitter_handle = recipient_handle\n return (self.parent_channel and\n TwitterServiceChannel.objects.get(self.parent_channel)._dm_access_check(twitter_handle))\n\n\n def set_allowed_langs(self, langs, clear_previous=False):\n\n dif_langs = set(langs) - set(self.langs)\n if not dif_langs:\n return\n\n if clear_previous:\n self.langs = langs\n else:\n self.langs = list(set(self.langs)|dif_langs)\n self.save()\n\n\n def get_allowed_langs(self):\n\n return self.langs\n\n\n def remove_langs(self, langs):\n\n for lang in langs:\n if lang in self.langs:\n self.langs.remove(lang)\n self.save()\n\n\nclass KeywordTrackingChannel(Channel, MultilanguageChannelMixin):\n \" for datasift keywords \"\n\n keywords = fields.ListField(fields.StringField())\n skipwords = fields.ListField(fields.StringField())\n watchwords = fields.ListField(fields.StringField())\n\n @property\n def requires_interim_status(self):\n return True\n\n def make_post_vector(self, post):\n 'Use configuration information to boost features'\n post_vector = Channel.make_post_vector(self, post)\n post_vector.update(mentions=self.mentions(post),\n keywords=self.keywords,\n watchwords=self.watchwords,\n direction=self.find_direction(post))\n return post_vector\n\n @property\n def platform(self):\n return \"Twitter\"\n\n def get_outbound_channel(self, user):\n return get_twitter_outbound_channel(user, self)\n\n def is_individual(self, post):\n if post.addressee and post.addressee not in set([kw.lower() for kw in self.keywords]):\n return True\n else:\n return False\n\n def on_suspend(self):\n super(KeywordTrackingChannel, self).on_suspend()\n\n from solariat_bottle.db.tracking import PostFilterStream\n stream = PostFilterStream.get()\n stream.untrack_channel(self)\n\n def on_active(self):\n \" run this handler when channel activated \"\n\n # It's a temporary status which will be overwritten\n # by datasift_sync2 script in 1.5 mins (at max)\n super(KeywordTrackingChannel, self).on_active()\n\n from solariat_bottle.db.tracking import PostFilterStream\n stream = PostFilterStream.get()\n for keyword in self.keywords:\n stream.track('KEYWORD', [LingualToken.unlangify(keyword)], [self], langs=self.__get_token_langs(keyword))\n for skipword in self.skipwords:\n stream.track('SKIPWORD', [LingualToken.unlangify(skipword)], [self], langs=self.__get_token_langs(skipword))\n\n def add_keyword(self, keyword):\n \" add keyword \"\n if not self.__is_token_valid(keyword, self.keywords):\n return False\n\n from solariat_bottle.db.tracking import PostFilterStream\n\n _keywords = set(self.keywords)\n _keywords.add(keyword)\n self.keywords = list(_keywords)\n\n self.update(addToSet__keywords=keyword)\n\n if self.status in ('Active', 'Interim'):\n stream = PostFilterStream.get()\n stream.track('KEYWORD', [LingualToken.unlangify(keyword)], [self], langs=self.__get_token_langs(keyword))\n return True\n\n def del_keyword(self, keyword):\n \" del keyword \"\n from solariat_bottle.db.tracking import PostFilterStream\n\n _keywords = set(self.keywords)\n _keywords.discard(keyword)\n self.keywords = list(_keywords)\n self.update(pull__keywords=keyword)\n stream = PostFilterStream.get()\n stream.untrack('KEYWORD', [LingualToken.unlangify(keyword)], [self], langs=self.__get_token_langs(keyword))\n\n def add_watchword(self, watchword):\n \" add watchword \"\n\n if not self.__is_token_valid(watchword, self.watchwords):\n return False\n\n _watchwords = set(self.watchwords)\n _watchwords.add(watchword)\n self.watchwords = list(_watchwords)\n self.update(addToSet__watchwords=watchword)\n return True\n\n def del_watchword(self, watchword):\n \" del watchword \"\n _watchwords = set(self.watchwords)\n _watchwords.discard(watchword)\n self.watchwords = list(_watchwords)\n self.update(pull__watchwords=watchword)\n\n def add_skipword(self, skipword):\n \" add skipword \"\n if not self.__is_token_valid(skipword, self.skipwords):\n return False\n\n from solariat_bottle.db.tracking import PostFilterStream\n\n _skipwords = set(self.skipwords)\n _skipwords.add(skipword)\n self.skipwords = list(_skipwords)\n self.update(addToSet__skipwords=skipword)\n\n if self.status in ('Active', 'Interim'):\n stream = PostFilterStream.get()\n stream.track('SKIPWORD', [LingualToken.unlangify(skipword)], [self], langs=self.__get_token_langs(skipword))\n return True\n\n def del_skipword(self, skipword):\n \" del skipword \"\n from solariat_bottle.db.tracking import PostFilterStream\n\n _skipwords = set(self.skipwords)\n _skipwords.discard(skipword)\n self.skipwords = list(_skipwords)\n self.update(pull__skipwords=skipword)\n stream = PostFilterStream.get()\n stream.untrack('SKIPWORD', [LingualToken.unlangify(skipword)], [self], langs=self.__get_token_langs(skipword))\n\n\n def has_private_access(self, sender_handle, recipient_handle):\n\n if not (self.is_service or self.is_inbound):\n twitter_handle = sender_handle\n else:\n twitter_handle = recipient_handle\n return (self.parent_channel and\n TwitterServiceChannel.objects.get(self.parent_channel)._dm_access_check(twitter_handle))\n\n\n def set_allowed_langs(self, langs, clear_previous=False):\n\n dif_langs = set(langs) - set(self.langs)\n if not dif_langs:\n return\n\n if clear_previous:\n self.langs = langs\n else:\n self.langs = list(set(self.langs)|dif_langs)\n self.save()\n\n self.__fix_tokens_langs(dif_langs, 'track')\n\n\n def get_allowed_langs(self):\n\n return self.langs\n\n\n def remove_langs(self, langs):\n\n for lang in langs:\n for keyword in self.keywords:\n if LingualToken.is_adopted_to_lang(keyword, lang):\n self.del_keyword(keyword)\n\n for skipword in self.skipwords:\n if LingualToken.is_adopted_to_lang(skipword, lang):\n self.del_skipword(skipword)\n\n for lang in langs:\n if lang in self.langs:\n self.langs.remove(lang)\n self.save()\n\n self.__fix_tokens_langs(langs, 'untrack')\n\n\n def __fix_tokens_langs(self, langs, action):\n\n keywords = [key for key in self.keywords if not is_token_lang_adopted(key)]\n skipwords = [skip for skip in self.skipwords if not is_token_lang_adopted(skip)]\n\n\n from solariat_bottle.db.tracking import PostFilterStream\n stream = PostFilterStream.get()\n\n if hasattr(stream, action):\n getattr(stream, action)('KEYWORD', keywords, [self], langs=langs)\n getattr(stream, action)('SKIPWORD', skipwords, [self], langs=langs)\n\n def __is_token_valid(self, token, values):\n\n result = False\n if token not in values:\n if is_token_lang_adopted(token):\n if LingualToken.unlangify(token) not in values:\n result = True\n else:\n if token not in LingualToken.unlangify(values):\n result = True\n return result\n\n\n def __get_token_langs(self, token):\n\n if is_token_lang_adopted(token):\n result = [token[0:2]]\n else:\n result = self.langs\n return result\n\n\n @property\n def lang_keywords(self):\n return [LingualToken(key, self.__get_token_langs(key)) for key in self.keywords]\n\n\n @property\n def lang_skipwords(self):\n return [LingualToken(key) for key in self.skipwords]\n\n\nclass GroupingConfig(SonDocument):\n MIN_GRP_TIMEOUT, MAX_GRP_TIMEOUT = 0, 7 * 24 * 60 * 60 # from 0 seconds to 7 days\n DEFAULT_GRP_TIMEOUT = 120 # seconds\n is_enabled = fields.BooleanField(default=False)\n group_by_type = fields.BooleanField(default=True)\n grouping_timeout = fields.NumField(default=DEFAULT_GRP_TIMEOUT) # seconds\n\n @classmethod\n def validate_grouping_timeout(cls, timeout):\n allowed_types = (int, float)\n if not isinstance(timeout, allowed_types):\n raise ValueError(\"%s is not instance of %s\" % (timeout, allowed_types))\n if not (timeout == 0 or cls.MIN_GRP_TIMEOUT <= timeout <= cls.MAX_GRP_TIMEOUT):\n raise ValueError(\"%s is not in range of [%s, %s]\" % (timeout, cls.MIN_GRP_TIMEOUT, cls.MAX_GRP_TIMEOUT))\n return timeout\n\n\nclass TwitterServiceChannel(ServiceChannel, TwitterChannel):\n\n auto_refresh_followers = fields.NumField(default=20)\n auto_refresh_friends = fields.NumField(default=20)\n skip_retweets = fields.BooleanField(default=False)\n # grouping configuration for api/queue\n _grouping_config = fields.EmbeddedDocumentField(GroupingConfig)\n\n @property\n def grouping_config(self):\n if self._grouping_config is None:\n self._grouping_config = GroupingConfig()\n return self._grouping_config\n\n @property\n def grouping_enabled(self):\n return self.grouping_config.is_enabled\n\n @grouping_enabled.setter\n def grouping_enabled(self, value):\n from solariat_bottle.utils.views import parse_bool\n self.grouping_config.is_enabled = parse_bool(value)\n\n @property\n def grouping_timeout(self):\n return self.grouping_config.grouping_timeout\n\n @grouping_timeout.setter\n def grouping_timeout(self, value):\n if isinstance(value, basestring):\n value = float(value)\n self.grouping_config.grouping_timeout = GroupingConfig.validate_grouping_timeout(value)\n\n @property\n def InboundChannelClass(self):\n return KeywordTrackingChannel\n\n @property\n def OutboundChannelClass(self):\n return UserTrackingChannel\n\n @property\n def DispatchChannelClass(self):\n return EnterpriseTwitterChannel\n\n @property\n def usernames(self):\n return get_sync_usernames_list(self.outbound_channel.usernames)\n\n @property\n def keywords(self):\n return self.inbound_channel.keywords if hasattr(self.inbound_channel, \"keywords\") else []\n\n @needs_postfilter_sync\n def add_username(self, username):\n usernames = get_sync_usernames_list([username])\n if self.status in {'Active', 'Interim'}:\n self._track_usernames(usernames)\n for username in usernames:\n self.outbound_channel.add_username(username)\n\n @needs_postfilter_sync\n def del_username(self, username):\n usernames = get_sync_usernames_list([username])\n if self.status in {'Active', 'Interim'}:\n self._untrack_usernames(usernames)\n for username in usernames:\n self.outbound_channel.del_username(username)\n\n @needs_postfilter_sync\n def add_keyword(self, keyword):\n return self.inbound_channel.add_keyword(keyword)\n\n @needs_postfilter_sync\n def del_keyword(self, keyword):\n return self.inbound_channel.del_keyword(keyword)\n\n def _track_usernames(self, usernames=None):\n # Implicitly track usernames as keywords\n usernames = usernames or self.usernames\n from solariat_bottle.db.tracking import PostFilterStream\n from solariat_bottle.utils.post import normalize_screen_name\n\n stream = PostFilterStream.get()\n stream.track('KEYWORD', map(normalize_screen_name, usernames), [self.inbound_channel], langs=self.langs)\n\n def _untrack_usernames(self, usernames=None):\n usernames = usernames or self.usernames\n from solariat_bottle.db.tracking import PostFilterStream\n from solariat_bottle.utils.post import normalize_screen_name\n\n stream = PostFilterStream.get()\n stream.untrack('KEYWORD', map(normalize_screen_name, usernames), [self.inbound_channel], langs=self.langs)\n\n def on_active(self):\n super(TwitterServiceChannel, self).on_active()\n self._track_usernames()\n\n def on_suspend(self):\n super(TwitterServiceChannel, self).on_suspend()\n self._untrack_usernames()\n\n def tracked_entities(self):\n from solariat_bottle.utils.post import normalize_screen_name\n\n if self.status not in {'Active', 'Interim'}:\n return []\n\n ic = self.inbound_channel\n oc = self.outbound_channel\n\n def gen_lang_keywords(kwds, all_langs=None):\n by_lang = defaultdict(list)\n for kwd in kwds:\n lang, kwd = LingualToken.parse(kwd)\n by_lang[lang or 'all'].append(kwd)\n\n for lang, words in by_lang.iteritems():\n langs = all_langs if lang == 'all' else [lang]\n yield words, langs\n\n def inflate_entities(filter_type, kwds, channel, all_langs):\n return [(filter_type, keywords, channel, langs)\n for keywords, langs in gen_lang_keywords(kwds, all_langs)]\n\n entities = [\n # (entity_type, entities, channels, langs)\n ('KEYWORD', map(normalize_screen_name, self.usernames), ic, self.langs),\n ('USER_NAME', oc.usernames, oc, self.langs)\n ]\n entities.extend(inflate_entities('KEYWORD', ic.keywords, ic, self.langs))\n entities.extend(inflate_entities('SKIPWORD', ic.skipwords, ic, self.langs))\n return entities\n\n def check_post_filter_entries(self, log_level=None, track_missing=False):\n from solariat_bottle.db.tracking import PostFilterStream\n\n if log_level:\n log = getattr(LOGGER, log_level)\n\n stream = PostFilterStream.get()\n tests_results = []\n for (filter_type, entries, channel, langs) in self.tracked_entities():\n tracked = stream.tracking_state(filter_type, entries, [channel], langs)\n all_tracked = all(is_tracked for (_, _, is_tracked) in tracked)\n tests_results.append(all_tracked)\n\n if not all_tracked:\n if log_level and log:\n log(\"Missing PostFilterEntries ({}) for channel '{}'\\n\"\n \"Details: {}\".format(filter_type, channel, tracked))\n # track missing PostFilterEntries\n if track_missing:\n stream.track(filter_type, entries, [channel], langs=langs)\n\n return all(tests_results)\n\n @needs_postfilter_sync\n def set_allowed_langs(self, langs, clear_previous=False):\n\n current_langs = set(self.langs)\n\n super(TwitterServiceChannel, self).set_allowed_langs(langs, clear_previous)\n from solariat_bottle.db.tracking import PostFilterStream\n from solariat_bottle.utils.post import normalize_screen_name\n\n new_langs = set(langs) - current_langs\n usernames = self.usernames\n stream = PostFilterStream.get()\n stream.track('KEYWORD', map(normalize_screen_name, usernames), [self.inbound_channel], langs=new_langs)\n stream.track('USER_NAME', usernames, [self.outbound_channel], langs=new_langs)\n\n @needs_postfilter_sync\n def remove_langs(self, langs):\n\n super(TwitterServiceChannel, self).remove_langs(langs)\n from solariat_bottle.db.tracking import PostFilterStream\n from solariat_bottle.utils.post import normalize_screen_name\n\n usernames = self.usernames\n stream = PostFilterStream.get()\n stream.untrack('KEYWORD', map(normalize_screen_name, usernames), [self.inbound_channel], langs=langs)\n stream.untrack('USER_NAME', usernames, [self.outbound_channel], langs=langs)\n\n def to_dict(self, fields2show=None):\n res = super(TwitterServiceChannel, self).to_dict(fields2show)\n res['langs'] = self.langs\n res['keywords'] = self.keywords\n res['watchwords'] = self.watchwords\n # res['skipwords'] = self.skipwords\n return res\n\n\nCHANNEL_ID_URL_MAP[EnterpriseTwitterChannel(title=\"\").type_id] = EnterpriseTwitterChannel(title=\"\").base_url\n\n","sub_path":"db/channel/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":41416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"402618473","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nimport re\r\nimport scrapy\r\nimport io\r\n\r\n\r\nURL_TEMPLATE = 'https://www.tripadvisor.com.au/Attraction_Review-g255103-d526770-r%s.html'\r\n#URL_TEMPLATE = 'https://www.tripadvisor.com.au/Attraction_Review-g255100-d269501-Reviews-or%s-Australian_Centre_for_the_Moving_Image-Melbourne_Victoria.html'\r\n\r\n#def url_generator():\r\n# for page in revID:\r\n# yield URL_TEMPLATE % (revID)\r\n\r\nwith io.open('reviewID.txt', 'rt') as f:\r\n reviewIDs = [url.strip() for url in f.readlines()]\r\n\r\nclass TripAdvisorReview(scrapy.Spider):\r\n name = \"tripadvisor\"\r\n start_urls = reviewIDs\r\n\r\n def parse(self, response):\r\n for review in response.css('.reviewSelector'):\r\n id = review.css('::attr(id)').extract_first()\r\n if id.startswith(\"review_title\"):\r\n continue\r\n\r\n yield {\r\n 'id': id.replace(\"review_\", \"\"),\r\n\t\t'date': review.css('.ratingDate ::attr(title)').extract_first(),\r\n 'title': review.css('.quote ::text').extract_first(),\r\n 'body': review.css('.partial_entry ::text').extract_first(),\r\n 'rating': int(review.css('.rating .ui_bubble_rating ::attr(class)').re(r'ui_bubble_rating bubble_(\\d\\d)')[0])/10.0,\r\n }\r\n\r\n\r\n","sub_path":"tripadvisorScraperFull.py","file_name":"tripadvisorScraperFull.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"4518303","text":"\"\"\"\n3040. 백설 공주와 일곱 난쟁이\n\n작성자: xCrypt0r\n언어: Python 3\n사용 메모리: 29,380 KB\n소요 시간: 60 ms\n해결 날짜: 2020년 9월 25일\n\"\"\"\n\nfrom itertools import combinations\n\ndef find_dwarf(case):\n if sum(case) == 100:\n print(*sorted(case), sep='\\n')\n\n return True\n\n return False\n\ndef main():\n heights = [int(input()) for _ in range(9)]\n\n for case in combinations(heights, 7):\n if find_dwarf(case):\n break\n\nif __name__ == '__main__':\n main()","sub_path":"src/3/3040.py","file_name":"3040.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"626813521","text":"from __future__ import unicode_literals\n\nfrom conformity import fields\n\nfrom pysoa.common.settings import (\n BasicClassSchema,\n SOASettings,\n)\nfrom pysoa.common.transport.base import ServerTransport as BaseServerTransport\nfrom pysoa.common.transport.local import (\n LocalServerTransport,\n LocalTransportSchema,\n)\nfrom pysoa.common.transport.redis_gateway.server import RedisServerTransport\nfrom pysoa.common.transport.redis_gateway.settings import RedisTransportSchema\nfrom pysoa.server.middleware import ServerMiddleware\n\n\nclass ServerSettings(SOASettings):\n \"\"\"\n Settings specific to servers\n \"\"\"\n\n schema = {\n 'transport': BasicClassSchema(BaseServerTransport),\n 'middleware': fields.List(BasicClassSchema(ServerMiddleware)),\n 'client_routing': fields.SchemalessDictionary(),\n 'logging': fields.SchemalessDictionary(),\n 'harakiri': fields.Dictionary({\n 'timeout': fields.Integer(gte=0), # seconds of inactivity before harakiri is triggered, 0 to disable\n 'shutdown_grace': fields.Integer(gte=0), # seconds to gracefully shutdown after harakiri is triggered\n }),\n }\n\n defaults = {\n 'client_routing': {},\n 'logging': {\n 'version': 1,\n 'formatters': {\n 'console': {\n 'format': '%(asctime)s %(levelname)7s: %(message)s'\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n 'formatter': 'console',\n },\n },\n 'root': {\n 'handlers': ['console'],\n 'level': 'INFO',\n },\n },\n 'harakiri': {\n 'timeout': 300,\n 'shutdown_grace': 30,\n },\n }\n\n\nclass RedisServerSettings(ServerSettings):\n defaults = {\n 'transport': {\n 'path': 'pysoa.common.transport.redis_gateway.server:RedisServerTransport',\n }\n }\n schema = {\n 'transport': RedisTransportSchema(),\n }\n\n\nclass LocalServerSettings(ServerSettings):\n defaults = {\n 'transport': {\n 'path': 'pysoa.common.transport.local:LocalServerTransport',\n }\n }\n schema = {\n 'transport': LocalTransportSchema(),\n }\n\n\nclass PolymorphicServerSettings(ServerSettings):\n \"\"\"\n Settings for Servers that can use any type of transport, while performing validation on certain transport types.\n \"\"\"\n defaults = {\n 'transport': {\n 'path': 'pysoa.common.transport.redis_gateway.server:RedisServerTransport',\n }\n }\n schema = {\n 'transport': fields.Polymorph(\n switch_field='path',\n contents_map={\n 'pysoa.common.transport.local:LocalServerTransport': LocalTransportSchema(LocalServerTransport),\n 'pysoa.common.transport:LocalServerTransport': LocalTransportSchema(LocalServerTransport),\n 'pysoa.common.transport.redis_gateway.server:RedisServerTransport': RedisTransportSchema(\n RedisServerTransport,\n ),\n '__default__': BasicClassSchema(BaseServerTransport),\n }\n ),\n }\n","sub_path":"pysoa/server/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"422778044","text":"#==============================================================================\n# Copyright (c) 2015, Kitware Inc., Los Alamos National Laboratory\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this\n# list of conditions and the following disclaimer in the documentation and/or other\n# materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors may\n# be used to endorse or promote products derived from this software without specific\n# prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN 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#==============================================================================\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\n\nclass QColorBar(QWidget):\n def __init__(self, parent=None):\n super(QColorBar, self).__init__(parent)\n\n self.lookup_table = None\n self._minMax = tuple([None, None])\n\n def minimumSizeHint(self):\n return QSize(100, 50)\n def sizeHint(self):\n return QSize(256, 50)\n\n def resizeEvent(self, e):\n self.repaint()\n\n def setMinMax(self, minMax):\n self._minMax = minMax\n\n def setLookupTable(self, lookup_table):\n self.lookup_table = lookup_table\n self.repaint()\n\n def paintEvent(self, e):\n painter = QPainter(self)\n if self.lookup_table != None and \\\n self.lookup_table.lut != None and \\\n self.lookup_table.x != None:\n colorCount = len(self.lookup_table.lut)\n fullWidth = self.rect().width()\n height = self.rect().height() / 2\n\n xs = self.lookup_table.x\n if self.lookup_table.x[-1] == 1.0:\n # Need to make some space for the 1.0 color\n P = 0.1\n for i in range(0, len(self.lookup_table.x)):\n xs[i] = xs[i] - i * P / colorCount\n\n # Render the color bar\n for i in range(0, colorCount):\n # Render the color block\n x = xs[i]\n if i == colorCount - 1:\n nextX = 1.0\n else:\n nextX = xs[i + 1]\n blockWidth = fullWidth * (nextX - x)\n startX = fullWidth * x\n blockRect = QRect(startX, 0, startX + blockWidth, height)\n color = QColor(self.lookup_table.lut[i][0], \\\n self.lookup_table.lut[i][1], \\\n self.lookup_table.lut[i][2])\n painter.fillRect(blockRect, color)\n\n # Render min/max labels\n # TODO: Get true min/max from current track\n blockRect = QRect(0, height, 18, 2*height)\n minStr = ('%0.1f' % self._minMax[0]) if self._minMax[0] != None else \"\"\n painter.drawText(blockRect, Qt.AlignLeft, minStr)\n\n blockRect = QRect(fullWidth - 18, height, fullWidth, 2*height)\n maxStr = ('%0.1f' % self._minMax[1]) if self._minMax[1] != None else \"\"\n painter.drawText(blockRect, Qt.AlignLeft, maxStr)\n\n # Render spaced labels (disabled)\n minimumLabelWidth = 25\n labelCount = len(self.lookup_table.x)\n labelCount = min(labelCount, fullWidth / minimumLabelWidth)\n step = len(self.lookup_table.x) / labelCount\n labelCount = 0 # TODO - figure out better label rendering\n for i in range(0, labelCount):\n # Render the text label\n x = xs[i * step]\n startX = fullWidth * x\n blockRect = QRect(startX, height, \\\n startX + minimumLabelWidth, 2*height)\n painter.drawText(blockRect, Qt.AlignLeft, '%0.1f' % x)\n\n else:\n painter.fillRect(self.rect(), QColor(236, 236, 236))\n","sub_path":"qtviewer/QColorBar.py","file_name":"QColorBar.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"375606403","text":"# -*- coding: utf-8 -*-\r\nimport MySQLdb\r\n\r\ndbargs = {\r\n 'host': 'localhost',\r\n 'port': 3306,\r\n 'user': 'root',\r\n 'passwd': '123456',\r\n}\r\nconn = MySQLdb.connect(**dbargs)\r\ncur = conn.cursor()\r\ncur.execute(\r\n \"\"\"\r\n create database if not exists yd_sports_consult\\\r\n default character set utf8 COLLATE utf8_general_ci;\r\n \"\"\")\r\n\r\ndbargs['db'] = 'yd_sports_consult'\r\ncreate_subject_tb = (\"\"\"\"\"\")\r\n\r\ncreate_subject_fragment = (\r\n\"\"\"\r\n\"\"\"\r\n)\r\n\r\n\r\nconn = MySQLdb.connect(**dbargs)\r\ncur = conn.cursor()\r\ncur.execute(create_subject_tb)\r\ncur.execute(create_subject_fragment)\r\nconn.commit()\r\ncur.close()\r\n","sub_path":"bin/create_database.py","file_name":"create_database.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"587404448","text":"import requests\nimport urllib\n\n\ndef download_image(name, link):\n opener = urllib.request.URLopener()\n # engañar a imgflip para que crea que es un usaurio real\n opener.addheader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 Edg/81.0.416.72')\n # es más fácil descargar cosas con urllib\n extension = link.split(\".\")[-1]\n opener.retrieve(link, name+\".\"+extension)# se me olvidó cambiar aqui el nombre de la variable\n return name+\".\"+extension\n\n\nif __name__ == \"__main__\":\n download_image(\"meme\", \"https://i.imgflip.com/1ur9b0.jpg\")\n print(\"descargado\")","sub_path":"ImageDownloader.py","file_name":"ImageDownloader.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"227989730","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 2 11:26:44 2020\r\n\r\n@author: Mauricio\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom helper import *\r\nimport os\r\n\r\n\r\nnp.random.seed(1234)\r\n\r\n\"\"\"\r\nPRECISIÓN Y ERRORES DE GENERALIZACION, ENTRENAMIENTO Y VALIDACION\r\n\"\"\"\r\nX_train = np.load(r\"SRC/Anexo/Arreglos ProPublica/X_train.npy\")\r\nX_val = np.load(r\"SRC/Anexo/Arreglos ProPublica/X_val.npy\")\r\nX_test = np.load(r\"SRC/Anexo/Arreglos ProPublica/X_test.npy\")\r\n\r\nX_train_v = np.load(r\"SRC/Anexo/Arreglos ProPublica/X_train_v.npy\")\r\nX_val_v = np.load(r\"SRC/Anexo/Arreglos ProPublica/X_val_v.npy\")\r\nX_test_v = np.load(r\"SRC/Anexo/Arreglos ProPublica/X_test_v.npy\")\r\n\r\n\r\n\r\ny_train = np.load(r\"SRC/Anexo/Arreglos ProPublica/y_train.npy\")\r\ny_train_v = np.load(r\"SRC/Anexo/Arreglos ProPublica/y_train_v.npy\")\r\ny_val = np.load(r\"SRC/Anexo/Arreglos ProPublica/y_val.npy\")\r\ny_val_v = np.load(r\"SRC/Anexo/Arreglos ProPublica/y_val_v.npy\")\r\ny_test = np.load(r\"SRC/Anexo/Arreglos ProPublica/y_test.npy\")\r\ny_test_v = np.load(r\"SRC/Anexo/Arreglos ProPublica/y_test_v.npy\")\r\n\r\ncoefs_freq = np.load(r\"SRC/Anexo/Arreglos ProPublica/coefs_freq.npy\")\r\ncoefs_freq_v = np.load(r\"SRC/Anexo/Arreglos ProPublica/coefs_freq_v.npy\")\r\n\r\ncoefs_opt = np.load(r\"SRC/Anexo/Arreglos ProPublica/perf_nbww.npy\")\r\ncoefs_opt_v = np.load(r\"SRC/Anexo/Arreglos ProPublica/perf_nbww_v.npy\")\r\n\r\ncoefs_bay = np.load(r\"SRC/Anexo/Arreglos ProPublica/perf_mean_bay.npy\")\r\ncoefs_bay_v = np.load(r\"SRC/Anexo/Arreglos ProPublica/perf_mean_bay_v.npy\")\r\n\r\ntraining_errors, validation_errors, test_errors = np.zeros((3,2,2)), np.zeros((3,2,2)), np.zeros((3,2,2))\r\n\r\ntraining_inputs = np.array([X_train, X_train_v])\r\nvalidation_inputs = np.array([X_val, X_val_v])\r\ntest_inputs = np.array([X_test, X_test_v])\r\n\r\ntraining_outputs = np.array([y_train, y_train_v])\r\nvalidation_outputs = np.array([y_val, y_val_v])\r\ntest_outputs = np.array([y_test, y_test_v])\r\n\r\ncoefs_freq = np.array([coefs_freq, coefs_freq_v])\r\ncoefs_opt = np.array([coefs_opt, coefs_opt_v])\r\ncoefs_bay = np.array([coefs_bay, coefs_bay_v])\r\n\r\ncoefs_all = np.array([coefs_freq, coefs_opt, coefs_bay])\r\n\r\n\r\ntraining_outputs = np.array([y_train, y_train_v])\r\nvalidation_outputs = np.array([y_val, y_val_v])\r\ntest_outputs = np.array([y_test, y_test_v])\r\n\r\n\r\n#Error de entrenamiento\r\nfor i in range(3):\r\n for j in range(2):\r\n X, y, w = training_inputs[j], training_outputs[j], coefs_all[i,j]\r\n training_errors[i,j] = logreg_cost_accuracy(X, y, w)[0]/len(y), logreg_cost_accuracy(X, y, w)[1]\r\n\r\n#Error de validación\r\nfor i in range(3):\r\n for j in range(2):\r\n X, y, w = validation_inputs[j], validation_outputs[j], coefs_all[i,j]\r\n validation_errors[i,j] = logreg_cost_accuracy(X, y, w)[0]/len(y), logreg_cost_accuracy(X, y, w)[1]\r\n\r\n#Error de prueba\r\nfor i in range(3):\r\n for j in range(2):\r\n X, y, w = test_inputs[j], test_outputs[j], coefs_all[i,j]\r\n test_errors[i,j] = logreg_cost_accuracy(X, y, w)[0]/len(y), logreg_cost_accuracy(X, y, w)[1]\r\n\r\n\"\"\"\r\nPRINTING:\r\n \r\nERRORS\r\nfor x in range(training_errors.shape[0]):\r\n print(str(x)+\":\")\r\n for y in range(training_errors.shape[1]):\r\n #change this line to val or test when getting those\r\n print(round(training_errors[x,y,0], 4))\r\n print(\"\\n\")\r\n \r\nACCURACIES\r\nfor x in range(training_errors.shape[0]):\r\n print(str(x)+\":\")\r\n for y in range(training_errors.shape[1]):\r\n print(round(training_errors[x,y,1], 3))\r\n print(\"\\n\")\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"SRC/Anexo/Generalization ProPublica.py","file_name":"Generalization ProPublica.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"9393716","text":"import pandas as pd\nimport sys\nimport warnings\n\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nfilename = sys.argv[1]\n\ndf = pd.read_csv(str(filename), delimiter='\\t')\ndf.drop(labels=['AllSubs','Frequency','gCoverage-q30','gMeanQ','gBaseCount[A,C,G,T]','gAllSubs','gFrequency'], axis=1, inplace=True)\n\n#break up BaseCount[A,C,G,T] into individual columns\ndf['Reads_A'] = df.apply(lambda row: int(row['BaseCount[A,C,G,T]'].split(',')[0][1:]), axis=1)\ndf['Reads_C'] = df.apply(lambda row: int(row['BaseCount[A,C,G,T]'].split(',')[1][1:]), axis=1)\ndf['Reads_G'] = df.apply(lambda row: int(row['BaseCount[A,C,G,T]'].split(',')[2][1:]), axis=1)\ndf['Reads_T'] = df.apply(lambda row: int(row['BaseCount[A,C,G,T]'].split(',')[3][1:-1]), axis=1)\n\ndf.drop(labels='BaseCount[A,C,G,T]', axis=1, inplace=True)\n#filter for coverage >= 10\ndf = df[df['Coverage-q30'] >= 10]\ndf.to_csv(str(filename)[:-4] + '_mod.csv')\n\n#filter by plus or minus strands\ndf_plus = df[df['Strand'] == 1]\ndf_plus = df_plus[df_plus.Reference == 'A']\n\ndf_minus = df[df['Strand'] == 0]\ndf_minus = df_minus[df_minus.Reference == 'T']\n\nplus_Reads_A = df_plus['Reads_A'].tolist()\nplus_Reads_T = df_plus['Reads_T'].tolist()\nplus_Reads_G = df_plus['Reads_G'].tolist()\nplus_Reads_C = df_plus['Reads_C'].tolist()\n\nminus_Reads_A = df_minus['Reads_A'].tolist()\nminus_Reads_T = df_minus['Reads_T'].tolist()\nminus_Reads_G = df_minus['Reads_G'].tolist()\nminus_Reads_C = df_minus['Reads_C'].tolist()\n\nwith open(filename + '.out.txt', 'w') as f:\n\tf.write('Total plus-strand A reads = ' + str(sum(plus_Reads_A) + sum(plus_Reads_T) + sum(plus_Reads_G) + sum(plus_Reads_C)) + '\\n')\n\tf.write('plus strand A-to-I reads = ' + str(sum(plus_Reads_G)) + '\\n')\n\tf.write('Total minus-strand A reads = ' + str(sum(minus_Reads_A) + sum(minus_Reads_T) + sum(minus_Reads_G) + sum(minus_Reads_C)) + '\\n')\n\tf.write('minus strand A-to-I reads = ' + str(sum(minus_Reads_C)))","sub_path":"share/script/tabulate_reads_AtoI-stranded.py","file_name":"tabulate_reads_AtoI-stranded.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"135489208","text":"\n# coding: utf-8\n\n# # Introduction\n# This tutorial will give an example application of using deep learning for categorization of images. This example will demonstrate how to implement a convolutional neural network for the identifying the type of MRI contrast or pulse sequence from a given input. The tutorial will have 3 main parts:\n# \n# 1. Loading and organization of data for model training\n# 2. Creating a multi-class categorization deep learning model\n# 3. Training with pre-defined networks\n# \n# Keep an eye out for questions through this demo to test your new DL knowledge and critical thinking. There are answers at the end of the document.\n\n# ### Initial Preparation\n# These are some modules that we will need throughout this example:\n\n# In[ ]:\n\n\n# This is not generally needed. Needed on Jupyter to explicitly set TensorFlow as backend\nimport os\nos.environ['KERAS_BACKEND'] = 'tensorflow'\n\nimport numpy\nfrom keras.models import Model\nfrom keras import layers\nfrom keras import optimizers\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# initialize random seeds for reproducible results\nfrom numpy.random import seed\nseed(1)\nfrom tensorflow import set_random_seed\nset_random_seed(2)\n\n\n# We will import other necessary modules as we go and need them.\n\n# # Part 1: Data Organization\n# Data for this example has already been prepared for you. The data utilized here is from the 2017 MICCAI Multimodal Brain Tumor Segmentation (BRATS) Challenge. The data consists of magnetic resonance imaging (MRI) data from 19 different institutions in subjects with glioblastoma/high grade glioma (GBM/HGG) and low grade glioma (LGG). The different MRI scans include: T1-weighted (t1), post-contrast Gadolinium-enhanced images (t1ce), T2-weighted (t2), and T2 fluid attenuated inversion recovery (flair). More information on the 2017 BRATS Challenge is available here: https://www.med.upenn.edu/sbia/brats2017/data.html\n# \n# Data preparation for this example is similar to the approach that utilized in the previous example. This includes the use of a Keras image data generator. Your instructor has converted the BRATS data from the NiFTI imaging format (https://nifti.nimh.nih.gov/nifti-1/) to portable network graphics (.png) files, which is an image file format that can be read natively in Keras. Each .png file is a 256x256 axial image. In a later exercise, you will load image data directly from DICOM files as a further example. The structure of the data folder is as follows:\n#
\n#   --brats_contrast_detector\n#      --test (17,100 files)\n#            --flair\n#            --t1\n#            --t1ce\n#            --t2\n#      --train (39,900 files)\n#            --flair\n#            --t1\n#            --t1ce\n#            --t2\n#      --validate (17,100 files)\n#            --flair\n#            --t1\n#            --t1ce\n#            --t2\n# 
\n# \n# Configuring the images in this particular folder structure allows easy use of a Keras ImageDataGenerator to perform the categorization of the different types of data for which we wish to discriminate. Specifically for this example, this includes the type of MRI scan: (flair, t1, t1ce, or t2) of each input image. The BRATS Dataset includes images from 285 subjects, and in this structure the data has been divided into ~66 subjects in the testing set (test), ~153 subjects in the training set (train), and ~66 subjects in the validation set (validate). Thus, each subject contributes 65 slices for each type of MRI scan.\n# \n# Now let's work on setting up the ImageDataGenerator to read in our data. Keras has built-in capabilities to perform basic types of data augmentation. That is the ability to apply different, randomized transformations to the input data to increase the diversity of the dataset. In this exercise we will explore the use of an ImageDataGenerator to perform varying types of augmentation. Let's try it out:\n\n# In[ ]:\n\n\n# first let's use some varaibles to record information about our data\ndims = 256 # this is the size of out input data, 256x256\n#classes = ? # how many types of MRI scans do we have?\n#\nclasses = 4\n#\nbatch_size = 15 # this is how many input images will be utilized for each training step\n\n# this is the folder that contains the 39,900 images that will be used for training\ntrain_folder = os.path.join(os.getcwd(),'train')\n# this is the folder htat contains the 17,100 images that will be used for validation\nvalid_folder = os.path.join(os.getcwd(),'validate')\n\n# set up the ImageDataGenerator for the validation data first. We will not perform augmentation on the validation data, but we do need to normalize the input intensity of the input images:\nvalid_datagen = ImageDataGenerator(rescale=1./255)\n\n# now set up the ImageDataGenerator for the training:\n# Go to the documentation page for the ImageDataGenerator (https://keras.io/preprocessing/image/#imagedatagenerator-class)\n# and learn how to add in a rotation, a shear, width shift, height shift, and zoom augmentation.\n# What are reasonable values for this type of dataset?\n#train_datagen = ?\n#\ntrain_datagen = ImageDataGenerator(rescale=1./255,rotation_range=10,shear_range=1,width_shift_range=0.2,height_shift_range=0.2,zoom_range=0.2)\n#\n\n\n# # Model Configuration\n# In this example we will explore the use of different model structures that are already available in Keras. But first let's start with the model that used in the last example. Can you modify the existing model structure? How will it work with the number of classes in this new dataset?\n\n# In[ ]:\n\n\n# insert the model you used in the last example here\n#\nimg_input = layers.Input(shape=(dims,dims,1))\nx = layers.Conv2D(15, (3, 3), strides=(4,4), padding='same', kernel_initializer='he_normal')(img_input)\nx = layers.Activation('relu')(x)\nx = layers.MaxPooling2D((2, 2), strides=None)(x)\nx = layers.Flatten()(x) #reshape to 1xN\nx = layers.Dense(20, activation='relu', kernel_initializer='he_normal')(x)\nx = layers.Dense(classes, activation='relu')(x)\nmodel = Model(inputs=img_input, outputs=x)\n#\n\n# now lets compile the model.\n# What loss function should be used? binary_crossentropy does not make sense anymore.\n# Here is a list of available loss functions in Keras: https://keras.io/losses/\n# What metrics should be used? accuracy is also not appropriate here.\n# Here is a list of available metrics in Keras: https://keras.io/metrics/\n#model.compile(loss=\"?\", optimizer=optimizers.Adam(lr=1e-3), metrics=[\"?\"])\n#\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=optimizers.Adam(lr=1e-5), metrics=[\"categorical_accuracy\"])\n#\n\n\n# # Model Training\n# Let's work on training this this model and dataset.\n# \n# First, let's set up the ImageDataGenerator to use the flow_from_directory function. This is very useful because it allows us to train large datasets that we might not be able to entirely load into our computer's memory. Also, it provides the facilities for on-the-fly augmentation that we are now using. \n\n# In[ ]:\n\n\n# the call to flow_from_directory, technically it returns a DirectoryIterator object\n# that we pass to the model.fit_generator. Let's set it up:\n# What should class_mode be set to here?\n#train_generator = train_datagen.flow_from_directory(train_folder, batch_size=batch_size, target_size=(dims,dims), shuffle=True, class_mode='?', color_mode='grayscale')\n#valid_generator = valid_datagen.flow_from_directory(valid_folder, batch_size=batch_size, target_size=(dims,dims), shuffle=True, class_mode='?', color_mode='grayscale')\n#\ntrain_generator = train_datagen.flow_from_directory(train_folder, batch_size=batch_size, target_size=(dims,dims), shuffle=True, class_mode='categorical', color_mode='grayscale')\nvalid_generator = valid_datagen.flow_from_directory(valid_folder, batch_size=batch_size, target_size=(dims,dims), shuffle=True, class_mode='categorical', color_mode='grayscale')\n#\n\n\n# Now we are ready to start training. Let's get this get this going:\n\n# In[ ]:\n\n\n# steps is the number of batches that are passed during each epoch\n# IRL, this should be large enough such that we pass through the entire\n# dataset (or equivalent) for each epoch. That is: 9975/batch_size\n# For practicality for this course, let's make it smaller so we can progress\n# through this exercise at a quicker pace.\nsteps = 500\n# val_steps is the number of batches that are passed during each validation epoch\n# IRL, this should be large enough such that we pass through the entire\n# dataset (or equivalent) for each epoch. That is: 4275/batch_size\n# For practicality for this course, let's make it smaller so we can progress\n# through this exercise at a quicker pace.\nval_steps = 100\n\n# now let's train for 5 epochs (note that this is unrealistic demonstration of model training)\nhistory = model.fit_generator(train_generator, steps_per_epoch=steps, epochs=5, \n validation_data=valid_generator, validation_steps=val_steps)\n\n# It should take approximately 5 minutes to train. Maybe you should take a break\n\n\n# Now that training is complete. Let's plot the losses:\n\n# In[ ]:\n\n\n# first, we need to import matplotlib to enable plotting\n#%matplotlib notebook\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(6.0, 4.0));\n# Plot the losses\nplt.subplot(121)\nplt.plot(history.epoch,history.history['loss'],'b-s')\nplt.plot(history.epoch,history.history['val_loss'],'r-s')\nplt.legend(['Training Data',\n 'Validation Data'])\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Loss Plot')\n# Plot the accuracy\nplt.subplot(122)\nplt.plot(history.epoch,history.history['categorical_accuracy'],'b-s')\nplt.plot(history.epoch,history.history['val_categorical_accuracy'],'r-s')\nplt.legend(['Training Data',\n 'Validation Data'])\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Accuracy Plot')\nplt.show()\n\n\n# **Question 1:** Given the number of input classes that we have. What would be the accuracy of a model that was as good as a random guess? What was the accuracy of your model?\n\n# ### Improved Network Structures\n# I hope you agree that we can do better. Let's try this again but with different model. Keras has the functionality to use pre-existing network structures. Let's explore that functionality. Please take a look at the Keras Applications page (https://keras.io/applications/), which describes pre-configured networks that are available.\n# \n# We will try MobileNet, which is designed to be an efficient network. Here is more information about the MobileNet structure: https://arxiv.org/pdf/1704.04861.pdf\n\n# In[ ]:\n\n\n# first we need to import MobileNet\nfrom keras.applications.mobilenet import MobileNet\n\n# here instantiate a MobileNet that is specific to our data (image size and number of classes) with randomized initial weights\n#model_mn = ?\n#\nmodel_mn = MobileNet(weights=None, input_shape=(dims,dims,1), classes=classes)\n#\n\n# now let's train it\nmodel_mn.compile(loss=\"categorical_crossentropy\", optimizer=optimizers.Adam(lr=1e-5), metrics=[\"categorical_accuracy\"])\nhistory_mn = model.fit_generator(train_generator, steps_per_epoch=steps, epochs=5,\n validation_data=valid_generator, validation_steps=val_steps)\n\n\n# Now we can plot the losses compared to our first network:\n\n# In[ ]:\n\n\nplt.figure(figsize=(6.0, 4.0));\nplt.subplot(121)\nplt.plot(history_mn.epoch,history_mn.history['loss'],'b-s')\nplt.plot(history.epoch,history.history['loss'],'g-s')\nplt.legend(['MobileNet Training Data',\n '1st Network Training Data'])\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Loss Plot')\nplt.subplot(122)\nplt.plot(history_mn.epoch,history_mn.history['val_categorical_accuracy'],'r-s')\nplt.plot(history.epoch,history.history['val_categorical_accuracy'],'c-s')\nplt.legend(['MobileNet Validation Data',\n '1st Network Validation Data'])\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Accuracy Plot')\nplt.show()\n\n\n# This looks like it is doing much better. Unfortunately we do not have the time today to complete the full training. Fortunately, your instructor has trained this network (and several others) for up to 30 epochs. Let's work on next loading these trained models and compare their performance. Note that we are using a Keras callback function, ModelCheckpoint (https://keras.io/callbacks/#modelcheckpoint), to save the best weights of the trained network. We will load these weight files in the next step. \n# \n# For your information, the code that was used to train the different networks is below:\n# \n# #### To define VGG16 - https://arxiv.org/abs/1409.1556\n#
\n# from keras.applications.vgg16 import VGG16\n# model = VGG16(weights=None, input_shape=(dims,dims,1), classes=classes)\n# 
\n# #### To define InceptionV3 - http://arxiv.org/abs/1512.00567\n#
\n# from keras.applications.inception_v3 import InceptionV3\n# model = InceptionV3(weights=None, input_shape=(dims,dims,1), classes=classes)\n# 
\n# #### To define DenseNet - https://arxiv.org/abs/1608.06993\n#
\n# from keras.applications.densenet import DenseNet121\n# model = DenseNet121(weights=None, input_shape=(dims,dims,1), classes=classes)\n# 
\n# #### Used to train all of the above models\n#
\n# model.compile(loss=\"categorical_crossentropy\", optimizer=optimizers.Adam(lr=1e-4), metrics=[\"categorical_accuracy\"])\n# from keras.callbacks import ModelCheckpoint\n# model_checkpoint = ModelCheckpoint('weights.h5', monitor='loss', save_best_only=True)\n# history = model.fit_generator(train_generator, steps_per_epoch=steps, epochs=30, callbacks=[model_checkpoint],\n#                               validation_data=valid_generator, validation_steps=val_steps )\n# 
\n# \n# \n\n# ### Comparing Different Models\n# Let's start by loading up the different history files that were saved for each model, and let's take a look at the loss plot for each epoch.\n\n# In[ ]:\n\n\n# load in history files\nhistory_inceptionv3 = numpy.load('history_inceptionv3.npy')\nhistory_mobilenet = numpy.load('history_mobilenet.npy')\nhistory_vgg16 = numpy.load('history_vgg16.npy')\n\n# let's plot them\nplt.figure(figsize=(6.0, 4.0));\nplt.subplot(121)\nplt.plot(history_inceptionv3.all()['loss'],'b-s')\nplt.plot(history_mobilenet.all()['loss'],'r-s')\nplt.plot(history_vgg16.all()['loss'],'g-s')\nplt.legend(['InceptionV3',\n 'MobileNet',\n 'VGG16'])\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.ylabel('Loss Plot')\n\nplt.subplot(122)\nplt.plot(history_inceptionv3.all()['categorical_accuracy'],'b-s')\nplt.plot(history_mobilenet.all()['categorical_accuracy'],'r-s')\nplt.plot(history_vgg16.all()['categorical_accuracy'],'g-s')\nplt.legend(['InceptionV3',\n 'MobileNet',\n 'VGG16'])\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Accuracy Plot')\nplt.show()\n\n\n# **Question 2:** Which network performs the best? Do you think training is complete after 30 epochs?\n\n# Now let's evaluate some data and see what happens. Let's using the InceptionV3 model and load the existing trained weights:\n\n# In[ ]:\n\n\nfrom keras.applications.inception_v3 import InceptionV3\nmodel_i = InceptionV3(weights='weights_inceptionv3.h5', input_shape=(dims,dims,1), classes=classes)\nmodel_i.compile(loss=\"categorical_crossentropy\", optimizer=optimizers.Adam(lr=1e-4), metrics=[\"categorical_accuracy\"])\n\n\n# Now let's work on testing the model with some data\n\n# In[ ]:\n\n\n# let's set up an ImageDataGenerator for the test data\ntest_folder = os.path.join(os.getcwd(),'test')\ntest_datagen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_datagen.flow_from_directory(valid_folder, batch_size=1, target_size=(dims,dims), class_mode='categorical', color_mode='grayscale')\n\n\n# In[ ]:\n\n\n# get the next image from the generator\nX,Y = test_generator.next()\n\n# visualize the current image\nplt.figure(figsize=(6.0, 4.0))\nplt.imshow(X[0,:,:,0],cmap='gray')\n\nplt.show()\n\n# now predict\ny = model_i.predict(X)\n\n# display the prediction as a printed text message\nactual_type = [key for key in test_generator.class_indices.items() if key[1] == numpy.argmax(Y)][0][0]\npredicted_type = [key for key in test_generator.class_indices.items() if key[1] == numpy.argmax(y)][0][0]\nprint('The actual type was {}, the predicted type was {}'.format(actual_type,predicted_type))\n\n\n# You can re-run the cell above to get the next iteration from the test data generator. Keep running it until you identify several misclassifications of the MRI pulse sequence type.\n\n# **Question 3:** When the network failed to identify the pulse sequence type, what characteristics did you notice in the images? For example, what regions of the brain did the algorithm seem to struggle with identifying? Do you think that you could have done better?\n\n# ### End of Exercise\n# This is the end of this exercise. If you have extra time and would like to try a few advanced ideas, please consider trying the following:\n# 1. Modify the code above to include predictions for MobileNet and VGG16. Perform the analysis on the 3 different networks for each slice. Are failure cases similar between networks?\n# 2. Try re-training the MobileNet network without augmentation. Do you notice any differences?\n# 3. Try adding different types of augmentation, such as left-right and up-down flips. What about adding more extreme degrees of augmentation? Does this improve network performance?\n# 4. Try adding augmentation to the evaluation stage to see how the network performs with augmentation.\n# 5. Explore the other types of available Callback functions during model fitting. There are many useful predefined types of callbacks that you can use to get more information from your network during training. Read more about them here: https://keras.io/callbacks/\n","sub_path":"ImageModalityDetector/MRI_Modality_Detection_SOLUTION.py","file_name":"MRI_Modality_Detection_SOLUTION.py","file_ext":"py","file_size_in_byte":17790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"249059527","text":"#!python3\n\"\"\"\n##### Task 2\nCreate a function called largest.\nThe input is a list.\nThe return value is the largest value in the list\n(2 points)\n\"\"\"\n\ndef largest(n):\n n.sort()\n answer=n[-1]\n return answer\n\nx=largest([3,6,1,4,2])\nprint(x)\n","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"545488411","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport math\nimport unittest\nimport numpy as np\nimport tensorflow as tf\nfrom onnx_tf.backend import run_node\nfrom onnx_tf.common import supports_device\nfrom onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\nfrom onnx import helper\nfrom onnx import TensorProto\nfrom onnx import defs\n\n\nclass TestNode(unittest.TestCase):\n \"\"\" Tests for nodes\n \"\"\"\n\n def _get_rnd(self, shape, low=-1.0, high=1.0):\n return np.random.uniform(low, high, np.prod(shape)) \\\n .reshape(shape) \\\n .astype(np.float32)\n\n def _get_irnd(self, shape):\n return np.arange(np.prod(shape)) \\\n .reshape(shape) \\\n .astype(np.float32)\n\n def _elu(self, x):\n # f(x) = alpha * (exp(x) - 1.) for x < 0,\n # f(x) = x for x >= 0\n if x < 0.:\n return np.expm1(x)\n return x\n\n def _leaky_relu(self, x, alpha):\n # f(x) = alpha * x for x < 0,\n # f(x) = x for x >= 0\n if x < 0.:\n return alpha * x\n return x\n\n def _pooling(self, inputMap, poolSize=3, poolStride=2, mode='max'):\n \"\"\"INPUTS:\n inputMap - input array of the pooling layer\n poolSize - X-size(equivalent to Y-size) of receptive field\n poolStride - the stride size between successive pooling squares\n\n OUTPUTS:\n outputMap - output array of the pooling layer\n\n Padding mode - 'edge'\n \"\"\"\n\n # inputMap sizes\n in_batch, in_channel, in_row, in_col = np.shape(inputMap)\n\n # outputMap sizes\n out_row, out_col = int(np.floor(in_row/poolStride)), int(np.floor(in_col/poolStride))\n row_remainder, col_remainder = np.mod(in_row,poolStride), np.mod(in_col,poolStride)\n if row_remainder != 0:\n out_row +=1\n if col_remainder != 0:\n out_col +=1\n outputMap = np.zeros((in_batch, in_channel, out_row, out_col))\n\n for i in range(0, in_batch):\n for j in range(0, in_channel):\n temp_map = np.lib.pad(inputMap[i][j], ((0,poolSize-row_remainder),(0,poolSize-col_remainder)), 'edge')\n for r_idx in range(0,out_row):\n for c_idx in range(0,out_col):\n startX = c_idx * poolStride\n startY = r_idx * poolStride\n poolField = temp_map[startY:startY + poolSize, startX:startX + poolSize]\n if mode == 'max':\n \tpoolOut = np.max(poolField)\n elif mode == 'average':\n \tpoolOut = np.average(poolField)\n else:\n \tpoolOut = np.min(poolField)\n outputMap[i, j, r_idx,c_idx] = poolOut\n return outputMap\n\n def test_abs(self):\n node_def = helper.make_node(\"Abs\", [\"X\"], [\"Y\"])\n x = self._get_rnd([1000])\n output = run_node(node_def, [x])\n np.testing.assert_almost_equal(output[\"Y\"], np.abs(x))\n\n def test_add(self):\n node_def = helper.make_node(\"Add\", [\"X\", \"Y\"], [\"Z\"])\n x = self._get_rnd([5, 10, 5, 5])\n y = self._get_rnd([10, 1, 1])\n output = run_node(node_def, [x, y])\n np.testing.assert_almost_equal(output[\"Z\"],\n np.add(x, y.reshape([1, 10, 1, 1])))\n\n# def test_average_pool(self):\n# device = \"CUDA\"\n# if not supports_device(device):\n# raise unittest.SkipTest(\n# \"Backend doesn't support device {}\".format(device))\n# shape = [1, 1, 40, 40]\n# node_def = helper.make_node(\n# \"AveragePool\", [\"X\"], [\"Y\"],\n# kernel_shape=[2, 2],\n# pads=[1, 1],\n# strides=[1, 1])\n# x = self._get_rnd(shape)\n# output = run_node(node_def, [x], device=device)\n# test_output = np.zeros(shape)\n# for i1 in range(0, shape[0]):\n# for i2 in range(0, shape[1]):\n# for j1 in range(0, shape[2]):\n# for j2 in range(0, shape[3]):\n# test_output[i1][i2][j1][j2] = 0\n# count = 0\n# for k in range(j2, min(j2 + 2, shape[3])):\n# test_output[i1][i2][j1][j2] += x[i1][i2][j1][k]\n# count += 1\n# test_output[i1][i2][j1][j2] /= count\n# np.testing.assert_almost_equal(output[\"Y\"], test_output)\n\n def test_average_pool(self):\n shape = [1, 1, 5, 5]\n x = self._get_irnd(shape)\n # print(x.shape)\n # print(x)\n test_output = self._pooling(x, 2, 2, 'average')\n # print(test_output.shape)\n # print(test_output)\n return\n\n def _batch_normalization(self, x, mean, variance, bias, scale,\n variance_epsilon):\n inv = np.reciprocal(np.sqrt(variance + variance_epsilon))\n if scale is not None:\n inv *= scale\n return x * inv + (bias - mean * inv if bias is not None else -mean * inv)\n\n def test_batch_normalization(self):\n if legacy_opset_pre_ver(6):\n raise unittest.SkipTest(\"Backend doesn't support consumed flag\")\n node_def = helper.make_node(\n \"BatchNormalization\", [\"X\", \"scale\", \"bias\", \"mean\", \"var\"], [\"Y\"],\n epsilon=0.001)\n x_shape = [3, 5, 4, 2]\n param_shape = [5]\n _param_shape = [1, 5, 1, 1]\n x = self._get_rnd(x_shape, 0, 1)\n m = self._get_rnd(param_shape, 0, 1)\n _m = m.reshape(_param_shape)\n v = self._get_rnd(param_shape, 0, 1)\n _v = v.reshape(_param_shape)\n scale = self._get_rnd(param_shape, 0, 1)\n _scale = scale.reshape(_param_shape)\n bias = self._get_rnd(param_shape, 0, 1)\n _bias = bias.reshape(_param_shape)\n golden = self._batch_normalization(x, _m, _v, _bias, _scale, 0.001)\n output = run_node(node_def, [x, scale, bias, m, v])\n np.testing.assert_almost_equal(output[\"Y\"], golden, decimal=5)\n\n def test_concat(self):\n shape = [10, 20, 5]\n for axis in range(len(shape)):\n node_def = helper.make_node(\"Concat\", [\"X1\", \"X2\"], [\"Y\"], axis=axis)\n x1 = self._get_rnd(shape)\n x2 = self._get_rnd(shape)\n output = run_node(node_def, [x1, x2])\n np.testing.assert_almost_equal(output[\"Y\"], np.concatenate((x1, x2),\n axis))\n def test_conv(self):\n device = \"CUDA\"\n if not supports_device(device):\n raise unittest.SkipTest(\n \"Backend doesn't support device {}\".format(device))\n\n N, C, H, W = 4, 3, 5, 5\n x_shape = [N, C, H, W]\n K, kH, kW = 6, 3, 3\n weight_shape = [K, C, kH, kW]\n node_def = helper.make_node(\n \"Conv\", [\"X\", \"weights\"], [\"Y\"],\n pads=[1, 1, 1, 1],\n kernel_shape=[kH, kW])\n\n x = self._get_rnd(x_shape)\n weights = self._get_rnd(weight_shape)\n output = run_node(node_def, [x, weights], device=device)\n\n out_shape = [N, K, H, W]\n test_output = np.zeros(out_shape)\n for n in range(N):\n for c in range(C):\n for h in range(H):\n for w in range(W):\n for k in range(K):\n for kh in range(kH):\n for kw in range(kW):\n h_in_range = (h - kH // 2 + kh) < H and (\n h - kH // 2 + kh) >= 0\n w_in_range = (w - kW // 2 + kw) < W and (\n w - kW // 2 + kw) >= 0\n if h_in_range and w_in_range:\n test_output[n][k][h][w] += (\n x[n][c][h - kH // 2 + kh][w - kW // 2 + kw] *\n weights[k][c][kh][kw])\n\n np.testing.assert_almost_equal(output[\"Y\"], test_output, decimal=5)\n\n def test_flatten(self):\n # If input tensor has shape (d_0, d_1, ... d_n) then the\n # output will have shape:\n #\n # (d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn)\n #\n # TODO: pass axis attribute which is supported in newer\n # versions of onnx\n node_def = helper.make_node(\"Flatten\", [\"X\"], [\"Y\"])\n x = self._get_rnd([10, 2, 3, 4, 5])\n output = run_node(node_def, [x])\n # TODO: pass axis=3 and uncomment the line below\n # np.testing.assert_almost_equal(output[\"Y\"], x.reshape([60, 20]))\n np.testing.assert_almost_equal(output[\"Y\"], x.reshape([10, 120]))\n\n def test_gemm(self):\n # Compute Y = alpha * A * B + beta * C\n node_def = helper.make_node(\n \"Gemm\", [\"A\", \"B\", \"C\"], [\"Y\"], transA=0, transB=0, alpha=1.0, beta=1.0)\n x = np.floor(self._get_rnd([10, 10]))\n y = np.floor(self._get_rnd([10, 10]))\n z = np.floor(self._get_rnd([10, 10]))\n output = run_node(node_def, [x, y, z])\n test_output = np.matmul(x, y) + z\n np.testing.assert_almost_equal(output[\"Y\"], test_output)\n\n def test_global_average_pool(self):\n # Image case: (N x C x H x W), where N is the batch size,\n # C is the number of channels, and H and W are the height\n # and the width of the data\n #\n # Non-image case: (N x C x D1 x D2 ... Dn)\n #\n # Output data tensor from pooling across the input tensor.\n # Dimensions will be N x C x 1 x 1\n node_def = helper.make_node(\"GlobalAveragePool\", [\"X\"], [\"Y\"])\n x = self._get_rnd([10, 10, 2, 3])\n output = run_node(node_def, [x])\n test_output = np.zeros([10, 10, 1, 1])\n for i1 in range(0, 10):\n for i2 in range(0, 10):\n sum = 0\n for j1 in range(0, 2):\n for j2 in range(0, 3):\n sum += x[i1][i2][j1][j2]\n test_output[i1][i2][0][0] = sum / 6.\n np.testing.assert_almost_equal(output[\"Y\"], test_output)\n\n def test_global_max_pool(self):\n # Image case: (N x C x H x W), where N is the batch size,\n # C is the number of channels, and H and W are the height\n # and the width of the data\n #\n # Non-image case: (N x C x D1 x D2 ... Dn)\n #\n # Output data tensor from pooling across the input tensor.\n # Dimensions will be N x C x 1 x 1\n node_def = helper.make_node(\"GlobalMaxPool\", [\"X\"], [\"Y\"])\n x = self._get_rnd([10, 10, 2, 3])\n output = run_node(node_def, [x])\n test_output = np.zeros([10, 10, 1, 1])\n for i1 in range(0, 10):\n for i2 in range(0, 10):\n max = x[i1][i2][0][0]\n for j1 in range(0, 2):\n for j2 in range(0, 3):\n if max < x[i1][i2][j1][j2]:\n max = x[i1][i2][j1][j2]\n test_output[i1][i2][0][0] = max\n np.testing.assert_almost_equal(output[\"Y\"], test_output)\n\n def test_l_r_n(self):\n # Each input value is divided by:\n #\n # (bias+(alpha/size)*sum(xi^2 for every xi in the local region))^beta\n alpha = 2.0\n beta = 1.0\n bias = 5.0\n size = 3\n node_def = helper.make_node(\n \"LRN\", [\"X\"], [\"Y\"], alpha=alpha, beta=beta, bias=bias, size=size)\n x = self._get_rnd([10, 2, 10, 10])\n output = run_node(node_def, [x])\n test_output = np.zeros([10, 10, 10, 2])\n x = np.transpose(x, axes=[0, 2, 3, 1])\n for i1 in range(0, 10):\n for i2 in range(0, 10):\n for j1 in range(0, 10):\n for j2 in range(0, 2):\n sqr_sum = 0.\n # size of 3 means radius 1 in TF speak\n # i.e. the immediate neighbouring values\n # if \"previous\" neighbour exists\n if j2 > 0:\n sqr_sum += x[i1][i2][j1][j2 - 1] * x[i1][i2][j1][j2 - 1]\n # current value\n sqr_sum += x[i1][i2][j1][j2] * x[i1][i2][j1][j2]\n # if \"next\" neighbour exists\n if j2 < 2 - 1:\n sqr_sum += x[i1][i2][j1][j2 + 1] * x[i1][i2][j1][j2 + 1]\n test_output[i1][i2][j1][j2] = \\\n x[i1][i2][j1][j2] / ((bias + (alpha * 1. / size) * sqr_sum) ** beta)\n test_output = np.transpose(test_output, axes=[0, 3, 1, 2])\n np.testing.assert_almost_equal(output[\"Y\"], test_output)\n\n# def test_max_pool(self):\n# return\n# node_def = helper.make_node(\n# \"MaxPool\", [\"X\"], [\"Y\"],\n# dilations=[1, 1],\n# kernel_shape=[1, 2],\n# pads=[0, 0],\n# strides=[1, 2])\n# x = self._get_rnd([10, 10, 4, 4])\n# output = run_node(node_def, [x])\n# test_output = np.zeros([10, 10, 4, 2])\n# for i1 in range(0, 10):\n# for i2 in range(0, 10):\n# for j1 in range(0, 4):\n# for j2 in range(0, 2):\n# test_output[i1][i2][j1][j2] = \\\n# max(x[i1][i2][j1][2*j2], x[i1][i2][j1][2*j2 + 1])\n# np.testing.assert_almost_equal(output[\"Y\"], test_output)\n\n def test_max_pool(self):\n shape = [1, 1, 5, 5]\n x = self._get_irnd(shape)\n # print(x.shape)\n # print(x)\n test_output = self._pooling(x, 2, 2, 'max')\n # print(test_output.shape)\n # print(test_output)\n return\n\n def test_mul(self):\n node_def = helper.make_node(\"Mul\", [\"X\", \"Y\"], [\"Z\"])\n x = self._get_rnd([5, 10, 5, 5])\n y = self._get_rnd([10, 1, 1])\n output = run_node(node_def, [x, y])\n # output[\"z\"].shape = (5, 10, 5, 5)\n np.testing.assert_almost_equal(output[\"Z\"],\n np.multiply(x, y.reshape([1, 10, 1, 1])))\n\n def test_relu(self):\n node_def = helper.make_node(\"Relu\", [\"X\"], [\"Y\"])\n x = self._get_rnd([1000])\n output = run_node(node_def, [x])\n np.testing.assert_almost_equal(output[\"Y\"], np.maximum(x, 0))\n\n def test_reshape(self):\n x = self._get_rnd(100)\n shape = [10, 10]\n if defs.onnx_opset_version() < 5:\n node_def = helper.make_node(\"Reshape\", [\"X\"], [\"Z\"], shape=shape)\n output = run_node(node_def, [x])\n else:\n node_def = helper.make_node(\"Reshape\", [\"X\", \"Y\"], [\"Z\"])\n output = run_node(node_def, [x, shape])\n\n np.testing.assert_almost_equal(output[\"Z\"], x.reshape([10, 10]))\n\n def test_sum(self):\n node_def = helper.make_node(\"Sum\", [\"X1\", \"X2\", \"X3\", \"X4\"], [\"Z\"])\n x1 = self._get_rnd([10, 10])\n x2 = self._get_rnd([10, 10])\n x3 = self._get_rnd([10, 10])\n x4 = self._get_rnd([10, 10])\n output = run_node(node_def, [x1, x2, x3, x4])\n test_output = x1 + x2 + x3 + x4\n np.testing.assert_almost_equal(output[\"Z\"], test_output)\n\n def test_transpose(self):\n node_def = helper.make_node(\"Transpose\", [\"X\"], [\"Y\"], perm=[0, 2, 1])\n x = self._get_rnd([1000]).reshape([10, 10, 10])\n output = run_node(node_def, [x])\n np.testing.assert_almost_equal(output[\"Y\"], np.transpose(x, (0, 2, 1)))\n\n def test_matmul(self):\n node_def = helper.make_node(\"MatMul\", [\"X\", \"Y\"], [\"Z\"])\n # 2d \n x = self._get_rnd([3, 4])\n y = self._get_rnd([4, 3])\n output = run_node(node_def, [x, y])\n np.testing.assert_almost_equal(output[\"Z\"], np.matmul(x, y))\n\n # 3d \n x = self._get_rnd([2, 3, 4])\n y = self._get_rnd([2, 4, 3])\n output = run_node(node_def, [x, y])\n np.testing.assert_almost_equal(output[\"Z\"], np.matmul(x, y))\n\n # 4d \n x = self._get_rnd([1, 2, 3, 4])\n y = self._get_rnd([1, 2, 4, 3])\n output = run_node(node_def, [x, y])\n np.testing.assert_almost_equal(output[\"Z\"], np.matmul(x, y))\n\n def test_softmax(self):\n node_def = helper.make_node(\"Softmax\", [\"X\"], [\"Y\"])\n x = np.array([[-1, 0, 1]]).astype(np.float32)\n # expected output [[0.09003058, 0.24472848, 0.66524094]]\n y = np.exp(x) / np.sum(np.exp(x), axis=1)\n output = run_node(node_def, [x])\n np.testing.assert_almost_equal(output[\"Y\"], y)\n\n def test_squeeze(self):\n node_def = helper.make_node(\"Squeeze\", [\"X\"], [\"Y\"], axes=[2])\n x = np.array([[[0], [1], [2]]])\n output = run_node(node_def, [x])\n np.testing.assert_almost_equal(output[\"Y\"], np.squeeze(x, axis=2))\n\n def test_unsqueeze(self):\n node_def = helper.make_node(\"Unsqueeze\", [\"X\"], [\"Y\"], axes=[0])\n x = np.random.randn(3, 4, 5).astype(np.float32)\n y = np.expand_dims(x, axis=0)\n output = run_node(node_def, [x])\n np.testing.assert_almost_equal(output[\"Y\"], y)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/backend/test_node_study.py","file_name":"test_node_study.py","file_ext":"py","file_size_in_byte":15471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"633591618","text":"#!/usr/bin/python3\nfrom sofabase3 import log_setup, SofaBase, SofaConfig, AlexaDevice\nfrom controllers import EndpointHealth, ForecastModeController, ForecastHighRangeController, ForecastLowRangeController, TemperatureSensor\n\nimport sys, os\nimport math\nimport random\nimport json\nimport asyncio\nimport aiohttp\nimport datetime\nimport re\nfrom definitions import RainMachineDefinitions\n\nlogger = log_setup(\"rainmachine\", level=\"INFO\")\n\nclass RainMachine(SofaBase):\n\n def add_adapter_fields(self):\n SofaConfig.add('device_password', mandatory=True)\n SofaConfig.add('device_address', mandatory=True)\n SofaConfig.add('device_port', default=8080)\n \n \n async def pre_activate(self):\n #self.sofa.dataset.nativeDevices['zones']=[]\n #self.sofa.dataset.nativeDevices['machines']=[]\n self.polltime=30 \n self.access_token = await self.get_auth_token()\n await self.update_provision()\n await self.get_api('dailystats')\n await self.get_zones()\n self.loop.create_task(self.pollRainMachine())\n \n \n async def pollRainMachine(self):\n while True:\n try:\n await self.update_data()\n except:\n logger.error('Error fetching Rain Machine Data', exc_info=True)\n \n await asyncio.sleep(self.polltime)\n\n async def update_provision(self):\n try:\n response=await self.get_api('/provision')\n self.device_name=response['system']['netName']\n await self.sofa.dataset.ingest( { \"machines\": { self.device_name: { \"name\": self.device_name, \"provision\": response }}} )\n except:\n logger.error('!! Error getting updated lcoation data from rain machine', exc_info=True)\n\n \n async def update_data(self):\n try:\n response=await self.get_api('/mixer/%s' % datetime.datetime.now().strftime(\"%Y-%m-%d\"))\n if 'statusCode' in response:\n if response['statusCode']==2 or response['message']=='Not Authenticated !':\n logger.info('.. Token expired. Refreshing token and retrying.')\n self.access_token=await self.get_auth_token()\n response=await self.get_api('/mixer/%s' % datetime.datetime.now().strftime(\"%Y-%m-%d\"))\n \n await self.sofa.dataset.ingest({ \"machines\": { self.device_name: { \"weather\" : await self.parse_mixer(response) }}} )\n\n except:\n logger.error('!! Error getting updated data from rain machine', exc_info=True)\n \n async def parse_mixer(self, data):\n try:\n weatherdata=data['mixerDataByDate'][0]\n weatherdata['conditionName']=RainMachineDefinitions.conditions[int(weatherdata['condition'])]\n for item in weatherdata:\n if item in ['temperature','minTemp','maxTemp']:\n weatherdata[item]=(int(weatherdata[item]) * 9/5) + 32\n #await self.sofa.dataset.ingest({ \"weather\" : weatherdata })\n return weatherdata\n except:\n logger.error('!! error ingesting weather data: %s' % data, exc_info=True)\n return {}\n \n async def get_zones(self):\n try:\n zonedata=await self.get_api('zone')\n await self.sofa.dataset.ingest(zonedata)\n for zone in zonedata['zones']:\n if zone['active']:\n await self.sofa.dataset.ingest({ \"machines\": { self.device_name: { \"zones\": { \"zone-%s\" % str(zone['uid']) : zone }}}})\n logger.info('Zone: %s %s' % (zone['name'],zone))\n except:\n logger.error('Error getting zones', exc_info=True) \n \n async def get_auth_token(self):\n try:\n data=json.dumps({\"pwd\": SofaConfig.device_password})\n url=\"https://%s:%s/api/4/auth/login\" % (SofaConfig.device_address, SofaConfig.device_port)\n headers={}\n #headers = { \"Content-type\": \"text/xml\" }\n async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as client:\n response=await client.post(url, data=data, headers=headers)\n result=await response.read()\n result=json.loads(result.decode())\n self.tokendata=result\n \n return self.tokendata[\"access_token\"]\n except:\n logger.error('Error getting auth token', exc_info=True)\n \n async def get_api(self, api_command):\n \n try:\n url=\"https://%s:%s/api/4/%s?access_token=%s\" % (SofaConfig.device_address, SofaConfig.device_port, api_command, self.access_token)\n async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as client:\n async with client.get(url) as response:\n status=response.status\n result=await response.text()\n #logger.info('result: %s' % result)\n \n if result:\n return json.loads(result)\n \n logger.warn('.! No Result returned') \n return {}\n\n except:\n logger.error(\"Error requesting state for %s\" % target, exc_info=True)\n return {}\n \n\n\n # Adapter Overlays that will be called from dataset\n async def add_sofa_device(self, endpointId, path):\n \n try:\n device_id=path.split(\"/\")[2]\n device_type=path.split(\"/\")[1]\n if device_type==\"machines\":\n nativeObject=self.sofa.dataset.nativeDevices[device_type][device_id]\n return await self.add_machine(device_id, nativeObject)\n except:\n logger.error('Error defining smart device', exc_info=True)\n return False\n\n\n async def add_machine(self, deviceid, nativeObject):\n try:\n if 'weather' in nativeObject: # shim right now to wait for first weather update\n logger.info('~~ Adding %s %s' % (deviceid, nativeObject))\n device = AlexaDevice('rainmachine/machines/%s' % deviceid, \"Rainmachine\", displayCategories=['OTHER'], adapter=self)\n device.ForecastHighRangeController = ForecastHighRangeController(\"Forecast High\",device=device, supportedRangePrecision=1, supportedRange=[0,120], nonControllable=True)\n device.ForecastLowRangeController = ForecastLowRangeController(\"Forecast Low\",device=device, supportedRangePrecision=1, supportedRange=[0,120], nonControllable=True)\n modes={}\n for mode in RainMachineDefinitions.conditions:\n modes[mode]=self.camel_spaces(mode)\n device.ForecastModeController = ForecastModeController('Weather Condition', device=device, supportedModes=modes, nonControllable=True)\n #device.TemperatureSensor=rainmachine.TemperatureSensor(device=device)\n device.EndpointHealth = EndpointHealth(device=device)\n return self.sofa.dataset.add_device(device)\n except:\n logger.error('!! Error defining smart device', exc_info=True)\n return False\n\n\n def camel_spaces(self, str1):\n return re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", str1) \n\n async def executePost(self, target, command, data=\"\"):\n \n try:\n url=self.targets[target][command]\n headers = { \"Content-type\": \"text/xml\" }\n async with aiohttp.ClientSession() as client:\n response=await client.post(url, data=data, headers=headers)\n result=await response.read()\n result=json.loads(result.decode())\n logger.info('Post result: %s' % result)\n return result\n \n logger.warn('.! No Result returned') \n return {}\n\n except:\n logger.error(\"Error requesting state for %s\" % endpointId,exc_info=True)\n return {}\n\n async def executeGet(self, target, command):\n \n try:\n url=self.targets[target][command]\n async with aiohttp.ClientSession() as client:\n async with client.get(url) as response:\n status=response.status\n result=await response.text()\n \n if result:\n await self.sofa.dataset.ingest({\"target\": { target : { \"status\": command==\"on\" }}})\n logger.info('.. Get result: %s' % result)\n return result\n \n logger.warn('.! No Result returned') \n return {}\n\n except:\n logger.error(\"Error requesting state for %s\" % target, exc_info=True)\n return {}\n\n\n\n async def processDirective(self, endpointId, controller, command, payload, correlationToken='', cookie={}):\n\n try:\n device=endpointId.split(\":\")[2]\n\n if controller==\"PowerController\":\n if command=='TurnOn':\n response=await self.executeGet(device, 'on')\n elif command=='TurnOff':\n response=await self.executeGet(device, 'off')\n\n response=await self.sofa.dataset.generateResponse(endpointId, correlationToken) \n return response\n except:\n logger.error('Error executing state change.', exc_info=True)\n\n\n def virtualControllers(self, itempath):\n\n try:\n nativeObject=self.sofa.dataset.getObjectFromPath(self.sofa.dataset.getObjectPath(itempath))\n logger.debug('Checking object for controllers: %s' % nativeObject)\n \n try:\n detail=itempath.split(\"/\",3)[3]\n except:\n detail=\"\"\n\n controllerlist={}\n if detail==\"on\" or detail==\"\":\n controllerlist[\"PowerController\"]=[\"powerState\"]\n\n return controllerlist\n except KeyError:\n pass\n except:\n logger.error('Error getting virtual controller types for %s' % itempath, exc_info=True)\n\n\n def virtualControllerProperty(self, nativeObj, controllerProp):\n \n try:\n if controllerProp=='powerState':\n return \"ON\" if nativeObj['status'] else \"OFF\"\n else:\n logger.info('Unknown controller property mapping: %s' % controllerProp)\n return {}\n except:\n logger.error('Error converting virtual controller property: %s %s' % (controllerProp, nativeObj), exc_info=True)\n \n \nif __name__ == '__main__':\n adapter = RainMachine(name='rainmachine')\n adapter.start()\n","sub_path":"rainmachine.py","file_name":"rainmachine.py","file_ext":"py","file_size_in_byte":10756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"234827692","text":"import asyncio\nimport logging\nimport os\nfrom otree.database import save_sqlite_db\nfrom .base import BaseCommand\nimport sys\nimport subprocess\n\nlogger = logging.getLogger(__name__)\n\n\ndef run_asgi_server(addr, port, *, is_devserver=False):\n run_uvicorn(addr, port, is_devserver=is_devserver)\n\n\ndef run_uvicorn(addr, port, *, is_devserver):\n from uvicorn.main import Config, Server\n\n class OTreeUvicornServer(Server):\n def __init__(self, config, *, is_devserver):\n self.is_devserver = is_devserver\n super().__init__(config)\n\n def handle_exit(self, sig, frame):\n if self.is_devserver:\n save_sqlite_db()\n return super().handle_exit(sig, frame)\n\n config = Config(\n 'otree.asgi:app',\n host=addr,\n port=int(port),\n log_level='warning' if is_devserver else \"info\",\n log_config=None, # oTree has its own logger\n # i suspect it was defaulting to something else\n workers=1,\n # websockets library handles disconnects & ping automatically,\n # so we can simplify code and also avoid H15 errors on heroku.\n ws='websockets',\n # ws='wsproto',\n )\n server = OTreeUvicornServer(config=config, is_devserver=is_devserver)\n server.run()\n\n\ndef get_addr_port(cli_addrport, is_devserver=False):\n default_addr = '127.0.0.1' if is_devserver else '0.0.0.0'\n default_port = os.environ.get('PORT') or 8000\n if not cli_addrport:\n return default_addr, default_port\n parts = cli_addrport.split(':')\n if len(parts) == 1:\n return default_addr, parts[0]\n return parts\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument(\n 'addrport', nargs='?', help='Optional port number, or ipaddr:port'\n )\n\n def handle(self, *args, addrport=None, verbosity=1, **kwargs):\n addr, port = get_addr_port(addrport)\n subprocess.Popen(\n ['otree', 'timeoutsubprocess', str(port)], env=os.environ.copy()\n )\n run_asgi_server(addr, port)\n","sub_path":"otree/cli/prodserver1of2.py","file_name":"prodserver1of2.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"537677844","text":"from __future__ import division\nimport os\nimport subprocess\nimport time\nimport random as rand\nfrom scipy.sparse import csr_matrix as sparsify\nimport shutil\nfrom Bio import pairwise2\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\nimport numpy as np\n\nfrom sca.tools import log\nfrom sca.tools.decorators import time_this\n\n\n# @time_this\ndef search_msa(headers, alignment_sequences, reference_sequence, species=None, path2_algprog=None):\n '''\n Identify the sequence in the alignment that most closely corresponds to the species of the reference sequence,\n and return its index.\n\n **Arguments:**\n - sequence alignment headers\n - alignment sequences\n - selected reference sequence (often from a PDB file)\n\n **Keyword Arguments:**\n - `species` = species of the reference sequence (Used to speed up alignment searching when possible)\n - `path2_algprog` = path to an alignment program\n\n **Example:**\n >>> strseqnum = MSASearch(headers, alg0, pdbseq, 'Homo sapiens')\n '''\n if path2_algprog is None:\n raise ValueError('No path provided for EMBOSS program')\n key_list = list()\n if species is not None:\n species = species.lower()\n for (i, h) in enumerate(headers):\n if species in h.lower():\n key_list.append(i)\n headers = [headers[k] for k in key_list]\n alignment_sequences = [alignment_sequences[k] for k in key_list]\n\n try:\n # log.info('Trying MSASearch with ggsearch')\n if not os.path.exists('tmp/'):\n os.makedirs('tmp/')\n output_handle = open('tmp/PDB_seq.fasta', 'w')\n SeqIO.write(SeqRecord(Seq(reference_sequence), id='PDB sequence'), output_handle, \"fasta\")\n output_handle.close()\n f = open(\"tmp/algn_seq.fasta\", \"w\")\n for i in range(len(alignment_sequences)):\n f.write(\">\" + headers[i] + \"\\n\")\n f.write(alignment_sequences[i] + \"\\n\")\n f.close()\n args = ['ggsearch36' ,'-M 1- ' + str(len(alignment_sequences[0])) , '-b' , '1' , '-m 8' , 'tmp/PDB_seq.fasta' , 'tmp/algn_seq.fasta']\n try:\n output = subprocess.check_output(args)\n except Exception as err:\n # log.debug('Failed to run ggsearch')\n # log.debug(err)\n raise err\n i_0 = [i for i in range(len(headers)) if output.split('\\t')[1] in headers[i]]\n if species is not None:\n strseqnum = key_list[i_0[0]]\n else:\n strseqnum = i_0[0]\n shutil.rmtree('tmp')\n return strseqnum\n except:\n try:\n from Bio.Emboss.Applications import NeedleCommandline\n # log.info('Trying MSASearch with EMBOSS')\n output_handle = open('tmp/PDB_seq.fasta', 'w')\n SeqIO.write(SeqRecord(Seq(reference_sequence), id='PDB sequence'), output_handle, \"fasta\")\n output_handle.close()\n output_handle = open(\"tmp/algn_seq.fasta\", \"w\")\n s_records = list()\n for k in range(len(alignment_sequences)):\n s_records.append(SeqRecord(Seq(alignment_sequences[k]), id=str(k), description=headers[k]))\n SeqIO.write(s_records, output_handle, \"fasta\")\n output_handle.close()\n needle_cline = NeedleCommandline(os.path.join(path2_algprog, \"needle\"), asequence=\"tmp/PDB_seq.fasta\",\n bsequence=\"tmp/algn_seq.fasta\", gapopen=10, gapextend=0.5,\n outfile=\"tmp/needle.txt\")\n try:\n stdout, stderr = needle_cline()\n except Exception as err:\n # log.debug('Failed to run EMBOSS')\n # log.debug(err)\n raise err\n # log.info(stdout + stderr)\n algres = open('tmp/needle.txt', 'r').readlines()\n score = list()\n for k in algres:\n if (k.find('Identity: ') > 0):\n score.append(int(k.split()[2].split('/')[0]))\n i_0 = score.index(max(score))\n if species is not None:\n strseqnum = key_list[i_0]\n else:\n strseqnum = i_0\n shutil.rmtree('tmp')\n return strseqnum\n except:\n # log.info('Trying MSASearch with BioPython')\n score = list()\n try:\n for k, s in enumerate(alignment_sequences):\n score.append(pairwise2.align.globalxx(alignment_sequences, s, one_alignment_only=1, score_only=1))\n except Exception as err:\n # log.debug('Failed to run with BioPython')\n # log.debug(err)\n # log.debug('Options for search_msa exhausted, removing dir tmp')\n shutil.rmtree('tmp')\n raise err\n i_0 = score.index(max(score))\n if species is not None:\n strseqnum = key_list[i_0]\n else:\n strseqnum = i_0\n # log.info(\"BP strseqnum is %i\" % strseqnum)\n return strseqnum\n\n\n# @time_this\ndef sequence_similarities(numeric_alignment):\n ''' Take an MxL alignment (converted to numeric representation using lett2num_)\n and compute a MxM matrix of sequence similarities.\n\n :Example:\n >>> simMat = sequence_similarities(numeric_alignment)\n\n '''\n # Get the number of sequences and number of positions:\n [Nseq, Npos] = numeric_alignment.shape\n # Convert into a M*(20L) (sparse) binary array:\n X2d = alignment_to_binary(numeric_alignment)\n # Make the product with sparse matrices and convert it back to a dense array:\n simMat = (X2d.dot(X2d.T)).todense() / Npos\n return simMat\n\n\ndef parse_fasta(file_path, progress=None):\n \"\"\"Read in a multiple sequence alignment in fasta format, and return the\n headers and sequences.\n\n >>> headers, sequences = parse_fasta(file_path)\n \"\"\"\n with open(file_path, 'r') as fasta:\n file_lines = fasta.readlines()\n _, file_name = os.path.split(file_path)\n headers = list()\n sequences = list()\n not_first = 0\n if progress is not None:\n with progress(file_lines, label=f'Parsing alignment file: {file_name}') as bar:\n for line in bar:\n if line[0] == '>':\n if not_first > 0:\n sequences.append(seq.replace('\\n', '').upper())\n headers.append(line[1:].replace('\\n', ''))\n seq = ''\n not_first = 1\n elif line != '\\n':\n seq += line\n else:\n for line in file_lines:\n if line[0] == '>':\n if not_first > 0:\n sequences.append(seq.replace('\\n', '').upper())\n headers.append(line[1:].replace('\\n', ''))\n seq = ''\n not_first = 1\n elif line != '\\n':\n seq += line\n sequences.append(seq.replace('\\n', '').upper())\n return headers, sequences\n\n\n# @time_this\ndef annotate_pfam(pfam_in, pfam_out, pfam_seq=None):\n ''' Phylogenetic annotation of a Pfam alignment (in fasta format) using information from pfamseq.txt. The output is\n a fasta file containing phylogenetic annotations in the header (to be parsed with '|' as a delimiter).\n\n Note: the headers for the original alignment take the form >AAA/x-y. If two entries have same AAA but correspond to\n different sequences only one of the two sequences will be represented (twice) in the output - this should however\n not practically be an issue.\n\n :Arguments:\n - input PFAM sequence alignment\n - output file name for the annotated PFAM alignment\n\n :Keyword Arguments:\n - `pfam_seq` = path to the file pfamseq.txt\n\n '''\n if pfam_seq is None:\n raise ValueError('Need to pass pfam_seq')\n start_time = time.time()\n # log.info('Beginning annotation')\n # Reads the pfam headers and sequences:\n headers, sequences = parse_fasta(pfam_in)\n pfamseq_ids = [h.split('/')[0] for h in headers]\n # Reads the sequence information for those sequences:\n seq_info = dict()\n with open(pfam_seq) as fp:\n for line in fp:\n pf_id = line.split('\\t')[1]\n if pf_id in pfamseq_ids:\n seq_info[pf_id] = line\n pfamseq_ids.remove(pf_id)\n end_time = time.time()\n # Writes in output file:\n f = open(pfam_out ,'w')\n pfamseq_ids = [h.split('/')[0] for h in headers]\n for i, key in enumerate(pfamseq_ids):\n # log.info('Current step %i, key %s' % (i, key))\n try:\n info = seq_info[key]\n except:\n info = '\\t'.join(['unknown' ] *10 + ['unknown;unknown'])\n # this f.write line works with older pfamseq.txt files (release 4 and before, was\n # used to annotate the tutorial alignments\n # f.write('>%s|%s|%s|%s\\n' % (key, info.split('\\t')[6], info.split('\\t')[9],\\\n # ','.join([name.strip() for name in info.split('\\t')[10].split(';')])))\n # this f.write line works with the new version of pfamseq.txt\n f.write('>%s|%s|%s|%s\\n' % (key, info.split('\\t')[5], info.split('\\t')[8], \\\n ','.join([name.strip() for name in info.split('\\t')[9].split(';')])))\n f.write('%s\\n' % (sequences[i]))\n f.close()\n # log.info('Elapsed time: %.1f min' % ((end_time -start_time ) /60))\n\n\n# @time_this\ndef choose_reference_sequence(sequence_alignment):\n \"\"\"This function chooses a default reference sequence if none is given by taking the\n sequence which has the mean pairwise sequence identity closest to that of the entire alignment.\n\n :Example:\n >>> i_ref = choose_reference_sequence(sequence_alignment)\n \"\"\"\n # log.debug('choose_reference_sequence')\n if len(sequence_alignment) > 1000:\n seqw = sequence_weights(sequence_alignment)\n keep_seq = random_selection(seqw, 1000)\n else:\n keep_seq = [k for k in range(len(sequence_alignment))]\n new_alignment = [sequence_alignment[k] for k in keep_seq]\n numeric_alignment = lett2num(new_alignment)\n similarity_matrix = sequence_similarities(numeric_alignment)\n listS = [similarity_matrix[i, j] for i in range(similarity_matrix.shape[0])\n for j in range(i + 1, similarity_matrix.shape[1])]\n meanSID = list()\n for k in range(len(similarity_matrix)):\n meanSID.append(similarity_matrix[k].mean())\n mean_difference = abs(meanSID - np.mean(listS))\n strseqnum = [i for i, k in enumerate(mean_difference) if k == min(mean_difference)]\n # TODO: why?\n # ix = keep_seq[strseqnum[0]]\n return strseqnum[0]\n\n\n# @time_this\ndef make_ats(sequences, refpos, refseq, iref=0, do_truncate=False):\n '''If specified, do_truncate the alignment to the structure (assumes MSAsearch_ has already been run to identify the\n reference sequence (iref)) and produce a mapping (ats) between alignment positions and the positions in the\n reference sequence (refpos).\n\n .. _MSAsearch: tools.html#tools.search_msa\n\n **Arguments:**\n - sequences\n - reference positions\n - reference sequence\n - iref, the index of the sequence in the alignment with the highest identity to the reference\n\n :Keyword Arguments:\n do_truncate -- do_truncate the alignment to positions that align to the reference sequence.\n\n :Example:\n >>> sequences_trun, ats_new = sca.make_ats(sequences_full, ats_pdb, seq_pdb, i_ref)\n\n '''\n if do_truncate:\n # log.info('Truncating to reference sequence')\n # Removing gaps:\n pos_ref = [i for i, a in enumerate(refseq) if a != '-']\n seq_ref = ''.join([refseq[i] for i in pos_ref])\n ats_ref = [refpos[i] for i in pos_ref]\n pos_alg = [i for i, a in enumerate(sequences[iref]) if a != '-']\n seq_tr = [''.join([sq[i] for i in pos_alg]) for sq in sequences]\n # Positions to keep in the alignment and pbd sequences\n # (no gap in any of them after co-alignment):\n seqal_ref, seqal_alg, _, _, _ = pairwise2.align.globalms(seq_ref, seq_tr[iref], \\\n 2, -1, -.5, -.1)[0]\n keep_ref, keep_alg = list(), list()\n j_ref, j_alg = 0, 0\n for i in range(len(seqal_ref)):\n if seqal_ref[i] != '-' and seqal_alg[i] != '-':\n keep_ref.append(j_ref)\n keep_alg.append(j_alg)\n if seqal_ref[i] != '-': j_ref += 1\n if seqal_alg[i] != '-': j_alg += 1\n sequences_out = [''.join([sq[i] for i in keep_alg]) for sq in seq_tr]\n ats_out = [ats_ref[i] for i in keep_ref]\n else:\n tmp = sequences[iref].replace('-', '.')\n refseq = refseq.replace('-', '');\n seqal_ref, seqal_alg, _, _, _ = pairwise2.align.globalms(refseq, tmp, \\\n 2, -1, -.5, -.1)[0]\n # log.info('Len refseq %i, len refpos %i, Len alg seq %i, len pairalg %i, len gloalg %i'\n # % (len(refseq), len(refpos), len(tmp), len(seqal_alg), len(sequences[0])))\n # print seqal_ref\n # print seqal_alg\n ats_out = list()\n j_ref = 0\n j_pdb = 0\n for i in range(len(seqal_alg)):\n if seqal_alg[i] == '.' and seqal_ref[i] == '-':\n ats_out.insert(j_ref, '-')\n j_ref += 1\n elif seqal_alg[i] != '.' and seqal_alg[i] != '-':\n if seqal_ref[i] != '-':\n ats_out.insert(j_ref, refpos[j_pdb])\n j_ref += 1\n j_pdb += 1\n else:\n ats_out.insert(j_ref, '-')\n j_ref += 1\n elif seqal_alg[i] == '.' and seqal_ref[i] != '-':\n ats_out.insert(j_ref, refpos[j_pdb])\n j_ref += 1\n j_pdb += 1\n elif seqal_alg[i] == '-':\n j_pdb += 1\n sequences_out = sequences\n return sequences_out, ats_out\n\n\n# @time_this\ndef lett2num(msa_lett, code='ACDEFGHIKLMNPQRSTVWY'):\n ''' Translate an alignment from a representation where the 20 natural amino\n acids are represented by letters to a representation where they are\n represented by the numbers 1,...,20, with any symbol not corresponding to an\n amino acid represented by 0.\n\n :Example:\n >>> msa_num = lett2num(msa_lett, code='ACDEFGHIKLMNPQRSTVWY')\n\n '''\n lett2index = {aa: i + 1 for i, aa in enumerate(code)}\n [Nseq, Npos] = [len(msa_lett), len(msa_lett[0])]\n msa_num = np.zeros((Nseq, Npos)).astype(int)\n for s, seq in enumerate(msa_lett):\n for i, lett in enumerate(seq):\n if lett in code:\n msa_num[s, i] = lett2index[lett]\n return msa_num\n\n\n# @time_this\ndef alignment_to_binary(alg, N_aa=20):\n ''' Translate an alignment of size M x L where the amino acids are represented\n by numbers between 0 and N_aa (obtained using lett2num) to a sparse binary\n array of size M x (N_aa x L).\n\n :Example:\n >>> Abin = alignment_to_binary(alg, N_aa=20) '''\n N_seq, N_pos = alg.shape\n Abin_tens = np.zeros((N_aa, N_pos, N_seq))\n for ia in range(N_aa):\n Abin_tens[ia, :, :] = (alg == ia + 1).T\n Abin = sparsify(Abin_tens.reshape(N_aa * N_pos, N_seq, order='F').T)\n return Abin\n\n\n# @time_this\ndef sequence_weights(sequence_alignment, max_seqid=.8, gaps=1):\n ''' Compute sequence weights for an alignment (format: list of sequences)\n where the weight of a sequence is the inverse of the number of sequences in\n its neighborhood, defined as the sequences with sequence similarity below\n max_seqid. The sum of the weights defines an effective number of sequences.\n\n **Arguments:**\n - `sequence_alignment` = list of sequences\n\n **Keyword Arguments:**\n - `max_seqid`\n - `gaps` = If gaps == 1 (default), considering gaps as a 21st amino acid, if gaps == 0, not considering them.\n\n :Example:\n >>> seqw = sequence_weights(sequence_alignment)\n\n '''\n codeaa = 'ACDEFGHIKLMNPQRSTVWY'\n if gaps == 1:\n codeaa += '-'\n msa_num = lett2num(sequence_alignment, code=codeaa)\n X2d = alignment_to_binary(msa_num, N_aa=len(codeaa))\n simMat = (X2d.dot(X2d.T)).todense() / msa_num.shape[1]\n seqw = np.array(1 / (simMat > max_seqid).sum(axis=0))\n return seqw\n\n\n# TODO: two usages in processMSA, make sure they're mutually exclusive\n# @time_this\ndef filter_sequence(alg0, sref=0.5, max_fracgaps=.2, min_seqid=.2, max_seqid=.8):\n \"\"\"Take in an alignment (alg0, assumed to be filtered to remove highly gapped positions),\n a reference sequence, the maximum fraction of gaps allowed per sequence (max_fracgaps),\n the minimum and maximum sequence identities to the reference sequence (min_seqid\n and max_seqid), and return\n (1) alg, the alignment filtered to remove sequences with more than max_fracgaps\n (i.e. partial seqs),\n (2) seqw, a vector of weights for each sequence,\n (3) seqkeep, the indices of the original alignment (alg0) retained in alg:\n\n **Note:** if sref is set to 0.5, filterSeq calls chooseRefSeq_ to automatically select a\n reference sequence.\n\n .. _chooseRefSeq: tools.html#tools.choose_reference_sequence\n\n **Example:**\n >>> alg, seqw, seqkeep = filter_sequence(alg0, iref, max_fracgaps=.2, min_seqid=.2, max_seqid=.8)\n\n \"\"\"\n if sref == 0.5:\n # log.info('choose reference sequence from filter sequence')\n sref = choose_reference_sequence(alg0)\n Nseq, Npos = len(alg0), len(alg0[0])\n\n # Elimination of sequences with too many gaps:\n seqkeep0 = [s for s in range(Nseq) if alg0[s].count('-') / Npos < max_fracgaps]\n # log.info('Keeping %i sequences of %i sequences (after filtering for gaps)' % (len(seqkeep0), Nseq))\n\n # Elimination of sequences too dissimilar to the reference (trimming):\n # TODO: overly complicated line. write into a standalone helper function\n seqkeep = [s for s in seqkeep0 if sum([alg0[s][i] == alg0[sref][i] for i in range(Npos)]) / Npos > min_seqid]\n # log.info(\n # 'Keeping %i sequences of %i sequences (after filtering for seq similarity)' % (len(seqkeep), len(seqkeep0)))\n alg = [alg0[s] for s in seqkeep]\n\n # Sequence weights (smoothing, here effectively treats gaps as a 21st amino acid):\n # TODO: what? why?\n # msa_num = lett2num(alg)\n seqw = sequence_weights(alg, max_seqid)\n return alg, seqw, seqkeep\n\n\n# TODO: paper specifies max_fracgaps is 0.4, why did it change?\n# @time_this\ndef truncate_alignments(alignment_sequences, sequence_weights=[1], max_fracgaps=.2):\n \"\"\"Truncate the positions of an input alignment to reduce gaps, taking into account sequence weights.\n\n **Arguments:**\n - `alignment_sequences` = An MxL list of sequences\n\n **Keyword Arguments:**\n - `sequence_weights` = vector of sequence weights (default is uniform weights)\n - `max_fracgaps` = maximum fraction of gaps allowed at a position\n\n **Returns:**\n - `truncated_alignment` = the truncated alignment\n - `selected_positions` = the index of retained positions (indices start at 0 for the first position)\n\n :Example:\n >>> truncated_alignment, selected_positions = truncate_alignments(alignment_sequences, sequence_weights, max_fracgaps=.2)\n\n \"\"\"\n num_sequences, num_positions = len(alignment_sequences), len(alignment_sequences[0])\n # log.debug(f'truncating alignments of num_seq: {num_sequences}, num_pos: {num_positions}')\n if len(sequence_weights) == 1:\n sequence_weights = np.tile(1, (1, num_sequences))\n\n # Fraction of gaps, taking into account sequence weights:\n gaps_matrix = np.array([[int(alignment_sequences[s][i] == '-')\n for i in range(num_positions)] for s in range(num_sequences)])\n\n norm_sequence_weights = sequence_weights / sequence_weights.sum()\n gaps_per_position = norm_sequence_weights.dot(gaps_matrix)[0]\n\n # Selected positions:\n selected_positions = [i for i in range(num_positions) if gaps_per_position[i] < max_fracgaps]\n\n # Truncation:\n truncated_alignment = [''.join([alignment_sequences[s][i] for i in selected_positions]) for s in range(num_sequences)]\n return truncated_alignment, selected_positions\n\n\n# @time_this\ndef random_selection(seqw, Mtot, keepSeq=[]):\n ''' Random selection of Mtot sequences, drawn with weights and without replacement.\n The seed for the random number generator is fixed to ensure reproducibility.\n\n **Arguments:**\n - `seqw` = the sequence weights\n - `Mtot` = the total number of sequences for selection\n\n **Keyword Arguments:**\n - `keepSeq` = an (optional) list of sequnces to keep. This can be useful if you would like to\n retain the reference sequence for example.\n\n :Example:\n >>> selection = random_selection(seqw, Mtot, [iref])\n '''\n rand.seed(0)\n return weighted_rand_list(seqw[0], Mtot, keepSeq)\n\n\n# @time_this\ndef weighted_rand_list(weights, Nmax, keepList):\n ''' Generate a random list of at most Nmax elements with weights (numpy array) but\n without replacement. Called by randSel_.\n\n .. _randSel: tools.html#tools.random_selection\n\n :Example:\n >>> selection = weighted_rand_list(weights, Nmax, [iref])\n\n '''\n Ntot = min((weights > 0).sum(), Nmax)\n wlist = [w for w in weights]\n selection = list()\n for k in keepList:\n selection.append(k)\n wlist[k] = 0\n Ntot -= 1\n for k in range(Ntot):\n i = weighted_rand_sel(wlist)\n selection.append(i)\n wlist[i] = 0\n return selection\n\n\n# @time_this\ndef weighted_rand_sel(weights):\n ''' Generate a random index with probability given by input weights.\n Called by weighted_rand_list_.\n\n .. _weighted_rand_list: tools.html#tools.weighted_rand_list\n\n :Example:\n >>> index = weighted_rand_sel(weights)\n\n '''\n rnd = rand.random() * sum(weights)\n for i, w in enumerate(weights):\n rnd -= w\n if rnd < 0:\n return i\n\n\n\n# TODO: this function isn't used anywhere....\n# @time_this\ndef clean_alignment(sequence_alignment, code='ACDEFGHIKLMNPQRSTVWY', gap='-'):\n ''' Replaces any character that is not a valid amino acid by a gap.\n\n :Arguments: amino acid sequence alignment\n\n :Keyword Arguments:\n - `code` = list of valid amino acid characters (case sensitive)\n - `gap` = gap character for replacement\n '''\n cleaned = list()\n for sequence in sequence_alignment:\n clean_sequence = ''\n for amino_index in range(len(sequence)):\n if code.find(sequence[amino_index]) != -1:\n clean_sequence += sequence[amino_index]\n else:\n clean_sequence += gap\n cleaned.append(clean_sequence)\n return cleaned","sub_path":"sca/tools/alignment_processing.py","file_name":"alignment_processing.py","file_ext":"py","file_size_in_byte":23085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"226235135","text":"# Copyright 2018 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Module to enforce authentication on endpoints.method.\n\nUsage:\n-----\n # configuration of an endpoints method with enforced user auth check only.\n@loaner_endpoints.authed_method(\n chrome_message.ChromeRequest,\n chrome_message.ChromeResponse,\n name='heartbeat',\n path='heartbeat',\n http_method='GET',\n user_auth_only=True)\ndef do_something(self, request):\n ...\n\nThe above method will execute if the current user is authenticated properly.\n\n # configuration of an endpoints method with enforced permission.\n@loaner_endpoints.authed_method(\n chrome_message.ChromeRequest,\n chrome_message.ChromeResponse,\n name='heartbeat',\n path='heartbeat',\n http_method='GET',\n permission='view')\ndef do_something(self, request):\n ...\n\nThe above method will only execute if the current user's role has the permission\n\"view\".\n\nNote:\n-----\nPlease see permission module for more information on how the check_auth()\ndecorator works.\n\"\"\"\n\nimport endpoints\n\nfrom loaner.web_app.backend.auth import permissions\n\n\nclass Error(Exception):\n \"\"\"Default error class for this module.\"\"\"\n\n\nclass AuthCheckNotPresent(Error):\n \"\"\"Raised when auth_method was called without auth check.\"\"\"\n\n\ndef authed_method(*args, **kwargs):\n \"\"\"Configures an endpoint method and enforces permissions.\"\"\"\n\n def auth_method_decorator(auth_function):\n \"\"\"Decorator for auth_method.\"\"\"\n kwarg_auth = None\n kwarg_permission = None\n for key in kwargs:\n if key is 'permission':\n kwarg_permission = kwargs.pop('permission')\n auth_function = permissions.check_auth(\n permission=kwarg_permission)(auth_function)\n break\n elif key is 'user_auth_only':\n kwarg_auth = kwargs.pop('user_auth_only')\n auth_function = permissions.check_auth(\n user_auth_only=kwarg_auth)(auth_function)\n break\n if not kwarg_auth and not kwarg_permission:\n raise AuthCheckNotPresent(\n 'No permission or user_auth_only was passed. Authentication on this '\n 'method cannot run.')\n # Always apply the standard `endpoints.method` decorator.\n return endpoints.method(*args, **kwargs)(auth_function)\n\n return auth_method_decorator\n","sub_path":"loaner/web_app/backend/api/loaner_endpoints.py","file_name":"loaner_endpoints.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"158567995","text":"__author__ = 'deschancesdjomo'\n\nclass blockClass:\n def __init__(self):\n self.name = None\n self.type = None\n self.state = []\n self.event = []\n self.transition = []\n self.observer = []\n\n\n def show(self):\n print(self.type + \" \" + self.name)\n print(\" state: \")\n print(self.state)\n print(\" event: \")\n print(self.event)\n print(\"end\")\n\n\nclass transition:\n def __init__(self):\n self.event = None\n self.state1 = None\n self.state2 = None\n\nclass observer:\n pass","sub_path":"automate.py","file_name":"automate.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"11360199","text":"#!/usr/bin/env python\n\nimport math,time\nimport traceback\n\nimport serial\n\nimport rospy\nfrom geometry_msgs.msg import WrenchStamped, Wrench, Vector3, Point\nfrom std_msgs.msg import Header\n\nfrom thruster_handling.msg import ThrusterInfo, ThrusterCommand\nfrom thruster_handling.broadcaster import ThrusterBroadcaster\n\nfrom propagator_motor_driver import MotorDriver\nfrom propagator_motor_driver.msg import motor_driver_statistics\n\n\nrospy.init_node('motor_driver')\n\nmotor_driver_statistics_publisher = rospy.Publisher('motor_driver_statistics', motor_driver_statistics)\n\n\nmessage_received = False\nport = rospy.get_param('~port')\nthruster_id = rospy.get_param('~id')\nthruster_position = rospy.get_param('~position')\nthruster_direction = rospy.get_param('~direction')\noutput_list = rospy.get_param('~output_list')\nassert sorted(output_list) == output_list\nforce_list = rospy.get_param('~force_list')\nassert sorted(force_list) == force_list\nassert output_list[0] == -1\nassert output_list[-1] == 1\n\nwhile True:\n\ttry:\n\t\tmotordriver = MotorDriver.MotorDriver(port)\n\texcept:\n\t\ttraceback.print_exc()\n\t\ttime.sleep(1)\n\telse:\n\t\tbreak\n\ndef map_curve(force):\n\tif force < force_list[0]: force = force_list[0]\n\tif force > force_list[-1]: force = force_list[-1]\n\tpairs = zip(force_list, output_list)\n\tfor (left_force, left_output), (right_force, right_output) in zip(pairs[:-1], pairs[1:]):\n\t\tif left_force <= force <= right_force:\n\t\t\tx = (force - left_force)/(right_force - left_force)\n\t\t\treturn x * (right_output - left_output) + left_output\n\tassert False\n\ndef apply_command(force):\n\t\n\tglobal message_received\n\tmessage_received = True\n\t#print 'speed: ',str(int(force*200/max_force)),' motor driver: ',thruster_id\n\toutput = map_curve(force)\n\tif output > 0:\n motordriver.set_forward_speed(thrust)\n\telif output < 0:\n motordriver.set_reverse_speed(-thrust)\n\telse:\n\t\tmotordriver.stop()\n\t\t\n\tmotordriverstat_msg = motor_driver_statistics(\n\t\theader=Header(\n\t\t\tstamp=rospy.Time.now(),\n\t\t\tframe_id=\"/base_link\",\n\t\t),\n\t\tid=thruster_id,\n\t\tcurrent \t = \"0\",#motordriver.get_current(),\n\t\tout_voltage = \"0\",#motordriver.get_out_voltage(),\n\t\tbatt_voltage = \"0\",#motordriver.get_batt_voltage(),\n\t\t)\t\n\t#motor_driver_statistics_publisher.publish(motordriverstat_msg)\n\n\n\t\nlifetime = rospy.Duration(1.)\t\nthruster_broadcaster = ThrusterBroadcaster('/base_link', thruster_id, lifetime, thruster_position, thruster_direction, -(1 - reverse_c0)/reverse_c1, (1 - forward_c0)/forward_c1, [0, 0, 0], apply_command)\n\ndef thrusterinfo_callback(event):\n\tglobal message_received\n\t\n\tthruster_broadcaster.send()\n\t\n\tif not message_received:\n\t\tmotordriver.stop()\n\telse:\n\t\tmessage_received = False\n\t\t\nrospy.Timer(lifetime/2., thrusterinfo_callback)\n\nrospy.spin()\nmotordriver.stop()\n","sub_path":"sensors/propagator_motor_driver/nodes/motor_driver_pub.py","file_name":"motor_driver_pub.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"271326771","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n BathCreatorDialog\n A QGIS plugin\n Helps to create CE-QUAL-W2 Bathymetric file \n Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/\n -------------------\n begin : 2019-02-04\n git sha : $Format:%H$\n copyright : (C) 2019 by Yoav Bornstein\n email : yoavborenst@gmail.com\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; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\nimport os\n\nfrom PyQt5 import uic\nfrom PyQt5 import QtWidgets\n#from PyQt5.QtWidgets import QFileDialog\n\nfrom .create_bathymetry_dialog import Ui_BathCreatorDialogBase\n\nclass BathCreatorDialog(QtWidgets.QDialog):\n def __init__(self, parent=None):\n \"\"\"Constructor.\"\"\"\n super(BathCreatorDialog, self).__init__(parent)\n self.ui = Ui_BathCreatorDialogBase()\n self.ui.setupUi(self)\n self.delta_valid = True\n self.delta_value = \"\"\n self.csv_value = \"\"\n self.dem_value = self.ui.dem.currentLayer().name()\n self.line_value = self.ui.line.currentLayer().name()\n self.polygone_value = self.ui.polygone.currentLayer().name()\n self.updateOkButton()\n self.ui.delta.textChanged.connect(self.updateDelta)\n self.ui.csv.textChanged.connect(self.updateCsv)\n self.ui.dem.layerChanged.connect(self.updateDem)\n self.ui.line.layerChanged.connect(self.updateLine)\n self.ui.polygone.layerChanged.connect(self.updatePolygone)\n self.ui.browsebttn.clicked.connect(self.getFile)\n \n def updateOkButton(self):\n if self.delta_valid and self.delta_value and self.csv_value:\n self.ui.button_box.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)\n else:\n self.ui.button_box.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n\n def updateDelta(self, newText):\n self.delta_value = newText\n try:\n if self.delta_value:\n delta = float(self.delta_value)\n self.delta_valid = 0 < delta\n else:\n self.delta_valid = True\n except:\n self.delta_valid = False\n if not self.delta_valid:\n self.ui.delta.setStyleSheet(\"background-color: rgb(238, 169, 169);\")\n else:\n self.ui.delta.setStyleSheet(\"\")\n self.updateOkButton()\n\n def updateCsv(self, newText):\n self.csv_value = newText\n self.updateOkButton()\n\n def updateDem(self, layer):\n self.dem_value = layer.name()\n\n def updateLine(self, layer):\n self.line_value = layer.name()\n\n def updatePolygone(self, layer):\n self.polygone_value = layer.name()\n \n def getFile(self):\n self.ui.csv.setText(QtWidgets.QFileDialog.getSaveFileName(self, 'Save File', '', 'CSV(*.csv)')[0])","sub_path":"create_bathymetry/dialog.py","file_name":"dialog.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"122169838","text":"from movies import *\n\n@app.route('/api/movies', methods=['GET'])\ndef get_movies():\n return jsonify({'Movies': Movie.get_all_movies()})\n\n@app.route('/api/movies/', methods=['GET'])\ndef get_movie_by_id(id):\n return_value = Movie.get_movie(id)\n return jsonify(return_value)\n\n@app.route('/api/movies', methods=['POST'])\ndef add_movie():\n request_data = request.get_json() #getting data from client\n Movie.add_movie(request_data['title'], request_data['year'], request_data['genre'])\n response = Response('Movie Added', 201, mimetype='application/json')\n return response\n\n@app.route('/api/movies/', methods=['PUT'])\ndef update_movie(id):\n request_data = request.get_json() #getting data from client\n Movie.update_movie(id, request_data['title'], request_data['year'], request_data['genre'])\n response = Response('Movie Updated', status=200, mimetype='application/json')\n\n@app.route('/api/movies/', methods=['DELETE'])\ndef delete_movie(id):\n Movie.delete_movie(id)\n response = Response(\"Movie Delete\", status=200, mimetype='application/json')\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"463578365","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nModule that contains templates widget\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\n\nfrom Qt.QtCore import *\nfrom Qt.QtWidgets import *\n\nfrom tpDcc.libs.qt.core import base\nfrom tpDcc.libs.qt.widgets import dividers\n\n\nclass BlueprintWidget(base.BaseWidget, object):\n def __init__(self, parent=None):\n super(BlueprintWidget, self).__init__(parent=parent)\n\n def ui(self):\n super(BlueprintWidget, self).ui()\n\n main_splitter = QSplitter(Qt.Vertical)\n self.main_layout.addWidget(main_splitter)\n\n self._presets_list = PresetsList()\n self._outliner = BlueprintsOutliner()\n main_splitter.addWidget(self._presets_list)\n main_splitter.addWidget(self._outliner)\n\n\nclass PresetsList(base.BaseWidget, object):\n def __init__(self, parent=None):\n super(PresetsList, self).__init__(parent=parent)\n\n def ui(self):\n super(PresetsList, self).ui()\n\n self._presets_list = QListWidget()\n\n self.main_layout.addWidget(dividers.Divider('Presets'))\n self.main_layout.addWidget(self._presets_list)\n\n\nclass BlueprintsOutliner(base.BaseWidget, object):\n def __init__(self, parent=None):\n super(BlueprintsOutliner, self).__init__(parent=parent)\n\n def ui(self):\n super(BlueprintsOutliner, self).ui()\n\n self._blueprints_list = QListWidget()\n\n self.main_layout.addWidget(dividers.Divider('Current Blueprints'))\n self.main_layout.addWidget(self._blueprints_list)\n","sub_path":"tpRigToolkit/tools/rigbuilder/widgets/blueprint/blueprint.py","file_name":"blueprint.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"248050341","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom functools import partial\nfrom os.path import dirname, join\n\nfrom pyramid.events import (ApplicationCreated, BeforeRender, NewRequest,\n subscriber)\nfrom pyramid.asset import abspath_from_asset_spec\nfrom pyramid.settings import asbool\n\nfrom atelierlaurier.lib.jinja2 import add_renderer_globals\nfrom atelierlaurier.lib import scss\n\nlog = logging.getLogger(__name__)\n\n\n@subscriber(ApplicationCreated)\ndef _initialize(event):\n settings = event.app.registry.settings\n if not asbool(settings.get('scss.reload')):\n log.debug('On-the-fly SCSS compilation disabled')\n compile.closure = lambda: None\n return\n log.debug('On-the-fly SCSS compilation launched')\n app_name = __name__.split('.')[0]\n scss.initialize(\n settings['app.static.url'],\n abspath_from_asset_spec(':'.join([app_name, 'static'])))\n assets_dir = abspath_from_asset_spec(settings['scss.directory'])\n bootstrap_dir = join(dirname(dirname(__file__)),\n 'libs', 'bootstrap-sass', 'vendor', 'assets',\n 'stylesheets')\n options = dict(load_paths=[assets_dir, bootstrap_dir],\n compress=asbool(settings.get('scss.compress')))\n compile.closure = partial(scss.compile, assets_dir, options)\n\n\n@subscriber(NewRequest)\ndef compile(event):\n compile.closure()\n\n\n@subscriber(BeforeRender)\ndef _add_renderer_globals(event):\n app_name = __name__.split('.')[0]\n add_renderer_globals(app_name, event)\n","sub_path":"atelierlaurier/subscribers.py","file_name":"subscribers.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"652220498","text":"#!/usr/bin/python3\n# iqtree_setup.py by josh\n\nimport glob\nimport re\nimport os\nimport subprocess\n\nIDPattern = re.compile(\"^>(\\S+)$\")\nseqPattern = re.compile(\"^[A-Z*-]+$\")\ngapPattern = re.compile(\"^-+$\")\nrepeatedUnderscore = re.compile(\"_+\")\ntrailingUnderscore = re.compile(\"_$\")\n\noutDir = \"../iqtree_gene_trees\"\n\nif not os.path.isdir(outDir):\n os.makedirs(outDir)\n\nalignList = [os.path.abspath(x) for x in glob.glob(\"./*_align_f.fas\")]\n\nalignList.sort()\n\nprint(len(alignList))\n\nmasterSpeciesList = []\nlengthList = []\n\nfor idx, alignment in enumerate(alignList):\n alignment = os.path.basename(alignment)\n print(idx, alignment)\n gene = alignment.replace(\"_align_f.fas\",\"\")\n print(gene)\n seqDict = {}\n taxaList = []\n inFile = open(alignment, \"r\")\n for indx, line in enumerate(inFile):\n line = line.strip()\n if IDPattern.match(line):\n # The following line removes useless transcript information and the \">\"\n editedLine = line.split(\"|\")[0][1:]\n editedLine = editedLine.replace(\"transcriptome\",\"tr\")\n editedLine = editedLine.replace(\"ranscriptome\",\"tr\")\n editedLine = editedLine.replace(\"RNAlib\",\"\")\n editedLine = editedLine.replace(\"Hyun1\", \"_\")\n editedLine = editedLine.replace(\"LS023Abrain\", \"LS023A\")\n editedLine = editedLine.replace(\"LS023Aliver\", \"LS023A\")\n editedLine = repeatedUnderscore.sub(\"_\",editedLine)\n editedLine = trailingUnderscore.sub(\"\",editedLine)\n if \"Lonchophylla_thomasi_PE171\" in editedLine or \"Lonchophylla_thomasi_Peru_mega\" in editedLine:\n editedLine = editedLine.replace(\"Lonchophylla_thomasi\", \"Lionycteris_spurrelli\")\n if \"Mimon_crenulatum\" in editedLine:\n editedLine = editedLine.replace(\"Mimon\", \"Gardnernycteris\")\n print(editedLine)\n taxon = \"_\".join([editedLine.split(\"_\")[0][0:3], editedLine.split(\"_\")[1]])\n print(taxon)\n sequence = inFile.readline().strip()\n if not seqPattern.match(sequence):\n print(editedLine)\n print(sequence)\n sys.exit(\"Error, sequence not in expected format\")\n seqLen = len(sequence)\n if indx == 0:\n refSeqLen = seqLen\n if seqLen != refSeqLen:\n sys.exit(\"Error, sequences not same length\")\n if \"Desmodus_rotundus_genome\" in editedLine:\n print(\"Desmodus genome found; skipping\")\n continue\n if \"GLSO-119148A\" in editedLine:\n print(\"Crappy Glossophaga found; skipping\")\n continue\n newSeq = \"\"\n for i in range(0, len(sequence), 3):\n codon = sequence[i:i+3]\n if codon.count(\"-\") in [1, 2]:\n codon = \"---\"\n newSeq += codon\n gapCount = newSeq.count(\"-\")\n if len(newSeq) == gapCount or gapPattern.match(newSeq):\n print(\"Sequence comprising only gaps found; skipping\")\n continue\n if taxon not in taxaList:\n taxaList.append(taxon)\n if taxon not in masterSpeciesList:\n masterSpeciesList.append(taxon)\n if taxon not in seqDict:\n seqDict[taxon] = [gapCount, newSeq, editedLine]\n elif gapCount < seqDict[taxon][0]:\n seqDict[taxon] = [gapCount, newSeq, editedLine]\n else:\n print(line)\n sys.exit(\"Error, line not in expected format\")\n inFile.close()\n taxaList.sort()\n taxaCount = len(taxaList)\n lengthList.append([\"{}_align.fasta\".format(gene), taxaCount])\n print(\"Number of taxa:\", taxaCount)\n outFile = open(\"{}/{}_align.fasta\".format(outDir,gene), \"w\")\n for taxon in taxaList:\n outFile.write(\">\" + taxon + \"\\n\")\n outFile.write(seqDict[taxon][1] + \"\\n\")\n outFile.close()\n\nprint(masterSpeciesList)\n\nprint(len(masterSpeciesList))\n\nlengthList.sort(key=lambda x:x[1], reverse=True)\n\nprint(len(lengthList))\n\nlistFile = open(\"{}/alignlist.txt\".format(outDir), \"w\")\n\nfor alignment in lengthList:\n listFile.write(alignment[0] + \"\\n\")\n\nlistFile.close()\n\narrayString = \"\"\"#!/bin/sh\n#$ -cwd # Use current working directory\n#$ -V # Verbose\n#$ -j y # Maximum output, inc errors\n#$ -r y # Condense error files into one\n#$ -l h_rt=47:0:0 # Request runtime (up to 240 hours)\n#$ -l h_vmem=2G # Request RAM per core\n#$ -m a # Status emails\n#$ -t 1-{}\n\nINFASTA=\"$(sed -n -e \"$SGE_TASK_ID p\" pamldirlist.txt)\"\n\necho $INFASTA\n\n/data/home/btw915/programs/login2/iqtree-1.6.8-Linux/bin/iqtree -s $INFASTA -st CODON -bb 1000\n\n\"\"\"\n\narrayFile = open(\"{}/iqtree_array.sh\".format(outDir), \"w\")\n\narrayFile.write(arrayString.format(str(len(lengthList))))\n\narrayFile.close()\n\nsubprocess.call([\"chmod\",\"u+x\",\"{}/iqtree_array.sh\".format(outDir)])\n\nquit()","sub_path":"iqtree_setup.py","file_name":"iqtree_setup.py","file_ext":"py","file_size_in_byte":5046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"629339107","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2020 GBC Networks Oy. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE 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\n# THE SOFTWARE.\n\nimport re\nimport sys\n\nfrom ft_dbconnect import MysqlDB\n\n\n# check python version >= 3.6\nassert sys.version_info >= (3, 6)\n\n\ndef simple_regex_check(word):\n \"\"\" C, Q, W, X or Z excluded \"\"\"\n regex = r'^([abd-pr-vyABD-PR-VYÅåÄäÖöŠšŽž\\-\\']+$)'\n rr = re.match(regex, word)\n return int(rr is not None)\n\n\ndef regex_vecfile(vecfile):\n \"\"\"\n Runs the regex on the vec file entries and add the word if the word\n did not match the regex=garbage word.\n Reads line by line from the vec file.\n Check if the word in line has a matching entry in garbwords table.\n Insert the word if not in the table.\n \"\"\"\n db = MysqlDB()\n with open(vecfile) as infile:\n for line in infile:\n text_regex = r'^([^ ]+) '\n m = re.match(text_regex, line) # get the first word\n if m is not None:\n word = m.group(1)\n if not simple_regex_check(word):\n result = db.words_insert_garbword(word, 1)\n if hasattr(result, 'lastrowid'):\n print(f'Added {word} because it failed the regex')\n else:\n print(f'Failed to add {word} to the database')\n # commit to db\n db.commit()\n\n\nif __name__ == \"__main__\":\n # execute only if run as a script\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--vec', required=False, default='./cc.fi.300.vec')\n args = parser.parse_args()\n\n regex_vecfile(args.vec)\n","sub_path":"ft_regex.py","file_name":"ft_regex.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"466336588","text":"#Task:\n# You’re given a CSV of Twitter’s user activity logs:\n\n# Timestamp,User,Action, Target User\n# Wed Sep 3 05:15:39 CDT 2011,143248659,Retweet,55121922\n# Thu Sep 4 13:13:33 CDT 2011,143248659,Retweet,189474615\n# Sun Sep 7 14:23:36 CDT 2011,65165115,Mention,143248659\n# Mon Sep 8 01:39:08 CDT 2011,65165115,Retweet,236403070\n# Tue Sep 9 17:59:26 CDT 2011,143248659,Retweet,65165115\n# Wed Sep 10 18:57:31 CDT 2011,65165115,Retweet,257366925\n# Fri Sep 12 22:52:33 CDT 2011,65165115,Retweet,55121922\n# Thu Sep 18 04:34:04 CDT 2011,143248659,Retweet,65165115\n# Thu Sep 18 23:10:32 CDT 2011,65165115,Mention,230627444\n# Sat Sep 20 18:49:28 CDT 2011,65165115,Reply,310962238\n\n# Actions can be:\n\n# Mention\n# Reply\n# Retweet\n\n# Produce a table containing, for each user and for each Sun 00:00:00 CDT (that’s the midnight of a Saturday), \n#from the earliest to the latest Sunday present in the dataset, a rolled-up summary of their activity over various time windows ending that midnight. The columns should be:\n\n# User\n# Timestamp (should always be a Sun 00:00:00 CDT)\n# # Mentions of Others in Past 7 Days\n# # Mentions of Others in Past 31 Days\n# # Replies in Past 7 Days\n# # Replies in Past 31 Days\n# # Retweets in Past 7 Days\n# # Retweets in Past 31 Days\n# Ratio of # Distinct Target Users to # Actions in Past 31 Days (0 if no actions)\n\n# So the above table should be transformed into:\n\n# 65165115,Sun Sep 7 00:00:00 CDT 2011,0,0,0,0,0,0,0\n# 65165115,Sun Sep 14 00:00:00 CDT 2011,1,1,0,0,3,3,1.0\n# 65165115,Sun Sep 21 00:00:00 CDT 2011,1,2,1,1,0,3,1.0\n# 143248659,Sun Sep 7 00:00:00 CDT 2011,0,0,0,0,2,2,1.0\n# 143248659,Sun Sep 14 00:00:00 CDT 2011,0,0,0,0,1,3,1.0\n# 143248659,Sun Sep 21 00:00:00 CDT 2011,0,0,0,0,1,4,0.75\n\nimport sqlite3\nfrom datetime import datetime\nimport time\nCONN = None\nDB = None\n\n\ndef insert_week_actions(user_tweets):\n\n User_id = user_tweets.keys()[0]\n Time = user_tweets[User_id]['date'] \n Mentions_week = user_tweets[User_id]['mentions']\n Mentions_month = 0\n Replies_week = user_tweets[User_id]['replies']\n Replies_month = 0\n Retweets_week = user_tweets[User_id]['retweets']\n Retweets_month = 0\n Ratio_users_actions = 0\n \n #input a user's week's data into database \n query = \"\"\"INSERT into User_Tweets values (?, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\"\n\n DB.execute(query, (User_id, Time, Mentions_week, Mentions_month, Replies_week, Replies_month, Retweets_week, Retweets_month, Ratio_users_actions,))\n CONN.commit()\n\ndef isweek(start_date, end_date):\n #convert time to format (2007, 9, 1 04:12:00) / (year, month, day hour:minute:second)\n start = datetime.strptime(start_date, '%d %b %Y %H:%M:%S')\n end = datetime.strptime(end_date, '%d %b %Y %H:%M:%S')\n diff = start-end\n\n if diff.days < 7:\n return True\n else:\n return False\n\ndef count_and_insert_week_actions(filename):\n\n f = open(filename)\n\n user_tweets = {}\n dates = []\n\n for line in f:\n tweet = line.rstrip().split(',')\n \n #extract date values\n date = tweet[0][8:10]\n month = tweet[0][4:7]\n year = tweet[0][-4:]\n mins = tweet[0][11:19]\n\n current_date = date + \" \" + month + \" \" + year + \" \" + mins\n dates.append(current_date)\n\n #call function to return True or False. If within week, return True\n is_week = isweek(dates[0], current_date)\n user_id = tweet[1]\n\n if is_week:\n \n # if key is already in dict, update counts for actions\n if user_tweets.get(user_id, False) != False:\n\n if tweet[2] == 'Mention':\n user_tweets[user_id]['mentions'] += 1\n\n elif tweet[2] == 'Reply':\n user_tweets[user_id]['replies'] += 1\n\n elif tweet[2] == 'Retweet':\n user_tweets[user_id]['retweets'] += 1\n\n #get last date in week\n user_tweets[user_id]['date'] = current_date\n\n # if key isn't there, input userID as key and initialize counts\n else: \n user_tweets[user_id] = {'date': '', 'mentions': 0 , 'replies': 0, 'retweets': 0}\n \n else: \n #insert row into db\n insert_week_actions(user_tweets)\n user_tweets = {}\n dates = []\n \n #what the user_tweets dict looks like now:\n #{'143248659': {'date': '23 Jul 2011 20:39:59', 'mentions': 19, 'retweets': 71, 'replies': 35}}\n\n f.close()\n\n\ndef connect_to_db():\n global DB, CONN\n CONN = sqlite3.connect(\"tweets.db\")\n DB = CONN.cursor()\n\ndef main():\n connect_to_db()\n \n # create table - run file first time, commented out so as not to create table every time file is run\n\n # DB.execute('''CREATE TABLE User_Tweets\n # (User_id INT, Time text, Mentions_week INT, Mentions_month INT, Replies_week INT, Replies_month INT, Retweets_week INT, Retweets_month INT, Ratio_users_actions INT)''')\n\n # CONN.commit()\n count_and_insert_week_actions('tweets.csv')\n\n CONN.close()\n\nif __name__ == \"__main__\":\n main()\n\n#Issues:\n#still need to solve how to calculate a rolling count for the 31 day column value, as well as calculating the ratio of distinct target users to actions. \n#Also, dates don't start on Sat, but start at first tweet of a user and then calculate to the next 7 days. \n","sub_path":"tweets_restructured.py","file_name":"tweets_restructured.py","file_ext":"py","file_size_in_byte":5385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"213832176","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport codecs\nimport json\nimport sys\nimport pdb\nimport os\nimport numpy\nimport logging\n\nimport tensorflow as tf\n\nreload(sys) \nsys.setdefaultencoding('utf-8')\n\nsess = tf.InteractiveSession()\n\nIS_SIMPLE_VERSION = False\nWANT_RESTORE = False\n\nwith codecs.open('metadata.json', encoding='UTF-8') as data_file:\n\tjsondata = json.load(data_file)\n\ncontenttypes = jsondata[\"contenttypes\"];\ncontentTypeNum = len(contenttypes);\nroomtypes = jsondata[\"roomtypes\"];\nroomTypeNum = len(roomtypes);\ntrainingDataDir = '../designjsons';\n\ntrainingDataFiles = [item for item in os.listdir(trainingDataDir) if os.path.isfile(os.path.join(trainingDataDir, item))]\ntrainingDataCount = len(trainingDataFiles);\nlogger = logging.getLogger();\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s');\ntestDataDir = '../validators';\n\ntestDataFiles = [item for item in os.listdir(testDataDir) if os.path.isfile(os.path.join(testDataDir, item))]\n\n\ndef read_data_sets(contentTypeNum, roomTypeNum, dataDir, dataFiles):\n\tdata = numpy.zeros((0, contentTypeNum));\n\tlabels = numpy.zeros((0, roomTypeNum))\n\n\tcountIndex = 0\n\tfor filename in testDataFiles:\n\t\tif filename == '.DS_Store':\n\t\t\tcontinue\n\n\t\twith codecs.open(os.path.join(testDataDir, filename), encoding='UTF-8') as designfile:\n\t\t\tdesignjson = json.load(designfile)\n\n\t\t\n\t\tif countIndex == (len(labels)):\n\t\t\tlogging.debug('extend labels and data')\n\t\t\trownum = len(designjson)\n\t\t\trow = numpy.zeros((rownum, roomTypeNum))\n\t\t\tlabels = numpy.vstack((labels, row))\n\t\t\trow = numpy.zeros((rownum, contentTypeNum))\n\t\t\tdata = numpy.vstack((data, row))\n\n\t\tfor roomid in designjson:\n\t\t\troom = designjson[roomid]\n\t\t\tcategory = room['category']\n\t\t\tcharacters = room['characters']\n\n\t\t\t# init labels\n\t\t\tfor idx, val in enumerate(roomtypes):\n\t\t\t\tif val['name'] == category:\n\t\t\t\t\tlogging.debug('idx = %d, countIndex = %d', idx, countIndex)\n\t\t\t\t\tlabels[countIndex][idx] = 1\n\t\t\t\t\tbreak\n\t\t\t# init data\n\t\t\tfor character in characters:\n\t\t\t\tfor idx, contenttype in enumerate(contenttypes):\n\t\t\t\t\tif character['contenttype'] == contenttype['name']:\n\t\t\t\t\t\t# logging.debug('characters: idx = %d, countIndex = %d', idx, countIndex)\n\t\t\t\t\t\tdata[countIndex][idx] = 1\n\t\t\t\t\t\tlogging.debug('data[countIndex][idx] = %d', data[countIndex][idx])\n\t\t\t\t\t\tbreak\n\t\t\tcountIndex += 1\n\n\treturn data, labels\n\ndef read_test_sets(contentTypeNum, roomTypeNum):\n\tlogging.debug('read test sets');\n\treturn read_data_sets(contentTypeNum, roomTypeNum, testDataDir, testDataFiles);\n\ndef read_training_sets(contentTypeNum, roomTypeNum):\n\tlogging.debug('read training sets');\n\treturn read_data_sets(contentTypeNum, roomTypeNum, trainingDataDir, trainingDataFiles);\n\n\n# batch_xs: n by m matrix, with n(row) = the number of training exmaples and m = the number of content types\n# batch_ys: n by m matrix, with n(row) = the number of training examples and m = the number of classifications (the number of room types)\nbatch_xs, batch_ys = read_training_sets(contentTypeNum, roomTypeNum)\n\nx = tf.placeholder(tf.float32, [None, contentTypeNum])\nW = tf.Variable(tf.zeros([contentTypeNum, roomTypeNum]))\nb = tf.Variable(tf.zeros([roomTypeNum]))\ny = tf.nn.softmax(tf.matmul(x, W) + b)\n\nsaver = tf.train.Saver()\n\nif WANT_RESTORE:\n\ty_ = tf.placeholder(tf.float32, [None, roomTypeNum])\n\tsaver.restore(sess, 'roomtype-softmax')\nelse:\n\t# Define loss and optimizer\n\ty_ = tf.placeholder(tf.float32, [None, roomTypeNum])\n\tcross_entropy = -tf.reduce_sum(y_ * tf.log(y))\n\ttrain_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)\n\n\ttf.initialize_all_variables().run()\n\t# train_step.run({x: batch_xs, y_: batch_ys})\n\tfor i in range(1000):\n\t\t# batch_xs, batch_ys = dataset.train\n\t\ttrain_step.run({x: batch_xs, y_: batch_ys})\n\n\tsaver.save(sess, 'roomtype-softmax')\n\n\nprediction = tf.argmax(y, 1)\ncorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\ntestdata, testlabel = read_test_sets(contentTypeNum, roomTypeNum)\nprint('accuracy: ')\nprint(sess.run(accuracy, feed_dict={x: testdata, y_: testlabel}))\nfor i in range(len(testdata)):\n\tindex = sess.run(prediction, feed_dict={x: [testdata[i]]})[0]\n\tprint (\"Test\", i, \"Prediction:\", roomtypes[index]['name'], \",True Class:\", roomtypes[numpy.argmax(testlabel[i])]['name'])\n\n# print(accuracy.eval({x: testdata, y_: testlabel}))\n","sub_path":"tensorf/roomtype-softmax.py","file_name":"roomtype-softmax.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"436878640","text":"from urlparse import urlparse\n\nfrom django import http\n# I'm so glad we named a function in here settings...\nfrom django.conf import settings as site_settings\nfrom django.contrib import admin\nfrom django.shortcuts import redirect\nfrom django.views import debug\n\nimport commonware.log\nfrom hera.contrib.django_forms import FlushForm\nfrom hera.contrib.django_utils import get_hera, flush_urls\nimport jinja2\nimport jingo\n\nfrom amo import messages\nimport amo.models\nfrom addons.models import Addon\nfrom files.models import Approval\nfrom versions.models import Version\n\nlog = commonware.log.getLogger('z.zadmin')\n\n\n@admin.site.admin_view\ndef flagged(request):\n addons = Addon.objects.filter(admin_review=True).order_by('-created')\n\n if request.method == 'POST':\n ids = map(int, request.POST.getlist('addon_id'))\n Addon.objects.filter(id__in=ids).update(admin_review=False)\n # The sql update doesn't invalidate anything, do it manually.\n invalid = [addon for addon in addons if addon.id in ids]\n Addon.objects.invalidate(*invalid)\n return redirect('zadmin.flagged')\n\n sql = \"\"\"SELECT {t}.* FROM {t} JOIN (\n SELECT addon_id, MAX(created) AS created\n FROM {t}\n GROUP BY addon_id) as J\n ON ({t}.addon_id = J.addon_id AND {t}.created = J.created)\n WHERE {t}.addon_id IN {ids}\"\"\"\n approvals_sql = sql + \"\"\"\n AND (({t}.reviewtype = 'nominated' AND {t}.action = %s)\n OR ({t}.reviewtype = 'pending' AND {t}.action = %s))\"\"\"\n\n ids = '(%s)' % ', '.join(str(a.id) for a in addons)\n versions_sql = sql.format(t=Version._meta.db_table, ids=ids)\n approvals_sql = approvals_sql.format(t=Approval._meta.db_table, ids=ids)\n\n versions = dict((x.addon_id, x) for x in\n Version.objects.raw(versions_sql))\n approvals = dict((x.addon_id, x) for x in\n Approval.objects.raw(approvals_sql,\n [amo.STATUS_NOMINATED,\n amo.STATUS_PENDING]))\n\n for addon in addons:\n addon.version = versions.get(addon.id)\n addon.approval = approvals.get(addon.id)\n\n return jingo.render(request, 'zadmin/flagged_addon_list.html',\n {'addons': addons})\n\n\n@admin.site.admin_view\ndef hera(request):\n form = FlushForm(initial={'flushprefix': site_settings.SITE_URL})\n\n boxes = []\n configured = False # Default to not showing the form.\n for i in site_settings.HERA:\n hera = get_hera(i)\n r = {'location': urlparse(i['LOCATION'])[1], 'stats': False}\n if hera:\n r['stats'] = hera.getGlobalCacheInfo()\n configured = True\n boxes.append(r)\n\n if not configured:\n messages.error(request, \"Hera is not (or mis-)configured.\")\n form = None\n\n if request.method == 'POST' and hera:\n form = FlushForm(request.POST)\n if form.is_valid():\n expressions = request.POST['flushlist'].splitlines()\n\n for url in expressions:\n num = flush_urls([url], request.POST['flushprefix'], True)\n msg = (\"Flushed %d objects from front end cache for: %s\"\n % (len(num), url))\n log.info(\"[Hera] (user:%s) %s\" % (request.user, msg))\n messages.success(request, msg)\n\n return jingo.render(request, 'zadmin/hera.html',\n {'form': form, 'boxes': boxes})\n\n\n@admin.site.admin_view\ndef settings(request):\n settings_dict = debug.get_safe_settings()\n\n # sigh\n settings_dict['HERA'] = []\n for i in site_settings.HERA:\n settings_dict['HERA'].append(debug.cleanse_setting('HERA', i))\n\n return jingo.render(request, 'zadmin/settings.html',\n {'settings_dict': settings_dict})\n\n\n@admin.site.admin_view\ndef env(request):\n return http.HttpResponse(u'
%s
' % (jinja2.escape(request)))\n","sub_path":"apps/zadmin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"79799326","text":"import os\nimport requests\nimport cv2\nimport base64\nimport json\nfrom trainTools import *\n\n\n# HTTP GET\ndef getProblemJsonFile(url):\n r = requests.get(url)\n return r.json()\n\n# 读取json文件\ndef readJsonFile(filePath):\n with open(filePath,'r') as jsonFile:\n dict = json.load(jsonFile)\n return dict\n# 把字典文件保存为json文件\ndef saveDictFile(dict,filePath):\n with open(filePath,'w') as jsonFile:\n json.dump(dict, jsonFile)\n\n# 把base64编码的图片保存到指定路径\ndef writeBase64Image(filePath, base64Image):\n image = base64.b64decode(base64Image)\n with open(filePath,'wb') as fileObject:\n fileObject.write(image)\n\n# 找到原图片中黑色图片的编号\ndef findSourceBlackPictureNo(filePath):\n BlackPictureNo = {}\n fileNames = os.listdir(filePath)\n fileNames.sort()\n for fileName in fileNames:\n for i in range(1,10):\n img = cv2.imread(filePath+'/'+fileName+'/'+str(i)+'.jpg')\n corners = getCorners(img)\n if(corners.size <= 1):\n if fileName[0] not in BlackPictureNo.keys():\n BlackPictureNo[fileName[0]] = str(i)\n else:\n BlackPictureNo[fileName[0]] += str(i)\n# for key,value in BlackPictureNo.items():\n# print(key+' : '+ value)\n return BlackPictureNo\n\nif __name__ == '__main__':\n print('fileTools.py')\n\n fileList = ['023456789.json','103456789.json','120456789.json','123056789.json','123406789.json','123450789.json','123456089.json','123456709.json','123456780.json']\n\n for file in fileList:\n dict = readJsonFile('./record/'+file)\n for key,value in dict.items():\n dict[key] = value[::-1]\n saveDictFile(dict,'./record/'+file)\n\n# with np.load('./record/knnTrainData.npz') as data:\n# print(data.files)\n# trainData = data['trainData']\n# responses = data['responses'] \n # charDict = getCharDict('./source')\n# saveDictFile(charDict,'./record/charDict.json')\n# charDict = readJsonFile('./record/charDict.json')\n# noDict = {}\n# for key,value in charDict.items():\n# noDict[value] = key\n# saveDictFile(noDict,'./record/noDict.json')\n\n ","sub_path":"fileTools.py","file_name":"fileTools.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"299827732","text":"from flask import Flask, request, jsonify\napp = Flask(__name__)\n\nresource = []\n\n@app.route('/user/', methods= ['GET'])\n#userid 가지고 오기\ndef get_user(user_id):\n for user in resource:\n if user['user_id'] is user_id:\n return jsonify(user)\n return jsonify(None)\n\n@app.route('/user', methods = ['POST'])\ndef add_user():\n print('hello')\n user = request.get_json()\n resource.append(user)\n return jsonify(resource)\n\nif __name__ == '__main__':\n app.run(port = '4040')\n","sub_path":"data_visualization/deeplearning/chatbot/hello_flask/basic_restapi/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"515766224","text":"import arrow\nfrom django import template\nfrom django.core.urlresolvers import reverse\n\nregister = template.Library()\n\n\n@register.filter\ndef get_total_subject_posts(subject):\n total_posts = 0\n for bug in subject.bugs.all():\n total_posts += bug.posts.count()\n return total_posts\n\n\n@register.filter\ndef started_time(created_at):\n return arrow.get(created_at).humanize()\n\n\n@register.simple_tag\ndef last_posted_user_name(bug):\n last_post = bug.posts.all().order_by('created_at').last()\n return last_post.user.username\n\n\n@register.simple_tag\ndef user_vote_button(bug, subject, user):\n vote = bug.votes.filter(user_id=user.id).first()\n\n if not vote:\n if user.is_authenticated():\n link = \"\"\"\n \"\"\" % reverse('cast_vote', kwargs={'bug_id': bug.id, 'subject_id': bug.subject_id})\n\n return link\n\n return \"\"\n\n\n@register.filter\ndef vote_count(subject):\n count = subject.votes.count()\n if count == 0:\n return 0\n total_votes = subject.votes.count()\n return total_votes\n","sub_path":"ua_bugs/templatetags/uabug_extras.py","file_name":"uabug_extras.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"164660813","text":"#!/usr/bin/env python\n\n'''\nCopyright (c) 2016, Nadya Ampilogova\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'''\n\n# Script for simulation\n# Launch gazebo world prior to run this script\n\nfrom __future__ import print_function\nimport sys\nimport rospy\nimport cv2\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nimport ConfigParser\nimport os\n\nconfigParser = ConfigParser.ConfigParser() \nconfigFilePath = '/home/zach/catkin_ws/src/andbot_smart/identify_family/env.config'\nconfigParser.read(configFilePath)\n\nclass TakePhoto:\n def __init__(self):\n self.bridge = CvBridge()\n self.image_received = False\n\n # Connect image topic\n img_topic = configParser.get('take_photo_index','img_topic')\n self.image_sub = rospy.Subscriber(img_topic, Image, self.callback)\n # Allow up to one second to connection\n take_photo_connect_t = float(configParser.get('take_photo_index','take_photo_connect_t'))\n \n rospy.sleep(take_photo_connect_t)\n\n def callback(self, data):\n\n # Convert image to OpenCV format\n try:\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n except CvBridgeError as e:\n print(e)\n\n self.image_received = True\n self.image = cv_image\n\n def take_picture(self, img_title):\n if self.image_received:\n # Save an image\n cv2.imwrite(img_title, self.image)\n return True\n else:\n return False\n\nif __name__ == '__main__':\n\n # Initialize\n rospy.init_node('take_photo_index', anonymous=False)\n label =rospy.get_param('~label', 'none')\n start =rospy.get_param('~start', -1)\n end = rospy.get_param('~end', -5)\n for i in range(start,end) : \n camera = TakePhoto()\n # Take a photo\n img_title_dir = configParser.get('take_photo_index','img_title_dir')\n img_label_dir = os.path.join(img_title_dir,str(label)) \n try:\n os.stat(img_label_dir)\n except:\n os.mkdir(img_label_dir)\n img_title = os.path.join(img_label_dir,'image-'+str(i)+'.jpg')\n while camera.take_picture(img_title)!=1:\n \tsleep(0.001) \n\t\t#rospy.loginfo(\"No images received\")\n\n rospy.loginfo(\"Saved image \" + img_title)\n\n # Sleep to give the last log messages time to be sent\n take_photo_t = float(configParser.get('take_photo_index','take_photo_t'))\n \n rospy.sleep(take_photo_t)\n\n","sub_path":"identify_family/script/take_photo_index.py","file_name":"take_photo_index.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"355201446","text":"#!/usr/bin/env python\n\nimport geojson\n\n\nfrom terragraph import utilities\n\nfrom terragraph.datastore import Datastore\n\nfrom terragraph.deployment_feature import DeploymentFeature\n\nfrom terragraph.deployment_repository import DeploymentRepository\n\nimport private\n\nimport folium\n\n\nif __name__ == '__main__':\n\n repo = DeploymentRepository()\n datastore = Datastore()\n load_selection = 1\n if load_selection ==1:\n load_namespace = 'some-new-deployment'\n features = datastore.read_namespace(load_namespace)\n else:\n features = datastore.read_gist(\n private.github_user,\n private.github_psswd,\n private.display_gist_id\n )\n\n # Add the newly loaded features into the repo\n for feature in features:\n repo.add(feature)\n\n\n map_1 = folium.Map(location=[45.372, -121.6972], zoom_start=12,\n tiles='Stamen Terrain')\n map_1.simple_marker([45.3288, -121.6625], popup='Mt. Hood Meadows')\n map_1.simple_marker([45.3311, -121.7113], popup='Timberline Lodge')\n map_1.create_map(path='mthood.html')\n\n datastore.graphic_map(features)\n\n\n save_selection = 4\n if save_selection ==1: #Export as dump\n save_namespace = 'some-new-deployment'\n datastore.write_namespace(repo.all.values(), save_namespace)\n\n elif save_selection == 2: # Save\n save_filename = input('Enter the name and path of the file: ')\n save_filename = 'export2.json'\n datastore.write_geojson_file(repo.all.values(), save_filename)\n elif save_selection == 3:\n datastore.write_gist(\n repo.all.values(),\n private.github_user,\n private.github_psswd,\n private.display_gist_id\n )\n","sub_path":"folio.py","file_name":"folio.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"46994199","text":"#!/imaging/local/software/anaconda/latest/x86_64/bin/python\n\"\"\"\n==========================================\nSubmit qsub jobs for WH Resolution analysis\nallow dependencies between jobs\n==========================================\n\nOH July 2018\n\"\"\"\n\nprint(__doc__)\n\nimport subprocess\nfrom os import path as op\n\n# indices of subjects to process\nsubjs = range(0,16)\n\njob_list = \\\n[\n # #####\n # # COMPUTING and MORPHING Sensitivity Maps\n # #####\n # {'N': 'R_SMap', # job name\n # 'Py': 'WH_Res_SensitivityMaps', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '1GB', # memory for qsub process\n # 'dep': '',\n # 'var': '\"RMS\"'}, # variable string for python script (e.g. for filenames)}, # name of preceeding process (optional)\n # {'N': 'R_MphSM', # job name\n # 'Py': 'WH_Res_MorphSTC_SMap', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '1GB', # memory for qsub process\n # 'dep': 'R_SMap',\n # 'var': '\"RMS\"'}, # additional variables for python script (optional)\n #####\n # AVERAGING Sensitivity Maps\n #####\n ### The following depends on completion of previous jobs for ALL subjects\n {'N': 'R_AvgMphSMap', # job name\n 'Py': 'WH_Res_AvgSTCs_SMaps', # Python script\n 'Cf': 'WH_MNE_Resolution_config', # configuration script\n 'Ss': [''], # subject indices, '' if across all subjects\n 'mem': '2GB', # memory for qsub process\n 'dep': '',\n 'var': '\"SensitivityMaps RMS\"'},\n \n # #####\n # # COMPUTING Resolution Metrics\n # #####\n # {'N': 'R_LocErrPeak', # job name\n # 'Py': 'WH_Res_ResolutionMetrics', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '1GB', # memory for qsub process\n # 'var': '\"locerr peak\"',\n # 'dep': ''},\n\n # {'N': 'R_LocErrCOG', # job name\n # 'Py': 'WH_Res_ResolutionMetrics', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '1GB', # memory for qsub process\n # 'var': '\"locerr cog\"',\n # 'dep': ''},\n\n # {'N': 'R_WidthSD', # job name\n # 'Py': 'WH_Res_ResolutionMetrics', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '1GB', # memory for qsub process\n # 'var': '\"width sd\"',\n # 'dep': ''},\n \n # {'N': 'R_WidthMR', # job name\n # 'Py': 'WH_Res_ResolutionMetrics', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '1GB', # memory for qsub process\n # 'var': '\"width maxrad\"',\n # 'dep': ''},\n \n # {'N': 'R_AmpSum', # job name\n # 'Py': 'WH_Res_ResolutionMetrics', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '1GB', # memory for qsub process\n # 'var': '\"amplitude sum\"',\n # 'dep': ''}, \n\n # {'N': 'R_AmpPeak', # job name\n # 'Py': 'WH_Res_ResolutionMetrics', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '1GB', # memory for qsub process\n # 'var': '\"amplitude peak\"',\n # 'dep': ''},\n \n # #####\n # # MORPHING Resolution Metrics\n # #####\n # {'N': 'R_MphLocErrPeak', # job name\n # 'Py': 'WH_Res_MorphSTC', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '2GB', # memory for qsub process\n # 'dep': 'R_LocErrPeak',\n # 'var': '\"ResolutionMetrics locerr_peak\"'},\n\n # {'N': 'R_MphLocErrCOG', # job name\n # 'Py': 'WH_Res_MorphSTC', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '2GB', # memory for qsub process\n # 'dep': 'R_LocErrCOG',\n # 'var': '\"ResolutionMetrics locerr_cog\"'},\n \n # {'N': 'R_MphWidthSD', # job name\n # 'Py': 'WH_Res_MorphSTC', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '2GB', # memory for qsub process\n # 'dep': 'R_WidthSD',\n # 'var': '\"ResolutionMetrics width_sd\"'},\n\n # {'N': 'R_MphWidthMR', # job name\n # 'Py': 'WH_Res_MorphSTC', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '2GB', # memory for qsub process\n # 'dep': 'R_WidthMR',\n # 'var': '\"ResolutionMetrics width_maxrad\"'},\n \n # {'N': 'R_MphAmpSum', # job name\n # 'Py': 'WH_Res_MorphSTC', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '2GB', # memory for qsub process\n # 'dep': 'R_AmpSum',\n # 'var': '\"ResolutionMetrics amplitude_sum\"'},\n\n # {'N': 'R_MphAmpPeak', # job name\n # 'Py': 'WH_Res_MorphSTC', # Python script\n # 'Cf': 'WH_MNE_Resolution_config', # configuration script\n # 'Ss': subjs, # subject indices\n # 'mem': '2GB', # memory for qsub process\n # 'dep': 'R_AmpPeak',\n # 'var': '\"ResolutionMetrics amplitude_peak\"'}\n \n #####\n # AVERAGING Resolution Metrics\n #####\n ### NOTE: The following depend on completion of previous jobs for ALL subjects\n {'N': 'R_AMLocErrPeak', # job name\n 'Py': 'WH_Res_AvgSTCs', # Python script\n 'Cf': 'WH_MNE_Resolution_config', # configuration script\n 'Ss': [''], # subject indices, '' if across all subjects\n 'mem': '1GB', # memory for qsub process\n 'var': '\"ResolutionMetrics locerr_peak\"'},\n\n {'N': 'R_AMLocErrCog', # job name\n 'Py': 'WH_Res_AvgSTCs', # Python script\n 'Cf': 'WH_MNE_Resolution_config', # configuration script\n 'Ss': [''], # subject indices, '' if across all subjects\n 'mem': '1GB', # memory for qsub process\n 'var': '\"ResolutionMetrics locerr_cog\"'},\n\n {'N': 'R_AMWidthSD', # job name\n 'Py': 'WH_Res_AvgSTCs', # Python script\n 'Cf': 'WH_MNE_Resolution_config', # configuration script\n 'Ss': [''], # subject indices, '' if across all subjects\n 'mem': '1GB', # memory for qsub process\n 'var': '\"ResolutionMetrics width_sd\"'},\n \n {'N': 'R_AMWidthMR', # job name\n 'Py': 'WH_Res_AvgSTCs', # Python script\n 'Cf': 'WH_MNE_Resolution_config', # configuration script\n 'Ss': [''], # subject indices, '' if across all subjects\n 'mem': '1GB', # memory for qsub process\n 'var': '\"ResolutionMetrics width_maxrad\"'},\n \n {'N': 'R_AMAmpSum', # job name\n 'Py': 'WH_Res_AvgSTCs', # Python script\n 'Cf': 'WH_MNE_Resolution_config', # configuration script\n 'Ss': [''], # subject indices, '' if across all subjects\n 'mem': '1GB', # memory for qsub process\n 'var': '\"ResolutionMetrics amplitude_sum\"'},\n\n {'N': 'R_AMAmpPeak', # job name\n 'Py': 'WH_Res_AvgSTCs', # Python script\n 'Cf': 'WH_MNE_Resolution_config', # configuration script\n 'Ss': [''], # subject indices, '' if across all subjects\n 'mem': '1GB', # memory for qsub process\n 'var': '\"ResolutionMetrics amplitude_peak\"'}\n]\n\n# directory where python scripts are\ndir_py = op.join('/', 'home', 'olaf', 'MEG', 'WakemanHensonEMEG', 'ScriptsResolution')\n\n# directory for qsub output\ndir_qsub = op.join('/', 'home', 'olaf', 'MEG', 'WakemanHensonEMEG', 'ScriptsResolution', 'qsub_out')\n\n# wrapper to run python script via qsub\nfname_wrap = op.join('/', 'home', 'olaf', 'MEG', 'WakemanHensonEMEG', 'wrapper_qsub_python_v015.sh')\n\n\n# keep track of qsub Job IDs\nJob_IDs = {}\n\nfor job in job_list:\n\n for Ss in job['Ss']:\n\n Ss = str(Ss) # turn into string for filenames etc.\n\n N = job['N']\n Py = op.join(dir_py, job['Py'])\n Cf = job['Cf']\n mem = job['mem']\n\n # files for qsub output\n file_out = op.join(dir_qsub, job['N'] + '_' + Cf + '-%s.out' % str(Ss))\n file_err = op.join(dir_qsub, job['N'] + '_' + Cf + '-%s.err' % str(Ss))\n\n # if job dependent of previous job, get Job ID and produce command\n if 'dep' in job: # if dependency on previous job specified \n if job['dep']=='':\n dep_str = ''\n else:\n job_id = Job_IDs[job['dep'], Ss]\n dep_str = '-W depend=afterok:%s' % (job_id)\n else:\n dep_str = ''\n\n if 'node' in job: # if node constraint present (e.g. Maxfilter)\n node_str = job['node']\n else:\n node_str = ''\n\n if 'var' in job: # if variables for python script specified\n var_str = job['var']\n else:\n var_str = ''\n\n # use wrapper to submit python script\n qsub_cmd = 'qsub %s \\\n -N %s%s \\\n -l walltime=24:00:00,mem=%s \\\n -o %s \\\n -e %s \\\n -v pycmd=\"%s.py %s\",subj_idx=%s,var=%s \\\n %s \\\n %s' \\\n % (fname_wrap, N, Ss, mem, file_out, file_err, Py, Cf, Ss, var_str, dep_str, node_str)\n\n # format string for display\n print_str = qsub_cmd.replace(' ' * 25, ' ')\n print('\\n%s\\n' % print_str)\n\n # execute qsub command\n proc = subprocess.Popen(qsub_cmd, stdout=subprocess.PIPE, shell=True)\n\n # get linux output\n (out, err) = proc.communicate()\n\n # keep track of Job IDs from qsub\n Job_IDs[N, Ss] = out.split('.')[0]\n\n# Done","sub_path":"WH_Res_QSUB.py","file_name":"WH_Res_QSUB.py","file_ext":"py","file_size_in_byte":13366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"412264584","text":"from platform import platform\r\nfrom pathlib import Path\r\nfrom typing import Dict, TYPE_CHECKING\r\n\r\nfrom Resources.DataHandlers.ExcelHandler import ExcelHandlerFacade\r\n\r\nif TYPE_CHECKING:\r\n from Resources.DataHandlers.ExcelHandler.ConverterTransfer import ConverterTransfer\r\n from Resources.TimeHandlers.TimeKeeper import TimeKeeper\r\n\r\n\r\ndef get_current_os() -> str:\r\n current_os: str = platform()\r\n\r\n if \"linux\" in current_os.lower():\r\n return \"linux\"\r\n\r\n return \"win\"\r\n\r\n\r\nif __name__ == \"__main__\":\r\n current_os = get_current_os()\r\n path_to_file: Dict[str, Path] = {\r\n \"linux\": Path(\"/media/gabriel/5272421C72420567/Dokumentumok/Hivatalos/Tom Tailor/Időrend.xlsx\"),\r\n \"win\": Path(\"D:\\\\Dokumentumok\\\\Hivatalos\\\\Tom Tailor\\\\Időrend.xlsx\"),\r\n }\r\n\r\n excel_handler: ExcelHandlerFacade = ExcelHandlerFacade()\r\n\r\n converter_transfer: 'ConverterTransfer' = excel_handler.process_workbook(path_to_file[current_os])\r\n\r\n timekeeper: 'TimeKeeper' = converter_transfer.get_timekeeper()\r\n\r\n print(f\"The current OS is: {current_os}\")\r\n\r\n print(f\"Total time balance: {timekeeper.get_printable_total_balance()}\")\r\n\r\n print(\"The following days had irregularities:\")\r\n\r\n for date, column in converter_transfer.get_irregularities():\r\n print(f\"On {date.strftime('%Y.%m.%d')}, in column: {column}\")\r\n","sub_path":"src/tests/Resources/DataHandlers/test_excel_handler.py","file_name":"test_excel_handler.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"144187538","text":"# Get search bar result\nimport requests\nfrom bs4 import BeautifulSoup\nimport pymongo\n\nazdb = pymongo.MongoClient('localhost', 27017)\naz = azdb['az']\naz_asin = az['az_asin']\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) \\\n AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'\n }\n\n\ndef get_page(p):\n url = 'http://www.amazon.com/gp/aw/s/\\\n ref=is_pn_1?rh=i%3Aaps%2Ck%3Awrap+bracelet&page={}&keywords=pendant+necklace'.format(p)\n return url\n\n\ndef get_asin(url):\n web_data = requests.get(url, headers=headers)\n # print(web_data.text)\n soup = BeautifulSoup(web_data.text, 'lxml')\n asins = soup.select('#resultItems li > a')\n # asin_list = []\n for i in asins:\n asin = i.get('data-asin')\n if asin not in list(i['asin'] for i in az_asin.find()):\n az_asin.insert_one({'asin': asin})\n print(asin)\n # asin_list.append(i.get('data-asin'))\n # return asin_list\n\n\n\nif __name__ == '__main__':\n pass\n # for p in range(1, 10):\n # get_asin(get_page(p))\n # get_asin('http://www.amazon.com/s/ref=sr_pg_2?rh=i%3Aaps%2Ck%3Asaae+bracelet&page=2&keywords=saae+bracelet&ie=UTF8&qid=1460537937')","sub_path":"amazon_project/azon_productinfo_getter.py","file_name":"azon_productinfo_getter.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"43161095","text":"class Solution:\n \"\"\"\n @param grid: a list of lists of integers\n @return: An integer, minimizes the sum of all numbers along its path\n \"\"\"\n\n # O(n) space, O(mn) time\n def minPathSum(self, grid):\n if not grid or not grid[0]:\n return 0\n\n m = len(grid)\n n = len(grid[0])\n dp = [[0] * n for _ in range(2)]\n dp[0][0] = grid[0][0]\n\n for i in range(m):\n for j in range(n):\n if i == 0 and j == 0:\n continue\n if i == 0:\n dp[0][j] += dp[0][j - 1] + grid[0][j]\n continue\n if j == 0:\n dp[i % 2][0] += dp[(i - 1) % 2][0] + grid[i][0]\n continue\n\n dp[i % 2][j] = min(dp[i % 2][j - 1], dp[(i - 1) % 2][j]) + grid[i][j]\n\n return dp[(m - 1) % 2][-1]\n\n\n # O(mn) Time, O(mn) Space\n # def minPathSum(self, grid):\n # if not grid or not grid[0]:\n # return 0\n\n # m = len(grid)\n # n = len(grid[0])\n # dp = [[0] * n for _ in range(m)]\n # dp[0][0] = grid[0][0]\n\n # for i in range(1, n):\n # dp[0][i] = dp[0][i - 1] + grid[0][i]\n\n # for j in range(1, m):\n # dp[j][0] = dp[j - 1][0] + grid[j][0]\n\n # for i in range(1, m):\n # for j in range(1, n):\n # dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]\n\n # return dp[-1][-1]\n","sub_path":"110_Minimum Path Sum.py","file_name":"110_Minimum Path Sum.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"647908532","text":"import time\nimport mywallet\nimport uuosconfig\nfrom pyeoskit import eosapi\n\nfrom threading import Thread, Event\nfrom kivy.uix.button import Label\nfrom kivy.clock import Clock, mainthread\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.uix.popup import Popup\n\nfrom kivy.uix.behaviors import ButtonBehavior\nfrom kivy.uix.boxlayout import BoxLayout\n\nimport customui\nimport time\nimport datetime\n\nclass HistoryRow(ButtonBehavior, BoxLayout):\n pass\n\nclass TransferHistoryScreen(Screen):\n def __init__(self, *args, **kwargs):\n super(TransferHistoryScreen, self).__init__(*args, **kwargs)\n self.event = Event()\n self.token_symbol = None\n self.actions = {}\n self.trxs = {}\n mywallet.add_account_observer(self.on_account_changed)\n \n def on_account_changed(self):\n self.trxs = {}\n self.actions = {}\n\n def get_transfer_history_thread(self):\n try:\n print(eosapi.client.node_url)\n network = uuosconfig.get_current_network()\n if network == 'eosnetwork':\n eosapi.set_nodes(['https://eos.greymass.com'])\n else:\n eosapi.set_nodes(['https://nodes.uuos.network'])\n\n history = eosapi.get_actions(uuosconfig.current_account, -1, -50)\n# print(uuosconfig.current_account, history)\n self.actions = history['actions']\n self.refresh_history()\n except Exception as e:\n uuosconfig.logger.exception(e)\n self.stop_loading()\n\n @mainthread\n def refresh_history(self):\n if self.ids.id_in.state == 'down':\n self.ids.id_in.color = uuosconfig.app.fontcolor_6\n self.ids.id_out.color = uuosconfig.app.fontcolor_1\n self.ids.id_all.color = uuosconfig.app.fontcolor_1\n self.ids.id_in.background_color = [1,1,1,1]\n self.ids.id_out.background_color = [1,1,1,0]\n self.ids.id_all.background_color = [1,1,1,0]\n elif self.ids.id_out.state == 'down':\n self.ids.id_out.color = uuosconfig.app.fontcolor_6\n self.ids.id_in.color = uuosconfig.app.fontcolor_1\n self.ids.id_all.color = uuosconfig.app.fontcolor_1\n self.ids.id_in.background_color = [1,1,1,0]\n self.ids.id_all.background_color = [1,1,1,0]\n self.ids.id_out.background_color = [1,1,1,1]\n elif self.ids.id_all.state == 'down':\n self.ids.id_all.color = uuosconfig.app.fontcolor_6\n self.ids.id_in.color = uuosconfig.app.fontcolor_1\n self.ids.id_out.color = uuosconfig.app.fontcolor_1\n self.ids.id_out.background_color = [1,1,1,0]\n self.ids.id_in.background_color = [1,1,1,0]\n self.ids.id_all.background_color = [1,1,1,1]\n self.ids.rv.data = []\n self.trxs = {}\n current_account = mywallet.get_current_account()\n for action in self.actions:\n trx_id = action['action_trace']['trx_id']\n if trx_id in self.trxs:\n continue\n self.trxs[trx_id] = 1\n act = action['action_trace']['act']\n if act['name'] != 'transfer':\n continue\n from_ = act['data']['from']\n to = act['data']['to']\n quantity = act['data']['quantity']\n if self.ids.id_in.state == 'down':\n if current_account != to:\n continue\n elif self.ids.id_out.state == 'down':\n if current_account != from_:\n continue\n if from_ == uuosconfig.current_account:\n direction = 'atlas://data/images/%s/zhuanchu' % uuosconfig.app.theme\n friend_account = to\n else:\n direction = 'atlas://data/images/%s/zhuanru' % uuosconfig.app.theme\n friend_account = from_\n \n now_stamp = time.time()\n local_time = datetime.datetime.fromtimestamp(now_stamp)\n utc_time = datetime.datetime.utcfromtimestamp(now_stamp)\n offset = local_time - utc_time\n\n t1 = action['action_trace']['block_time']\n UTC_FORMAT = \"%Y-%m-%dT%H:%M:%S.%f\"\n t2 = datetime.datetime.strptime(t1, UTC_FORMAT)\n t3 = str(t2 + offset)\n try:\n time_array = time.strptime(t3, \"%Y-%m-%d %H:%M:%S.%f\")\n except ValueError:\n time_array = time.strptime(t3, \"%Y-%m-%d %H:%M:%S\")\n dt_new = time.strftime(\"%Y-%m-%d %H:%M:%S\",time_array)\n\n values = {'direction':direction,\n 'friend_account': friend_account,\n 'quantity': quantity,\n 'block_time': dt_new,\n 'action': action\n }\n self.ids.rv.data.insert(0, values)\n\n @mainthread\n def stop_loading(self):\n self.ids.id_loading.stop()\n \n def on_more(self):\n link = 'https://eospark.com/account/' + mywallet.get_current_account()\n import webbrowser\n webbrowser.open(link)\n\n def on_enter(self):\n self.event.clear()\n eosapi.set_nodes(['https://eos.greymass.com'])\n if not self.actions:\n self.ids.id_loading.start()\n self.refresh_history()\n# customui.show_widget(self.ids.loading, True)\n Thread(target=self.get_transfer_history_thread).start()\n\n uuosconfig.register_network_change_listener(self.on_network_changed)\n\n def on_network_changed(self):\n Thread(target=self.get_transfer_history_thread).start()\n\n def on_leave(self):\n self.event.set()\n self.ids.id_loading.stop()\n\n def on_stop(self):\n self.ids.id_loading.stop()\n\n def on_press(self, item):\n uuosconfig.app.show_screen('transfer_detail_screen')\n screen = uuosconfig.app.get_screen('transfer_detail_screen')\n screen.action = item.action\n","sub_path":"transferhistoryscreen.py","file_name":"transferhistoryscreen.py","file_ext":"py","file_size_in_byte":5951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"468672949","text":"#!/bin/python\nfrom deap import tools\nimport numpy as np\nimport os\nstatisticsNames = {'avg': 'Average profit',\n 'std': 'Profit variation',\n 'min': 'Minimum profit',\n 'max': 'Maximum profit',\n 'size': 'Population size',\n 'maxsize': 'Max population size'}\n\ndef getStatisticsMeter():\n stats = tools.Statistics(lambda ind: ind.fitness.values[0])\n stats.register(\"avg\", np.mean)\n stats.register(\"std\", np.std)\n stats.register(\"min\", np.min)\n stats.register(\"max\", np.max)\n\n\n return stats\n\ndef write_evolution_logs(i, stats, filename=\"output/evolution_gen.csv\"):\n #print(i, stats)\n if type(stats) == dict:\n message = ','.join([str(x) for x in [i,stats['avg'],\n stats['std'],\n stats['min'],\n stats['max'],\n stats['dateRange']]])\n elif type(stats) == list:\n message = ','.join([str(x) for x in [i] + stats])\n else:\n raise\n #print(message)\n\n if i == 0 and os.path.isfile(filename):\n os.remove(filename)\n f=open(filename, 'a+')\n f.write(message+\"\\n\")\n #print(message)\n f.close()\n\n\n\n","sub_path":"promoterz/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"620355465","text":"class Solution:\n def wordBreak(self, s, wordDict):\n \"\"\"\n :type s: str\n :type wordDict: List[str]\n :rtype: bool\n \"\"\"\n # dp[i] denotes whether s[:i] can be built\n dp = [True]\n for i in range(1, len(s) + 1):\n dp += any(dp[j] and s[j:i] in wordDict for j in range(i)), # comma makes it a list.\n return dp[-1]\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.wordBreak(\"leetcode\", [\"leet\", \"code\"]))","sub_path":"wordBreak.py","file_name":"wordBreak.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"140214999","text":"#!/usr/bin/env python\n\n#===========================================================================\n#\n# Produce plots for ZDR bias by volume - paper\n#\n#===========================================================================\n\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport subprocess\nfrom optparse import OptionParser\nimport numpy as np\nfrom numpy import convolve\nfrom numpy import linalg, array, ones\nimport matplotlib.pyplot as plt\nfrom matplotlib import dates\nimport math\nimport datetime\nimport contextlib\n\ndef main():\n\n# globals\n\n global options\n global debug\n global startTime\n global endTime\n\n# parse the command line\n\n usage = \"usage: %prog [options]\"\n parser = OptionParser(usage)\n parser.add_option('--debug',\n dest='debug', default=False,\n action=\"store_true\",\n help='Set debugging on')\n parser.add_option('--verbose',\n dest='verbose', default=False,\n action=\"store_true\",\n help='Set verbose debugging on')\n parser.add_option('--bias_file',\n dest='biasFilePath',\n default='../data/pecan/zdr_bias.spol.paper.txt',\n help='File path for bias results')\n parser.add_option('--cp_file',\n dest='cpFilePath',\n default='../data/pecan/spol_pecan_CP_analysis_20150528_000553.txt',\n help='CP results file path')\n parser.add_option('--title',\n dest='title',\n default='ZDR BIAS FROM ICE AND BRAGG',\n help='Title for plot')\n parser.add_option('--width',\n dest='figWidthMm',\n default=400,\n help='Width of figure in mm')\n parser.add_option('--height',\n dest='figHeightMm',\n default=200,\n help='Height of figure in mm')\n parser.add_option('--lenMean',\n dest='lenMean',\n default=1,\n help='Len of moving mean filter')\n parser.add_option('--start',\n dest='startTime',\n default='2015 06 15 00 00 00',\n help='Start time for XY plot')\n parser.add_option('--end',\n dest='endTime',\n default='2015 07 16 12 00 00',\n help='End time for XY plot')\n parser.add_option('--sur_only',\n dest='surOnly', default=False,\n action=\"store_true\",\n help='Only process surveillance scans')\n parser.add_option('--rhi_only',\n dest='rhiOnly', default=False,\n action=\"store_true\",\n help='Only process RHI scans')\n \n (options, args) = parser.parse_args()\n \n if (options.verbose == True):\n options.debug = True\n\n year, month, day, hour, minute, sec = options.startTime.split()\n startTime = datetime.datetime(int(year), int(month), int(day),\n int(hour), int(minute), int(sec))\n\n year, month, day, hour, minute, sec = options.endTime.split()\n endTime = datetime.datetime(int(year), int(month), int(day),\n int(hour), int(minute), int(sec))\n\n if (options.debug == True):\n print(\"Running %prog\", file=sys.stderr)\n print(\" cpFilePath: \", options.cpFilePath, file=sys.stderr)\n print(\" biasFilePath: \", options.biasFilePath, file=sys.stderr)\n print(\" startTime: \", startTime, file=sys.stderr)\n print(\" endTime: \", endTime, file=sys.stderr)\n\n # read in column headers for bias results\n\n iret, biasHdrs, biasData = readColumnHeaders(options.biasFilePath)\n if (iret != 0):\n sys.exit(-1)\n\n # read in data for bias results\n\n biasData, biasTimes = readInputData(options.biasFilePath, biasHdrs, biasData)\n\n # read in column headers for CP results\n\n iret, cpHdrs, cpData = readColumnHeaders(options.cpFilePath)\n if (iret != 0):\n sys.exit(-1)\n\n # read in data for CP results\n\n cpData, cpTimes = readInputData(options.cpFilePath, cpHdrs, cpData)\n\n # prepare the data for plotting\n\n prepareData(biasData, biasTimes, cpData, cpTimes)\n\n # render the plot\n \n doPlot()\n\n # done\n\n sys.exit(0)\n \n########################################################################\n# Read columm headers for the data\n# this is in the first line\n\ndef readColumnHeaders(filePath):\n\n colHeaders = []\n colData = {}\n\n fp = open(filePath, 'r')\n line = fp.readline()\n fp.close()\n \n commentIndex = line.find(\"#\")\n if (commentIndex == 0):\n # header\n colHeaders = line.lstrip(\"# \").rstrip(\"\\n\").split()\n if (options.debug == True):\n print(\"Reading file: \", filePath, file=sys.stderr)\n for icol, var in enumerate(colHeaders, start=0):\n print(\"colHeader[\", icol, \"] = \", colHeaders[icol], file=sys.stderr)\n else:\n print(\"ERROR - readColumnHeaders\", file=sys.stderr)\n print(\" First line does not start with #\", file=sys.stderr)\n return -1, colHeaders, colData\n \n for icol, var in enumerate(colHeaders, start=0):\n colData[var] = []\n \n return 0, colHeaders, colData\n\n########################################################################\n# Read in the data\n\ndef readInputData(filePath, colHeaders, colData):\n\n # open file\n\n fp = open(filePath, 'r')\n lines = fp.readlines()\n\n # read in a line at a time, set colData\n for line in lines:\n \n commentIndex = line.find(\"#\")\n if (commentIndex >= 0):\n continue\n \n # data\n \n data = line.strip().split()\n if (len(data) != len(colHeaders)):\n if (options.debug == True):\n print(\"skipping line: \", line, file=sys.stderr)\n continue;\n\n for index, var in enumerate(colHeaders, start=0):\n # print >>sys.stderr, \"index, data[index]: \", index, \", \", data[index]\n if (var == 'count' or var == 'year' or var == 'month' or var == 'day' or \\\n var == 'hour' or var == 'min' or var == 'sec' or \\\n var == 'unix_time'):\n colData[var].append(int(data[index]))\n else:\n colData[var].append(float(data[index]))\n\n fp.close()\n\n # load observation times array\n\n year = colData['year']\n month = colData['month']\n day = colData['day']\n hour = colData['hour']\n minute = colData['min']\n sec = colData['sec']\n\n obsTimes = []\n for ii, var in enumerate(year, start=0):\n thisTime = datetime.datetime(year[ii], month[ii], day[ii],\n hour[ii], minute[ii], sec[ii])\n obsTimes.append(thisTime)\n\n if (options.verbose == True):\n print(\"Read in file: \", filePath, file=sys.stderr)\n for itime, obsTime in enumerate(obsTimes, start=0):\n sys.stdout.write('===>> ')\n sys.stdout.write(str(obsTime))\n sys.stdout.write(': ')\n for icol, var in enumerate(colHeaders, start=0):\n sys.stdout.write(colHeaders[icol] + ':')\n sys.stdout.write(str(colData[var][itime]))\n sys.stdout.write(' ')\n sys.stdout.write('\\n')\n\n return colData, obsTimes\n\n########################################################################\n# Moving average filter\n\ndef movingAverage(values, window):\n\n if (window < 2):\n return values\n\n weights = np.repeat(1.0, window)/window\n sma = np.convolve(values, weights, 'same')\n return sma\n\n########################################################################\n# Prepare data sets for plotting\n\ndef prepareData(biasData, biasTimes, cpData, cpTimes):\n\n lenMeanFilter = int(options.lenMean)\n\n # set up arrays for ZDR bias\n\n global btimes\n btimes = np.array(biasTimes).astype(datetime.datetime)\n \n isRhi = np.array(biasData[\"IsRhi\"]).astype(np.int)\n \n biasIce = np.array(biasData[\"ZdrInIcePerc25.00\"]).astype(np.double)\n biasIce = movingAverage(biasIce, lenMeanFilter)\n validIce = (np.isfinite(biasIce) & (btimes >= startTime) & (btimes <= endTime))\n \n biasIceM = np.array(biasData[\"ZdrmInIcePerc25.00\"]).astype(np.double)\n biasIceM = movingAverage(biasIceM, lenMeanFilter)\n validIceM = (np.isfinite(biasIceM) & (btimes >= startTime) & (btimes <= endTime))\n \n biasBragg = np.array(biasData[\"ZdrInBraggPerc32.00\"]).astype(np.double)\n biasBragg = movingAverage(biasBragg, lenMeanFilter)\n validBragg = (np.isfinite(biasBragg) & (btimes >= startTime) & (btimes <= endTime))\n\n biasBraggM = np.array(biasData[\"ZdrmInBraggPerc25.00\"]).astype(np.double)\n biasBraggM = movingAverage(biasBraggM, lenMeanFilter)\n validBraggM = np.isfinite(biasBraggM)\n validBraggM = (np.isfinite(biasBraggM) & (btimes >= startTime) & (btimes <= endTime))\n\n if (options.rhiOnly):\n validIce = (np.isfinite(biasIce) & (isRhi == 1))\n validIceM = (np.isfinite(biasIceM) & (isRhi == 1))\n validBragg = (np.isfinite(biasBragg) & (isRhi == 1))\n validBraggM = (np.isfinite(biasBraggM) & (isRhi == 1))\n if (options.surOnly):\n validIce = (np.isfinite(biasIce) & (isRhi == 0))\n validIceM = (np.isfinite(biasIceM) & (isRhi == 0))\n validBragg = (np.isfinite(biasBragg) & (isRhi == 0))\n validBraggM = (np.isfinite(biasBraggM) & (isRhi == 0))\n\n global validIceBtimes, validIceVals\n validIceBtimes = btimes[validIce]\n validIceVals = biasIce[validIce]\n\n global validIceMBtimes, validIceMVals\n validIceMBtimes = btimes[validIceM]\n validIceMVals = biasIceM[validIceM]\n\n global validBraggBtimes, validBraggVals\n validBraggBtimes = btimes[validBragg]\n validBraggVals = biasBragg[validBragg]\n\n global validBraggMBtimes, validBraggMVals\n validBraggMBtimes = btimes[validBraggM]\n validBraggMVals = biasBraggM[validBraggM]\n \n # load up receiver gain etc - axis 4\n \n (dailyTimeIce, dailyValIce) = computeDailyStats(validIceBtimes, validIceVals)\n (dailyTimeBragg, dailyValBragg) = computeDailyStats(validBraggBtimes, validBraggVals)\n\n (dailyTimeIceM, dailyValIceM) = computeDailyStats(validIceMBtimes, validIceMVals)\n (dailyTimeBraggM, dailyValBraggM) = computeDailyStats(validBraggMBtimes, validBraggMVals)\n\n # site temp, vert pointing and sun scan results\n\n ctimes = np.array(cpTimes).astype(datetime.datetime)\n ZdrmVert = np.array(cpData[\"ZdrmVert\"]).astype(np.double)\n validZdrmVert = np.isfinite(ZdrmVert)\n \n SunscanZdrm = np.array(cpData[\"SunscanZdrm\"]).astype(np.double)\n validSunscanZdrm = np.isfinite(SunscanZdrm)\n\n global cptimes\n cptimes = np.array(cpTimes).astype(datetime.datetime)\n tempSite = np.array(cpData[\"TempSite\"]).astype(np.double)\n validTempSite = np.isfinite(tempSite)\n \n # tx ratio\n\n txPwrH = np.array(cpData[\"TxPwrH\"]).astype(np.double)\n txPwrV = np.array(cpData[\"TxPwrV\"]).astype(np.double)\n\n global ratioTimes, ratioIceVals, ratioIceBias, ratioTxCorrBias, ratioTempVals\n ratioTimes = []\n ratioIceVals = []\n ratioTempVals = []\n ratioIceBias = []\n\n for ii, biasVal in enumerate(validIceMVals, start=0):\n btime = validIceMBtimes[ii]\n ratioTime, ratioTemp, ratioVal = getClosestRatio \\\n (btime, cptimes, tempSite, txPwrH, txPwrV)\n ratioTempVals.append(ratioTemp)\n txCorrBias = biasVal - ratioVal\n ratioTimes.append(ratioTime)\n ratioIceVals.append(ratioVal)\n ratioIceBias.append(biasVal)\n if (options.verbose):\n print(\"==>> btime, rtime, bias, txPwrH, txPwrV, ratioVal, txCorrBias:\", \\\n btime, ratioTime, biasVal, txPwrH[ii], txPwrV[ii], ratioVal, txCorrBias, file=sys.stderr)\n\n meanRatio = np.mean(ratioIceVals)\n normRatios = ratioIceVals - meanRatio\n ratioTxCorrBias = validIceMVals - normRatios\n \n # ZDR bias vs temp\n\n global tempTimes, tempIceMVals, tempIceMBias\n tempTimes = []\n tempIceMVals = []\n tempIceMBias = []\n\n for ii, biasVal in enumerate(validIceMVals, start=0):\n btime = validIceMBtimes[ii]\n tempTime, tempVal = getClosestTemp(btime, cptimes, tempSite)\n tempTimes.append(tempTime)\n tempIceMVals.append(tempVal)\n tempIceMBias.append(biasVal)\n if (options.verbose):\n print(\"==>> biasTime, biasVal, tempTime, tempVal:\", \\\n btime, biasVal, tempTime, tempVal, file=sys.stderr)\n\n global tempMean, tempSdev, tempNorm\n #tempMean = np.mean(tempIceMVals)\n #tempSdev = np.std(tempIceMVals)\n #tempNorm = (tempIceMVals - tempMean) / (tempSdev * 10.0)\n tempMean = np.mean(tempSite)\n tempSdev = np.std(tempSite)\n tempNorm = (tempSite - tempMean) / (tempSdev * 10.0)\n if (options.debug):\n print(\"==>> tempMean, tempSdev: \", tempMean, tempSdev, file=sys.stderr)\n\n # linear regression for bias vs temp\n # obtain the fit, ww[0] is slope, ww[1] is intercept\n\n global AA, ww, tempRegrX, tempRegrY, minTemp, maxTemp\n\n AA = array([tempIceMVals, ones(len(tempIceMVals))])\n ww = linalg.lstsq(AA.T, tempIceMBias)[0]\n minTemp = min(tempIceMVals)\n maxTemp = max(tempIceMVals)\n\n tempRegrX = []\n tempRegrY = []\n tempRegrX.append(minTemp)\n tempRegrX.append(maxTemp)\n tempRegrY.append(ww[0] * minTemp + ww[1])\n tempRegrY.append(ww[0] * maxTemp + ww[1])\n\n # linear regression for tx-corrected bias vs temp\n # obtain the fit, ww[0] is slope, ww[1] is intercept\n\n global AA2, ww2, tempRegrX2, tempRegrY2, minTemp2, maxTemp2\n\n AA2 = array([ratioTempVals, ones(len(ratioTempVals))])\n ww2 = linalg.lstsq(AA2.T, ratioTxCorrBias)[0]\n minTemp2 = min(ratioTempVals)\n maxTemp2 = max(ratioTempVals)\n\n tempRegrX2 = []\n tempRegrY2 = []\n tempRegrX2.append(minTemp2)\n tempRegrX2.append(maxTemp2)\n tempRegrY2.append(ww2[0] * minTemp2 + ww2[1])\n tempRegrY2.append(ww2[0] * maxTemp2 + ww2[1])\n\n # correct bias for linear regression\n\n slope = ww2[0]\n intercept = ww2[1]\n\n global ratioCorrBias\n ratioCorrBias = []\n for ii, rtime in enumerate(ratioTimes, start=0):\n tempC = ratioTempVals[ii]\n biasDb = ratioIceBias[ii]\n tempCorr = intercept + tempC * slope\n corrBias = biasDb - tempCorr\n ratioCorrBias.append(corrBias)\n\n########################################################################\n# Plot\n\ndef doPlot():\n\n fileName = options.biasFilePath\n titleStr = \"File: \" + fileName\n hfmt = dates.DateFormatter('%y/%m/%d')\n\n lenMeanFilter = int(options.lenMean)\n\n # set up plots\n \n widthIn = float(options.figWidthMm) / 25.4\n htIn = float(options.figHeightMm) / 25.4\n \n fig1 = plt.figure(1, (widthIn, htIn))\n \n ax1a = fig1.add_subplot(1,1,1,xmargin=0.0)\n #ax1b = fig1.add_subplot(2,1,2,xmargin=0.0)\n #ax1c = fig1.add_subplot(3,1,3,xmargin=0.0)\n\n fig2 = plt.figure(2, (widthIn/2, htIn))\n ax2a = fig2.add_subplot(1,1,1,xmargin=1.0, ymargin=1.0)\n\n fig3 = plt.figure(3, (widthIn/2, htIn))\n ax3a = fig3.add_subplot(1,1,1,xmargin=1.0, ymargin=1.0)\n\n oneDay = datetime.timedelta(1.0)\n #ax1a.set_xlim([btimes[0] - oneDay, btimes[-1] + oneDay])\n timeRange = endTime - startTime\n timeRangeMargin = timeRange / 10\n ax1a.set_xlim(startTime - timeRangeMargin, endTime + timeRangeMargin)\n title = \"ZDRM bias in ice and Bragg\"\n if (options.rhiOnly):\n title = title + \" - RHI only\"\n elif (options.surOnly):\n title = title + \" - SUR only\"\n ax1a.set_title(title)\n\n #ax1b.set_xlim([btimes[0] - oneDay, btimes[-1] + oneDay])\n #ax1b.set_title(\"Daily mean ZDR bias in ice and Bragg (dB)\")\n #ax1c.set_xlim([btimes[0] - oneDay, btimes[-1] + oneDay])\n #ax1c.set_title(\"Site temperature (C)\")\n\n # ax1a.plot(validBraggBtimes, validBraggVals, \\\n # \"o\", label = 'ZDR Bias In Bragg', color='green')\n # ax1a.plot(validBraggBtimes, validBraggVals, \\\n # label = 'ZDR Bias In Bragg', linewidth=1, color='green')\n \n # ax1a.plot(validIceBtimes, validIceVals, \\\n # \"o\", label = 'ZDR Bias In Ice', color='magenta')\n # ax1a.plot(validIceBtimes, validIceVals, \\\n # label = 'ZDR Bias In Ice', linewidth=1, color='magenta')\n\n ax1a.plot(validBraggMBtimes, validBraggMVals, \\\n \"o\", label = 'ZDRM Bias In Bragg', color='blue')\n #ax1a.plot(validBraggMBtimes, validBraggMVals, \\\n # label = 'ZDRM Bias In Bragg', linewidth=1, color='blue')\n \n # ax1a.plot(validIceMBtimes, validIceMVals, \\\n # \"o\", label = 'ZDRM Bias In Ice', color='red')\n # ax1a.plot(validIceMBtimes, validIceMVals, \\\n # label = 'ZDRM Bias In Ice', linewidth=1, color='red')\n \n ax1a.plot(validIceMBtimes, ratioTxCorrBias, \\\n \"o\", label = 'ZDRM Tx-Corr Bias In Ice', color='green')\n # ax1a.plot(validIceMBtimes, ratioTxCorrBias, \\\n # label = 'ZDRM Tx-Corr Bias In Ice', linewidth=1, color='green')\n\n #ax1a.plot(ratioTimes, ratioCorrBias, \\\n # \"o\", label = 'Temp-corr bias', color='magenta')\n \n #ax1a.plot(tempTimes, tempNorm, \\\n # label = 'Norm-temps', color='orange', linewidth=1)\n ax1a.plot(cptimes, tempNorm, \\\n label = 'Norm-temps', color='orange', linewidth=1)\n \n #ax1a.plot(ctimes[validSunscanZdrm], SunscanZdrm[validSunscanZdrm], \\\n # linewidth=2, label = 'Zdrm Sun/CP (dB)', color = 'green')\n \n #ax1a.plot(ctimes[validZdrmVert], ZdrmVert[validZdrmVert], \\\n # \"^\", markersize=10, linewidth=1, label = 'Zdrm Vert (dB)', color = 'orange')\n\n #ax1b.plot(dailyTimeBraggM, dailyValBraggM, \\\n # label = 'Daily Bias Bragg M', linewidth=1, color='green')\n #ax1b.plot(dailyTimeBraggM, dailyValBraggM, \\\n # \"^\", label = 'Daily Bias Bragg M', color='green', markersize=10)\n\n #ax1b.plot(dailyTimeIceM, dailyValIceM, \\\n # label = 'Daily Bias Ice M', linewidth=1, color='magenta')\n #ax1b.plot(dailyTimeIceM, dailyValIceM, \\\n # \"^\", label = 'Daily Bias Ice M', color='magenta', markersize=10)\n\n # ax1b.plot(dailyTimeBragg, dailyValBragg, \\\n # label = 'Daily Bias Bragg', linewidth=1, color='blue')\n # ax1b.plot(dailyTimeBragg, dailyValBragg, \\\n # \"^\", label = 'Daily Bias Bragg', color='blue', markersize=10)\n\n # ax1b.plot(dailyTimeIce, dailyValIce, \\\n # label = 'Daily Bias Ice', linewidth=1, color='red')\n # ax1b.plot(dailyTimeIce, dailyValIce, \\\n # \"^\", label = 'Daily Bias Ice', color='red', markersize=10)\n\n #ax1c.plot(cptimes[validTempSite], tempSite[validTempSite], \\\n # linewidth=1, label = 'Site Temp', color = 'blue')\n \n #configDateAxis(ax1a, -9999, 9999, \"ZDR Bias (dB)\", 'upper right')\n #configDateAxis(ax1a, -0.3, 0.7, \"ZDR Bias (dB)\", 'upper right')\n configDateAxis(ax1a, -9999, 9999, \"ZDR Bias (dB)\", 'upper right')\n #configDateAxis(ax1b, -0.5, 0.5, \"ZDR Bias (dB)\", 'upper right')\n #configDateAxis(ax1c, -9999, 9999, \"Temp (C)\", 'upper right')\n\n # ZDR vs temp\n\n label2a = \"ZDR Bias In Ice = \" + (\"%.5f\" % ww[0]) + \" * temp + \" + (\"%.3f\" % ww[1])\n ax2a.plot(tempIceMVals, tempIceMBias, \n \"x\", label = label2a, color = 'blue')\n ax2a.plot(tempRegrX, tempRegrY, linewidth=3, color = 'blue')\n \n legend2a = ax2a.legend(loc=\"upper left\", ncol=4)\n for label2a in legend2a.get_texts():\n label2a.set_fontsize(12)\n ax2a.set_xlabel(\"Site temperature (C)\")\n ax2a.set_ylabel(\"ZDR Bias (dB)\")\n ax2a.grid(True)\n ax2a.set_ylim([-0.5, 0.5])\n ax2a.set_xlim([minTemp - 1, maxTemp + 1])\n title2a = \"ZDR Bias In Ice Vs Temp: \" + str(startTime) + \" - \" + str(endTime)\n ax2a.set_title(title2a)\n\n # tx corrected ZDR vs temp\n\n label3a = \"Tx-corr ZDR Bias In Ice = \" + (\"%.5f\" % ww2[0]) + \" * temp + \" + (\"%.3f\" % ww2[1])\n ax3a.plot(ratioTempVals, ratioTxCorrBias,\n \"x\", label = label3a, color = 'red')\n ax3a.plot(ratioTempVals, ratioCorrBias,\n \"x\", label = label3a, color = 'magenta')\n ax3a.plot(tempRegrX2, tempRegrY2, linewidth=3, color = 'red')\n \n legend3a = ax3a.legend(loc=\"upper left\", ncol=4)\n for label3a in legend3a.get_texts():\n label3a.set_fontsize(12)\n ax3a.set_xlabel(\"Site temperature (C)\")\n ax3a.set_ylabel(\"Tx-corr ZDR Bias (dB)\")\n ax3a.grid(True)\n ax3a.set_ylim([-0.5, 0.5])\n ax3a.set_xlim([minTemp2 - 1, maxTemp2 + 1])\n title3a = \"Tx-corr ZDR Bias In Ice Vs Temp: \" + str(startTime) + \" - \" + str(endTime)\n ax3a.set_title(title3a)\n\n fig1.autofmt_xdate()\n fig1.tight_layout()\n fig1.subplots_adjust(bottom=0.08, left=0.06, right=0.97, top=0.96)\n plt.show()\n\n########################################################################\n# initialize legends etc\n\ndef configDateAxis(ax, miny, maxy, ylabel, legendLoc):\n \n legend = ax.legend(loc=legendLoc, ncol=4)\n for label in legend.get_texts():\n label.set_fontsize('x-small')\n ax.set_xlabel(\"Date\")\n ax.set_ylabel(ylabel)\n ax.grid(True)\n if (miny > -9990 and maxy > -9990):\n ax.set_ylim([miny, maxy])\n hfmt = dates.DateFormatter('%y/%m/%d')\n #hfmt = dates.DateFormatter('%y/%m/%d-%H:%M:%S')\n ax.xaxis.set_major_locator(dates.DayLocator())\n #ax.xaxis.set_major_locator(dates.HourLocator())\n ax.xaxis.set_major_formatter(hfmt)\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(8) \n\n########################################################################\n# get temp closest in time to the search time\n\ndef getClosestTemp(biasTime, tempTimes, obsTemps):\n\n twoHours = datetime.timedelta(0.0, 7200.0)\n\n validTimes = ((tempTimes > (biasTime - twoHours)) & \\\n (tempTimes < (biasTime + twoHours)))\n\n if (len(validTimes) < 1):\n return (biasTime, float('NaN'))\n \n searchTimes = tempTimes[validTimes]\n searchTemps = obsTemps[validTimes]\n\n if (len(searchTimes) < 1 or len(searchTemps) < 1):\n return (biasTime, float('NaN'))\n\n minDeltaTime = 1.0e99\n ttime = searchTimes[0]\n temp = searchTemps[0]\n for ii, temptime in enumerate(searchTimes, start=0):\n if (np.isfinite(searchTemps[ii])):\n ttemp = searchTemps[ii]\n deltaTime = math.fabs((temptime - biasTime).total_seconds())\n if (deltaTime < minDeltaTime):\n minDeltaTime = deltaTime\n temp = ttemp\n ttime = temptime\n\n return (ttime, temp)\n\n########################################################################\n# get tx power ratio closest in time to the search time\n\ndef getClosestRatio(biasTime, powerTimes, obsTemps, txPwrH, txPwrV):\n\n twoHours = datetime.timedelta(0.0, 7200.0)\n\n validTimes = ((powerTimes > (biasTime - twoHours)) & \\\n (powerTimes < (biasTime + twoHours)))\n \n if (len(validTimes) < 1):\n return (biasTime, float('NaN'))\n \n searchTimes = powerTimes[validTimes]\n searchTemps = obsTemps[validTimes]\n searchTxPwrH = txPwrH[validTimes]\n searchTxPwrV = txPwrV[validTimes]\n\n if (len(searchTimes) < 1 or len(searchTxPwrH) < 1):\n return (biasTime, float('NaN'))\n\n minDeltaTime = 1.0e99\n rtime = searchTimes[0]\n ratio = searchTxPwrH[0] - searchTxPwrV[0]\n temp = searchTemps[0]\n for ii, pwrtime in enumerate(searchTimes, start=0):\n if (np.isfinite(searchTemps[ii]) &\n np.isfinite(searchTxPwrH[ii]) &\n np.isfinite(searchTxPwrV[ii])):\n ttemp = searchTemps[ii]\n tratio = searchTxPwrH[ii] - searchTxPwrV[ii]\n deltaTime = math.fabs((pwrtime - biasTime).total_seconds())\n if (deltaTime < minDeltaTime):\n minDeltaTime = deltaTime\n ratio = tratio\n rtime = pwrtime\n temp = ttemp\n\n return (rtime, temp, ratio)\n\n########################################################################\n# compute daily stats for a variable\n\ndef computeDailyStats(times, vals):\n\n dailyTimes = []\n dailyMeans = []\n\n nptimes = np.array(times).astype(datetime.datetime)\n npvals = np.array(vals).astype(np.double)\n\n validFlag = np.isfinite(npvals)\n timesValid = nptimes[validFlag]\n valsValid = npvals[validFlag]\n\n if (len(nptimes) < 1):\n return (dailyTimes, dailyMeans)\n \n startTime = nptimes[0]\n endTime = nptimes[-1]\n \n startDate = datetime.datetime(startTime.year, startTime.month, startTime.day, 0, 0, 0)\n endDate = datetime.datetime(endTime.year, endTime.month, endTime.day, 0, 0, 0)\n\n oneDay = datetime.timedelta(1)\n halfDay = datetime.timedelta(0.5)\n \n thisDate = startDate\n while (thisDate < endDate + oneDay):\n \n nextDate = thisDate + oneDay\n result = []\n \n sum = 0.0\n sumDeltaTime = datetime.timedelta(0)\n count = 0.0\n for ii, val in enumerate(valsValid, start=0):\n thisTime = timesValid[ii]\n if (thisTime >= thisDate and thisTime < nextDate):\n sum = sum + val\n deltaTime = thisTime - thisDate\n sumDeltaTime = sumDeltaTime + deltaTime\n count = count + 1\n result.append(val)\n if (count > 5):\n mean = sum / count\n meanDeltaTime = datetime.timedelta(0, sumDeltaTime.total_seconds() / count)\n dailyMeans.append(mean)\n dailyTimes.append(thisDate + meanDeltaTime)\n # print >>sys.stderr, \" daily time, meanStrong: \", dailyTimes[-1], meanStrong\n result.sort()\n \n thisDate = thisDate + oneDay\n\n return (dailyTimes, dailyMeans)\n\n\n########################################################################\n# Run a command in a shell, wait for it to complete\n\ndef runCommand(cmd):\n\n if (options.debug == True):\n print(\"running cmd:\",cmd, file=sys.stderr)\n \n try:\n retcode = subprocess.call(cmd, shell=True)\n if retcode < 0:\n print(\"Child was terminated by signal: \", -retcode, file=sys.stderr)\n else:\n if (options.debug == True):\n print(\"Child returned code: \", retcode, file=sys.stderr)\n except OSError as e:\n print(\"Execution failed:\", e, file=sys.stderr)\n\n########################################################################\n# Run - entry point\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"projDir/qc/scripts/PlotIceBraggZdrBias.spol.paper.pecan.py","file_name":"PlotIceBraggZdrBias.spol.paper.pecan.py","file_ext":"py","file_size_in_byte":26804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"211700897","text":"import os\nfrom data.config import projectPath\n\n\nclass Folder:\n instance = None\n\n def get_instance(cls):\n if cls.instance is None:\n cls.instance = Folder()\n return cls.instance\n\n def __init__(self):\n print()\n\n def create_directory(self, directory_name):\n path = os.path.join(projectPath, directory_name)\n if folder.check_if_directory_exists(path) is False:\n os.mkdir(path)\n print(\"Directory '% s' created\" % directory_name)\n else:\n print(directory_name, \" : Already Exists\")\n\n def check_if_directory_exists(self, directory_path):\n return os.path.isdir(directory_path)\n\n\nfolder = Folder().get_instance()\n","sub_path":"utilities/folder_operations.py","file_name":"folder_operations.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"649110636","text":"\ndef unclength(data):\n length = 0\n index = 0\n output = []\n while index < len(data):\n if data[index] == '(':\n index += 1\n marker = []\n while data[index] != ')':\n marker.append(data[index])\n index += 1\n index += 1 # skip final \")\"\n m = \"\".join(marker).split(\"x\")\n l = int(m[0])\n r = int(m[1])\n cdata = data[index:index+l]\n length += r * unclength(cdata)\n index += l - 1\n else:\n length += 1\n index += 1\n\n return length\n\nwith open(\"input.txt\", mode=\"r\") as f:\n data = f.readline().strip()\n output = unclength(data)\n\nprint(output)\n\n","sub_path":"2016/09/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"483483367","text":"import numpy as np\nfrom tools.utils import Helper, INFO, ERROR, NOTE\nimport sys\nimport argparse\n\ndef main(train_set: str):\n centroids = np.load(f'data/{train_set}_anchor.npy')\n print(NOTE, f'Now anchors are :\\n{centroids}')\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('train_set', type=str, help=NOTE + 'this is train dataset name , the output *.npy file will be {train_set}_anchors.list')\n return parser.parse_args(argv)\n\n\nif __name__ == '__main__':\n args = parse_arguments(sys.argv[1:])\n main(args.train_set)\n","sub_path":"get_anchor_list.py","file_name":"get_anchor_list.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"397782367","text":"# -*- coding: utf-8 -*-\n# weapon.py\nimport re\nfrom enum import Enum\nfrom classes.element import ElementType\n\nclass WeaponSkill():\n\n\tclass WeaponSkillFactorType(Enum):\n\t\tnormal = 0\n\t\tmag = 1\n\t\tetc = 2\n\n\tskill_datas = [\n\t\t{\n\t\t\t'type_txt': '일반공인(소)',\n\t\t\t'type_txt_len': 12,\n\t\t\t'regex': '^atk_._1$',\n\t\t\t'type': WeaponSkillFactorType.normal,\n\t\t\t'factors': [0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.104, 0.108, 0.112, 0.116, 0.12]\n\t\t},\n\t\t{\n\t\t\t'type_txt': '일반공인(중)',\n\t\t\t'type_txt_len': 12,\n\t\t\t'regex': '^atk_._2$',\n\t\t\t'type': WeaponSkillFactorType.normal,\n\t\t\t'factors': [0, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12]\n\t\t},\n\t\t{\n\t\t\t'type_txt': '일반공인(대)',\n\t\t\t'type_txt_len': 12,\n\t\t\t'regex': '^atk_._3$',\n\t\t\t'type': WeaponSkillFactorType.normal,\n\t\t\t'factors': [0, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.156, 0.162, 0.168, 0.174, 0.18]\n\t\t},\n\t\t{\n\t\t\t'type_txt': '일반공인 II',\n\t\t\t'type_txt_len': 11,\n\t\t\t'regex': '^normal_2$',\n\t\t\t'type': WeaponSkillFactorType.normal,\n\t\t\t'factors': [0, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.168, 0.176, 0.184, 0.192, 0.2]\n\t\t},\n\t\t{\n\t\t\t'type_txt': '방진공인',\n\t\t\t'type_txt_len': 8,\n\t\t\t'regex': '^atk_m_._2$',\n\t\t\t'type': WeaponSkillFactorType.mag,\n\t\t\t'factors': [0, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.125, 0.13, 0.135, 0.14, 0.145]\n\t\t},\n\t\t{\n\t\t\t'type_txt': '방진공인 II',\n\t\t\t'type_txt_len': 11,\n\t\t\t'regex': '^atk_m_._3$',\n\t\t\t'type': WeaponSkillFactorType.mag,\n\t\t\t'factors': [0, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.156, 0.162, 0.168, 0.174, 0.18]\n\t\t},\n\t\t{\n\t\t\t'type_txt': '기타',\n\t\t\t'type_txt_len': 4,\n\t\t\t'regex': '(.*)',\n\t\t\t'type': WeaponSkillFactorType.etc,\n\t\t\t'factors': [0]\n\t\t}\n\t]\n\n\t@staticmethod\n\tdef new_instance_from_json(json, skill_lv):\n\t\tskill_type = json['image'].replace('skill_', '')\n\t\tif json['attribute'] == '':\n\t\t\tskill_element_type = None\n\t\telse:\n\t\t\tskill_element_type = ElementType(int(json['attribute']))\n\t\treturn WeaponSkill(skill_type, skill_lv, skill_element_type)\n\n\tdef __init__(self, skill_type, skill_lv, skill_element_type):\n\t\tself.type = skill_type\n\t\tself.level = skill_lv\n\t\tself.element_type = skill_element_type\n\t\tfor s_d in WeaponSkill.skill_datas:\n\t\t\tmatched = re.match(s_d['regex'], self.type)\n\t\t\tif matched != None:\n\t\t\t\tself.skill_data = s_d\n\t\t\t\tbreak\n\n\tdef factors(self, element_type):\n\t\tfactors = [0, 0]\n\t\tif self.element_type != element_type:\n\t\t\treturn factors\n\t\ts_t = self.skill_data['type']\n\t\ts_f = self.skill_data['factors']\n\t\tif s_t != WeaponSkill.WeaponSkillFactorType.etc:\n\t\t\tfactors[s_t.value] = s_f[min(len(s_f) - 1, self.level)]\n\t\treturn factors\n\n\n\nclass WeaponRarity():\n\tmax_lv_value = [\n\t\t[0],\n\t\t[10, 20, 30, 40],\n\t\t[20, 30, 40, 50],\n\t\t[30, 45, 60, 75],\n\t\t[40, 60, 80, 100, 150]\n\t]\n\n\t@staticmethod\n\tdef max_lv(rarity, limit_lv):\n\t\treturn WeaponRarity.max_lv_value[rarity][min(len(WeaponRarity.max_lv_value[rarity])-1, limit_lv)]\n\n\nclass Weapon():\n\t@staticmethod\n\tdef new_instance_from_packet(json):\n\t\tname = json['master']['name']\n\t\tlevel = json['param']['level']\n\t\tlimit_lv = int(json['param']['evolution'])\n\t\trarity = int(json['master']['rarity'])\n\t\thp = int(json['param']['hp'])\n\t\tatk = int(json['param']['attack'])\n\t\telement_type_name = ElementType(int(json['master']['attribute'])).name\n\t\tweapon_type = int(json['master']['kind'])\n\t\tskills = []\n\t\tif json['skill1']['name'] != None:\n\t\t\tskills.append(WeaponSkill.new_instance_from_json(json['skill1'], int(json['param']['skill_level'])))\n\t\tif json['skill2']['name'] != None:\n\t\t\tskills.append(WeaponSkill.new_instance_from_json(json['skill2'], int(json['param']['skill_level'])))\n\t\treturn Weapon(name, level, limit_lv, rarity, hp, atk, element_type_name, weapon_type, skills)\n\n\t@staticmethod\n\tdef new_instance_from_json(json):\n\t\tname = json['name']\n\t\tlevel = json['level']\n\t\tlimit_lv = json['limit_lv']\n\t\trarity = json['rarity']\n\t\thp = json['hp']\n\t\tatk = json['atk']\n\t\telement_type_name = json['element_type']\n\t\tweapon_type = json['weapon_type']\n\t\tskills = []\n\t\tfor sk_obj in json['skills']:\n\t\t\tskill_type = sk_obj['skill_type']\n\t\t\tskill_element_type = ElementType(int(skill_type[len(skill_type)-3:len(skill_type)-2]))\n\t\t\tskills.append(WeaponSkill(sk_obj['skill_type'], int(sk_obj['skill_lv']), skill_element_type))\n\t\treturn Weapon(name, level, limit_lv, rarity, hp, atk, element_type_name, weapon_type, skills)\n\n\tdef __init__(self, name, level, limit_lv, rarity, hp, atk, element_type_name, weapon_type, skills):\n\t\tself.name = name\n\t\tself.level = level\n\t\tself.limit_lv = limit_lv\n\t\tself.rarity = rarity\n\t\tself.max_lv = WeaponRarity.max_lv(rarity, limit_lv)\n\t\tself.hp = hp\n\t\tself.atk = atk\n\t\tself.element_type = ElementType[element_type_name]\n\t\tself.weapon_type = weapon_type\n\t\tself.skills = skills\n\n\tdef set_skill_lv(self, skill_type_s, skill_lv):\n\t\t# _s == short\n\t\tfor skill in self.skills:\n\t\t\tif skill_type_s == 'a' \\\n\t\t\t\tor (skill_type_s == 'n' and skill.skill_data['type'] == WeaponSkill.WeaponSkillFactorType.normal) \\\n\t\t\t\tor (skill_type_s == 'm' and skill.skill_data['type'] == WeaponSkill.WeaponSkillFactorType.mag):\n\t\t\t\tskill.level = skill_lv\n\t\treturn self\n\n\t# return [normal, mag]\n\tdef factors(self, element_type):\n\t\tfactors = [0, 0]\n\t\tfor skill in self.skills:\n\t\t\tf1, f2 = skill.factors(element_type)\n\t\t\tfactors[0] = factors[0] + f1\n\t\t\tfactors[1] = factors[1] + f2\n\t\treturn factors\n\n\tdef to_json(self):\n\t\tjson = {}\n\t\tjson['name'] = self.name\n\t\tjson['level'] = self.level\n\t\tjson['limit_lv'] = self.limit_lv\n\t\tjson['rarity'] = self.rarity\n\t\tjson['hp'] = self.hp\n\t\tjson['atk'] = self.atk\n\t\tjson['element_type'] = self.element_type.name\n\t\tjson['weapon_type'] = self.weapon_type\n\t\tsk_objs = []\n\t\tfor sk in self.skills:\n\t\t\tsk_obj = {}\n\t\t\tsk_obj['skill_type'] = sk.type\n\t\t\tsk_obj['skill_lv'] = sk.level\n\t\t\tsk_objs.append(sk_obj)\n\t\tjson['skills'] = sk_objs\n\t\treturn json\n\n\n\tdef to_str(self):\n\t\tskills_str = \"\"\n\t\tmultibyte_len = 0\n\t\tskills_str = \"%s\" % (self.skills[0].skill_data['type_txt'])\n\t\tmultibyte_len = self.skills[0].skill_data['type_txt_len']\n\t\tfor i in range(1, len(self.skills)):\n\t\t\tskills_str = skills_str + \" / %s\" % (self.skills[i].skill_data['type_txt'])\n\t\t\tmultibyte_len = multibyte_len + self.skills[i].skill_data['type_txt_len'] + 3\n\t\tskills_str = (' ' * (20 - multibyte_len)) + skills_str\n\t\treturn \"%50s - [ %4d / %s ]: %s\" % (self.element_type.name, self.atk, skills_str.decode('utf-8'), self.name)\n\n\n","sub_path":"classes/weapon.py","file_name":"weapon.py","file_ext":"py","file_size_in_byte":6413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"444930836","text":"from types import FunctionType, MethodType\n\nfrom functools import wraps\n\nclass PointlessMetaClass(type):\n def __new__(meta, classname, bases, classDict): #@NoSelf\n for b in bases:\n if hasattr(b, \"final\"):\n if b.final:\n raise ValueError()\n\n newClassDict = {}\n for attributeName, attribute in classDict.items():\n if type(attribute) != FunctionType:\n newClassDict[attributeName] = attribute\n continue\n\n if hasattr(attribute, \"subclasses_must_call\"):\n if attribute.subclasses_must_call:\n orgAtt = attribute\n @wraps(orgAtt)\n def tmp(self, *args, **kwargs):\n ret = orgAtt(args, kwargs)\n #zapisac ze zostala wykonana\n return ret\n\n attribute = tmp\n\n for b in bases:\n if attributeName in dir(b):\n prev_a = getattr(b, attributeName)\n if type(prev_a) != MethodType:\n newClassDict[attributeName] = attribute\n continue\n if hasattr(prev_a, \"final\"):\n if prev_a.final:\n raise ValueError()\n\n if hasattr(prev_a, \"subclasses_must_call\"):\n if prev_a.subclasses_must_call:\n orgAtt2 = attribute\n @wraps(orgAtt2)\n def tmp(self, *args, **kwargs):\n ret = orgAtt(args, kwargs)\n # sprawdzic czy z nadklasy zostalo wykonane\n return ret\n attribute = orgAtt2\n\n\n newClassDict[attributeName] = attribute\n\n return type.__new__(meta, classname, bases, newClassDict)\n\nclass Freezer(object):\n __metaclass__ = PointlessMetaClass\n\n\n#class A(Freezer):\n# def fn(self):\n# return 12\n#\n#class B(Freezer):\n# def fn(self):\n# super(B, self).fn()\n# return 15\n#\n#from byteplay import *\n#from pprint import pprint\n#\n#x = B()\n#c = Code.from_code(x.fn.func_code)\n#pprint(c.code)\n","sub_path":"ztp/zadanie7/freezer.py","file_name":"freezer.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"318762035","text":"class Solution:\r\n # Morris In-order traverse解法\r\n def recoverTree(self, root: TreeNode) -> None:\r\n \"\"\"\r\n Do not return anything, modify root in-place instead.\r\n \"\"\"\r\n cur, change, prev = root,[], TreeNode(float('-inf'))\r\n \r\n while cur:\r\n if cur.left:\r\n tmp = cur.left\r\n # 找出左孩子的最右叶子节点\r\n while tmp.right and tmp.right!= cur: tmp = tmp.right\r\n # 第一次遍历左子树,将最右叶子节点连接到cur\r\n if not tmp.right:\r\n tmp.right, cur = cur, cur.left #继续往左子树遍历\r\n continue\r\n # 如果tmp.right不为None,说明左孩子已经遍历过\r\n tmp.right = None\r\n # print(cur.val) 直接访问cur \r\n if cur.val <= prev.val: change.append([prev, cur])\r\n # 继续遍历cur的右孩子部分\r\n prev, cur = cur, cur.right\r\n # Recover the tree\r\n change[0][0].val, change[-1][1].val = change[-1][1].val, change[0][0].val\r\n ","sub_path":"codes/AndrewSun/0099.py","file_name":"0099.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"572311022","text":"# =========================================================\n# @purpose: inferencing images cropped by sliding window \n# and writing results into json file\n# @date: 2019/11\n# @version: v1.0\n# @author: Xu Huasheng\n# @github: \n# @How to run: move cervical_detection.py to $mmdetecton_root\n# cd $mmdetecton_root (~/anaconda3/envs/pytorch/mmdetection)\n# conda activate pytorch\n# python cervical_detection.py\n# ==========================================================\nfrom mmdet.apis import init_detector, inference_detector, show_result\nimport os\nimport argparse\nimport progressbar\nimport kfbReader\nimport cv2\nimport json\n\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='MMDetection inference')\n parser.add_argument('--cfg', \n dest='config',\n help='inference config file path',\n type=str, \n default=None\n )\n parser.add_argument('--checkpoint', \n dest='checkpoint',\n help='checkpoint file path',\n type=str, \n default=None\n )\n parser.add_argument('--in', \n dest='img_input',\n help='the input path of image to inference',\n type=str, \n default=None\n )\n parser.add_argument('--out', \n dest='img_output',\n help='the output path of image that has inferenced',\n type=str, \n default=None\n )\n\n args = parser.parse_args()\n return args\n \n\n\ndef main():\n # 默认路径\n CONFIG_FILE = 'configs/faster_rcnn_r50_fpn_1x.py' # 模型的配置文件\n CHECKPOINT_FILE = 'work_dirs/faster_rcnn_r50_fpn_1x/latest.pth' # 训练好的模型权重\n KFB_PATH = '/media/watson/Documents/tianchi/cervical/dataset/test' # kfb文件路径\n TEMP_RESULT_PATH = '/media/watson/Documents/tianchi/cervical/dataset/temp_result' # 临时滑窗检测结果\n OUT_JSON_PATH = '/media/watson/Documents/tianchi/cervical/output' # json输出路径\n\n # 如果路径不存在则创建路径\n if not os.path.exists(TEMP_RESULT_PATH):\n os.makedirs(TEMP_RESULT_PATH)\n if not os.path.exists(OUT_JSON_PATH):\n os.makedirs(OUT_JSON_PATH)\n\n # 解析参数\n # args = parse_args()\n # if args.config is not None:\n # CONFIG_FILE = args.config\n # if args.checkpoint is not None:\n # CHECKPOINT_FILE = args.checkpoint\n # if args.img_input is not None:\n # KFB_PATH = args.img_input\n # if args.img_output is not None:\n # OUT_JSON_PATH = args.img_output\n\n SCALE = 20 # 缩放尺度\n window_size = (600, 600) # 滑窗大小(w, h)\n step_size = (400, 400) # 滑窗步进(dx, dy)\n checkpoint = 167 # 从检查点开始,检查点为上一次最后生成的json文件的顺序索引\n\n # 初始化模型\n print('=== initialing detector ===')\n # model = init_detector(CONFIG_FILE, CHECKPOINT_FILE)\n ## copy from detect.py\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--image_folder\", type=str, default=\"data/samples\", help=\"path to dataset\")\n parser.add_argument(\"--model_def\", type=str, default=\"config/yolov3.cfg\", help=\"path to model definition file\")\n parser.add_argument(\"--weights_path\", type=str, default=\"weights/yolov3.weights\", help=\"path to weights file\")\n parser.add_argument(\"--class_path\", type=str, default=\"data/coco.names\", help=\"path to class label file\")\n parser.add_argument(\"--conf_thres\", type=float, default=0.8, help=\"object confidence threshold\")\n parser.add_argument(\"--nms_thres\", type=float, default=0.4, help=\"iou thresshold for non-maximum suppression\")\n parser.add_argument(\"--batch_size\", type=int, default=1, help=\"size of the batches\")\n parser.add_argument(\"--n_cpu\", type=int, default=0, help=\"number of cpu threads to use during batch generation\")\n parser.add_argument(\"--img_size\", type=int, default=416, help=\"size of each image dimension\")\n parser.add_argument(\"--checkpoint_model\", type=str, help=\"path to checkpoint model\")\n opt = parser.parse_args()\n print(opt)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n # Set up model\n model = Darknet(opt.model_def, img_size=opt.img_size).to(device)\n if opt.weights_path.endswith(\".weights\"):\n # Load darknet weights\n model.load_darknet_weights(opt.weights_path)\n else:\n # Load checkpoint weights\n model.load_state_dict(torch.load(opt.weights_path))\n model.eval() # Set in evaluation mode\n \n\n # 推断图片\n print('=== inference start ===')\n kfbread = kfbReader.reader() # 创建阅读器对象\n kfb_list = os.listdir(KFB_PATH)\n kfb_list.sort(key=lambda x: int(x[6:-4])) # 按文件名排序\n \n # 遍历kfb文件\n kfb_cnt = checkpoint\n kfb_total = len(kfb_list)\n for kfb_fileName in kfb_list[checkpoint:]:\n kfb_cnt += 1\n # 读取kfb文件\n kfb_fullFileName = os.path.join(KFB_PATH, kfb_fileName)\n kfbread.ReadInfo(kfb_fullFileName, SCALE, True) # 读取kfb文件信息(必须的)\n fullImg_width = kfbread.getWidth() # 读取全图的宽度\n fullImg_heigth = kfbread.getHeight() # 读取全图的高度\n\n # 滑动窗口检测\n bboxes_list = []\n # bbox_dict = {} # 错误定义的地方\n window_cnt = 0\n window_nums = ((fullImg_width-window_size[0]+step_size[0])//step_size[0]) * ((fullImg_heigth-window_size[1]+step_size[1])//step_size[1])\n barPrefix = '('+str(kfb_cnt)+'/'+str(kfb_total)+')...' + kfb_fileName\n bar = progressbar.ProgressBar(prefix=barPrefix, max_value=window_nums).start() \n for (x, y, w, h) in sliding_window(fullImg_width, fullImg_heigth, window_size, step_size):\n window_cnt += 1\n bar.update(window_cnt)\n # 截取滑窗图片\n window_img = kfbread.ReadRoi(x, y, w, h, SCALE)\n # 目标检测\n # result = inference_detector(model, window_img)\n with torch.no_grad():\n detections = model(input_imgs)\n # 若有检测结果\n if result[0].shape[0] > 0:\n # 存储结果\n for xmin, ymin, xmax, ymax, p in result[0]:\n bbox_dict = {} # 必须定义在这里(每次进入for循环都是实例化新的字典对象, 每次append的元素都指向新的对象),\n # 不能定义在前面(实质只有一个实例化的字典对象, 导致append的每一个元素都指向同一个对象)\n bbox_dict[\"x\"] = int(round(x + xmin))\n bbox_dict[\"y\"] = int(round(y + ymin))\n bbox_dict[\"w\"] = int(round(xmax - xmin))\n bbox_dict[\"h\"] = int(round(ymax - ymin))\n bbox_dict[\"p\"] = round(float(p), 5)\n bboxes_list.append(bbox_dict) \n # 显示检测结果 -option\n # result_imgName = kfb_fileName.split('.')[0] + '_win' + str(window_cnt) + '.jpg'\n # result_imgFullName = os.path.join(TEMP_RESULT_PATH, result_imgName)\n # show_result(window_img, result, model.CLASSES, score_thr=0.0, wait_time=30, show=True, out_file=None)\n\n # 写入json\n json_fileName = kfb_fileName.split('.')[0] + '.json'\n json_filePath = os.path.join(OUT_JSON_PATH, json_fileName)\n with open(json_filePath, 'w') as outfile: \n outfile.write(json.dumps(bboxes_list))\n bar.finish()\n # print('\\n')\n\n\n\n\ndef sliding_window(image_w, image_h, window_size, step_size):\n '''\n parameters:\n image_w - width of image to be slided\n image_h - height of image to be slided\n window_size - Size of Sliding Window, (w, h)\n step_size - Incremented Size of Window, (dx, dy)\n returns:\n (x, y, w, h) of the sliding window image\n '''\n for y in range(0, image_h - window_size[1], step_size[1]):\n for x in range(0, image_w - window_size[0], step_size[0]):\n yield (x, y, window_size[0], window_size[1])\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"cervical_detection.py","file_name":"cervical_detection.py","file_ext":"py","file_size_in_byte":8484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"486360594","text":"from absl import app, flags, logging\nfrom absl.flags import FLAGS\nimport os\nimport sys\nimport tensorflow as tf\nfrom track1_bicubic.modules.models import RRDB_Model, DiscriminatorVGG128,RRDB_Model_scale\nfrom track1_bicubic.modules.lr_scheduler import MultiStepLR\nfrom track1_bicubic.modules.losses import (PixelLoss, ContentLoss, EdgeLoss,DiscriminatorLoss,\n GeneratorLoss)\nfrom track1_bicubic.modules.utils import (load_yaml, load_dataset, ProgressBar,\n set_memory_growth)\n\n# flags.DEFINE_string('cfg_path', './configs/esrgan_ea_x4_bicubic.yaml', 'config file path')\n# flags.DEFINE_string('gpu', '7', 'which gpu to use')\n\n\ndef main(gpu,yaml_path):\n # init\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n os.environ['CUDA_VISIBLE_DEVICES'] = gpu # which GPU to use\n\n logger = tf.get_logger()\n logger.disabled = True\n logger.setLevel(logging.FATAL)\n set_memory_growth()\n\n cfg = load_yaml(yaml_path)\n\n # define network\n generator = RRDB_Model_scale(cfg['input_size'], cfg['ch_size'], cfg['network_G'],scale=cfg['scale'])\n generator.summary(line_length=80)\n discriminator = DiscriminatorVGG128(cfg['gt_size'], cfg['ch_size'])\n discriminator.summary(line_length=80)\n\n # extration_variables = [var for var in generator.trainable_variables if 'upsample' not in var.name]\n # upsample_variables = [var for var in generator.trainable_variables if 'upsample' in var.name]\n\n train_dataset = load_dataset(cfg, 'train_dataset', shuffle=False)\n\n # define optimizer\n learning_rate_G = MultiStepLR(cfg['lr_G'], cfg['lr_steps'], cfg['lr_rate'])\n learning_rate_D = MultiStepLR(cfg['lr_D'], cfg['lr_steps'], cfg['lr_rate'])\n optimizer_G = tf.keras.optimizers.Adam(learning_rate=learning_rate_G,\n beta_1=cfg['adam_beta1_G'],\n beta_2=cfg['adam_beta2_G'])\n optimizer_D = tf.keras.optimizers.Adam(learning_rate=learning_rate_D,\n beta_1=cfg['adam_beta1_D'],\n beta_2=cfg['adam_beta2_D'])\n\n\n\n # define losses function\n pixel_loss_fn = PixelLoss(criterion=cfg['pixel_criterion'])\n fea_loss_fn = ContentLoss(criterion=cfg['feature_criterion'])\n gen_loss_fn = GeneratorLoss(gan_type=cfg['gan_type'])\n edge_loss_fn = EdgeLoss(criterion=cfg['edge_criterion'])\n dis_loss_fn = DiscriminatorLoss(gan_type=cfg['gan_type'])\n\n # load checkpoint\n checkpoint_dir = './track1_bicubic/checkpoints/' + cfg['sub_name']\n checkpoint = tf.train.Checkpoint(step=tf.Variable(0, name='step'),\n model=generator,\n discriminator=discriminator,\n optimizer_G=optimizer_G,\n optimizer_D=optimizer_D)\n\n manager = tf.train.CheckpointManager(checkpoint=checkpoint,\n directory=checkpoint_dir,\n max_to_keep=3)\n\n\n\n if not manager.latest_checkpoint:\n print(\"[*] training from scratch.\")\n # loading pre-trained esrgan model for bootstraping\n if cfg['bootstrap_model'] is not None:\n # generate bootstrap model: esragan\n bootstrap_model = RRDB_Model(32, cfg['ch_size'], cfg['network_G'])\n pretrain_dir = './track1_bicubic/checkpoints/' + cfg['bootstrap_model']\n if tf.train.latest_checkpoint(pretrain_dir) and not manager.latest_checkpoint:\n checkpoint_pretrained = tf.train.Checkpoint(model=bootstrap_model,\n )\n checkpoint_pretrained.restore(tf.train.latest_checkpoint(pretrain_dir))\n # extraction_variables = [var.value for var in generator.trainable_variables]\n # for i in range(len(extraction_variables)):\n # generator.trainable_variables[i].value = extraction_variables[i]\n for var1,var2 in zip(generator.trainable_variables[:698],bootstrap_model.trainable_variables[:698]):\n var1.assign(var2)\n del checkpoint_pretrained\n del pretrain_dir\n del bootstrap_model\n print('bootstrap from model [{}]'.format(cfg['bootstrap_model']))\n #del extraction_variables\n\n else:\n if manager.latest_checkpoint:\n checkpoint.restore(manager.latest_checkpoint)\n print('[*load ckpt from {} at step {}]'.format(manager.latest_checkpoint,checkpoint.step.numpy()))\n\n\n\n # define training step function\n @tf.function\n def train_step(lr, hr):\n with tf.GradientTape(persistent=True) as tape:\n sr = generator(lr, training=True)\n hr_output = discriminator(hr, training=True)\n sr_output = discriminator(sr, training=True)\n\n losses_G = {}\n losses_D = {}\n losses_G['reg'] = tf.reduce_sum(generator.losses)\n losses_D['reg'] = tf.reduce_sum(discriminator.losses)\n losses_G['pixel'] = cfg['w_pixel'] * pixel_loss_fn(hr, sr)\n losses_G['feature'] = cfg['w_feature'] * fea_loss_fn(hr, sr)\n losses_G['edge'] = cfg['w_edge'] * edge_loss_fn(hr,sr)\n losses_G['gan'] = cfg['w_gan'] * gen_loss_fn(hr_output, sr_output)\n losses_D['gan'] = dis_loss_fn(hr_output, sr_output)\n\n total_loss_G = tf.add_n([l for l in losses_G.values()])\n total_loss_D = tf.add_n([l for l in losses_D.values()])\n\n\n\n grads_G = tape.gradient(\n total_loss_G, generator.trainable_variables)\n\n grads_D = tape.gradient(\n total_loss_D, discriminator.trainable_variables)\n\n optimizer_G.apply_gradients(\n zip(grads_G, generator.trainable_variables))\n optimizer_D.apply_gradients(\n zip(grads_D, discriminator.trainable_variables))\n\n return total_loss_G, total_loss_D, losses_G, losses_D\n\n # training loop\n summary_writer = tf.summary.create_file_writer(\n './track1_bicubic/logs/' + cfg['sub_name'])\n prog_bar = ProgressBar(cfg['niter'], checkpoint.step.numpy())\n remain_steps = max(cfg['niter'] - checkpoint.step.numpy(), 0)\n\n for lr, hr in train_dataset.take(remain_steps):\n checkpoint.step.assign_add(1)\n steps = checkpoint.step.numpy()\n\n total_loss_G, total_loss_D, losses_G, losses_D = train_step(lr, hr)\n\n prog_bar.update(\n \"loss_G={:.4f}, loss_D={:.4f}, lr_G={:.1e}, lr_D={:.1e}\".format(\n total_loss_G.numpy(), total_loss_D.numpy(),\n optimizer_G.lr(steps).numpy(), optimizer_D.lr(steps).numpy()))\n\n if steps % 10 == 0:\n with summary_writer.as_default():\n tf.summary.scalar(\n 'loss_G/total_loss', total_loss_G, step=steps)\n tf.summary.scalar(\n 'loss_D/total_loss', total_loss_D, step=steps)\n for k, l in losses_G.items():\n tf.summary.scalar('loss_G/{}'.format(k), l, step=steps)\n for k, l in losses_D.items():\n tf.summary.scalar('loss_D/{}'.format(k), l, step=steps)\n\n tf.summary.scalar(\n 'learning_rate_G', optimizer_G.lr(steps), step=steps)\n tf.summary.scalar(\n 'learning_rate_D', optimizer_D.lr(steps), step=steps)\n\n if steps % cfg['save_steps'] == 0:\n manager.save()\n print(\"\\n[*] save ckpt file at {}\".format(\n manager.latest_checkpoint))\n\n print(\"\\n [*] training done!\")\n\n\ndef train(gpu,scale):\n # config files dictionary\n yaml_dicts = {2:'./track1_bicubic/configs/esrgan_ea_x2_bicubic.yaml',\n 3:'./track1_bicubic/configs/esrgan_ea_x3_bicubic.yaml',\n 4:'./track1_bicubic/configs/esrgan_ea_x4_bicubic.yaml'}\n\n if(scale in yaml_dicts):\n main(gpu,yaml_dicts[scale])\n else:\n print('Only support scale 2, scale 3 and scale 4.')\n\n\n\nif __name__ == '__main__':\n #app.run(main)\n main()\n\n","sub_path":"track1_bicubic/train_esrgan_ea_bicubic.py","file_name":"train_esrgan_ea_bicubic.py","file_ext":"py","file_size_in_byte":8190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"386590363","text":"import datetime\n\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import BucketType\n\nfrom cfg import Rance01\nfrom guilds import cnx, nickCache, guildNameCache, update_system_roles, discordSystemRoleCache, roleCache\nfrom libs.GuildOwnerCommandsLib.deleteProcedure import delete_initial\nfrom libs.cheks.cheks_inserts import check_insert_discordid\nfrom libs.embed.trade_embed import create_trade_log_embed\nfrom libs.img.at2Construct import construct_guild_at2\nfrom libs.img.grandConstruct import construct_guild_grand\nfrom libs.img.guildsConstruct import constructGuilds\nfrom libs.img.recruitConstruct import construct_kick_leave, construct_promote\nfrom libs.img.upgradeConstruct import construct_guild_upgrade\nfrom libs.trade.resourcelib import add_money\nfrom libs.cheks.checks_regex import regex_nickname\nfrom libs.universal.getInfo import get_member_data\n\n\nclass Debug(commands.Cog):\n # init\n def __init__(self, bot):\n self.bot = bot\n\n # Commands\n @commands.command()\n async def _test1(self,ctx, username):\n DID = ctx.author.id\n if DID != Rance01:\n return\n check_insert_discordid(DID)\n data = get_member_data(player_id=nickCache[DID]['UUID'])\n\n\n @commands.cooldown(1, 2, BucketType.user)\n @commands.command()\n async def _sync(self, ctx, username, sudo=-1):\n DID = ctx.author.id\n if sudo != -1:\n DID = sudo\n if not regex_nickname(username):\n await ctx.send('Неправильный ник!')\n return\n\n query = \"\"\"\n SELECT NickName, UUID, Discord FROM maintable WHERE Discord = '%s' OR NickName = '%s'\"\"\" % (DID, username)\n add_user = (\"INSERT INTO maintable \"\n \"(NickName, UUID, Discord) \"\n \"VALUES (%s, %s, %s)\")\n data_user = (username, DID, DID)\n cursor = cnx.cursor()\n cursor.execute(query)\n data = cursor.fetchall()\n if len(data) > 0:\n if data[0][2] != str(DID):\n await ctx.send('Этот ник уже занял кто-то другой!')\n return\n else:\n query_update = \"UPDATE maintable SET NickName = '%s' WHERE Discord = '%s'\" % (username, DID)\n cursor.execute(query_update)\n nickCache[DID] = {\n 'nick': username,\n 'UUID': DID\n }\n else:\n cursor.execute(add_user, data_user)\n nickCache[DID] = {\n 'nick': username,\n 'UUID': DID\n }\n cnx.commit()\n cursor.close()\n await ctx.send('Данные успешно добавлены')\n\n @commands.cooldown(1, 2, BucketType.user)\n @commands.command()\n async def _perm(self, ctx, perm='j', sudo=-1):\n DID = ctx.author.id\n if DID != Rance01:\n return\n author = ctx.author.id\n if sudo != -1:\n author = sudo\n DID = check_insert_discordid(str(author))\n if DID == False:\n await ctx.send('Ваш дискорд не привязан к аккаунту!')\n return\n pid = str(nickCache[author]['UUID'])\n query = \"555\"\n if perm == 'j':\n query = \"INSERT IGNORE INTO guilds_joinperm VALUES ('%s')\" % (pid,)\n if perm == 'c':\n query = \"INSERT IGNORE INTO guilds_createperm VALUES ('%s')\" % (pid,)\n cursor = cnx.cursor()\n cursor.execute(query)\n cnx.commit()\n cursor.close()\n await ctx.send('Права выданы!')\n\n @commands.cooldown(1, 2, BucketType.user)\n @commands.command()\n async def _kick(self, ctx, atype, nick):\n DID = ctx.author.id\n if DID != Rance01:\n return\n imagePath = construct_kick_leave(atype, nick)\n await ctx.send(file=discord.File(imagePath))\n\n @commands.cooldown(1, 2, BucketType.user)\n @commands.command()\n async def _promote(self, ctx, atype, nick, rid: str):\n DID = ctx.author.id\n if DID != Rance01:\n return\n imagePath = construct_promote(atype, nick, roleCache[int(rid)]['name'])\n await ctx.send(file=discord.File(imagePath))\n\n @commands.cooldown(1, 2, BucketType.user)\n @commands.command()\n async def _u(self, ctx, uname: str):\n DID = ctx.author.id\n if DID != Rance01:\n return\n imagePath = construct_guild_upgrade(uname)\n await ctx.send(file=discord.File(imagePath))\n\n @commands.cooldown(1, 2, BucketType.user)\n @commands.command()\n async def _t(self, ctx):\n DID = ctx.author.id\n if DID != Rance01:\n return\n emb = create_trade_log_embed(\n 'guild_SELL', 'guild_BUY', str(1234), str(0), str(10),\n str(1), str(10000)\n )\n await ctx.send(embed=emb)\n\n # end\n\n @commands.command()\n async def echo(self, ctx, *args):\n DID = ctx.author.id\n if DID != Rance01:\n return\n print(args)\n await ctx.send(args)\n\n\ndef setup(client):\n client.add_cog(Debug(client))\n","sub_path":"cogs/Debug.py","file_name":"Debug.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"232078802","text":"# -*- coding: utf-8 -*-\n\nexec(open('../model_data.py').read())\n#exec(open('../../PSs/captionTexts.py').read())\nfrom postprocess.xcVtk import vtk_graphic_base\nfrom postprocess.xcVtk.FE_model import vtk_FE_graphic\n\n# caption: text to write in the graphic\n# defFScale: factor to paply to current displacement of nodes so that the\n# display position of each node equals to the initial position plus\n# its displacement multiplied by this factor. (Defaults to 0.0,\n# i.e. display of initial/undeformed shape)\n\n# nodeSize: size of the points that represent nodes (defaults to 0.01)\n# scaleConstr: scale of SPContraints symbols (defaults to 0.2)\n\ndisplaySettings= vtk_FE_graphic.DisplaySettingsFE()\n\nlstSets=[zap,murestrZ1,murestrZ2,aletiZ1,aletiZ2,aletiZ3,aletdZ1,aletdZ2,aletdZ3]\nif Lvoladzi >0:\n lstSets.append(voladzi)\nif Lvoladzd >0:\n lstSets.append(voladzd)\n \n#lstSets=[zap,murestr,aleti,aletd]\n\n\n\n#displaySettings.displayMesh(xcSets=[pilasInf,pilasSup,losInf,losSup,murAlig,murExtAlig,voladzCent,voladzExtr],caption='Mesh',nodeSize=0.030,scaleConstr=0.70)\n#displaySettings.displayMesh(xcSets=[losInf,losSup,murAlig,murExtAlig,voladzCent],caption='Mesh',nodeSize=0.030,scaleConstr=0.70)\n#displaySettings.displayMesh(xcSets=lstSets, fileName= 'estribo1.jpg',caption='P.S. 101.3. Estribo 1. Malla de elementos',nodeSize=0.050,scaleConstr=0.70)\n#displaySettings.displayMesh(xcSets=lstSets,caption='P.S. 101.3. Estribo 1. Malla de elementos',nodeSize=0.050,scaleConstr=0.70)\ndisplaySettings.displayMesh(xcSets=lstSets,caption='P.S. 101.3. Estribo 1. Malla de elementos. Vista dorsal',nodeSize=0.050,scaleConstr=0.70)\ndisplaySettings.displayMesh(xcSets=lstSets,caption='P.S. 101.3. Estribo 1. Malla de elementos. Vista frontal',nodeSize=0.050,scaleConstr=0.70)\n\n","sub_path":"ave_SR/PS_101_3_estribo1/display/display_mesh.py","file_name":"display_mesh.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"605584428","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nImport these modules for a good use of the plateforme\n\"googlemaps\" and \"wikipedia\" for communication with them\n\"nltk\" is a librairie for delete an stopword as a start point\n\"\"\"\n\n# Import install lib\nimport googlemaps\nimport wikipedia\n\n# Import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\n# Import local lib\nfrom os import environ\nimport string\n\n# Import Flask\nfrom flask import Flask, render_template, request, jsonify\n\napp = Flask(__name__)\napp.config['STRIPE_API'] = environ.get('STRIPE_API_KEY')\napp.config['EMAIL'] = environ.get('EMAIL')\n\n# Gmap is a variable for config the secret api key\ngmaps = googlemaps.Client(key=app.config['STRIPE_API'])\n\n\n@app.route(\"/\")\ndef index():\n \"\"\"\n Create of the \"renders templates\" for create the \"endpoints\"\n Here, the base -> index\n \"\"\"\n return render_template(\"index.html\")\n\n\n@app.route(\"/search\", methods=['POST'])\ndef search():\n \"\"\"\n The search function is the function that\n goes using the JS start executing the search query\n \"\"\"\n stop_words = set(stopwords.words(\"french\"))\n result_words = []\n inputUser = request.get_json()['input']\n\n # We exclude the special characters\n exclude = set(string.punctuation)\n ch_input = \"\"\n for ch in inputUser:\n if ch in exclude:\n ch_input += \" \"\n else:\n ch_input += ch\n inputUser = ch_input\n inputUser_new = word_tokenize(inputUser)\n wikipedia.set_lang(\"fr\")\n\n # We create a loop get the key words\n for word in inputUser_new:\n if word.lower() not in stop_words:\n file = open(\"words_list_opcr.txt\")\n for words_list in file:\n if word.lower() not in words_list:\n result_words.append(word.lower())\n return check_input(result_words)\n\n\ndef check_input(key_treatment):\n \"\"\"\n This method is ued for check\n if this query contains a keyword or not\n \"\"\"\n del_c = ' '.join(key_treatment)\n if len(key_treatment) == 0:\n return jsonify({'error': 'Oups ... '\n 'Je crains ne pas avoir compris.'\n 'On recommence ?'})\n else:\n return wiki_result(del_c)\n\n\ndef wiki_result(key_words):\n \"\"\"This method is ued for create a request to Wiki API\"\"\"\n response_wiki_search = wikipedia.search(key_words)\n if len(response_wiki_search) != 0:\n # Get the wiki answer and check if valid or not\n response_wiki = wikipedia.summary(key_words,\n sentences=1)\n response_page_wiki = wikipedia.page(key_words)\n response_url_wiki = response_page_wiki.url\n response = {\n 'wiki_summary': response_wiki,\n 'wiki_url': response_url_wiki,\n }\n return geocode_result(response, key_words)\n\n else:\n response = {\n 'error_wiki': 'Oups ... Je crains de ne pas disposer '\n 'des informations nécéssaires'\n 'Toutes mes excuses.'\n ' Je vais tout de même vous faire '\n 'part de cette carte:'\n }\n return geocode_result(response, key_words)\n\n\ndef geocode_result(response_wiki, key_words_g):\n \"\"\"This method is ued for create a request to Gmaps API\"\"\"\n geocode = gmaps.geocode(key_words_g,\n region=\"fr\")\n\n # Check whether or not this query contains a valid geolocation\n if not geocode:\n response = {'error_geo': 'Je crains cependant de ne pas avoir '\n 'de carte à disposition. '\n 'Toutes mes excuses.'}\n return display_result(response_wiki, response)\n else:\n response_geo = {\n 'geocode': geocode[0]['geometry']['location'],\n 'geocode_address': geocode[0]['formatted_address']\n }\n return display_result(response_wiki, response_geo)\n\n\ndef display_result(result_wiki, result_geo):\n \"\"\"\n This method is the display method.\n This method returns the results of the query\n to JS and displays them in the user window.\n \"\"\"\n if 'error_geo' in result_geo and 'error_wiki' in result_wiki:\n return jsonify({'error': 'Oups ... '\n 'Je crains ne pas avoir compris.'\n 'On recommence ?'})\n elif 'error_geo' in result_geo:\n response = {\n 'error_geo': result_geo['error_geo'],\n 'wiki_summary': result_wiki['wiki_summary'],\n 'wiki_url': result_wiki['wiki_url']\n }\n return jsonify(response)\n elif 'error_wiki' in result_wiki:\n response = {\n 'error_wiki': result_wiki['error_wiki'],\n 'geocode': result_geo['geocode'],\n 'geocode_address': result_geo['geocode_address']\n }\n return jsonify(response)\n else:\n response = {\n 'wiki_summary': result_wiki['wiki_summary'],\n 'wiki_url': result_wiki['wiki_url'],\n 'geocode': result_geo['geocode'],\n 'geocode_address': result_geo['geocode_address']\n }\n return jsonify(response)\n\n\n@app.route(\"/who_i_am\")\ndef who_i_am():\n \"\"\"\n Here is a rendering,\n this page is the page for the description of the character\n \"\"\"\n return render_template(\"who_i_am.html\")\n\n\n@app.route(\"/contact\")\ndef contact():\n \"\"\"Here is a rendering, this page is the page for contact me\"\"\"\n email = app.config['EMAIL']\n return render_template(\"contact.html\", email=email)\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"329686694","text":"import logging\n\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\nfrom django.db import connections\n\nfrom usaspending_api.etl.broker_etl_helpers import PhonyCursor\nfrom usaspending_api.etl.executive_compensation_etl import load_executive_compensation\n\nlogger = logging.getLogger('console')\nexception_logger = logging.getLogger(\"exceptions\")\n\n\nclass Command(BaseCommand):\n \"\"\"\n This command loads the executive compensation data from the broker using\n either a list of DUNS or all duns present in the data store\n \"\"\"\n help = \"Loads a set of DUNS's executive compensation data from the configured data broker database\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n '-d',\n '--duns',\n dest=\"duns\",\n nargs='+',\n type=int,\n help=\"DUNS to load subawards for\"\n )\n\n parser.add_argument(\n '-a',\n '--all',\n action='store_true',\n dest='update_all',\n default=False,\n help='Update all DUNS present in the datastore',\n )\n\n parser.add_argument(\n '-t',\n '--test',\n action='store_true',\n dest='test',\n default=False,\n help='Runs the submission loader in test mode, and uses stored data rather than pulling from a database'\n )\n\n def handle(self, *args, **options):\n # Grab the data broker database connections\n if not options['test']:\n try:\n db_conn = connections['data_broker']\n db_cursor = db_conn.cursor()\n except Exception as err:\n logger.critical('Could not connect to database. Is DATA_BROKER_DATABASE_URL set?')\n logger.critical(print(err))\n return\n else:\n db_cursor = PhonyCursor()\n\n # Require users to explicitly call -a to use the \"All\" case so that\n # it is not accidentally triggered by omitting an option\n if options[\"duns\"] is None and options[\"update_all\"]:\n load_executive_compensation(db_cursor, None)\n elif options[\"duns\"] is not None:\n load_executive_compensation(db_cursor, options[\"duns\"])\n else:\n logger.info(\"Please specify either a list of DUNS (using the --duns) flag, or set to update all mode using the (--all) flag.\")\n","sub_path":"usaspending_api/etl/management/commands/load_executive_compensation.py","file_name":"load_executive_compensation.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"97504884","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Тесты для задания «E-mail domains» + тесты\"\"\"\n\nimport unittest\nfrom emaildomains import check_email, main\nfrom os import remove\n\n\nclass TestSequenceFunctions(unittest.TestCase):\n\n def setUp(self):\n\n self.name_test_file = 'test_list.txt'\n self.name_null_file = 'test_null.txt'\n\n self.ok_emails = (\n 'stanislav+spam@yandex.ru',\n 'info@mail.ru',\n 'support@vk.com',\n 'ddd@rambler.ru',\n 'rexette@mail.ru',\n 'ivan@xn--c1ad6a.xn--p1ai')\n self.err_emails = (\n 'stas@a.u',\n 'spammer@8.8.8.8',\n 'stas@xn--c1ad6a.xn---p1ai',\n '.@a.ru',\n '.yaa@mail.ru',\n 'stas.@yandex.ru'\n 'example@localhost',\n 'sdfsdf@@@@rdgfdf',\n 'иван@иванов.рф',)\n\n with open(self.name_test_file, 'w') as f:\n for email in self.ok_emails + self.err_emails:\n f.write('%s\\n' % email)\n\n with open(self.name_null_file, 'w') as f:\n f.write('\\n')\n\n def tearDown(self):\n remove(self.name_test_file)\n remove(self.name_null_file)\n\n def test_check_email(self):\n\n for i in self.ok_emails:\n self.assertTrue(check_email(i), '%s is False' % i)\n\n for i in self.err_emails:\n self.assertFalse(check_email(i), '%s is True' % i)\n\n def test_main(self):\n res = main(self.name_test_file)\n self.assertEqual(len(res['INVALID']), len(self.err_emails))\n\n def test_null_file(self):\n res = main(self.name_null_file)\n self.assertEqual(len(res['INVALID']), 1)\n\n\nif __name__ == \"__main__\":\n suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"emaildomains-test.py","file_name":"emaildomains-test.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"525103757","text":"import pandas as pd\nfrom rpy2.robjects import r, pandas2ri\nri2py = pandas2ri.ri2py\n\n\ndef compute_fdr(dfs):\n\n new_dfs = []\n for i, df in enumerate(dfs):\n\n r[\"write.table\"](df, str(i) + \"_enriched_regions_pre_fdr.csv\", sep=\" \")\n if df is None:\n continue\n\n new_dfs.append(df)\n\n df = r[\"do.call\"](\"rbind\", new_dfs)\n if r[\"is.null\"](df)[0]:\n return pd.DataFrame()\n\n r[\"write.table\"](df, \"enriched_regions_pre_fdr.csv\", sep=\" \")\n\n _compute_fdr = r(\"\"\"function(INFO) {\n INFO <- INFO[order(-INFO$NLP),]\n nlps <- unique(INFO$NLP)\n sizes <- sapply(nlps,function(nlp) sum(INFO$NLP == nlp))\n indices <- sapply(nlps,function(nlp) sum(INFO$NLP >= nlp))\n\n nlrs <- mapply(function(nlp, j) {\n \tm <- sum(INFO$MAX.NLP >= nlp)\t# Tarone modification for discrete nlp\n \tb.y <- log10(sum((1:m)^-1))\t\t# discrete Benjamini-Yekutieli offset\n \tnls <- nlp + log10(j/m)\t\t\t\t# discrete Benjamini-Hochberg adjustment\n \tmax(nls-b.y,0)\t\t\t\t\t\t\t\t# discrete Benjamini-Yekutieli adjustment\n }, nlp=nlps, j=indices)\n\n M <- length(nlrs)\n nlqs <- numeric(M)\n for(i in 1:M) nlqs[i] <- max(nlrs[i:M])\t\t# step-up procedure\n nlqss <- unlist(mapply(function(nlq,size) rep(nlq,size),\n \t\t\t\t\t\t\t\tnlq=nlqs, size=sizes))\n\n cbind(QVAL=10^-nlqss, NLQ=nlqss, INFO)\n }\"\"\")\n\n df = ri2py(_compute_fdr(df))\n idx = df.index.get_level_values(0).to_series().astype(str).str.split(\n \":\",\n expand=True).ix[:, 0].to_frame()\n\n df = idx.join(df).reset_index(drop=True)\n df.columns = [\"CHROMOSOME\"] + list(df.columns)[1:]\n df = df.set_index(\"CHROMOSOME START END\".split())\n\n return df.sort_values([\"QVAL\", \"FORM\"])\n","sub_path":"triform/compute_fdr.py","file_name":"compute_fdr.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"560693878","text":"from __future__ import unicode_literals\n\nfrom django.shortcuts import render\nfrom django.http import Http404\n\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.decorators import (\n api_view,\n detail_route,\n permission_classes,\n authentication_classes,\n throttle_classes\n)\nfrom rest_framework.reverse import reverse\nfrom rest_framework import (\n status,\n generics,\n permissions,\n authentication,\n throttling,\n renderers,\n viewsets\n)\n\nfrom index.models import User\nfrom .models import Snippet\nfrom .permissions import IsOwnerOrReadOnly\nfrom .serializers import (\n SnippetSerializer,\n UserSerializer\n)\n\n\n# Create your views here.\n\n# 创建阀值\n# @throttle_classes((\n# throttling.AnonRateThrottle\n# ))\nclass SnippetViewSet(viewsets.ModelViewSet):\n \"\"\"\n This viewset automatically provides `list`, `create`, `retrieve`,\n `update` and `destroy` actions.\n\n Additionally we also provide an extra `highlight` action.\n \"\"\"\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n queryset = Snippet.objects.all()\n serializer_class = SnippetSerializer\n\n # @detail_route装饰器来创建自定义动作\n # https://whatwewant.gitbooks.io/django-rest-framework-tutorial-cn/content/6.ViewSetsAndRouters.html\n # 如果开启了的认证,post方法需要认证\n @detail_route(methods=['get', 'post'], renderer_classes=[renderers.StaticHTMLRenderer])\n def highlight(self, request, *args, **kwargs):\n snippet = self.get_object()\n return Response(snippet.highlighted)\n\n def perform_create(self, serializer):\n \"\"\"\n 该方法允许修改如何保存实例\n 修改任何请求对象或者请求连接里的信息\n \"\"\"\n serializer.save(owner=self.request.user)\n\n\nclass UserViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n This viewset automatically provides `list` and `detail` actions.\n \"\"\"\n permission_classes = (\n permissions.IsAuthenticated,\n permissions.IsAdminUser\n )\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n\nclass OwnViewSet(viewsets.ViewSet):\n \"\"\"\n 自定义示例\n 用于通过判断执行的动作来决定需要的权限\n \"\"\"\n def get_permissions(self):\n if self.action == 'list':\n permission_classes = [permissions.IsAuthenticated]\n else:\n permission_classes = [permissions.IsAdminUser]\n","sub_path":"api_snippet/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"117498554","text":"import sys\nfrom copy import deepcopy as copy\nfrom hqca.tools.quantum_strings import *\nfrom hqca.tools._operator import *\n\ndef ParityTransform(op):\n Nq = len(op.s)\n pauli = ['I'*Nq]\n new = Operator()+PauliString('I'*Nq,op.c)\n for qi,o in enumerate(op.s):\n # q index, op\n if o=='i':\n continue\n if qi==0:\n if o in ['+','-']:\n s1 = 'X'+(Nq-qi-1)*'X'\n s2 = 'Y'+(Nq-qi-1)*'X'\n c1,c2 = 0.5,((o=='-')-0.5)*1j\n elif o in ['p','h']:\n s1 = 'I'+(Nq-qi-1)*'I'\n s2 = 'Z'+(Nq-qi-1)*'I'\n c1,c2 = 0.5,(o=='h')-0.5\n else:\n if o in ['+','-']:\n s1 = 'I'*(qi-1)+'ZX'+(Nq-qi-1)*'X'\n s2 = 'I'*(qi-1)+'IY'+(Nq-qi-1)*'X'\n c1,c2 = 0.5,((o=='-')-0.5)*1j\n elif o in ['p','h']:\n s1 = 'I'*(qi-1)+'II'+(Nq-qi-1)*'I'\n s2 = 'I'*(qi-1)+'ZZ'+(Nq-qi-1)*'I'\n c1,c2 = 0.5,(o=='h')-0.5\n tem = Operator()\n tem+= PauliString(s1,c1)\n tem+= PauliString(s2,c2)\n new = tem*new\n return new\n\ndef Parity(operator,\n **kw,\n ):\n if isinstance(operator,type(QuantumString())):\n return ParityTransform(operator)\n else:\n new = Operator()\n for op in operator:\n new+= ParityTransform(op)\n return new\n\n\n'''\n for q,o in zip(op.qInd[::-1],op.qOp[::-1]):\n p1s,c1s,p2s,c2s = [],[],[],[]\n for p,c in zip(pauli,coeff):\n c1,c2 = [],[]\n if o=='+':\n if q>0:\n tc0,tp0 = _commutator_relations(\n 'Z',p[q-1])\n tc1,tp1 = _commutator_relations(\n 'X',p[q])\n tc2,tp2 = _commutator_relations(\n 'Y',p[q])\n if q==0:\n p1 = p[:q]+tp1+p[q+1:]\n else:\n p1 = p[:q-1]+tp0+tp1+p[q+1:]\n p2 = p[:q]+tp2+p[q+1:]\n c1.append(c*0.5*tc1)\n c2.append(-1j*c*0.5*tc2)\n elif o=='-':\n if q>0:\n tc0,tp0 = _commutator_relations(\n 'Z',p[q-1])\n tc1,tp1 = _commutator_relations(\n 'X',p[q])\n tc2,tp2 = _commutator_relations(\n 'Y',p[q])\n if q==0:\n p1 = p[:q]+tp1+p[q+1:]\n else:\n p1 = p[:q-1]+tp0+tp1+p[q+1:]\n p2 = p[:q]+tp2+p[q+1:]\n c1.append(c*0.5*tc1)\n c2.append(1j*c*0.5*tc2)\n if o in ['+','-']:\n for i in range(q+1,MapSet.Nq):\n nc1,np1 = _commutator_relations(\n 'X',p1[i])\n nc2,np2 = _commutator_relations(\n 'X',p2[i])\n p1 = p1[:i]+np1+p1[i+1:]\n p2 = p2[:i]+np2+p2[i+1:]\n c1[0]*=nc1\n c2[0]*=nc2\n elif o in ['1','p']:\n if q>0:\n tc1,tp1 = _commutator_relations(\n 'Z',p[q-1])\n else:\n tc1,tp1 = 1,p\n tc2,tp2 = _commutator_relations(\n 'Z',p[q])\n if q==0:\n p1 = p[:q]+tp2+p[q+1:]\n else:\n p1 = p[:q-1]+tp1+tp2+p[q+1:]\n p2 = p[:]\n c1.append(-c*0.5*tc1*tc2)\n c2.append(c*0.5)\n elif o in ['0','h']:\n if q>0:\n tc1,tp1 = _commutator_relations(\n 'Z',p[q-1])\n else:\n tc1,tp1 = 1,p\n tc2,tp2 = _commutator_relations(\n 'Z',p[q])\n if q==0:\n p1 = tp2+p[q+1:]\n else:\n p1 = p[:q-1]+tp1+tp2+p[q+1:]\n p2 = p[:]\n c1.append(c*0.5*tc1*tc2)\n c2.append(c*0.5)\n p1s.append(p1)\n p2s.append(p2)\n c1s+= c1\n c2s+= c2\n pauli = p1s+p2s\n coeff = c1s+c2s\n if MapSet.reduced:\n q1,q2 = MapSet._reduced_set[0],MapSet._reduced_set[1]\n c1,c2 = MapSet._reduced_coeff[q1],MapSet._reduced_coeff[q2]\n npauli = []\n ncoeff = []\n for n in range(len(pauli)):\n tc = copy(coeff[n])\n if pauli[n][q1]=='Z':\n tc = tc*c1\n if pauli[n][q2]=='Z':\n tc = tc*c2\n #if pauli[n][q1] in ['Y','X'] or pauli[n][q2] in ['Y','X']:\n # print(pauli[n])\n npauli.append(pauli[n][:q1]+pauli[n][(q1+1):q2])\n ncoeff.append(tc)\n pauli = npauli[:]\n coeff = ncoeff[:]\n #print(pauli)\n return pauli,coeff\n'''\n\n\n\n\n","sub_path":"hqca/transforms/_parity.py","file_name":"_parity.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"53819826","text":"# pylint: skip-file\nimport pytest\nimport numpy as np\nimport pyomo.environ as aml\nfrom suspect.convexity import Convexity\nfrom suspect.expression import ExpressionType\nfrom galini.pyomo import problem_from_pyomo_model\nfrom galini.suspect import ProblemContext\nfrom galini.expression_relaxation.convex import ConvexExpressionRelaxation\n\n\n@pytest.fixture\ndef problem():\n m = aml.ConcreteModel()\n\n m.x = aml.Var()\n m.y = aml.Var()\n m.z = aml.Var()\n\n m.obj = aml.Objective(expr=aml.exp(m.x) + aml.exp(m.y))\n m.c0 = aml.Constraint(expr=2.0 * m.x*m.x + 3.0 * m.x*m.y + 4.0 * m.y*m.y >= 0)\n return problem_from_pyomo_model(m)\n\n\n\nclass TestConvexUnderestimator:\n def test_sum_of_convex_expressions(self, problem):\n ctx = ProblemContext(problem)\n r = ConvexExpressionRelaxation()\n\n constraint_expr = problem.objective.root_expr\n ctx.set_convexity(constraint_expr, Convexity.Convex)\n assert r.can_relax(problem, constraint_expr, ctx)\n\n result = r.relax(problem, constraint_expr, ctx)\n assert len(result.expression.children) == 2\n assert result.expression.expression_type == ExpressionType.Sum\n a, b = result.expression.children\n\n assert a.expression_type == ExpressionType.UnaryFunction\n assert b.expression_type == ExpressionType.UnaryFunction\n\n assert result.constraints == []\n\n def test_quadratic_expression(self, problem):\n ctx = ProblemContext(problem)\n r = ConvexExpressionRelaxation()\n\n constraint_expr = problem.constraint('c0').root_expr\n ctx.set_convexity(constraint_expr, Convexity.Unknown)\n assert r.can_relax(problem, constraint_expr, ctx)\n\n result = r.relax(problem, constraint_expr, ctx)\n expr = result.expression\n assert expr.expression_type == ExpressionType.Quadratic\n assert len(expr.terms) == 2\n for term in expr.terms:\n assert term.var1 == term.var2\n assert term.coefficient == 2.0 or term.coefficient == 4.0\n\n assert result.constraints == []\n","sub_path":"tests/unit/expression_relaxations/test_convex.py","file_name":"test_convex.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"515478756","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport re\n\nfrom setuptools import setup\n\n\ndef get_version(package):\n \"\"\"\n Return package version as listed in `__version__` in `init.py`.\n \"\"\"\n init_py = open(os.path.join(package, '__init__.py')).read()\n return re.search(\"__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py).group(1)\n\n\nversion = get_version('djbitcoin')\nreadme = open('README.rst').read()\n\nsetup(\n name='dj-bitcoin',\n version=version,\n url='https://github.com/silverlogic/dj-bitcoin',\n license='MIT',\n description='Django helpers for working with bitcoin',\n long_description=readme,\n author='Ryan Pineo',\n author_email='ryanpineo@gmail.com',\n packages=['djbitcoin'],\n install_requires=[],\n zip_safe=False,\n classifiers=[\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Internet :: WWW/HTTP',\n ]\n)\n","sub_path":"pypi_install_script/dj-bitcoin-0.0.4.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"64412067","text":"## Part 1\nimport tkinter as tk, random \nclass SnakeGUI:\n def __init__(self):\n self.win = tk.Tk()\n self.canvas = tk.Canvas(self.win, width = 660, height = 660)\n self.canvas.pack()\n self.board = self.canvas.create_rectangle(30, 30, 630, 630)\n self.player_snake = Snake(330, 330, 'green', self.canvas)\n self.enemy_snake = Enemy(270, 300, 'purple', self.canvas)\n self.food()\n self.gameloop()\n self.win.bind('',self.player_snake.go_down)\n self.win.bind('', self.player_snake.go_right)\n self.win.bind('', self.player_snake.go_left)\n self.win.bind('', self.player_snake.go_up)\n def restart(self, event):\n self.canvas.delete(self.text)\n self.board = self.canvas.create_rectangle(30, 30, 630, 630)\n self.player_snake = Snake(330, 330, 'green', self.canvas)\n self.food()\n self.win.bind('',self.player_snake.go_down)\n self.win.bind('', self.player_snake.go_right)\n self.win.bind('', self.player_snake.go_left)\n self.win.bind('', self.player_snake.go_up)\n self.enemy_snake = Enemy(270, 300, 'purple', self.canvas)\n self.gameloop()\n def gameloop(self):\n if self.player_snake.end == False:\n snake_has_eaten = self.player_snake.move(self.food_x, self.food_y)\n if (snake_has_eaten == True):\n self.canvas.delete(self.pellet)\n self.food()\n enemy_has_eaten = self.enemy_snake.move(self.food_x, self.food_y)\n if (enemy_has_eaten == True):\n self.canvas.delete(self.pellet)\n self.food()\n for block in self.player_snake.segments:\n coord = self.canvas.coords(block)\n if coord != [] and self.enemy_snake.x == coord[0] and self.enemy_snake.y == coord[1]:\n self.player_snake.end = True\n for block2 in self.enemy_snake.segments:\n coords2 = self.canvas.coords(block2)\n if coords2 != [] and self.player_snake.x == coords2[0] and self.player_snake.y == coords2[1]:\n self.player_snake.end = True\n self.canvas.after(100, self.gameloop)\n else:\n self.canvas.delete(tk.ALL)\n self.text = self.canvas.create_text(300,300, text = 'Game has ended')\n self.win.bind('r', self.restart)\n def food(self):\n self.food_x = 30*random.randint(1,20)\n self.food_y = 30*random.randint(1,20)\n self.pellet = self.canvas.create_oval(self.food_x, self.food_y, self.food_x + 30, self.food_y + 30, fill = 'red')\n return self.pellet\nclass Snake:\n def __init__(self, x, y, color, obj):\n self.x = x\n self.y = y\n self.color = color\n self.canvas = obj\n self.snake1 = self.canvas.create_rectangle(self.x, self.y, self.x + 30, self.y + 30, fill = self.color)\n self.segments = [self.snake1]\n self.vx = 0\n self.vy = 0\n self.end = False\n def move(self, food_x, food_y):\n self.x += self.vx\n self.y += self.vy\n self.grow = self.canvas.create_rectangle(self.x, self.y, self.x + 30, self.y + 30, fill = self.color)\n self.segments.insert(0, self.grow)\n remover = self.segments.pop()\n self.canvas.delete(remover)\n for part in self.segments[1:]:\n coords = self.canvas.coords(part)\n if self.x == coords[0] and self.y == coords[1] and self.x + 30 == coords[2] and self.y + 30 == coords[3]:\n self.end = True\n if (self.x == food_x and self.y == food_y):\n self.segments.insert(0, self.canvas.create_rectangle(self.x , self.y, self.x + 30 - self.vx, self.y + 30 - self.vy, fill = self.color))\n return True\n elif self.x - self.vx > 660 or self.y - self.vy > 660 or self.x + 30 < 0 or self. y + 30 < 0:\n self.end = True\n def go_down(self, event):\n self.vx = 0\n self.vy = 30\n def go_right(self, event):\n self.vx = 30\n self.vy = 0\n def go_left(self, event):\n self.vx = -30\n self.vy = 0\n def go_up(self, event):\n self.vx = 0\n self.vy = -30\nclass Enemy(Snake):\n def __init__(self, x, y, color, obj):\n Snake.__init__(self, x, y, color, obj)\n self.end = False\n def move(self, food_x, food_y):\n self.vx = 30\n self.vy = 30\n if self.x < food_x:\n self.x += self.vx\n self.vy = 0\n elif self.y < food_y:\n self.y += self.vy\n self.vx = 0\n elif self.x > food_x:\n self.x -= self.vx\n self.vy = 0\n elif self.y > food_y:\n self.y -= self.vy\n self.vx = 0\n self.grow = self.canvas.create_rectangle(self.x, self.y, self.x + 30, self.y + 30, fill = self.color)\n self.segments.insert(0, self.grow)\n remove = self.segments.pop()\n self.canvas.delete(remove)\n if (self.x == food_x and self.y == food_y):\n self.segments.insert(0, self.canvas.create_rectangle(self.x, self.y, self.x - self.vx + 30, self.y + 30 - self.vy, fill = self.color))\n return True\nSnakeGUI()\ntk.mainloop()\n \n","sub_path":"Snakegame.py","file_name":"Snakegame.py","file_ext":"py","file_size_in_byte":5274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"199935630","text":"\"\"\"\nConvert a raw Mobius dataset to the TFRecords format\n\nBased on pascalvoc_to_tfrecords.py\n\nJSON files contain class information\n\nUsage:\n```shell\npython tf_convert_data.py \\\n --dataset_name='mobius_all' \\\n --dataset_dir='../data/cv/mobius_all_small/trainval/' \\\n --output_name='mobius_all_small_train' \\\n --output_dir='./tfrecords/mobius_all_small'\n```\n\"\"\"\nimport os\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\n\nimport json\n\nfrom PIL import Image\n\nfrom datasets.dataset_utils import int64_feature, float_feature, bytes_feature\n\n# Original dataset organization:\nDIRECTORY_ANNOTATIONS = 'Annotations/'\nDIRECTORY_IMAGES = 'JPEGImages/'\n\n# TFRecords conversion parameters:\nRANDOM_SEED = 2424\nSAMPLES_PER_FILE = 200\n\nVOC_LABELS = [\n 'none',\n 'aeroplane',\n 'bicycle',\n 'bird',\n 'boat',\n 'bottle',\n 'bus',\n 'car',\n 'cat',\n 'chair',\n 'cow',\n 'diningtable',\n 'dog',\n 'horse',\n 'motorbike',\n 'person',\n 'pottedplant',\n 'sheep',\n 'sofa',\n 'train',\n 'tvmonitor'\n]\n\n\ndef _process_image(directory, name):\n \"\"\"Process an image and annotation file.\n\n Args:\n directory: Dataset directory\n name: Image base filename\n Returns:\n image_data: Image data\n shape: Image size\n bboxes: Bounding boxes, relative coordinates\n labels: Bounding box integer labels\n labels_text: Bounding box label text\n \"\"\"\n # Read the image file:\n image_filename = os.path.join(directory, DIRECTORY_IMAGES, name + '.jpg')\n image_data = tf.gfile.FastGFile(image_filename, 'rb').read()\n\n # Read the JSON annotation file:\n json_filename = os.path.join(directory, DIRECTORY_ANNOTATIONS,\n name + '.json')\n with open(json_filename, 'r') as f:\n json_annotation = json.load(f)\n\n # Image shape:\n im = Image.open(image_filename)\n shape = [int(im.size[0]), int(im.size[1]), 3]\n\n # Read annotations:\n bboxes = []\n labels = []\n labels_text = []\n for cur_bbox in json_annotation['bboxes']:\n label = int(cur_bbox['class'])\n labels.append(label)\n labels_text.append(VOC_LABELS[label].encode('ascii'))\n bboxes.append(cur_bbox['bbox'])\n\n return image_data, shape, bboxes, labels, labels_text\n\n\ndef _convert_to_example(image_data, labels, labels_text, bboxes, shape):\n \"\"\"Build an example proto for an image example.\n\n Args:\n image_data: string, JPEG encoding of RGB image\n labels: list of integers, Identifier for ground truth\n labels_text: list of strings, Human-readable labels\n bboxes: list of bounding boxes, each box a list of 4 ratios specifying\n [ymin, xmin, ymax, xmax]\n shape: 3 integers, Image shape in pixels\n Returns:\n example: Example proto\n \"\"\"\n xmin = []\n ymin = []\n xmax = []\n ymax = []\n for b in bboxes:\n assert len(b) == 4\n [l.append(point) for l, point in zip([ymin, xmin, ymax, xmax], b)]\n\n image_format = b'JPEG'\n example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': int64_feature(shape[0]),\n 'image/width': int64_feature(shape[1]),\n 'image/channels': int64_feature(shape[2]),\n 'image/shape': int64_feature(shape),\n 'image/object/bbox/xmin': float_feature(xmin),\n 'image/object/bbox/xmax': float_feature(xmax),\n 'image/object/bbox/ymin': float_feature(ymin),\n 'image/object/bbox/ymax': float_feature(ymax),\n 'image/object/bbox/label': int64_feature(labels),\n 'image/object/bbox/label_text': bytes_feature(labels_text),\n 'image/format': bytes_feature(image_format),\n 'image/encoded': bytes_feature(image_data)}))\n\n return example\n\n\ndef _add_to_tfrecord(dataset_dir, name, tfrecord_writer):\n \"\"\"Loads data from images and annotations files and adds them to a TFRecord.\n\n Args:\n dataset_dir: Dataset directory\n name: Image name to add to the TFRecord\n tfrecord_writer: The TFRecord writer to use for writing\n \"\"\"\n\n image_data, shape, bboxes, labels, labels_text = _process_image(dataset_dir,\n name)\n example = _convert_to_example(image_data, labels, labels_text, bboxes,\n shape)\n tfrecord_writer.write(example.SerializeToString())\n\n\ndef _get_output_filename(output_dir, name, idx):\n return '%s/%s_%03d.tfrecord' % (output_dir, name, idx)\n\n\ndef run(dataset_dir, output_dir, name='mobius_new', shuffling=False):\n \"\"\"Runs the conversion operation.\n\n Args:\n dataset_dir: The directory where the dataset is stored\n output_dir: The desired output directory\n \"\"\"\n if not tf.gfile.Exists(output_dir):\n tf.gfile.MakeDirs(output_dir)\n\n # Find dataset filenames:\n filepath = os.path.join(dataset_dir, DIRECTORY_ANNOTATIONS)\n filenames = sorted(os.listdir(filepath))\n\n # Shuffle files:\n if shuffling:\n random.seed(RANDOM_SEED)\n random.shuffle(filenames)\n\n # Process dataset files:\n i = 0\n fidx = 0\n while i < len(filenames):\n # Open new TFRecord file:\n tf_filename = _get_output_filename(output_dir, name, fidx)\n with tf.python_io.TFRecordWriter(tf_filename) as tfrecord_writer:\n j = 0\n while i < len(filenames) and j < SAMPLES_PER_FILE:\n sys.stdout.write('\\r>> Converting image %d/%d' % (i+1, len(filenames)))\n sys.stdout.flush()\n\n filename = filenames[i]\n img_name = filename[:-5]\n _add_to_tfrecord(dataset_dir, img_name, tfrecord_writer)\n i += 1\n j += 1\n fidx += 1\n\n print('\\nFinished converting the Mobius dataset!')\n","sub_path":"ssd-tensorflow/datasets/mobius_all_to_tfrecords.py","file_name":"mobius_all_to_tfrecords.py","file_ext":"py","file_size_in_byte":5706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"447302952","text":"import time, os.path\r\nfrom random import randint\r\n\r\nlineNum = 1\r\nexist = True\r\n\r\nif not os.path.isfile(\"Reaction times.txt\"):\r\n file = open(\"Reaction times.txt\", \"w\")\r\n exist = False\r\nelse:\r\n file = open(\"Reaction times.txt\", \"r\")\r\n results = list()\r\n userInput = input(\"Would you like to access your previous scores? Y/N \").lower()\r\n for line in file:\r\n lineNum += 1\r\n if userInput == \"y\":\r\n score = line[15:].strip()\r\n results.append(score)\r\n if userInput == \"y\":\r\n userInput = input(\"\"\"\\nEnter the number of the option you wish to choose\r\n1. Display all scores\r\n2. Display 10 highest scores\r\n3. Display average score\\n\"\"\")\r\n while True:\r\n try:\r\n userInput = int(userInput)\r\n break\r\n except:\r\n print (\"\\nPlease enter a valid answer.\")\r\n userInput = input(\"Enter the number of the option you wish to choose\")\r\n while not 1 <= userInput <= 3:\r\n print (\"\\nPlease enter a valid answer\")\r\n userInput = input(\"Enter the number of the option you wish to choose\")\r\n if userInput == 1:\r\n print ()\r\n for p in results:\r\n print (p)\r\n print ()\r\n elif userInput == 2:\r\n print ()\r\n a = sorted(results)\r\n for i in range(10):\r\n print (a[i])\r\n print ()\r\n else:\r\n totalScore = 0\r\n for q in results:\r\n totalScore += float(q)\r\n print (\"\\nAverage score: \" + str(totalScore/lineNum) + \"\\n\")\r\n \r\n file.close()\r\n\r\n file = open(\"Reaction times.txt\", \"a\")\r\n\r\nprint (\"\"\"--------------------\r\n Reaction time test\r\n--------------------\"\"\")\r\nwhile True:\r\n print (\"When the 'O' appears, tap enter. Your reaction time will be measured\\n\")\r\n time.sleep(randint(4, 6))\r\n start = time.time()\r\n reaction = input (\"O\")\r\n end = time.time()\r\n reaction = end - start\r\n file.write(\"Try {}:\".format(lineNum) + ((10-len(str(lineNum)))*\" \") + \"{}\\n\".format(reaction))\r\n lineNum += 1\r\n print (\"\\nYour reaction time was {} seconds\".format(reaction))\r\n cont = input(\"Would you like to try again? Y/N \").lower()\r\n print ()\r\n if cont == \"n\":\r\n break\r\n \r\nfile.close()\r\n","sub_path":"Python/Reaction time measurer/reaction time.py","file_name":"reaction time.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"594318534","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 25 12:01:29 2021\r\n\r\n@author: rearu\r\n\"\"\"\r\nimport numpy as np\r\nimport xarray as xr\r\n\r\nmonths = ['JUN', 'JUL', 'AUG']\r\nyears1980s = np.arange(1980, 1990)\r\nyears2010s = np.arange(2010, 2020)\r\n\r\nds1=xr.open_dataset(path+'JUN1980.aijh12iWISO_20th_MERRA2_ANL.nc')\r\nfor y in years1980s:\r\n for m in months:\r\n if [m, y] != [\"JUN\", 1980]:\r\n fname = '{}{}.aijh12iWISO_20th_MERRA2_ANL.nc'.format(m, y)\r\n ds2=xr.open_dataset(path+fname)\r\n ds1 = xr.concat([ds1, ds2], dim=\"time\")\r\n \r\n#print(ds1.time.count().values)\r\nds1.to_netcdf(path=path+'1980s_prec.nc')\r\n\r\nds3=xr.open_dataset(path+'JUN2010.aijh12iWISO_20th_MERRA2_ANL.nc')\r\nfor y in years2010s:\r\n for m in months:\r\n if [m, y] != [\"JUN\", 2010]:\r\n fname = '{}{}.aijh12iWISO_20th_MERRA2_ANL.nc'.format(m, y)\r\n ds4=xr.open_dataset(path+fname)\r\n ds3 = xr.concat([ds3, ds4], dim=\"time\")\r\n \r\n#print(ds1.time.count().values)\r\nds1.to_netcdf(path=path+'2010s_prec.nc')","sub_path":"file_prep.py","file_name":"file_prep.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"633317702","text":"import sys\nimport math\nfrom six import print_\n\nif sys.version_info > (3,):\n xrange = range\n\n\ndef main():\n ret = ['2', ]\n fn = 'P_1M.txt'\n cnt = 1\n n = 3\n GOAL = 1000000\n while cnt < GOAL:\n is_prime = True\n for x in xrange(3, int(math.sqrt(n))+1, 2):\n if (n % x == 0):\n is_prime = False\n break\n if is_prime:\n cnt += 1\n ret.append(str(n))\n if cnt % 1000 == 0:\n print_('Reached %d out of %d' % (cnt, GOAL))\n n += 2\n print_('Writing')\n with open(fn, 'wb') as fh:\n for c in ret[::-1]:\n fh.write(c[::-1])\n print_('Finished writing')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"project-euler/603/euler_603_v1_step0.py","file_name":"euler_603_v1_step0.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"626398397","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom azure.core.exceptions import HttpResponseError\nimport msrest.serialization\n\n\nclass CollectionOfNotification(msrest.serialization.Model):\n \"\"\"Collection of notification.\n\n :param value:\n :type value: list[~notification.models.MicrosoftGraphNotification]\n :param odata_next_link:\n :type odata_next_link: str\n \"\"\"\n\n _attribute_map = {\n 'value': {'key': 'value', 'type': '[MicrosoftGraphNotification]'},\n 'odata_next_link': {'key': '@odata\\\\.nextLink', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n super(CollectionOfNotification, self).__init__(**kwargs)\n self.value = kwargs.get('value', None)\n self.odata_next_link = kwargs.get('odata_next_link', None)\n\n\nclass MicrosoftGraphEntity(msrest.serialization.Model):\n \"\"\"entity.\n\n :param id: Read-only.\n :type id: str\n \"\"\"\n\n _attribute_map = {\n 'id': {'key': 'id', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n super(MicrosoftGraphEntity, self).__init__(**kwargs)\n self.id = kwargs.get('id', None)\n\n\nclass MicrosoftGraphNotification(MicrosoftGraphEntity):\n \"\"\"notification.\n\n :param id: Read-only.\n :type id: str\n :param target_host_name:\n :type target_host_name: str\n :param expiration_date_time:\n :type expiration_date_time: ~datetime.datetime\n :param display_time_to_live:\n :type display_time_to_live: int\n :param priority: Possible values include: \"None\", \"High\", \"Low\".\n :type priority: str or ~notification.models.MicrosoftGraphPriority\n :param group_name:\n :type group_name: str\n :param target_policy: targetPolicyEndpoints.\n :type target_policy: ~notification.models.MicrosoftGraphTargetPolicyEndpoints\n :param raw_content:\n :type raw_content: str\n :param visual_content: visualProperties.\n :type visual_content: ~notification.models.MicrosoftGraphVisualProperties\n \"\"\"\n\n _validation = {\n 'display_time_to_live': {'maximum': 2147483647, 'minimum': -2147483648},\n }\n\n _attribute_map = {\n 'id': {'key': 'id', 'type': 'str'},\n 'target_host_name': {'key': 'targetHostName', 'type': 'str'},\n 'expiration_date_time': {'key': 'expirationDateTime', 'type': 'iso-8601'},\n 'display_time_to_live': {'key': 'displayTimeToLive', 'type': 'int'},\n 'priority': {'key': 'priority', 'type': 'str'},\n 'group_name': {'key': 'groupName', 'type': 'str'},\n 'target_policy': {'key': 'targetPolicy', 'type': 'MicrosoftGraphTargetPolicyEndpoints'},\n 'raw_content': {'key': 'payload.rawContent', 'type': 'str'},\n 'visual_content': {'key': 'payload.visualContent', 'type': 'MicrosoftGraphVisualProperties'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n super(MicrosoftGraphNotification, self).__init__(**kwargs)\n self.target_host_name = kwargs.get('target_host_name', None)\n self.expiration_date_time = kwargs.get('expiration_date_time', None)\n self.display_time_to_live = kwargs.get('display_time_to_live', None)\n self.priority = kwargs.get('priority', None)\n self.group_name = kwargs.get('group_name', None)\n self.target_policy = kwargs.get('target_policy', None)\n self.raw_content = kwargs.get('raw_content', None)\n self.visual_content = kwargs.get('visual_content', None)\n\n\nclass MicrosoftGraphTargetPolicyEndpoints(msrest.serialization.Model):\n \"\"\"targetPolicyEndpoints.\n\n :param platform_types:\n :type platform_types: list[str]\n \"\"\"\n\n _attribute_map = {\n 'platform_types': {'key': 'platformTypes', 'type': '[str]'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n super(MicrosoftGraphTargetPolicyEndpoints, self).__init__(**kwargs)\n self.platform_types = kwargs.get('platform_types', None)\n\n\nclass MicrosoftGraphVisualProperties(msrest.serialization.Model):\n \"\"\"visualProperties.\n\n :param title:\n :type title: str\n :param body:\n :type body: str\n \"\"\"\n\n _attribute_map = {\n 'title': {'key': 'title', 'type': 'str'},\n 'body': {'key': 'body', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n super(MicrosoftGraphVisualProperties, self).__init__(**kwargs)\n self.title = kwargs.get('title', None)\n self.body = kwargs.get('body', None)\n\n\nclass OdataError(msrest.serialization.Model):\n \"\"\"OdataError.\n\n All required parameters must be populated in order to send to Azure.\n\n :param error: Required.\n :type error: ~notification.models.OdataErrorMain\n \"\"\"\n\n _validation = {\n 'error': {'required': True},\n }\n\n _attribute_map = {\n 'error': {'key': 'error', 'type': 'OdataErrorMain'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n super(OdataError, self).__init__(**kwargs)\n self.error = kwargs['error']\n\n\nclass OdataErrorDetail(msrest.serialization.Model):\n \"\"\"OdataErrorDetail.\n\n All required parameters must be populated in order to send to Azure.\n\n :param code: Required.\n :type code: str\n :param message: Required.\n :type message: str\n :param target:\n :type target: str\n \"\"\"\n\n _validation = {\n 'code': {'required': True},\n 'message': {'required': True},\n }\n\n _attribute_map = {\n 'code': {'key': 'code', 'type': 'str'},\n 'message': {'key': 'message', 'type': 'str'},\n 'target': {'key': 'target', 'type': 'str'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n super(OdataErrorDetail, self).__init__(**kwargs)\n self.code = kwargs['code']\n self.message = kwargs['message']\n self.target = kwargs.get('target', None)\n\n\nclass OdataErrorMain(msrest.serialization.Model):\n \"\"\"OdataErrorMain.\n\n All required parameters must be populated in order to send to Azure.\n\n :param code: Required.\n :type code: str\n :param message: Required.\n :type message: str\n :param target:\n :type target: str\n :param details:\n :type details: list[~notification.models.OdataErrorDetail]\n :param innererror: The structure of this object is service-specific.\n :type innererror: object\n \"\"\"\n\n _validation = {\n 'code': {'required': True},\n 'message': {'required': True},\n }\n\n _attribute_map = {\n 'code': {'key': 'code', 'type': 'str'},\n 'message': {'key': 'message', 'type': 'str'},\n 'target': {'key': 'target', 'type': 'str'},\n 'details': {'key': 'details', 'type': '[OdataErrorDetail]'},\n 'innererror': {'key': 'innererror', 'type': 'object'},\n }\n\n def __init__(\n self,\n **kwargs\n ):\n super(OdataErrorMain, self).__init__(**kwargs)\n self.code = kwargs['code']\n self.message = kwargs['message']\n self.target = kwargs.get('target', None)\n self.details = kwargs.get('details', None)\n self.innererror = kwargs.get('innererror', None)\n","sub_path":"msgraph-cli-extensions/src/notification/azext_notification/vendored_sdks/notification/models/_models.py","file_name":"_models.py","file_ext":"py","file_size_in_byte":7458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"403418311","text":"from django import forms\r\nfrom django.core import validators\r\nfrom . import models\r\n\r\n\r\ndef must_be_empty(value):\r\n if value:\r\n raise forms.ValidationError('is not empty')\r\n\r\n\r\nclass ContactForm(forms.ModelForm):\r\n\r\n class Meta:\r\n model = models.Contact\r\n fields = [\r\n 'name',\r\n 'phone_number',\r\n 'email',\r\n 'message',\r\n ]\r\n\r\n # Validating the fields in contact form\r\n\r\n phone_number = forms.CharField(\r\n required=True,\r\n validators=[\r\n validators.RegexValidator(\r\n regex=r'^\\+?1?\\d{9,15}$',\r\n message=(\r\n \"Phone number must be entered in the format: '+999999999'.\"\r\n \" Up to 15 digits allowed.\"\r\n ),\r\n )\r\n ],\r\n )\r\n\r\n honeypot = forms.CharField(\r\n required=False,\r\n widget=forms.HiddenInput,\r\n label=\"Leave empty\",\r\n validators=[must_be_empty],\r\n )\r\n","sub_path":"contact/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"189059074","text":"from tkinter import *\n\nwindow = Tk()\nwindow.title(\"ch3_2\")\nwindow.iconbitmap(r\"C:\\Users\\wywu\\Downloads\\favicon (4).ico\")\n\nlab1 = Label(window,text=\"明智科技大学\",\n bg=\"lightyellow\",\n width=15)\nlab2 = Label(window,text=\"长庚大学\",\n bg=\"lightgreen\",\n width=15)\nlab3 = Label(window,text=\"长庚科技大学\",\n bg=\"lightblue\",\n width=15)\nlab1.pack(side=BOTTOM)\nlab2.pack(side=BOTTOM)\nlab3.pack(side=BOTTOM)\n\nwindow.mainloop()","sub_path":"Python和GUI设计Tkinter菜单编程/ch3_2.py","file_name":"ch3_2.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"270776396","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nThis experiment was created using PsychoPy2 Experiment Builder (v1.81.03), February 24, 2015, at 13:33\nIf you publish work using this script please cite the relevant PsychoPy publications\n Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of Neuroscience Methods, 162(1-2), 8-13.\n Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy. Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008\n\"\"\"\n\nfrom __future__ import division # so that 1/3=0.333 instead of 1/3=0\nfrom psychopy import visual, core, data, event, logging, sound, gui\nfrom psychopy.constants import * # things like STARTED, FINISHED\nimport numpy as np # whole numpy lib is available, prepend 'np.'\nfrom numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray\nfrom numpy.random import random, randint, normal, shuffle, np\nfrom jkpsycho import *\nimport os # handy system and path functions\n\n# Ensure that relative paths start from the same directory as this script\n_thisDir = os.path.dirname(os.path.abspath(__file__))\nos.chdir(_thisDir)\n\n# Store info about the experiment session\nexpName = 'test' # from the Builder filename that created this script\nexpInfo = {}\nexpInfo['date'] = data.getDateStr() # add a simple timestamp\nexpInfo['expName'] = expName\n\n# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc\nfilename = _thisDir + os.sep + u'data' + os.sep + u'psychopy_data_' + data.getDateStr()\n\n# An ExperimentHandler isn't essential but helps with data saving\nthisExp = data.ExperimentHandler(name=expName, version='',\n extraInfo=expInfo, runtimeInfo=None,\n originPath=None,\n savePickle=True, saveWideText=False,\n dataFileName=filename)\nlogging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file\n\nendExpNow = False # flag for 'escape' or other condition => quit the exp\n\n# Start Code - component code to be run before the window creation\n\n# Setup the Window\nwin = visual.Window(size=(1680, 1050), fullscr=True, screen=0, allowGUI=False, allowStencil=False,\n monitor='testMonitor', color=[0,0,0], colorSpace='rgb',\n blendMode='avg', useFBO=True,\n )\n# store frame rate of monitor if we can measure it successfully\nexpInfo['frameRate']=win.getActualFrameRate()\nif expInfo['frameRate']!=None:\n frameDur = 1.0/round(expInfo['frameRate'])\nelse:\n frameDur = 1.0/60.0 # couldn't get a reliable measure so guess\n\n# Initialize components for Routine \"init\"\ninitClock = core.Clock()\n\n\n######################################################################\n## scanner_coms_connect - initialize #################################\n######################################################################\nscanner_coms_connect=CompDetails()\nscanner_coms = ScannerComs(port=3, timeout=0.001, baudrate=19200, keyboard=True)\n######################################################################\n\n\npause_text_2 = visual.TextStim(win=win, ori=0, name='pause_text_2',\n text='default text', font='Arial',\n pos=[0, 0], height=0.1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-1.0)\n\n# Initialize components for Routine \"test_response_test\"\ntest_response_testClock = core.Clock()\n\n\n######################################################################\n## tr1 - initialize ##################################################\n######################################################################\ntr1=CompDetails()\n######################################################################\n\n\n\n\n######################################################################\n## tr2 - initialize ##################################################\n######################################################################\ntr2=CompDetails()\n######################################################################\n\n\ntext_3 = visual.TextStim(win=win, ori=0, name='text_3',\n text='default text', font=u'Arial',\n pos=[0, 0], height=0.1, wrapWidth=None,\n color=u'white', colorSpace='rgb', opacity=1,\n depth=-2.0)\n\n# Initialize components for Routine \"instr\"\ninstrClock = core.Clock()\npause_text = visual.TextStim(win=win, ori=0, name='pause_text',\n text=\"Next, you will have 10 seconds to press buttons. You'll see a list of presses on screen. An * will be appended on subsequent frames to show that you have't pressed anything since last time.\", font='Arial',\n pos=[0, 0], height=0.1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=0.0)\n\n_text = \"Next, you will have 10 seconds to press buttons. You'll see a list of presses on screen. An * will be appended on subsequent frames to show that you have't pressed anything since last time.\"+'\\n\\n'\nif ['1','2','5']:\n _text+='press a key to continue:\\n'+str(list(['1','2','5']))[1:-1]\nelse:\n _text+='press any key to continue'\npause_text.setText(_text)\n\n\n# Initialize components for Routine \"simple_coms_test\"\nsimple_coms_testClock = core.Clock()\n\nbutton_display = visual.TextStim(win=win, ori=0, name='button_display',\n text='default text', font='Arial',\n pos=[0, 0], height=0.1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-1.0)\n\n# Initialize components for Routine \"trial\"\ntrialClock = core.Clock()\nISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI')\n\n\n######################################################################\n## scanner_coms_use - initialize #####################################\n######################################################################\nscanner_coms_use=CompDetails()\n######################################################################\n\n\n\ntext = visual.TextStim(win=win, ori=0, name='text',\n text='default text', font='Arial',\n pos=[0, 0], height=0.1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-3.0)\n\n\n######################################################################\n## routine_stopper - initialize ######################################\n######################################################################\nroutine_stopper=CompDetails()\n######################################################################\n\n\n\n# Initialize components for Routine \"TableLooperTest\"\nTableLooperTestClock = core.Clock()\n\n\n######################################################################\n## scanner_coms_use_2 - initialize ###################################\n######################################################################\nscanner_coms_use_2=CompDetails()\n######################################################################\n\n\n\n\n######################################################################\n## table_looper - initialize #########################################\n######################################################################\ntable_looper=CompDetails()\ntrial=TableLooper(u'conds.csv')\n######################################################################\n\n\nrow_printer = visual.TextStim(win=win, ori=0, name='row_printer',\n text='default text', font=u'Arial',\n pos=[0, 0], height=0.1, wrapWidth=None,\n color=u'white', colorSpace='rgb', opacity=1,\n depth=-2.0)\ndo_table_looper_test = True\n\n# Initialize components for Routine \"done\"\ndoneClock = core.Clock()\npause_text_3 = visual.TextStim(win=win, ori=0, name='pause_text_3',\n text='default text', font=u'Arial',\n pos=[0, 0], height=0.1, wrapWidth=None,\n color=u'white', colorSpace='rgb', opacity=1,\n depth=0.0)\n\n# Create some handy timers\nglobalClock = core.Clock() # to track the time since experiment started\nroutineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine \n\n#------Prepare to start Routine \"init\"-------\nt = 0\ninitClock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\npause_text_2.setText('''This is the test suite for JkPsycho Components\n\nFollow instructions to thoroughly test the components. If there is a problem, contact me (Josh Kinnison) and I'll fix it as soon as possible.\n\nScanner Coms connected?: {}'''.format(scanner_coms.connected_to_serial()))\nevent.clearEvents(eventType='keyboard')\n\n_text = '''This is the test suite for JkPsycho Components\n\nFollow instructions to thoroughly test the components. If there is a problem, contact me (Josh Kinnison) and I'll fix it as soon as possible.\n\nScanner Coms connected?: {}'''.format(scanner_coms.connected_to_serial())+'\\n\\n'\nif None:\n _text+='press a key to continue:\\n'+str(list(None))[1:-1]\nelse:\n _text+='press any key to continue'\npause_text_2.setText(_text)\n\n# keep track of which components have finished\ninitComponents = []\ninitComponents.append(pause_text_2)\nfor thisComponent in initComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"init\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = initClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n \n ######################################################################\n ## scanner_coms_connect - frame updates ##############################\n ######################################################################\n # timing logic\n if scanner_coms_connect.status==NOT_STARTED: scanner_coms_connect.status=STARTED\n ######################################################################\n \n \n \n # *pause_text_2* updates\n if t >= 0.0 and pause_text_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n pause_text_2.tStart = t # underestimates by a little under one frame\n pause_text_2.frameNStart = frameN # exact frame index\n pause_text_2.setAutoDraw(True)\n # stop routine if pause_text_2's buttons are pressed\n if pause_text_2.status==STARTED:\n if event.getKeys(keyList=None): stopRoutine()\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n routineTimer.reset() # if we abort early the non-slip timer needs reset\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in initComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n else: # this Routine was not non-slip safe so reset non-slip timer\n routineTimer.reset()\n\n#-------Ending Routine \"init\"-------\nfor thisComponent in initComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n\n#------Prepare to start Routine \"test_response_test\"-------\nt = 0\ntest_response_testClock.reset() # clock \nframeN = -1\nroutineTimer.add(20.000000)\n# update component parameters for each repeat\n\n\n######################################################################\n## tr1 - pre-routine #################################################\n######################################################################\ntr1 = TextGrabber(txt='', multiline=False) # will automatically start when status set to STARTED, else will be stopped. Usage here is a bit wacky due to constraints of PsychoPy code generation.\n######################################################################\n\n\n\n\n######################################################################\n## tr2 - pre-routine #################################################\n######################################################################\ntr2 = TextGrabber(txt='', multiline=True) # will automatically start when status set to STARTED, else will be stopped. Usage here is a bit wacky due to constraints of PsychoPy code generation.\n######################################################################\n\n\n# keep track of which components have finished\ntest_response_testComponents = []\ntest_response_testComponents.append(tr1)\ntest_response_testComponents.append(tr2)\ntest_response_testComponents.append(text_3)\nfor thisComponent in test_response_testComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"test_response_test\"-------\ncontinueRoutine = True\nwhile continueRoutine and routineTimer.getTime() > 0:\n # get current time\n t = test_response_testClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n \n ######################################################################\n ## tr1 - frame updates ###############################################\n ######################################################################\n # timing logic\n if t >= 2 and tr1.status == NOT_STARTED:\n # keep track of start time/frame for later\n tr1.tStart = t # underestimates by a little under one frame\n tr1.frameNStart = frameN # exact frame index\n tr1.status=STARTED\n if tr1.status == STARTED and t >= (2 + (8-win.monitorFramePeriod*0.75)): #most of one frame period left\n tr1.status = STOPPED\n ######################################################################\n \n \n \n \n ######################################################################\n ## tr2 - frame updates ###############################################\n ######################################################################\n # timing logic\n if t >= 10 and tr2.status == NOT_STARTED:\n # keep track of start time/frame for later\n tr2.tStart = t # underestimates by a little under one frame\n tr2.frameNStart = frameN # exact frame index\n tr2.status=STARTED\n if tr2.status == STARTED and t >= (10 + (8-win.monitorFramePeriod*0.75)): #most of one frame period left\n tr2.status = STOPPED\n ######################################################################\n \n \n \n # *text_3* updates\n if t >= 0.0 and text_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_3.tStart = t # underestimates by a little under one frame\n text_3.frameNStart = frameN # exact frame index\n text_3.setAutoDraw(True)\n if text_3.status == STARTED and t >= (0.0 + (20-win.monitorFramePeriod*0.75)): #most of one frame period left\n text_3.setAutoDraw(False)\n if text_3.status == STARTED: # only update if being drawn\n text_3.setText(\"{}\\none line 2-10 seconds: {}\\nmulti-line 10-18 seconds:{}\".format(t,tr1.text,tr2.text), log=False)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n routineTimer.reset() # if we abort early the non-slip timer needs reset\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in test_response_testComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"test_response_test\"-------\nfor thisComponent in test_response_testComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n\n\n######################################################################\n## tr1 - post-routine ################################################\n######################################################################\ntr1.stop()\n######################################################################\n\n\n\n\n######################################################################\n## tr2 - post-routine ################################################\n######################################################################\ntr2.stop()\n######################################################################\n\n\n\n#------Prepare to start Routine \"instr\"-------\nt = 0\ninstrClock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nevent.clearEvents(eventType='keyboard')\n# keep track of which components have finished\ninstrComponents = []\ninstrComponents.append(pause_text)\nfor thisComponent in instrComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"instr\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = instrClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *pause_text* updates\n if t >= 0.0 and pause_text.status == NOT_STARTED:\n # keep track of start time/frame for later\n pause_text.tStart = t # underestimates by a little under one frame\n pause_text.frameNStart = frameN # exact frame index\n pause_text.setAutoDraw(True)\n # stop routine if pause_text's buttons are pressed\n if pause_text.status==STARTED:\n if event.getKeys(keyList=['1','2','5']): stopRoutine()\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n routineTimer.reset() # if we abort early the non-slip timer needs reset\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in instrComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n else: # this Routine was not non-slip safe so reset non-slip timer\n routineTimer.reset()\n\n#-------Ending Routine \"instr\"-------\nfor thisComponent in instrComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n\n#------Prepare to start Routine \"simple_coms_test\"-------\nt = 0\nsimple_coms_testClock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nmsgs=''\n# keep track of which components have finished\nsimple_coms_testComponents = []\nsimple_coms_testComponents.append(button_display)\nfor thisComponent in simple_coms_testComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"simple_coms_test\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = simple_coms_testClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n new_msgs = scanner_coms.messages()\n if new_msgs:\n msgs=', '.join(new_msgs)\n elif not msgs.endswith('*'):\n msgs+='*'\n \n \n # *button_display* updates\n if t >= 0.0 and button_display.status == NOT_STARTED:\n # keep track of start time/frame for later\n button_display.tStart = t # underestimates by a little under one frame\n button_display.frameNStart = frameN # exact frame index\n button_display.setAutoDraw(True)\n if button_display.status == STARTED and t >= (0.0 + (0-win.monitorFramePeriod*0.75)): #most of one frame period left\n button_display.setAutoDraw(False)\n if button_display.status == STARTED: # only update if being drawn\n button_display.setText('{}\\n{:02.2f}'.format(msgs,t), log=False)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n routineTimer.reset() # if we abort early the non-slip timer needs reset\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in simple_coms_testComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n else: # this Routine was not non-slip safe so reset non-slip timer\n routineTimer.reset()\n\n#-------Ending Routine \"simple_coms_test\"-------\nfor thisComponent in simple_coms_testComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n\n\n#------Prepare to start Routine \"trial\"-------\nt = 0\ntrialClock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\n\n\n######################################################################\n## scanner_coms_use - pre-routine ####################################\n######################################################################\n\n# initialize storage\nif True:\n coms=set([])\nelse:\n coms=[]\n\n# clear old stuff (always)\nscanner_coms.clear()\n\n######################################################################\n\n\npre=''\nif scanner_coms.connected_to_serial():\n pre+='serial+'\nif scanner_coms.connected_to_keyboard():\n pre+='keyboard'\nif not pre:\n pre='not connected to any inputs!!'\npre+='\\n'\n\nprint(scanner_coms._coms)\nprint(bool(scanner_coms._coms))\n\n# keep track of which components have finished\ntrialComponents = []\ntrialComponents.append(ISI)\ntrialComponents.append(scanner_coms_use)\ntrialComponents.append(text)\ntrialComponents.append(routine_stopper)\nfor thisComponent in trialComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"trial\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = trialClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n \n ######################################################################\n ## scanner_coms_use - frame updates ##################################\n ######################################################################\n # timing logic\n if t >= 1 and scanner_coms_use.status == NOT_STARTED:\n # keep track of start time/frame for later\n scanner_coms_use.tStart = t # underestimates by a little under one frame\n scanner_coms_use.frameNStart = frameN # exact frame index\n scanner_coms_use.status=STARTED\n # update\n if scanner_coms_use.status == STARTED:\n \n # pull messages from scanner coms (maybe keyboard too)\n _new_messages = scanner_coms.messages(clear_after=True,as_set=True)\n \n # update or replace\n if True:\n coms=_new_messages\n else:\n if True:\n coms.update(_new_messages)\n else:\n coms.extend(_new_messages)\n \n ######################################################################\n \n \n \n if scanner_coms_use.status==NOT_STARTED:\n txt=pre+'not started'\n elif scanner_coms_use.status==STOPPED:\n txt=pre+'stopped'\n else:\n print(coms)\n if 'not started' in txt:\n txt=pre\n if coms:\n txt=pre+','.join(coms)\n elif not txt.endswith('*'):\n txt+='*'\n \n \n # *text* updates\n if t >= 0.0 and text.status == NOT_STARTED:\n # keep track of start time/frame for later\n text.tStart = t # underestimates by a little under one frame\n text.frameNStart = frameN # exact frame index\n text.setAutoDraw(True)\n if text.status == STARTED: # only update if being drawn\n text.setText(txt, log=False)\n \n \n ######################################################################\n ## routine_stopper - frame updates ###################################\n ######################################################################\n # timing logic\n if t >= 0.0 and routine_stopper.status == NOT_STARTED:\n # keep track of start time/frame for later\n routine_stopper.tStart = t # underestimates by a little under one frame\n routine_stopper.frameNStart = frameN # exact frame index\n routine_stopper.status=STARTED\n # update\n if routine_stopper.status == STARTED:\n if '6' in coms: stopRoutine()\n ######################################################################\n \n \n # *ISI* period\n if t >= 0.0 and ISI.status == NOT_STARTED:\n # keep track of start time/frame for later\n ISI.tStart = t # underestimates by a little under one frame\n ISI.frameNStart = frameN # exact frame index\n ISI.start(0.5)\n elif ISI.status == STARTED: #one frame should pass before updating params and completing\n ISI.complete() #finish the static period\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n routineTimer.reset() # if we abort early the non-slip timer needs reset\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in trialComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n else: # this Routine was not non-slip safe so reset non-slip timer\n routineTimer.reset()\n\n#-------Ending Routine \"trial\"-------\nfor thisComponent in trialComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n\n\n######################################################################\n## scanner_coms_use - post-routine ###################################\n######################################################################\nscanner_coms.clear()\n######################################################################\n\n\n\n\n# set up handler to look after randomisation of conditions etc\ntrials = data.TrialHandler(nReps=500, method='random', \n extraInfo=expInfo, originPath=None,\n trialList=[None],\n seed=None, name='trials')\nthisExp.addLoop(trials) # add the loop to the experiment\nthisTrial = trials.trialList[0] # so we can initialise stimuli with some values\n# abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb)\nif thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\n\nfor thisTrial in trials:\n currentLoop = trials\n # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)\n if thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\n \n #------Prepare to start Routine \"TableLooperTest\"-------\n t = 0\n TableLooperTestClock.reset() # clock \n frameN = -1\n # update component parameters for each repeat\n \n \n ######################################################################\n ## scanner_coms_use_2 - pre-routine ##################################\n ######################################################################\n \n # initialize storage\n if True:\n coms=set([])\n else:\n coms=[]\n \n # clear old stuff (always)\n scanner_coms.clear()\n \n ######################################################################\n \n \n #being routine!\n # keep track of which components have finished\n TableLooperTestComponents = []\n TableLooperTestComponents.append(scanner_coms_use_2)\n TableLooperTestComponents.append(row_printer)\n for thisComponent in TableLooperTestComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n \n #-------Start Routine \"TableLooperTest\"-------\n continueRoutine = True\n while continueRoutine:\n # get current time\n t = TableLooperTestClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n \n ######################################################################\n ## scanner_coms_use_2 - frame updates ################################\n ######################################################################\n # timing logic\n if t >= 0.0 and scanner_coms_use_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n scanner_coms_use_2.tStart = t # underestimates by a little under one frame\n scanner_coms_use_2.frameNStart = frameN # exact frame index\n scanner_coms_use_2.status=STARTED\n # update\n if scanner_coms_use_2.status == STARTED:\n \n # pull messages from scanner coms (maybe keyboard too)\n _new_messages = scanner_coms.messages(clear_after=True,as_set=True)\n \n # update or replace\n if True:\n coms=_new_messages\n else:\n if True:\n coms.update(_new_messages)\n else:\n coms.extend(_new_messages)\n \n ######################################################################\n \n \n \n \n ######################################################################\n ## table_looper - frame updates ######################################\n ######################################################################\n # timing logic\n if table_looper.status==NOT_STARTED: table_looper.status=STARTED\n ######################################################################\n \n \n \n # *row_printer* updates\n if t >= 0.0 and row_printer.status == NOT_STARTED:\n # keep track of start time/frame for later\n row_printer.tStart = t # underestimates by a little under one frame\n row_printer.frameNStart = frameN # exact frame index\n row_printer.setAutoDraw(True)\n if row_printer.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left\n row_printer.setAutoDraw(False)\n if row_printer.status == STARTED: # only update if being drawn\n row_printer.setText('press 5 to step, 6 to stop\\n'+str(trial), log=False)\n if '5' in coms:\n stopRoutine()\n if '6' in coms:\n do_table_looper_test=False\n if not do_table_looper_test:\n stopRoutine()\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n routineTimer.reset() # if we abort early the non-slip timer needs reset\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in TableLooperTestComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n else: # this Routine was not non-slip safe so reset non-slip timer\n routineTimer.reset()\n \n #-------Ending Routine \"TableLooperTest\"-------\n for thisComponent in TableLooperTestComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n \n \n ######################################################################\n ## scanner_coms_use_2 - post-routine #################################\n ######################################################################\n scanner_coms.clear()\n ######################################################################\n \n \n \n \n ######################################################################\n ## table_looper - post-routine #######################################\n ######################################################################\n trial+=1\n ######################################################################\n \n \n \n thisExp.nextEntry()\n \n# completed 500 repeats of 'trials'\n\n\n#------Prepare to start Routine \"done\"-------\nt = 0\ndoneClock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\npause_text_3.setText(u'All Done!')\nevent.clearEvents(eventType='keyboard')\n\n_text = u'All Done!'+'\\n\\n'\nif None:\n _text+='press a key to continue:\\n'+str(list(None))[1:-1]\nelse:\n _text+='press any key to continue'\npause_text_3.setText(_text)\n\n# keep track of which components have finished\ndoneComponents = []\ndoneComponents.append(pause_text_3)\nfor thisComponent in doneComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"done\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = doneClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *pause_text_3* updates\n if t >= 0.0 and pause_text_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n pause_text_3.tStart = t # underestimates by a little under one frame\n pause_text_3.frameNStart = frameN # exact frame index\n pause_text_3.setAutoDraw(True)\n # stop routine if pause_text_3's buttons are pressed\n if pause_text_3.status==STARTED:\n if event.getKeys(keyList=None): stopRoutine()\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n routineTimer.reset() # if we abort early the non-slip timer needs reset\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in doneComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n else: # this Routine was not non-slip safe so reset non-slip timer\n routineTimer.reset()\n\n#-------Ending Routine \"done\"-------\nfor thisComponent in doneComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n\n\n######################################################################\n## scanner_coms_connect - cleanup ####################################\n######################################################################\nscanner_coms.close()\n######################################################################\n\n\n\n\n\nwin.close()\ncore.quit()\n","sub_path":"UPN/jkpsycho_install/tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":36279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"514076764","text":"#! /usr/bin/env python2.7\n\nfrom __future__ import print_function, division; __metaclass__ = type\n\nimport numpy as np\nimport h5py\nimport warnings\nwarnings.filterwarnings('ignore', category=DeprecationWarning)\nwarnings.filterwarnings('ignore', category=RuntimeWarning)\nwarnings.filterwarnings('ignore', category=FutureWarning)\nimport os, sys, select, time\n\nfrom threading import Thread\n\nimport blessed\nfrom blessed import Terminal\n# This is Python3. Python2 has Queue.\n#from queue import Queue\nfrom Queue import Queue\n#import curses\n#stdscr = curses.initscr()\n\n\nclass MsgBus():\n def __init__(self):\n self.Systems = []\n self.SystemThreads = []\n self.MsgQueue = Queue(maxsize=0)\n self.Run = True\n self.updateTime = .015\n def RegisterSystem(self, system):\n self.Systems.append(system)\n def LaunchSystems(self):\n for i in range(0, len(self.Systems)):\n self.SystemThreads.append(Thread(target=self.Systems[i].MainLoop))\n for i in range(0, len(self.Systems)):\n self.SystemThreads[i].start()\n def KillSystems(self):\n # This doesn't work, but whatever.\n # We'll have to poll for a signal command.\n # works well enough, at least.\n self.Run = False\n for i in range(0, len(self.Systems)):\n self.Systems[i].Run = False\n # self.SystemThreads[i].join()\n #sys.exit(0)\n def ReceiveMessage(self, msg):\n self.MsgQueue.put(msg)\n def SendMessages(self, msg):\n for i in range(0, len(self.Systems)):\n self.Systems[i].ReceiveMessage(msg)\n def SortMessages(self):\n if not self.MsgQueue.empty():\n while not self.MsgQueue.empty():\n self.SendMessages(self.MsgQueue.get())\n else:\n return 0\n def start_clock(self):\n self.start_time = time.time()\n def end_clock(self):\n self.end_time = time.time()\n if self.end_time - self.start_time < self.updateTime:\n time.sleep(self.updateTime - (self.end_time - self.start_time))\n def MainLoop(self):\n while self.Run:\n self.start_clock()\n self.SortMessages()\n self.end_clock()\n\nclass Systems():\n def __init__(self, MsgBusInstance):\n self.MsgQueue = Queue(maxsize=0)\n self.MsgBus = MsgBusInstance\n self.Run = True\n self.updateTime = .015\n def ReceiveMessage(self, msg):\n self.MsgQueue.put(msg)\n def SendMessage(self, msg):\n self.MsgBus.ReceiveMessage(msg)\n def HandleMessage(self, msg):\n # Put in some code here for the various proper systems.\n return 0\n def MainLoop(self):\n return 0\n def SortMessages(self):\n # Just loops through and handles the messsages.\n if not self.MsgQueue.empty():\n while not self.MsgQueue.empty():\n self.HandleMessage(self.MsgQueue.get())\n else:\n return 0\n def start_clock(self):\n self.start_time = time.time()\n def end_clock(self):\n self.end_time = time.time()\n if self.end_time - self.start_time < self.updateTime:\n time.sleep(self.updateTime - (self.end_time - self.start_time))\n\nclass Msg():\n def __init__(self, name, mtype, code=0):\n # Very basic. Name, message type, and a particular thing to actually send. Can be anything.\n self.name = name\n self.mtype = mtype\n self.code = code\n\nclass Input(Systems):\n def __init__(self, MsgBusInstance, terminal):\n Systems.__init__(self, MsgBusInstance)\n self.terminal = terminal\n def MainLoop(self):\n while self.Run:\n with self.terminal.cbreak():\n keypress = self.terminal.inkey()\n msg = Msg('input!', mtype='INPUT', code=keypress)\n self.SendMessage(msg)\n self.SortMessages()\n #if keypress.code == 'q':\n # # shut it down.\n # self.Run = False\n\nclass AppState(Systems):\n def __init__(self, MsgBusInstance, terminal, h5file):\n Systems.__init__(self, MsgBusInstance)\n self.terminal = terminal\n self.ActiveBox = None\n self.ActiveKeys = None\n self.Boxes = [{}]\n self.h5file = h5file\n # Possible states: insert, command\n self.State = 'command'\n self.h = self.terminal.height\n self.w = self.terminal.width\n self.storedCommand = '/'\n self.potentialCommand = ''\n self.potentialCommandId = -1\n def MainLoop(self):\n # We're setting up the first box, as we start the program...\n #self.h = self.terminal.height\n #self.w = self.terminal.width\n # Let's set this to the 'active' box, which will move our cursor to it.\n #self.registerNewBox(boxWindow(size=(int(self.h/2), int(self.w/2)), pos=(int(self.h/4),int(self.w/4)), level=1, name='Main'))\n #msg = Msg('active_box', mtype='ACTIVATE_BOX', code=boxWindow(size=(int(self.h/2), int(self.w/2)), pos=(int(self.h/4),int(self.w/4)), level=1, name='Main'))\n #self.SendMessage(msg)\n self.modeWindow(self.State)\n while self.Run:\n self.start_clock()\n self.SortMessages()\n self.end_clock()\n def HandleMessage(self, msg):\n if msg.mtype == 'RETURN_CURRENT_KEYS':\n self.ActiveKeys = msg.code\n if msg.mtype == 'INPUT':\n if msg.code.code == self.terminal.KEY_ESCAPE:\n self.State = 'command'\n self.modeWindow(self.State)\n elif self.State == '/':\n # We're going into 'terminal' mode.\n # If we're not using tab...\n if msg.code.code == 512:\n if self.potentialCommandId >= len(self.ActiveKeys)-1:\n self.potentialCommandId = -1\n for ii,i in enumerate(self.ActiveKeys):\n if self.storedCommand[1:] in i and self.potentialCommandId < ii:\n self.potentialCommand = '/' + str(i)\n self.potentialCommandId = ii\n self.modeWindow(self.potentialCommand)\n break\n if msg.code.code == self.terminal.KEY_BACKSPACE:\n self.potentialCommand = ''\n self.potentialCommandId = -1\n self.storeInput(msg.code)\n self.modeWindow(self.storedCommand)\n if msg.code.code == self.terminal.KEY_ENTER:\n self.storedCommand = self.potentialCommand\n self.potentialCommand = ''\n self.potentialCommandId = -1\n self.storeInput(msg.code)\n self.modeWindow(self.storedCommand)\n else:\n self.storeInput(msg.code)\n if self.potentialCommandId == -1:\n self.modeWindow(self.storedCommand)\n elif self.State == 'move':\n if msg.code.code == self.terminal.KEY_LEFT:\n self.nextBox()\n if msg.code.code == self.terminal.KEY_RIGHT:\n self.prevBox()\n elif self.State == 'command':\n # Move windows, if necessary. We already know we have an input message...\n\n #if msg.code == 'l':\n # msg = Msg('new_box', mtype='H5_LOAD', code=None)\n # self.SendMessage(msg)\n if msg.code == 'i':\n self.State = 'insert'\n self.modeWindow(self.State)\n if msg.code == 'm':\n self.State = 'move'\n self.modeWindow(self.State)\n if msg.code == '/':\n self.State = '/'\n self.modeWindow(self.State)\n # Let's get the current active keys!\n newmsg = Msg('input!', mtype='H5_RETURN_CURRENT_KEYS', code={})\n self.SendMessage(newmsg)\n if msg.code == 'e':\n for i in range(0, 8):\n msg = Msg('input!', mtype='INPUT', code=Msg('', mtype='', code=self.terminal.KEY_RIGHT))\n self.SendMessage(msg)\n #if msg.code == 'A':\n # msg = Msg('new_box', mtype='NEW_BOX', code=boxWindow(size=(int(self.h/4), int(self.w/4)), pos=(0,0), level=1, name='New'))\n # self.SendMessage(msg)\n # This usually has to wait, I'm afraid, so we can't pull from the Boxes list yet. We just send in something with the proper name and level, though.\n # msg = Msg('new_box', mtype='ACTIVATE_BOX', code=boxWindow(size=(int(self.h/4), int(self.w/4)), pos=(0,0), level=1, name='New'))\n # self.SendMessage(msg)\n if msg.code == 'q':\n self.MsgBus.KillSystems()\n #if msg.code == 'P':\n # string = 'Hey! This is a test message that we are sending when something happens. Can I write to the correct window? LET US FIND OUT.'\n # msg = Msg('print_data', mtype='PRINT_DATA', code={ 'box': self.ActiveBox, 'data': string })\n # self.SendMessage(msg)\n if msg.code != None:\n if msg.code.code == self.terminal.KEY_BACKSPACE or msg.code.code == self.terminal.KEY_DELETE:\n # Now we'll try and load up a dataset, and print it to another window... or just modify the current, maybe? We'll see.\n msg = Msg('load_item', mtype='H5_PREV_GROUP', code=None)\n self.SendMessage(msg)\n elif msg.code.code == self.terminal.KEY_ENTER:\n # Now we'll try and load up a dataset, and print it to another window... or just modify the current, maybe? We'll see.\n msg = Msg('load_item', mtype='H5_LOAD', code=None)\n self.SendMessage(msg)\n elif self.State == 'insert':\n if msg.code.code == None:\n # We're just handling raw input, here.\n msg = Msg('print_data', mtype='PRINT_CHAR', code={ 'box': self.ActiveBox, 'data': msg.code })\n self.SendMessage(msg)\n\n\n elif msg.mtype == 'ACTIVATE_BOX':\n # Stored in the code is the box object information\n self.activateBox(msg.code)\n self.State = 'command'\n elif msg.mtype == 'NEW_BOX':\n # Stored in the code is the box object information\n self.registerNewBox(msg.code)\n #self.State = 'command'\n elif msg.mtype == 'PRINT_COMMAND':\n self.modeWindow(msg.code)\n\n def modeWindow(self, dataset):\n box = boxWindow(size=(3, int(self.w)), pos=(int(self.h-4),int(1)), level=3, name='Mode', data=[dataset])\n box.decorate = False\n box.damaged = True\n msg = Msg('new_box', mtype='NEW_BOX', code=box)\n self.SendMessage(msg)\n\n def tabWindow(self, dataset):\n box = boxWindow(size=(3, int(self.w)), pos=(int(self.h-3),int(1)), level=3, name='tab', data=[dataset])\n box.decorate = False\n box.damaged = True\n msg = Msg('new_box', mtype='NEW_BOX', code=box)\n self.SendMessage(msg)\n\n def storeInput(self, char):\n if char.code == self.terminal.KEY_ENTER:\n msg = Msg('handle_input', mtype='H5_USER_LOAD', code=self.storedCommand[1:])\n self.SendMessage(msg)\n self.storedCommand = '/'\n self.State = 'command'\n self.modeWindow(self.State)\n elif char.code == 330:\n self.storedCommand = self.storedCommand[:-1]\n elif char.code == 512:\n pass\n else:\n self.storedCommand += char\n\n def nextBox(self):\n stop_next = False\n level = self.ActiveBox.level - 1\n if len(self.Boxes[level]) > 1:\n for box in self.Boxes[level].values():\n if stop_next == True:\n msg = Msg('activate_box', mtype='ACTIVATE_BOX', code=box)\n self.SendMessage(msg)\n stop_next = False\n if self.ActiveBox.name == box.name:\n stop_next = True\n\n def prevBox(self):\n stop_now = False\n level = self.ActiveBox.level - 1\n returnBox = None\n if len(self.Boxes[level]) > 1:\n for box in self.Boxes[level].values():\n if self.ActiveBox.name == box.name:\n stop_now = True\n if returnBox == None:\n returnBox = box\n if stop_now == True:\n msg = Msg('activate_box', mtype='ACTIVATE_BOX', code=returnBox)\n self.SendMessage(msg)\n stop_now = False\n returnBox = box\n\n\n def activateBox(self, box):\n # We move the cursor to the active box, then set active box to the current one.\n pos = self.Boxes[box.level-1][box.name]\n msg = Msg('move cursor', mtype='MOVE_CURSOR', code=(pos.pos[0]+1, pos.pos[1]+1))\n self.SendMessage(msg)\n self.ActiveBox = box\n\n def registerNewBox(self, box):\n # Here, we create a new box to draw. It has a level and a certain position.\n # If we don't have that many levels, we'll enlarge our list of dictionaries until we do.\n while len(self.Boxes) < box.level:\n self.Boxes.append({})\n self.Boxes[box.level-1][box.name] = box\n def getActiveBox(self):\n return self.ActiveBox\n def getState(self):\n return self.State\n\nclass H5DataLoader(Systems):\n def __init__(self, MsgBusInstance, AppStateInstance, TerminalInstance, terminal):\n Systems.__init__(self, MsgBusInstance)\n self.h5 = h5py.File(AppStateInstance.h5file)\n # We've initialized and the loaded the file. Now what do we need? We need to load and print the datasets...\n self.AppState = AppStateInstance\n #self.csr = self.AppState.csr\n self.ActiveBox = self.AppState.getActiveBox\n self.currentGroup = '/'\n self.ActiveKeys = []\n self.Terminal = TerminalInstance\n self.csr = self.Terminal.returnBoxCsr\n self.terminal = terminal\n self.h = self.terminal.height\n self.w = self.terminal.width\n def HandleMessage(self, msg):\n # We need to set a current dataset/group...\n # When we print a message to the terminal, we want what dataset we get to... well, we'll just see.\n if msg.mtype == 'H5_RETURN_CURRENT_KEYS':\n msg = Msg('print_data', mtype='RETURN_CURRENT_KEYS', code=self.returnGroupKeys(self.currentGroup))\n self.SendMessage(msg)\n if msg.mtype == 'H5_PRINT_CURRENT':\n self.printGroupKeys(self.currentGroup, self.ActiveBox())\n if msg.mtype == 'H5_GET_DATASET':\n msg = Msg('print_data', mtype='PRINT_DATA', code={ 'box': self.ActiveBox(), 'data': str(self.h5[msg.code]) })\n self.SendMessage(msg)\n if msg.mtype == 'H5_SWITCH_GROUP':\n self.currentGroup = msg.code\n if msg.mtype == 'H5_PREV_GROUP':\n self.prevGroup()\n self.returnGroupKeys(self.currentGroup)\n box = boxWindow(size=(int(self.h-5), int(self.w/4)), pos=(int(1),int(1)), level=1, name='Main', data=self.ActiveKeys)\n #box = boxWindow(size=(int(self.h/4), int(self.w/4)), pos=(0,0), level=1, name='New', data=self.ActiveKeys)\n msg = Msg('new_box', mtype='NEW_BOX', code=box)\n self.SendMessage(msg)\n # This usually has to wait, I'm afraid, so we can't pull from the Boxes list yet. We just send in something with the proper name and level, though.\n msg = Msg('new_box', mtype='ACTIVATE_BOX', code=box)\n self.SendMessage(msg)\n if msg.mtype == 'H5_RETURN_CURRENT_GROUP':\n msg = Msg('print_data', mtype='H5_GROUP', code=self.currentGroup)\n self.SendMessage(msg)\n if msg.mtype == 'H5_LOAD':\n try:\n self.changeGroup(self.ActiveKeys[self.csr(self.ActiveBox())[0] + self.ActiveBox().y_coord[0]])\n except:\n # This happens when we load up the dataset for the first time.\n pass\n # We'll just check to see if it's a group. Otherwise, it's a dataset.\n try:\n # This shouldn't really be happening unless we ACTUALLY change groups. But hey...\n self.returnGroupKeys(self.currentGroup)\n box = boxWindow(size=(int(self.h-5), int(self.w/4)), pos=(int(1),int(1)), level=1, name='Main', data=self.ActiveKeys)\n except:\n self.returnDataset(self.currentGroup)\n box = boxWindow(size=(int(self.h-5), int(self.w/4*3)-5), pos=(int(1),int(self.w/4)+5), level=2, name='Data', data=self.data)\n box.isGrid = True\n msg = Msg('new_box', mtype='NEW_BOX', code=box)\n self.SendMessage(msg)\n msg = Msg('new_box', mtype='ACTIVATE_BOX', code=box)\n try:\n self.ActiveBox().damaged = False\n except:\n pass\n self.SendMessage(msg)\n self.statusWindow(self.currentGroup)\n if msg.mtype == 'H5_USER_LOAD':\n group = str(self.currentGroup)\n try:\n self.changeGroup(msg.code)\n try:\n # This shouldn't really be happening unless we ACTUALLY change groups. But hey...\n self.returnGroupKeys(self.currentGroup)\n box = boxWindow(size=(int(self.h-5), int(self.w/4)), pos=(int(1),int(1)), level=1, name='Main', data=self.ActiveKeys)\n except:\n self.returnDataset(self.currentGroup)\n box = boxWindow(size=(int(self.h-5), int(self.w/4*3)-5), pos=(int(1),int(self.w/4)+5), level=2, name='Data', data=self.data)\n box.isGrid = True\n msg = Msg('new_box', mtype='NEW_BOX', code=box)\n self.SendMessage(msg)\n msg = Msg('new_box', mtype='ACTIVATE_BOX', code=box)\n try:\n self.ActiveBox().damaged = False\n except:\n pass\n self.SendMessage(msg)\n self.statusWindow(self.currentGroup)\n except:\n self.currentGroup = group\n self.statusWindow(self.currentGroup)\n msg = Msg('print_data', mtype='H5_GROUP', code=self.currentGroup)\n self.SendMessage(msg)\n # We'll just check to see if it's a group. Otherwise, it's a dataset.\n\n def statusWindow(self, dataset):\n box = boxWindow(size=(3, int(self.w)), pos=(int(self.h-3),int(1)), level=1, name='Status', data=[dataset])\n box.decorate = False\n msg = Msg('new_box', mtype='NEW_BOX', code=box)\n self.SendMessage(msg)\n\n def changeGroup(self, newGroup):\n self.currentGroup += newGroup + '/'\n self.statusWindow(self.currentGroup)\n\n def prevGroup(self):\n currentGroup = '/' + str.join('/', list(filter(None, self.currentGroup.split('/')))[0:-1]) + '/'\n if currentGroup[1] == '/':\n currentGroup = currentGroup[1:]\n self.currentGroup = currentGroup\n self.statusWindow(self.currentGroup)\n\n def returnGroupKeys(self, group):\n self.ActiveKeys = []\n for key, value in self.h5[group].items():\n # Should we do it here, or have the other sort it out?\n self.ActiveKeys.append(key)\n return self.ActiveKeys\n\n def returnDataset(self, group):\n #self.data = []\n #for item in range(0, self.h5[group].shape[0]):\n # Should we do it here, or have the other sort it out?\n # self.data.append(self.h5[group][item,:])\n self.data = self.h5[group][:]\n\n def MainLoop(self):\n while self.Run:\n self.start_clock()\n self.SortMessages()\n self.end_clock()\n\n\nclass TerminalPrinter(Systems):\n def __init__(self, MsgBusInstance, terminal, AppStateInstance):\n # This also handles creating and printing to windows.\n Systems.__init__(self, MsgBusInstance)\n self.terminal = terminal\n self.AppState = AppStateInstance\n self.csr = self.terminal.get_location()\n #self.csr = self.AppState.csr\n self.Boxes = self.AppState.Boxes\n self.ActiveBox = self.AppState.getActiveBox\n self.State = self.AppState.getState\n\n def HandleMessage(self, msg):\n if msg.mtype == 'INPUT':\n # Let's handle how we do the cursor, yeah?\n if msg.code.code != None:\n # We don't want to move out of the box...\n # ... so this global input keeps us moving around the current, active box.\n if self.State() == 'insert' or self.State() == 'command':\n if msg.code.code == self.terminal.KEY_LEFT:\n if self.ActiveBox().isGrid == False:\n if self.csr[1] - 1 > self.ActiveBox().pos[1]:\n self.csr = (self.csr[0], self.csr[1] - 1)\n else:\n self.ActiveBox().move_left()\n else:\n self.ActiveBox().move_left()\n elif msg.code.code == self.terminal.KEY_RIGHT:\n # Check if the active box is a grid.\n if self.ActiveBox().isGrid == False:\n if self.csr[1] + 1 < self.ActiveBox().pos[1] + self.ActiveBox().size[1] - 1:\n self.csr = (self.csr[0], self.csr[1] + 1)\n else:\n # Useful for debugging.\n newmsg = Msg('print_data', mtype='PRINT_COMMAND', code=(self.ActiveBox().x_coord, self.ActiveBox().data.shape[1]))\n #msg.mtype = mtype='PRINT_COMMAND'\n #msg.code.code = (self.ActiveBox().x_coord, self.ActiveBox().data.shape[0])\n #self.SendMessage(newmsg)\n self.ActiveBox().move_right()\n else:\n self.ActiveBox().move_right()\n elif msg.code.code == self.terminal.KEY_DOWN:\n if self.ActiveBox().isGrid == False:\n if self.csr[0] + 1 < self.ActiveBox().pos[0] + self.ActiveBox().size[0] - 1:\n if self.csr[0] + 1 - self.ActiveBox().pos[0] <= self.ActiveBox().y_items:\n self.csr = (self.csr[0] + 1, self.csr[1])\n self.ActiveBox().damaged = True\n else:\n self.ActiveBox().move_down()\n self.ActiveBox().damaged = True\n else:\n self.ActiveBox().move_down()\n self.ActiveBox().damaged = True\n elif msg.code.code == self.terminal.KEY_UP:\n if self.ActiveBox().isGrid == False:\n if self.csr[0] - 1 > self.ActiveBox().pos[0]:\n if self.csr[0] - 1 - self.ActiveBox().pos[0] >= 0:\n self.csr = (self.csr[0] - 1, self.csr[1])\n self.ActiveBox().damaged = True\n\n else:\n self.ActiveBox().move_up()\n self.ActiveBox().damaged = True\n else:\n self.ActiveBox().move_up()\n self.ActiveBox().damaged = True\n # Temp standin for page down\n elif msg.code.code == 338:\n # What is the height?\n if self.ActiveBox().isGrid == False:\n if self.csr[0] + 10 < self.ActiveBox().pos[0] + self.ActiveBox().size[0] - 10:\n if self.csr[0] + 10 - self.ActiveBox().pos[0] <= self.ActiveBox().y_items:\n self.csr = (self.csr[0] + 10, self.csr[1])\n self.ActiveBox().damaged = True\n else:\n self.ActiveBox().move_down(10)\n self.ActiveBox().damaged = True\n else:\n self.ActiveBox().move_down(10)\n self.ActiveBox().damaged = True\n if msg.code.code == 339:\n # What is the height?\n if self.ActiveBox().isGrid == False:\n if self.csr[0] - 10 > self.ActiveBox().pos[0]:\n if self.csr[0] - 10 - self.ActiveBox().pos[0] >= 0:\n self.csr = (self.csr[0] - 10, self.csr[1])\n self.ActiveBox().damaged = True\n else:\n self.ActiveBox().move_up(10)\n self.ActiveBox().damaged = True\n else:\n self.ActiveBox().move_up(10)\n self.ActiveBox().damaged = True\n if self.State() == 'command':\n if msg.code == '+':\n # What is the height?\n #print(msg.code)\n self.ActiveBox().move_layer_up()\n if msg.code == '-':\n # What is the height?\n self.ActiveBox().move_layer_down()\n elif msg.mtype == 'MOVE_CURSOR':\n self.csr = msg.code\n self.ActiveBox().damaged = True\n elif msg.mtype == 'PRINT_DATA':\n self.printToBox(msg.code['box'], msg.code['data'])\n elif msg.mtype == 'PRINT_CHAR':\n self.printAtChar(msg.code['data'])\n\n def loopBoxes(self):\n for level in range(0,len(self.Boxes)):\n # First, get the box object, and the position...\n for box in self.Boxes[level].values():\n # ... now draw it.\n if box.damaged == True:\n self.clearBoxFast(box)\n #self.clearBox(box)\n # THIS FUNCTION IS SUPER SLOW.\n if box.decorate == True:\n self.drawBox(box)\n if box.isGrid == False:\n self.printListBox(box, box.draw_data)\n else:\n self.printGridBox(box, box.draw_data)\n box.damaged = False\n\n def clearBox(self, box):\n # but not the frame!\n for y in range(1, box.size[0]-1):\n for x in range(1, box.size[1]-1):\n # FILL CODE\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + ' ')\n\n def clearBoxFast(self, box):\n for y in range(1, box.size[0]-1):\n #clearstring = str('|'*(box.size[1]-2) + '\\n')*(box.size[0]-2)\n clearstring = str(' '*(box.size[1]-1))\n print(self.terminal.move(box.pos[0]+y,box.pos[1]) + clearstring)\n #clearstring = str((box.size))\n\n def drawBox(self, box):\n x_offset = 0\n for y in range(0, box.size[0]+1):\n if y == 0:\n for x in range(0, box.size[1]+1-len(box.name)-3):\n # This is the top!\n if x == 0:\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + u'\\u250c')\n elif x == box.size[1]-len(box.name)-3:\n print(self.terminal.move(y+box.pos[0],x+x_offset+box.pos[1]) + u'\\u2510')\n elif x == int(box.size[1]/2)-int((len(box.name)+4)/2):\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + u'\\u2524 ' + box.name + ' ' + u'\\u251c')\n x_offset = len(box.name)+3\n else:\n print(self.terminal.move(y+box.pos[0],x+x_offset+box.pos[1]) + u'\\u2500')\n elif y == box.size[0]:\n for x in range(0, box.size[1]+1):\n # This is the top!\n if x == 0:\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + u'\\u2514')\n elif x == box.size[1]:\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + u'\\u2518')\n else:\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + u'\\u2500')\n\n else:\n for x in [0, box.size[1]]:\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + u'\\u2502')\n\n def printAtChar(self, data):\n #print((self.terminal.move(self.csr[0], self.csr[1]) + data))\n print(data)\n self.csr = (self.csr[0], self.csr[1] + 1)\n\n def printListBox(self, box, data):\n i = 0\n y = 1\n x = 1\n underline = False\n # Here, we assume the data is a list.\n for item in data:\n # We want to know if the current item is highlighted...\n if self.csr[0] == y + 1:\n underline = True\n if len(item) < box.size[1]:\n if underline == True:\n print(self.terminal.underline + self.terminal.move(y+box.pos[0],x+box.pos[1]) + str(item) + self.terminal.normal)\n else:\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + str(item))\n else:\n if underline == True:\n print(self.terminal.underline + self.terminal.move(y+box.pos[0],x+box.pos[1]) + str(item[0:box.size[1]]) + self.terminal.normal)\n else:\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + str(item[0:box.size[1]]))\n underline = False\n y += 1\n if y == box.size[0]-1:\n break\n\n def printGridBox(self, box, data):\n i = 0\n y = 1\n x = 1\n # Data is a numpy array. We can't sort through it the normal way; instead, we want to print it item by item.\n stringToPrint = ''\n for iline, line in enumerate(data):\n if iline == 0:\n if data.dtype.names == None:\n # We're printing headers, here! But what if we're not a blah blah blah?\n #padding = int(np.ceil(np.log10(data.shape[0]))) + 1\n padding = int(np.ceil(np.log10(data.shape[0]))) + 1\n padding = int(np.ceil(np.log10(box.y_items))) + 1\n #padding = 8\n stringToPrint += ' '*padding + ' '\n for iitem in range(box.x_coord[0], box.x_coord[1]):\n padding = 8\n item = str(iitem).zfill(padding)\n stringToPrint += ' ' + item + ' '\n x += 1\n if x == box.cells - 1:\n x = 1\n break\n else:\n padding = int(np.ceil(np.log10(data.shape[0]))) + 1\n #padding = 8\n padding = int(np.ceil(np.log10(box.y_items))) + 1\n stringToPrint += ' '*padding + ' '\n for item in data.dtype.names:\n new_padding = 8\n if len(str(item)) > new_padding:\n item = str(item)[0:new_padding]\n else:\n item = str(item) + (' '*(new_padding-len(str(item))))\n stringToPrint += ' ' + item + ' '\n x += 1\n if x == box.cells - 1:\n x = 1\n break\n\n print(self.terminal.move(y+box.pos[0]+1,box.pos[1]+1) + str(stringToPrint))\n y += 1\n stringToPrint = ''\n try:\n for iitem, item in enumerate(line):\n # Our box should ultimately have a 'cell', and we just jump to cell coordinates. Eventually.\n #for x in range(0, box.cells):\n new_padding = int(np.ceil(np.log10(data.shape[0]))) + 1\n new_padding = 8\n new_padding = box.n_digits + 4\n # Spacing, you know?\n if iitem == 0:\n #padding = int(np.ceil(np.log10(data.shape[0]))) + 1\n padding = int(np.ceil(np.log10(box.y_items))) + 1\n stringToPrint += str(iline+box.y_coord[0]).zfill(padding) + (' ')\n if type(item) is np.float32 or type(item) is np.double:\n item = '%.2e' % float(item)\n else:\n if len(str(item)) > new_padding:\n item = str(item)[0:new_padding]\n else:\n item = str(item) + (' '*(new_padding-len(str(item))))\n stringToPrint += ' ' + item + ' '\n x += 1\n if x == box.cells - 1:\n x = 1\n break\n except:\n # We should really just try and sort the dataset. But this is 'single value' sets which are sooort of escaping\n # the logic used to sort the data shape.\n padding = int(np.ceil(np.log10(data.shape[0]))) + 1\n stringToPrint += str(iline+box.y_coord[0]).zfill(padding) + ' '\n if type(line) is float:\n item = '%.2e' % float(line)\n else:\n item = str(line)\n stringToPrint += ' ' + item + ' '\n print(self.terminal.move(y+box.pos[0]+1,box.pos[1]+1) + str(stringToPrint))\n stringToPrint = ''\n y += 1\n if y == box.size[0]-2:\n break\n\n def printToBox(self, box, data):\n i = 0\n y = 1\n x = 1\n # We just sort through and print. Probably not that fast, but it'll work for the moment.\n while i < len(data) - 1:\n #while y < box.size[0]-1:\n # while x < box.size[1]-1:\n # So, this is the character position of the box. We're temporarily looping through, but...\n # .. what we really want to do is work like a typewriter.\n try:\n if data[i:i+1] == '\\n':\n y += 1\n x = 0\n except:\n pass\n\n if x == box.size[1]-1:\n x = 0\n y += 1\n if y == box.size[0]-1:\n if x == box.size[1]-1:\n break\n print(self.terminal.move(y+box.pos[0],x+box.pos[1]) + data[i])\n i += 1\n x += 1\n #x = 0\n #y += 1\n #self.csr = (y+box.pos[0],x+box.pos[1])\n def returnBoxCsr(self, box):\n return (self.csr[0] - box.pos[0]-1, self.csr[1] - box.pos[1]-1)\n\n\n def MainLoop(self):\n # Let's set up the terminal!\n with self.terminal.hidden_cursor():\n with self.terminal.fullscreen():\n while self.Run:\n self.start_clock()\n # Move the cursor to the current position.\n # Draw all the boxes we want to draw!\n #with self.terminal.hidden_cursor():\n self.loopBoxes()\n # Can we highlight the entire box line?\n #with self.terminal.hidden_cursor():\n #print(self.terminal.move(self.csr[0], self.csr[1]), end='')\n\n #print(self.terminal.normal)\n #print(self.terminal.color(5))\n #try:\n # with self.terminal.location(self.ActiveBox().pos[0], self.csr[1]):\n #except:\n # pass\n self.SortMessages()\n self.end_clock()\n sys.stdout.flush()\n\nclass boxWindow():\n def __init__(self, size, pos, level, name, data=None):\n self.size = size\n self.pos = pos\n self.name = name\n self.level = level\n self.drawn = False\n self.new = True\n # These are values about the window on the dataset, here...\n self.y_coord = (0, self.size[0] - 1)\n # This coord is a little more difficult. Just using the box size isn't good enough,\n # as we need to also limit the number of elements we show. Ergo, let's start with... 3\n #self.x_coord = (0, self.size[1] - 1)\n # Let's say we always want to show... oh, 4 digits.\n # How many cells do we have? Well, we need space, so that's 6 for each...\n self.n_digits = 4\n try:\n self.cells = min((int(np.floor(self.size[1]/(self.n_digits+5)))) - 1, data.shape[1]-1)\n except:\n self.cells = 1\n self.x_coord = (0, self.cells)\n self.data = data\n self.damaged = True\n self.decorate = True\n self.isGrid = False\n self.y_items = 0\n # Let's set it to layer 0, here...\n if self.data != None:\n self.sort_data()\n self.activeLayer = 0\n self.updateDrawData()\n def sort_data(self):\n # It works by drawing lines.\n # Let's assume the data is brought in as a list or numpy array. It's not hard, whatever.\n # First, figure out the number of dimensions...\n try:\n self.dim = len(self.data.shape)\n except:\n # we're a list, then!\n # We shouldn't really assume 1 dimension, but it's fine for now.\n self.dim = 1\n self.y_items = len(self.data)\n # If it's two dimensions, our number of layers are 1. Otherwise, we set\n # it to the third value.\n if self.dim == 2:\n self.y_items = self.data.shape[0]\n elif self.dim == 1:\n self.y_items = len(self.data)\n else:\n self.layers = self.data.shape[2]\n self.y_items = self.data.shape[0]\n def updateDrawData(self):\n if self.dim == 3:\n self.draw_data = self.data[self.y_coord[0]:self.y_coord[1],self.x_coord[0]:self.x_coord[1],self.activeLayer]\n elif self.dim == 2:\n self.draw_data = self.data[self.y_coord[0]:self.y_coord[1],self.x_coord[0]:self.x_coord[1]]\n else:\n self.draw_data = self.data[self.y_coord[0]:self.y_coord[1]]\n def move_down(self, items=1):\n if self.y_coord[1] < self.data.shape[0]:\n self.y_coord = (self.y_coord[0]+items, self.y_coord[1]+items)\n self.updateDrawData()\n self.damaged = True\n def move_up(self, items=1):\n if self.y_coord[0] > 0:\n self.y_coord = (self.y_coord[0]-items, self.y_coord[1]-items)\n self.updateDrawData()\n self.damaged = True\n def move_left(self):\n if self.x_coord[0] > 0:\n self.x_coord = (self.x_coord[0]-1, self.x_coord[1]-1)\n self.updateDrawData()\n self.damaged = True\n def move_right(self):\n # If this doesn't work, then eh.\n # If we have a complex datatype with N values, we'll need to figure that out.\n if len(self.data.shape) > 1:\n comparison = self.data.shape[1]\n else:\n comparison = len(self.data.dtype)\n if self.x_coord[1] <= comparison:\n self.x_coord = (self.x_coord[0]+1, self.x_coord[1]+1)\n self.updateDrawData()\n self.damaged = True\n def move_layer_up(self):\n if self.dim == 3:\n if self.activeLayer < self.data.shape[2]-1:\n self.activeLayer += 1\n self.updateDrawData()\n self.damaged = True\n def move_layer_down(self):\n if self.dim == 3:\n if self.activeLayer > 0:\n self.activeLayer -= 1\n self.updateDrawData()\n self.damaged = True\n\n # There's no real limit on how big a box can be, internally.\n # We just have a window into it, and that's the 'size'.\n # We should be able to shift the viewport...\n # ... so we should be able to store and sort through lines of data.\n\nmsgbus = MsgBus()\nterminal = Terminal()\ninputsys = Input(msgbus, terminal)\nimport sys\nappstate = AppState(msgbus, terminal, sys.argv[1])\ntermprint = TerminalPrinter(msgbus, terminal, appstate)\ndataloader = H5DataLoader(msgbus, appstate, termprint, terminal)\nmsgbus.RegisterSystem(appstate)\nmsgbus.RegisterSystem(termprint)\nmsgbus.RegisterSystem(inputsys)\nmsgbus.RegisterSystem(dataloader)\nmsgbus.LaunchSystems()\n# Let's create a message and load up the file!\nmsg = Msg('new_box', mtype='H5_LOAD', code=None)\nappstate.SendMessage(msg)\nmsgbus.MainLoop()\n","sub_path":"h5.py","file_name":"h5.py","file_ext":"py","file_size_in_byte":41441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"310413261","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2019/4/17\n\nauthor: ni&YunkeYu\n\"\"\"\n\n#from __future__ import print_function\nimport roslib\n# roslib.load_manifest('my_package')\n#roslib.load_manifest(\"pick_brick_ur5\")\nimport sys, cv2,math\nimport numpy as np\nimport rospy\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom rospy_tutorials.msg import Floats\nfrom cv_bridge import CvBridge, CvBridgeError\n\nfrom geometry_msgs.msg import PointStamped\nimport tf\n\n\nC_PARAM = [320/math.tan(math.pi/6), 320/math.tan(math.pi/6), 320, 240] # 相机4个内参\n\nclass brick_detection:\n def __init__(self):\n self.image_pub = rospy.Publisher(\"brick_position\", Floats,queue_size=1)\n\n self.bridge = CvBridge()\n self.image_sub = rospy.Subscriber(\"/kinect/rgb/image_raw\", Image, self.callback)\n self.depth_sub = rospy.Subscriber(\"/kinect/depth/image_raw\", Image, \\\n self.callback_depth)\n self.depth_flag = False\n self.tflistener = tf.TransformListener()\n self.videoWriter = cv2.VideoWriter('../media/pick&placeV2_camera.avi', cv2.VideoWriter_fourcc(*'XVID'), 10, (640,480),True)\n self.sysmode_pub = rospy.Subscriber('sys_mode', String, self.sysmode_callback,\\\n queue_size=1)\n self.det_bool=False\n\n def callback(self, data):\n try:\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n except CvBridgeError as e:\n rospy.loginfo(e)\n if self.det_bool is True:\n img_position = self.brick_detect(cv_image)\n brick_base = [0,0,0,1]\n if img_position[1] == 0 :\n #rospy.loginfo(\"There is't brick\") \n brick_base = [0,0,0,0]\n else:\n while not self.depth_flag:\n pass\n self.depth_flag = False\n brick_depth = self.depth_img[img_position[1], img_position[0]]\n c_para = C_PARAM # 相机4个内参\n brick_world = self.depth2world(img_position, brick_depth, c_para)\n brick_base = self.brick2base(brick_world)\n \n # print(img_position, brick_depth, c_para)\n cv2.circle(cv_image, tuple(img_position), 5, (255, 0, 0)) # 画圆\n\n #cv2.imshow(\"Image window\", cv_image)\n #self.videoWriter.write(cv_image)\n #cv2.waitKey(3)\n\n try:\n position_ = brick_base\n rospy.loginfo(\"brick position:\\n\"+str(position_))\n self.image_pub.publish(position_)\n except CvBridgeError as e:\n rospy.loginfo(e)\n else:\n pass\n \n cv2.imshow(\"Image window\", cv_image)\n self.videoWriter.write(cv_image)\n cv2.waitKey(3)\n\n def callback_depth(self, data):\n try:\n depth_image = self.bridge.imgmsg_to_cv2(data, \"32FC1\")\n except CvBridgeError as e:\n print(e)\n\n if False: # 保存图片时使用\n depth_image[np.isnan(depth_image)] = 0\n depth_image = 255*depth_image/np.max(depth_image)\n depth_image = depth_image.astype(np.uint8)\n cv2.imwrite(\"1_depth.png\", depth_image) # 保存测试图片\n cv2.imshow(\"depth window\", depth_image)\n cv2.waitKey(3)\n\n self.depth_img = depth_image\n self.depth_flag = True\n\n def sysmode_callback(self,msg):\n if int(msg.data) == 0: \n #print(mode)\n self.det_bool = True\n else:\n self.det_bool = False\n\n def brick_detect(self, img): # 砖块检测算法\n img = img.copy()\n\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # 转hsv颜色空间\n\n z_hsv = np.array([9, 194, 57]) # 砖块hsv值需要标定\n lower = np.array([2, 170, 37])\n upper = np.array([29, 220, 110])\n z_mask = cv2.inRange(hsv, lower, upper) # 通过颜色提取砖块的掩膜\n\n if True: # 掩膜形态学处理\n hsv_mask = z_mask\n elem=cv2.getStructuringElement(shape=cv2.MORPH_ELLIPSE, ksize=(3, 3))\n z_open = cv2.morphologyEx(hsv_mask, cv2.MORPH_OPEN, elem)\n elem=cv2.getStructuringElement(shape=cv2.MORPH_ELLIPSE, ksize=(7, 7))\n z_out = cv2.morphologyEx(z_open, cv2.MORPH_CLOSE, elem)\n else:\n hsv_mask = z_mask\n z_out = hsv_mask\n\n _, contours, hierarchy = cv2.findContours(z_out, cv2.RETR_EXTERNAL, \\\n cv2.CHAIN_APPROX_SIMPLE) # 从掩膜图像提取轮廓, cv2.CHAIN_APPROX_NONE\n\n c_max = []\n for i in range(len(contours)):\n cnt = contours[i]\n area = cv2.contourArea(cnt)\n # 处理掉小的轮廓区域,这个区域的大小自己定义\n if(area < (30*30)):\n continue\n else:\n c_max.append(cnt)\n\n z_center = [0, 0]\n for i in range(len(c_max)):\n im_temp = cv2.drawContours(img.copy(), [c_max[i]], -1, (0, 0, 255), \\\n thickness=1) # 画出轮廓图\n\n z_rect = cv2.minAreaRect(c_max[i]) # 获取最小外接矩形顶点坐标\n z_rect = cv2.boxPoints(z_rect)\n z_rect = z_rect.astype(np.int32)\n\n epsilon = 0.01 * cv2.arcLength(c_max[i],True)\n z_cor = cv2.approxPolyDP(c_max[i], epsilon, True) # 获取拟合多边形顶点坐标\n\n z_box = np.zeros([4, 2], dtype=np.int32)\n d_cor = np.array(z_cor)\n d_cor = d_cor.reshape((-1, 2))\n if len(d_cor)>4: # 拟合多边形顶点过多,选择有效顶点\n for j in range(len(z_rect)):\n d_rect = np.array([z_rect[j] for _ in range(len(d_cor))])\n n_cor = np.multiply(d_cor-d_rect, d_cor-d_rect)\n n_cor = np.argmin(n_cor[:, 0]+n_cor[:, 1])\n z_box[j] = d_cor[n_cor]\n d_cor = np.delete(d_cor, n_cor, 0)\n elif len(d_cor)==4: # 拟合多边形顶点满足四边形\n z_box = d_cor\n elif len(d_cor)<4: # 拟合多边形顶点过少,放弃该轮廓\n continue\n\n for j in range(len(z_box)):\n z_center += z_box[j]\n z_center = z_center//4 # 计算砖块中心像素坐标\n\n position_ = z_center\n return position_\n\n def depth2world(self, point, depth, c_para):\n \"\"\"parameter:\n point: (x, y) 像素坐标\n depth: d 深度值\n c_para: (fx, fy, cx, cy) 相机内参\n \"\"\"\n world_p = [0, 0, 0, 1]\n world_p[0] = depth*(point[0]-c_para[2])/c_para[0]\n world_p[1] = depth*(point[1]-c_para[3])/c_para[1]\n world_p[2] = depth\n return world_p\n \n def brick2base(self, brick2camera):\n brick_camera = PointStamped()\n brick_camera.header.stamp = rospy.Time(0);\n brick_camera.header.frame_id = \"kinect_frame_optical\";\n brick_camera.point.x = brick2camera[0];\n brick_camera.point.y = brick2camera[1];\n brick_camera.point.z = brick2camera[2];\n brick2base = [0, 0, 0, 1]\n try:\n #(trans,rot) =self.tflistener.lookupTransform('/base_link', '/kinect_frame_optical', rospy.Time(0))\n brick_base=self.tflistener.transformPoint(\"base_link\",brick_camera);\n #rospy.loginfo(brick_base)\n brick2base[0] = brick_base.point.x;\n brick2base[1] = brick_base.point.y;\n brick2base[2] = brick_base.point.z;\n return brick2base\n except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n rospy.loginfo(\"compute the brick2base failed\")\n return False\n \n\ndef main(args):\n rospy.init_node(\"brick_detection\", anonymous=True)\n rospy.loginfo(\"\\n***********brick_detection node***********\")\n ic = brick_detection()\n try:\n rospy.spin()\n except KeyboardInterrupt:\n rospy.loginfo(\"Shutting down\")\n cv2.destroyAllWindows()\n \n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"backup/brick_det_2base_1.py","file_name":"brick_det_2base_1.py","file_ext":"py","file_size_in_byte":8108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"276185044","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nfrom ..function import AddressVector\nfrom .builder import Builder\n\n\nclass SoapFunction:\n \"\"\"Build soap request to create the site.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialise an instance with the specified values.\"\"\"\n self._builder: Builder = None # type: ignore\n\n @property\n def builder(self) -> Builder:\n \"\"\"Return builder property.\"\"\"\n return self._builder\n\n @builder.setter\n def builder(self, builder: Builder) -> None:\n \"\"\"Set builder property.\"\"\"\n self._builder = builder\n\n def group_to_domain(self, group_id: int) -> None:\n self._builder.add(\"fun\", \"onyma_api_onyma_get_dom_for_gid\")\n self._builder.add(\"pgid\", group_id)\n\n def ins_pay(self, account_number: int, amount: float) -> None:\n now = datetime.now()\n options = {\n \"fun\": \"o_mdb_api_pay_ins_pay\",\n \"pdogid\": account_number,\n \"pamount\": amount,\n \"pbdate\": None,\n \"pmdate\": None,\n \"pidate\": None,\n \"ppaydoc\": f\"{now:%Y%m%d%H%M%S}\",\n \"pppdate\": None,\n \"premark\": \"Auto-test\",\n \"pcurrid\": 2,\n \"pppid\": 137,\n }\n self._builder.add_dict(options)\n\n def get_vec_id(self, vector: AddressVector, vector_type: int) -> None:\n options = [{\"column_value\": i} for i in vector]\n self._builder.add(\"fun\", \"onyma_uni_api_get_vec_id\")\n self._builder.add(\"pvec_type\", vector_type)\n self._builder.add(\"pval\", options)\n","sub_path":"api/onyma/soap/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"555635503","text":"from django.conf.urls import patterns, include, url\nfrom django.views.generic import ListView,TemplateView\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('', \n url(r'^$', 'core.views.index'),\n url(r'^list/$', 'core.views.list'),\n url(r'^show/$', 'core.views.show'),\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"496267978","text":"import shlex\nimport subprocess\nimport re\nimport hashlib\nimport os\nimport tempfile\nimport glob\nimport Image\nimport math\nfrom decimal import *\n\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.files import File\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Avg, Sum, Q\nfrom django.template.loader import render_to_string\n\nfrom video.models import VideoScreenshot, Video, UserVideo, VideoRating, VideoView, Cart, VideoPurchaseRecord\n\nimport userprofile.utils\nimport payment.utils\nimport videostore.utils\nfrom videostore.utils import log\n\nNUM_SCREENSHOTS = 10\n\ndef __process_video(video, logfile=None):\n\t\"\"\" Attempts to process the given Video object. Returns True/False depending\n\ton failure or success.\n\n\tThis function sets the video's md5 hash, but does not do dupe-checking.\n\n\tIf log is a file handle, writes debug info to that file.\n\t\"\"\"\n\tpath = video.video.path\n\t(stdout, info) = subprocess.Popen(['avconv', '-i', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()\n\tlog(logfile, \"Path to video: %s\" % path, \"Video info stdout: %s\" % stdout, \"Video info: %s\" % info)\n\n\t# MD5 sum. We need to do this before watermarking to get the md5 hash of the original file.\n\tif not video.md5:\n\t\twith open(path) as f:\n\t\t\tmd5 = hashlib.md5(f.read()).hexdigest()\n\t\tvideo.md5 = md5\n\t\tlog(logfile, \"Generated md5 sum: %s\" % md5)\n\t\tvideo.save()\n\telse:\n\t\tlog(logfile, \"Md5 sum already exists: %s\" % video.md5)\n\n\tfilename = os.path.basename(path)\n\t(name, ext) = os.path.splitext(filename)\n\n\ttempdir = tempfile.gettempdir()\n\tif not video.watermarked:\n\t\tlog(logfile, \"Watermarking video...\")\n\t\t# Need to get the bitrate in order to add the watermark\n\t\tmatch = re.search(r'bitrate: (\\d+) kb/s', info)\n\t\tif match:\n\t\t\tbitrate = match.group(1)\n\t\t\tlog(logfile, \"Found bitrate: %s\" % bitrate)\n\t\telse:\n\t\t\tlog(logfile, \"ERROR: Bitrate not found!\")\n\t\t\treturn False\n\n\t\t# We may be changing the extension of the file, so split off the base name\n\t\toutput = os.path.join(tempdir, name + '.mp4')\n\t\twatermark_path = os.path.join(settings.MEDIA_ROOT, 'private', 'watermark.png')\n\t\tlog(logfile, \"Temporary output: %s\" % output, \"Using watermark at: %s\" % watermark_path)\n\n\t\t# Figure out whether the watermark goes in the lower left or lower right (default)\n\t\tif video.watermark == 'left':\n\t\t\twatermark_command = 'overlay=2:main_h-overlay_h-2'\n\t\t\tlog(logfile, \"Watermarking in the lower left.\")\n\t\telse:\n\t\t\twatermark_command = 'overlay=main_w-overlay_w-2:main_h-overlay_h-2'\n\t\t\tlog(logfile, \"Watermarking in the lower right.\")\n\n\t\tcommand = 'avconv -i %s -r 65535/2733 -strict experimental -vb %sk -vcodec libx264 -y -vf \"movie=%s [logo]; [in][logo] %s [out]\" %s' % (\n\t\t\tpath,\n\t\t\tbitrate,\n\t\t\twatermark_path,\n\t\t\twatermark_command,\n\t\t\toutput,\n\t\t)\n\t\tlog(logfile, \"Running command: %s\" % command)\n\n\t\t(stdout, stderr) = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()\n\t\tlog(logfile, \"Command stdout: %s\" % stdout, \"Command stderr: %s\" % stderr)\n\t\tif 'Error' in stderr:\n\t\t\tlog(logfile, \"ERROR: 'Error' in stderr!\")\n\t\t\treturn False\n\n\t\t# Now we need to save the watermarked version.\n\t\twith open(output) as f:\n\t\t\tlog(logfile, \"Saving watermarked video...\")\n\t\t\tfile_object = File(f)\n\t\t\tvideo.video.delete()\n\t\t\tvideo.video.save(os.path.basename(output), file_object)\n\n\t\tvideo.watermarked = True\n\t\tvideo.save()\n\n\t\tos.remove(output)\n\n\t\t# We need to get the file info from avconv/ffmpeg again because we just changed the file.\n\t\tpath = video.video.path\n\t\tlog(logfile, \"New path to video: %s\" % path)\n\t\tfilename = os.path.basename(path)\n\t\t(name, ext) = os.path.splitext(filename)\n\t\t(stdout, info) = subprocess.Popen(['avconv', '-i', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()\n\t\tlog(logfile, \"New video info stdout: %s\" % stdout, \"New video info: %s\" % stderr)\n\t\tif 'Error' in info:\n\t\t\tlog(logfile, \"ERROR: 'Error' in video info!\")\n\t\t\treturn False\n\n\t# Video dimensions\n\tmatch = re.search(r' (\\d+)x(\\d+)', info)\n\tif match:\n\t\twidth = int(match.group(1))\n\t\theight = int(match.group(2))\n\t\tlog(logfile, \"Found video dimensions: %d x %d\" % (width, height))\n\telse:\n\t\tlog(logfile, \"ERROR: Video dimensions not found!\")\n\t\treturn False\n\n\t# Video length\n\tmatch = re.search(r'Duration: (\\d+):(\\d+):(\\d+)\\.(\\d+)', info)\n\tif match:\n\t\thours = int(match.group(1))\n\t\tminutes = int(match.group(2))\n\t\tseconds = int(match.group(3))\n\n\t\tlength = 3600*hours + 60*minutes + seconds\n\t\tlog(logfile, \"Found video length: %d hours, %d minutes, %d seconds; Total length: %d\" % (hours, minutes, seconds, length))\n\t\tif length <= 1:\n\t\t\tlog(logfile, \"ERROR: Video too short!\")\n\t\t\treturn False\n\telse:\n\t\tlog(logfile, \"ERROR: Video length not found!\")\n\t\treturn False\n\n\t# File size\n\tsize = os.path.getsize(path)\n\tlog(logfile, \"Video size: %d\" % size)\n\n\t# Screenshots\n\tframerate = NUM_SCREENSHOTS / float(length)\n\tbasename = 'video_' + name + '_%02d'\n\tbasepath = os.path.join(tempdir, basename)\n\tcommand = 'avconv -i %s -vsync 1 -r %f -bt 20M -an -y %s.jpg' % (\n\t\tpath,\n\t\tframerate,\n\t\tbasepath,\n\t)\n\tlog(logfile, \"Generating screenshots... Command: %s\" % command)\n\n\t(stdout, stderr) = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()\n\tlog(logfile, \"Screenshots stdout: %s\" % stdout, \"Screenshots stderr: %s\" % stderr)\n\n\tscreenshots = glob.glob(os.path.join(tempdir, 'video_' + name) + '*' + '.jpg')\n\tlog(logfile, \"Created %d screenshots.\" % len(screenshots))\n\tscreenshots.sort()\n\n\t# If we got fewer screenshots than expected, something went wrong.\n\tif 'Error' in stderr or len(screenshots) < NUM_SCREENSHOTS / 2:\n\t\tlog(logfile, \"ERROR: Screenshot generation!\")\n\t\treturn False\n\n\t# Delete the old screenshots (but leave the screenshot files)\n\tvideo.videoscreenshot_set.all().delete()\n\n\t# Create thumbs of the screenshots and save them to the database\n\tfor i, screenshot in enumerate(screenshots):\n\t\tlog(logfile, \"Processing screenshot #%d: %s\" % (i, screenshot))\n\t\tpil_image = Image.open(screenshot)\n\t\tpil_image.thumbnail((200, 200), Image.ANTIALIAS)\n\n\t\t# Save the thumbnail to a temporary file\n\t\tbasename = os.path.basename(screenshot)\n\t\tthumbname = 'thumb_' + basename\n\t\tthumbpath = os.path.join(tempdir, thumbname)\n\t\tpil_image.save(thumbpath, 'JPEG', quality=90)\n\n\t\t# Instantiate a new VideoScreenshot, then save the screenshot and thumbnail.\n\t\tvs = VideoScreenshot(video=video)\n\n\t\t# Use a screenshot from near the middle of the video as the primary screenshot\n\t\tif i == NUM_SCREENSHOTS/2 - 1:\n\t\t\tlog(logfile, \"Set screenshot %d as primary screenshot for this video.\" % i)\n\t\t\tvs.primary = True\n\n\t\tvs.save()\n\n\t\twith open(screenshot) as f:\n\t\t\tfile_object = File(f)\n\t\t\tvs.image.save(basename, file_object)\n\n\t\twith open(thumbpath) as f:\n\t\t\tfile_object = File(f)\n\t\t\tvs.thumbnail.save(thumbname, file_object)\n\n\t\t# Clean-up\n\t\tos.remove(thumbpath)\n\t\tos.remove(screenshot)\n\n\t# Now save the video info to the database\n\tlog(logfile, \"Saving video info to database...\")\n\tvideo.width = width\n\tvideo.height = height\n\tvideo.length = length\n\tvideo.size = size\n\tvideo.save()\n\n\tlog(logfile, \"Video processing successful.\")\n\treturn True\n\ndef process_video(video):\n\t\"\"\" Wrapper function for video processing. Results in either the processed or invalid\n\tflags being set depending on whether processing was a success. Also sets the duplicate\n\tflag if the video is a duplicate.\n\t\"\"\"\n\n\tlogdir = os.path.join(settings.MEDIA_ROOT, 'private', 'log')\n\tif not os.path.exists(logdir):\n\t\tos.makedirs(logdir)\n\n\tlogfile = open(os.path.join(logdir, 'video_%d.log' % video.id), 'w')\n\n\tsuccess = __process_video(video, logfile)\n\n\tvideo.processed = False\n\tvideo.invalid = False\n\tvideo.duplicate = False\n\n\tif success:\n\t\tvideo.processed = True\n\telse:\n\t\tvideo.invalid = True\n\n\tduplicates = Video.objects.filter(md5=video.md5, id__lt=video.id, deleted=False, invalid=False)\n\tif duplicates:\n\t\tids = [str(d.id) for d in duplicates]\n\t\tlog(logfile, \"Found duplicate video(s): %s\" % \", \".join(ids))\n\t\tvideo.duplicate = True\n\n\tlog(logfile, \"--FINAL RESULTS--\", \"Processed: %s, Invalid: %s, Duplicate: %s\" % (video.processed, video.invalid, video.duplicate))\n\tlogfile.close()\n\tvideo.save()\n\ndef uploaded_video_time(user):\n\t\"\"\" Returns the total length of all the valid videos uploaded by this user, in seconds.\"\"\"\n\tvalid_videos = Video.objects.filter(user=user, processed=True, invalid=False, duplicate=False, deleted=False)\n\treturn valid_videos.aggregate(Sum('length'))['length__sum']\n\ndef uploaded_video_time_string(user):\n\t\"\"\" Returns a string representation of the total video time uploaded by this user, as MM:SS.\"\"\"\n\tvideo_time = uploaded_video_time(user)\n\t(video_mins, video_secs) = (0, 0)\n\tif video_time:\n\t\tvideo_mins = video_time / 60\n\t\tvideo_secs = video_time - 60*video_mins\n\n\treturn \"%s:%s\" % (str(video_mins).zfill(2), str(video_secs).zfill(2))\n\ndef maybe_award_bonus(request):\n\t\"\"\" If the producer has uploaded more than VIDEO_BONUS_MINS minutes of video, award them the bonus.\n\t\tChecks both the referral bonus and the video upload bonus. (The referral bonus is awarded\n\t\tto the user who referred this producer.)\n\t\"\"\"\n\tsum_length = uploaded_video_time(request.user)\n\n\tif sum_length >= settings.VIDEO_BONUS_MINS * 60:\n\t\t# Video upload bonus\n\t\tif not request.user.producer.video_bonus:\n\t\t\tpayment.utils.transaction(\n\t\t\t\tuser=request.user,\n\t\t\t\ttriggered_by=request.user,\n\t\t\t\tamount=settings.VIDEO_BONUS,\n\t\t\t\tnote=\"You've uploaded %d minutes of video!\" % settings.VIDEO_BONUS_MINS,\n\t\t\t)\n\n\t\t\trequest.user.producer.video_bonus = True;\n\t\t\trequest.user.producer.save()\n\n\t\t# Referral bonus\n\t\treferred_by = request.user.producer.referred_by\n\t\tif referred_by and not request.user.producer.referral_bonus:\n\t\t\tif userprofile.utils.is_producer(referred_by):\n\t\t\t\tbonus = settings.REFERRAL_PRODUCER_BONUS\n\t\t\telse:\n\t\t\t\tbonus = settings.REFERRAL_BONUS\n\n\t\t\tpayment.utils.transaction(\n\t\t\t\tuser=referred_by,\n\t\t\t\ttriggered_by=request.user,\n\t\t\t\tamount=bonus,\n\t\t\t\tnote=\"Referred user uploaded %d minutes of video\" % settings.VIDEO_BONUS_MINS,\n\t\t\t)\n\n\t\t\trequest.user.producer.referral_bonus = True;\n\t\t\trequest.user.producer.save()\n\n\ndef get_primary_screenshot(video):\n\t\"\"\" Returns the screenshot to use as the main picture for the given video.\n\t\"\"\"\n\tscreenshots = video.videoscreenshot_set.filter(primary=True)\n\n\tif len(screenshots) == 1:\n\t\treturn screenshots[0]\n\n\t# For some reason, there is an incorrect number of primary screenshots defined for this\n\t# video. Let's just pick one from the middle of the video.\n\tscreenshots = video.videoscreenshot_set.all()\n\n\tnum_screenshots = len(screenshots)\n\treturn screenshots[num_screenshots / 2]\n\ndef get_price(video):\n\t\"\"\" Given a video, returns the price as a Decimal, taking into account the video's and producer's\n\tmultipliers.\n\t\"\"\"\n\tif video.price_override:\n\t\treturn video.price_override\n\n\treturn get_recommended_price(video)\n\ndef get_discounted_price(video, user):\n\t\"\"\" If the video is discounted for the user, returns the discounted price. Otherwise, returns\n\tget_price.\n\t\"\"\"\n\t# Referral discount (video is free if the user referred the uploader)\n\treferred_by = video.user.producer.referred_by\n\tif referred_by and referred_by.id == user.id:\n\t\treturn Decimal('0.00')\n\n\treturn get_price(video)\n\ndef get_recommended_price(video):\n\t\"\"\" Returns the recommended price even if it has been overridden. \"\"\"\n\t# mult1 = video.user.producer.multiplier\n\t# mult2 = video.multiplier\n\tlength_minutes = video.length / 60.0\n\n\t# Complex equation to figure out the price\n\tprice = 3*(length_minutes/4.0)**(3.0/4)\n\n\t# Now round up the price to $1 if it is too low\n\tif price < 1:\n\t\tprice = 1\n\n\t# Round to nearest $0.10\n\trounded_price = Decimal(price).quantize(Decimal('0.1'))\n\n\treturn rounded_price.quantize(Decimal('0.01'))\n\ndef purchase_allowed(user, video):\n\t\"\"\" Returns true if user is allowed to buy the video, false otherwise. Does NOT take\n\twhether the user has enough funds into account.\n\t\"\"\"\n\tif not user.is_authenticated():\n\t\treturn False\n\n\tbuyable = False\n\tbought = video.uservideo_set.filter(user=user).count()\n\tif not bought and not userprofile.utils.is_producer(user) and not video.deleted:\n\t\tbuyable = True\n\n\treturn buyable\n\ndef has_funds(user, video):\n\t\"\"\" Returns True if the user has enough money in their account to buy the video.\n\t\"\"\"\n\tvideo_price = get_discounted_price(video, user)\n\tbalance = payment.utils.get_balance(user)\n\n\treturn video_price <= balance\n\ndef can_buy(user, video):\n\t\"\"\" Returns True if the user both has enough funds to buy the video, and is allowed\n\tto do so.\n\t\"\"\"\n\tif purchase_allowed(user, video) and has_funds(user, video):\n\t\tcan_buy = True\n\telse:\n\t\tcan_buy = False\n\n\treturn can_buy\n\ndef buy(request, video, do_check=True):\n\t\"\"\" Attempts to have the requesting user buy the video, and returns True/False depending on success.\n\t\tIf do_check is False, skips the check on whether the user can buy the video.\n\t\"\"\"\n\n\tsuccess = False\n\tuser = request.user\n\tuser_price = get_discounted_price(video, user)\n\tproducer_price = get_price(video)\n\tnote = \"Purchased video %d\" % video.id\n\n\tif not do_check or can_buy(user, video):\n\t\t# Subtract the price of video from user\n\t\ttransaction_success = payment.utils.transaction(\n\t\t\tuser=user,\n\t\t\tamount=-user_price,\n\t\t\tnote=note,\n\t\t\ttriggered_by=video.user,\n\t\t)\n\n\t\tif transaction_success:\n\t\t\tsuccess = True\n\n\t\t\tproducer_share = Decimal(float(producer_price) * settings.PRODUCER_SHARE).quantize(Decimal('0.01'))\n\n\t\t\t# Give the producer their share. This is based on the full cost of the video, not the discounted price.\n\t\t\tpayment.utils.transaction(\n\t\t\t\tuser=video.user,\n\t\t\t\tamount=producer_share,\n\t\t\t\tnote=note,\n\t\t\t\ttriggered_by=user,\n\t\t\t)\n\n\t\t\t# Set the video as purchased by the user\n\t\t\tuv = UserVideo(\n\t\t\t\tuser=user,\n\t\t\t\tvideo=video,\n\t\t\t\tpaid=user_price,\n\t\t\t)\n\t\t\tuv.save()\n\n\t\t\t# Create a VideoPurchaseRecord to log this purchase\n\t\t\tVideoPurchaseRecord(\n\t\t\t\tuser=user,\n\t\t\t\tuploader=video.user,\n\t\t\t\tvideo=video,\n\t\t\t\tuser_paid=user_price,\n\t\t\t\tuploader_paid=producer_share,\n\t\t\t\tip=videostore.utils.get_ip(request),\n\t\t\t).save()\n\n\treturn success\n\ndef bought(user, video):\n\t\"\"\" Returns True if the user has bought the video, False otherwise.\n\t\"\"\"\n\tif not user.is_authenticated():\n\t\treturn False\n\n\tuv = UserVideo.objects.filter(user=user, video=video).count()\n\n\treturn uv >= 1\n\ndef get_ratings(video):\n\t\"\"\" returns: {'avg': X or None, 'count': X}\n\tThe avg is the number of stars between 1 and 5, to a resolution of 0.5.\n\t\"\"\"\n\tratings = VideoRating.objects.filter(video=video, rating__isnull=False)\n\tnumratings = ratings.count()\n\n\tif numratings == 0:\n\t\treturn {'avg': None, 'count': numratings}\n\telse:\n\t\tavg = int(ratings.aggregate(Avg('rating'))['rating__avg'] * 2) / 2.0\n\t\treturn {\n\t\t\t'avg': avg,\n\t\t\t'count': numratings,\n\t\t}\n\ndef get_video_thumb_entries(videos):\n\treturn [{\n\t\t'video': v,\n\t\t'screenshot': get_primary_screenshot(v),\n\t\t'rating': get_ratings(v),\n\t} for v in videos]\n\ndef exclude_bought_videos(user, videos):\n\t\"\"\" Returns the list of videos without any videos that the user has already bought. \"\"\"\n\tbought_video_ids = UserVideo.objects.filter(user=user).values_list('video__id', flat=True)\n\treturn videos.exclude(id__in=bought_video_ids)\n\ndef viewed_video(request, video):\n\tvw = VideoView.objects.filter(video=video)\n\tif request.user.is_authenticated():\n\t\treturn vw.filter(Q(user=request.user) | Q(ip=videostore.utils.get_ip(request))).count() > 0\n\telse:\n\t\treturn vw.filter(ip=videostore.utils.get_ip(request)).count() > 0\n\ndef in_cart(user, video):\n\tif not user.is_authenticated():\n\t\treturn False\n\n\treturn Cart.objects.filter(user=user, video=video).count() > 0\n\ndef cart_add(user, video, add=True):\n\t\"\"\" Tries to add or remove the video to/from the user's cart. Returns whether the\n\tvideo is in the user's cart.\n\t\"\"\"\n\tif not purchase_allowed(user, video):\n\t\treturn False\n\n\tif add and not video.deleted:\n\t\tif in_cart(user, video):\n\t\t\t# The video is already in the user's cart, so we do nothing\n\t\t\treturn True\n\t\telse:\n\t\t\t# Need to add the video to the cart.\n\t\t\tCart(\n\t\t\t\tuser=user,\n\t\t\t\tvideo=video,\n\t\t\t).save()\n\telse:\n\t\tCart.objects.filter(user=user, video=video).delete()\n\n\t# For good measure return the value of in_cart so we can accurately\n\t# report the status of the video in the cart.\n\treturn in_cart(user, video)\n\ndef cart_num_items(user):\n\t\"\"\" Returns the number of videos in the user's cart.\n\t\"\"\"\n\tif not user.is_authenticated():\n\t\treturn 0\n\n\treturn Cart.objects.filter(user=user).count()\n\ndef cart_html(user):\n\t\"\"\" Returns the HTML for displaying the items in a user's cart when viewing the\n\tcart page, as well as info about the cart total cost.\n\t\"\"\"\n\titems = Cart.objects.filter(user=user)\n\n\t# PERFORMANCE\n\tnew_items = []\n\tfor item in items:\n\t\ttry:\n\t\t\titem.screenshot = VideoScreenshot.objects.get(video=item.video, primary=True)\n\t\t\titem.price_html = video_price_html(item.video, user)\n\t\t\tnew_items.append(item)\n\t\texcept ObjectDoesNotExist:\n\t\t\t# If there wasn't a screenshot, something went wrong and we want to\n\t\t\t# delete this item from the cart.\n\t\t\titem.delete()\n\titems = new_items\n\n\tbalance = payment.utils.get_balance(user)\n\tsubtotal = cart_total(user)\n\n\ttotal = subtotal - balance\n\tif total < 0:\n\t\ttotal = Decimal('0.00')\n\n\treturn {\n\t\t'items': render_to_string('video/snippets/cart_items.html', {\n\t\t\t'items': items,\n\t\t}),\n\t\t'payment': render_to_string('video/snippets/cart_payment.html', {\n\t\t\t'balance': balance,\n\t\t\t'subtotal': cart_total(user),\n\t\t\t'total': total,\n\t\t\t'settings': settings,\n\t\t\t'num_items': len(items),\n\t\t}),\n\t}\n\ndef cart_total(user):\n\t\"\"\" Returns the total cost of the items in the user's cart as a Decimal. Takes into account\n\tdiscounted video prices.\n\t\"\"\"\n\titems = Cart.objects.filter(user=user)\n\n\tcost = Decimal('0.00')\n\tfor item in items:\n\t\tcost += get_discounted_price(item.video, user)\n\n\treturn cost\n\ndef video_price_html(video, user):\n\treturn render_to_string('video/snippets/video_price.html', {\n\t\t'price': get_price(video),\n\t\t'discounted_price': get_discounted_price(video, user),\n\t})\n\ndef video_to_api(video):\n\t\"\"\" Returns a dictionary of information about the video. Useful in responses\n\tto API calls.\n\t\"\"\"\n\tuploader = video.user\n\tuploader_type = 'producer'\n\n\tscreenshot = get_primary_screenshot(video)\n\n\treturn {\n\t\t'id': video.id,\n\t\t'title': video.title,\n\t\t'uploader': uploader.username,\n\t\t'uploader_type': uploader_type,\n\t\t'uploader_url': settings.SITEURL + reverse('producerprofile', kwargs={'username': uploader.username}),\n\t\t'thumbnail': screenshot.thumbnail.url,\n\t\t'thumbnail_width': screenshot.thumbnail.width,\n\t\t'thumbnail_height': screenshot.thumbnail.height,\n\t\t'url': settings.SITEURL + reverse('video:detail', kwargs={'videoid': video.id}),\n\t}\n\ndef download_folder(user, key):\n\t\"\"\" Returns the folder path into which a symlink to a video is placed to create a single\n\tdownload link.\n\t\"\"\"\n\tpostfix = os.path.join('p', 'downloads', user.username, key)\n\treturn {\n\t\t'local': os.path.join(settings.MEDIA_ROOT, postfix),\n\t\t'url': os.path.join(settings.MEDIA_URL, postfix),\n\t}\n","sub_path":"site/video/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":18907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"168422131","text":"# Just to explore types of anomalies in Yahoo benchmark dataset\n\n# Import libraries\nimport pandas as pd\nimport numpy as np\nimport os\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport os\nfrom tensorflow import keras\nimport seaborn as sns\n\n# Load Dataset\nos.chdir('/Users/sylviachadha/Desktop/Anomaly_Detection/Practice_Dataset')\ndf = pd.read_csv('real_20.csv', index_col = 'timestamp')\nprint(df.head(6))\n\n# Index column timestamp data type should be datetime (hourly data)\ndf.index.freq = 'H'\ndf.index\ndf.index = pd.to_datetime(df.index, origin=pd.Timestamp('2020-01-01'), unit = 'h')\ndf.index\n\n# Plot data (showing point anomalies)\nax = df['value'].plot(figsize = (12,6), title = 'yahoo traffic data');\nxlabel = 'hourly data'\nylabel = 'traffic - yahoo properties'\nax.set(xlabel = xlabel, ylabel = ylabel)\nplt.show()\n\n# We’ll use 90% of the data and train our model on it:\ntrain_size = int(len(df) * 0.90)\ntest_size = len(df) - train_size\ntrain, test = df.iloc[0:train_size],df.iloc[train_size:len(df)]\nprint(train.shape,test.shape)\n\n# To check how many anomalies are present in Training and how many in test\na = train.loc[train.is_anomaly == 1]\nprint(a)\ntotal_rows = a['is_anomaly'].count()\nprint('is_anomaly_training_count',total_rows)\n\nb = test.loc[test.is_anomaly == 1]\nprint(b)\ntotal_rows = b['is_anomaly'].count()\nprint('is_anomaly_test_count',total_rows)\n\nprint(min(df['value']))\nprint(max(df['value']))\na = np.mean(df['value'])\nb = np.std(df['value'])\nc = (a + 3*b)\nprint('c is',c)\n","sub_path":"models/Exp4.py","file_name":"Exp4.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"222521433","text":"import json\nimport requests\nfrom flask import Flask, render_template, request\nfrom flask_assistant import Assistant, ask, tell\nfrom proto_blight import blight_result\nfrom proto_time import start, stop\nfrom proto_hue import hue_on, hue_off\n\napp = Flask(__name__)\nassist = Assistant(app, '/')\n\n@app.route(\"/blight\", methods=['POST'])\ndef blight():\n result = request.data.decode()\n data = {\n \"blight_lux\":int(result)\n }\n file = open(\"blight.json\", \"w\")\n json.dump(data, file)\n return result\n\n@assist.action('Default Welcome Intent')\ndef greet_and_start():\n result = blight_result()\n text = \"はいプロトです。宿題をはじめる時は、宿題をはじめるよって言ってね。\"\n return ask(text)\n\n@assist.action('stydyStart')\ndef studyStart():\n start()\n result = blight_result()\n print(\"blight:\" + str(result) + \"lux\")\n if result < 500:\n text = \"手もとが暗いですね。明かりをつけますか?\"\n return ask(\"宿題をはじめます。\" + text)\n else:\n return tell(\"宿題をはじめます。\")\n\n@assist.action('studyEnd')\ndef studyEnd():\n result_time = stop()\n\n result = blight_result()\n print(\"blight:\" + str(result) + \"lux\")\n\n if 500 <= result:\n text = \"明かりを消しますか?\"\n return ask('机に向かった時間は' + str(result_time) + 'でした。' + text)\n else:\n return tell('机に向かった時間は' + str(result_time) + 'でした。お疲れさまでした。')\n\n@assist.action('onIntent')\ndef on():\n hue_on()\n return tell('最適な明かりで設定しました。宿題頑張ってね。')\n\n@assist.action('offIntent')\ndef off():\n hue_off()\n result = stop()\n return tell('明かりを消しました。お疲れさまでした。')\n\nif __name__ == \"__main__\":\n app.run(host=\"127.0.0.1\", port=5000)\n","sub_path":"Chapter4/GoogleHome_desk/proto_g_desk.py","file_name":"proto_g_desk.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"390933189","text":"# to calculate onsite exchange parameter\n# we need at least two scf calculations\nreference = 'test_NiO/perturb_Ni1_2/scf.out'\nperturbed = 'test_NiO/perturb_Ni1_2/dm_dlz_1.out'\n\n# hard-coded perturbation parameters\nlambdas = [0.0, 0.01]\n\n# get magnetic moments of the last iteration of each pwout file.\nimport base.pwo\nm_ref = base.pwo.Pwout(reference).iterations[-1].magnetic_moment\nm0 = base.pwo.Pwout(perturbed).iterations[0].magnetic_moment\nm = base.pwo.Pwout(perturbed).iterations[-1].magnetic_moment\n\n# calculate response vector delta_m\ndelta_m = (m - m_ref)/(lambdas[1] - lambdas[0])\ndelta_m0 = (m0 - m_ref)/(lambdas[1] - lambdas[0])\n\n# find symmetry operations\nimport base.pwi\nimport symm.equivatom\nimport numpy as np\n\npwi = base.pwi.Pwin('test_NiO/perturb_Ni1_2/scf.in')\nequiv_atom_map = pwi.get_symmetrizing_map(0)\n\n# calculate response matrix delta_m_delta_l\ndelta_m_delta_l = symm.equivatom.get_response_matrix(delta_m[:, 2], equiv_atom_map)\ndelta_m0_delta_l = symm.equivatom.get_response_matrix(delta_m0[:, 2], equiv_atom_map)\n\ndelta_l_delta_m = np.linalg.inv(delta_m_delta_l)\ndelta_l_delta_m0 = np.linalg.inv(delta_m0_delta_l)\n\nonsite_exchange = - delta_l_delta_m + delta_l_delta_m0\nprint('J = {:f} meV'.format(onsite_exchange[0, 0]*13.6*1000.0))\n\n","sub_path":"calculate_onsite_exchange.py","file_name":"calculate_onsite_exchange.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"422589747","text":"#!/usr/bin/env python3\ndef solve(year):\n '''Trả về tuple-2 chứa year và tên gọi can chi tương ứng. Các từ trong tên\n đề phải viết hoa các chữ cái đầu.\n\n Biết có 10 thiên can::\n\n ['giáp', 'ất', 'bính', 'đinh', 'mậu', 'kỷ', 'canh', 'tân', 'nhâm', 'quý']\n\n Và 12 địa chi::\n\n ['tý', 'sửu', 'dần', 'mão', 'thìn', 'tị', 'ngọ', 'mui', 'thân', 'dậu',\n 'tuất', 'hợi']\n\n Năm 2017 là năm \"Đinh Dậu\".\n'''\n thien_can = ['giáp', 'ất', 'bính', 'đinh', 'mậu', 'kỷ', 'canh', 'tân', 'nhâm', 'quý']\n dia_chi = ['tý', 'sửu', 'dần', 'mão', 'thìn', 'tị', 'ngọ', 'mui', 'thân', 'dậu','tuất', 'hợi']\n\n can = thien_can[(year - 4 )% 10]\n chi = dia_chi[(year - 4 ) % 12]\n\n thien_dia = '{0} {1}'.format(can, chi).title()\n return (year,thien_dia)\n\ndef main():\n print(\"Năm {0} là năm {1}\".format(*solve(1696)))\n print(\"Năm {0} là năm {1}\".format(*solve(1988)))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"exercises/ex4_7.py","file_name":"ex4_7.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"444571810","text":"import pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\ndef get_corpus():\n c1 = \"Do you like Green eggs and ham\"\n c2 = \"I do not like them Sam I am I do not like Green eggs and ham\"\n c3 = \"Would you like them Here or there\"\n c4 = \"I would not like them Here or there I would not like them Anywhere\"\n return [c1, c2, c3, c4]\n\n\ndef cv_demo1():\n corpus = get_corpus()\n cvec = CountVectorizer(lowercase=True)\n doc_term_matrix = cvec.fit_transform(corpus)\n print(cvec.get_feature_names())\n print(doc_term_matrix.toarray())\n\n\ndef split_into_tokens(data, normalize=True, min_length=0):\n word_list = []\n\n if normalize is True:\n data = data.lower()\n\n data = data.split()\n\n for i in data:\n if len(data) > min_length:\n word_list.append(i)\n\n return word_list\n\n\ndef cv_demo2():\n corpus = get_corpus()\n cvec = CountVectorizer(tokenizer=split_into_tokens)\n doc_term_matrix = cvec.fit_transform(corpus)\n tokens = cvec.get_feature_names()\n\n return doc_term_matrix, tokens\n\n\ndef word_matrix_to_df(wm, feature_names):\n doc_names = ['Doc{:d}'.format(idx + 1) for idx, _ in enumerate(wm)]\n df = pd.DataFrame(data=wm.toarray(), index=doc_names, columns=feature_names)\n return df\n\n\ndef cv_demo3():\n doc_term_matrix, tokens = cv_demo2()\n df = word_matrix_to_df(doc_term_matrix, tokens)\n return df\n\n\ndef cv_demo_idf():\n doc_term_matrix, tokens = cv_demo2()\n tfidf_transformer = TfidfTransformer()\n tfidf_transformer.fit(doc_term_matrix)\n df = pd.DataFrame(tfidf_transformer.idf_, index=tokens, columns=[\"idf_weights\"])\n df.sort_values(by=['idf_weights'], inplace=True, ascending=False)\n return df\n\n\ndef cv_demo_tf_idf():\n doc_term_matrix, tokens = cv_demo2()\n tfidf_transformer = TfidfTransformer(smooth_idf=True)\n tfidf_transformer.fit(doc_term_matrix)\n idf = tfidf_transformer.idf_\n tf_idf_vector = tfidf_transformer.transform(doc_term_matrix)\n print(tf_idf_vector)\n\n\ndef cv_demo_pd_tf_idf():\n doc_term_matrix, tokens = cv_demo2()\n tfidf_transformer = TfidfTransformer(smooth_idf=True, sublinear_tf=True, norm=None)\n tfidf_transformer.fit(doc_term_matrix)\n idf = tfidf_transformer.idf_\n tf_idf_vector = tfidf_transformer.transform(doc_term_matrix)\n token = 'i'\n doc = 1\n df_idf = pd.DataFrame(idf, index=tokens, columns=[\"idf_weights\"])\n df_idf.sort_values(by=['idf_weights'], inplace=True, ascending=False)\n idf_token = df_idf.loc[token]['idf_weights']\n doc_vector = tf_idf_vector[doc]\n df_tfidf = pd.DataFrame(doc_vector.T.todense(), index=tokens, columns=[\"tfidf\"])\n df_tfidf.sort_values(by=[\"tfidf\"], ascending=False, inplace=True)\n tfidf_token = df_tfidf.loc[token]['tfidf']\n tf_token = tfidf_token / idf_token\n print('TF {:s} {:2.4f}'.format(token, tf_token))\n print('IDF {:s} {:2.4f}'.format(token, idf_token))\n print('TFIDF {:s} {:2.4f}'.format(token, tfidf_token))\n\n\ndef dump_sparse_matrix():\n vec = TfidfVectorizer(use_idf=True)\n corpus = [\"another day of rain; rain rain go away, comeback another day\"]\n matrix = vec.fit_transform(corpus)\n print(matrix.shape)\n print(vec.idf_)\n coo_format = matrix.tocoo()\n print(coo_format.col)\n print(coo_format.data)\n tuples = zip(coo_format.col, coo_format.data)\n in_order = sorted(tuples, key=lambda x: (x[1], x[0]), reverse=True)\n features = vec.get_feature_names() # the unique words\n print(features)\n for score in in_order:\n idx = score[0]\n word = features[idx]\n print(\"{:10s} tfidf:\".format(word), score)\n\n\n'''\n***********************************************\nReview Questions\nQ1)What does CountVectorizer do?\nQ2)What does TfidfTransformer do?\nQ3)What does sklearn's fit function do?\nQ4)What does sklearn's transform function do?\n\n## It converts a text to a vector on the basis of the frequency of each word that occurs in the text.\n## It converts the vector of the word count to a TF.IDF matrix. \n## Sklearn's fit attempts to build & train the model based on the data provided. In this case based on the given documents fit builds idf vector.\n## Sklearn's transform applies what was fitted using fit to incoming data. In this case it was used to create the TF.IDF vector\n***********************************************\n'''","sub_path":"TFIDF_SKLearn.py","file_name":"TFIDF_SKLearn.py","file_ext":"py","file_size_in_byte":4452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"150015625","text":"import collections\nfrom collections import defaultdict\nfrom typing import Iterable, Optional, Union\n\nfrom logzero import logger\n\nfrom comb_spec_searcher import CombinatorialSpecificationSearcher\nfrom comb_spec_searcher.strategies import StrategyFactory\nfrom permuta import Perm\nfrom permuta.descriptors import Basis\nfrom tilings import GriddedPerm, Tiling\nfrom tilings.strategy_pack import TileScopePack\n\n__all__ = (\"TileScope\", \"TileScopePack\")\n\n\nclass TileScope(CombinatorialSpecificationSearcher):\n \"\"\"\n An instance of TileScope is used to build up knowledge about tilings with\n respect to the given basis.\n \"\"\"\n\n def __init__(\n self,\n start_class: Union[str, Iterable[Perm], Tiling],\n strategy_pack: TileScopePack,\n logger_kwargs: Optional[dict] = None,\n **kwargs\n ) -> None:\n\n \"\"\"Initialise TileScope.\"\"\"\n if isinstance(start_class, str):\n basis = Basis(\n [Perm.to_standard([int(c) for c in p]) for p in start_class.split(\"_\")]\n )\n elif isinstance(start_class, Tiling):\n start_tiling = start_class\n if start_class.dimensions == (1, 1):\n basis = Basis([o.patt for o in start_class.obstructions])\n elif isinstance(start_class, collections.abc.Iterable):\n basis = Basis(start_class)\n assert all(\n isinstance(p, Perm) for p in basis\n ), \"Basis must contains Perm only\"\n else:\n raise ValueError(\n \"start class must be a string, an iterable of Perm or a tiling\"\n )\n\n if not isinstance(start_class, Tiling):\n start_tiling = Tiling(\n obstructions=[GriddedPerm.single_cell(patt, (0, 0)) for patt in basis]\n )\n\n if start_tiling.dimensions == (1, 1):\n procname = kwargs.get(\"logger_kwargs\", {\"processname\": \"runner\"})\n logger.debug(\"Fixing basis in OneByOneVerificationStrategy\", extra=procname)\n strategy_pack = strategy_pack.fix_one_by_one(basis)\n\n super().__init__(\n start_tiling, strategy_pack, logger_kwargs=logger_kwargs, **kwargs,\n )\n\n @staticmethod\n def _strat_dict_to_jsonable(dict_):\n keys = []\n values = []\n for k, v in dict_.items():\n if k == \"is empty\":\n keys.append(k)\n else:\n keys.append(k.to_jsonable())\n values.append(v)\n return {\"keys\": keys, \"values\": values}\n\n @staticmethod\n def _strat_dict_from_jsonable(dict_):\n keys = dict_[\"keys\"]\n values = dict_[\"values\"]\n d = {}\n for k, v in zip(keys, values):\n if k == \"is empty\":\n d[k] = v\n else:\n d[StrategyFactory.from_dict(k)] = v\n values.append(v)\n return defaultdict(int, d)\n","sub_path":"tilings/tilescope.py","file_name":"tilescope.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"16214278","text":"from abc import abstractmethod\nfrom ipaddress import IPv4Address, IPv6Address\nfrom socket import AddressFamily, SocketType\nfrom typing import (\n TypeVar, Tuple, Union, Generic, Callable, Any, Optional, AsyncContextManager)\n\nfrom .tasks import TaskGroup\nfrom .streams import UnreliableObjectStream, ByteStream, Listener, T_Stream\n\nIPAddressType = Union[str, IPv4Address, IPv6Address]\nIPSockAddrType = Tuple[str, int]\nSockAddrType = Union[IPSockAddrType, str]\nUDPPacketType = Tuple[bytes, IPSockAddrType]\nT_Retval = TypeVar('T_Retval')\nT_SockAddr = TypeVar('T_SockAddr', str, IPSockAddrType)\n\n\nclass _NullAsyncContextManager:\n async def __aenter__(self):\n pass\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n pass\n\n\nclass SocketProvider(Generic[T_SockAddr]):\n \"\"\"Abstract base class for socket-based streams and listeners.\"\"\"\n\n @property\n @abstractmethod\n def raw_socket(self) -> SocketType:\n \"\"\"\n The underlying raw socket object.\n\n .. warning:: This should only be used for advanced use cases, so only use this if you know\n what you're doing. Otherwise you might break things in subtle ways.\n \"\"\"\n\n def getsockopt(self, level, optname, *args):\n \"\"\"\n Get a socket option from the underlying socket.\n\n :return: the return value of :meth:`~socket.socket.getsockopt`\n\n \"\"\"\n return self.raw_socket.getsockopt(level, optname, *args)\n\n def setsockopt(self, level, optname, value, *args) -> None:\n \"\"\"\n Set a socket option on the underlying socket.\n\n This calls :meth:`~socket.socket.setsockopt` on the underlying socket.\n\n \"\"\"\n self.raw_socket.setsockopt(level, optname, value, *args)\n\n @property\n def family(self) -> AddressFamily:\n \"\"\"The address family of the underlying socket.\"\"\"\n return self.raw_socket.family\n\n @property\n def local_address(self) -> T_SockAddr:\n \"\"\"\n The bound address of the underlying local socket.\n\n For TCP streams, this is a tuple of (IP address, port).\n For UNIX socket streams, this is the path to the socket.\n\n \"\"\"\n from anyio._core._sockets import convert_ipv6_sockaddr\n return convert_ipv6_sockaddr(self.raw_socket.getsockname())\n\n\nclass SocketStream(Generic[T_SockAddr], ByteStream, SocketProvider[T_SockAddr]):\n \"\"\"Transports bytes over a socket.\"\"\"\n\n @property\n def remote_address(self) -> T_SockAddr:\n \"\"\"\n The address this socket is connected to.\n\n For TCP streams, this is a tuple of (IP address, port).\n For UNIX socket streams, this is the path to the socket.\n\n \"\"\"\n from anyio._core._sockets import convert_ipv6_sockaddr\n return convert_ipv6_sockaddr(self.raw_socket.getpeername())\n\n\nclass SocketListener(Generic[T_SockAddr], Listener[SocketStream[T_SockAddr]],\n SocketProvider[T_SockAddr]):\n \"\"\"Listens to incoming socket connections.\"\"\"\n\n @abstractmethod\n async def accept(self) -> SocketStream[T_SockAddr]:\n \"\"\"Accept an incoming connection.\"\"\"\n\n async def serve(self, handler: Callable[[T_Stream], Any],\n task_group: Optional[TaskGroup] = None) -> None:\n from .. import create_task_group\n\n context_manager: AsyncContextManager\n if task_group is None:\n task_group = context_manager = create_task_group()\n else:\n # Can be replaced with AsyncExitStack once on py3.7+\n context_manager = _NullAsyncContextManager()\n\n # There is a mypy bug here\n async with context_manager: # type: ignore[attr-defined]\n while True:\n stream = await self.accept()\n await task_group.spawn(handler, stream)\n\n\nclass UDPSocket(UnreliableObjectStream[UDPPacketType], SocketProvider[IPSockAddrType]):\n \"\"\"Represents an unconnected UDP socket.\"\"\"\n\n async def sendto(self, data: bytes, host: str, port: int) -> None:\n return await self.send((data, (host, port)))\n\n\nclass ConnectedUDPSocket(UnreliableObjectStream[bytes], SocketProvider[IPSockAddrType]):\n \"\"\"Represents an connected UDP socket.\"\"\"\n\n @property\n def remote_address(self) -> IPSockAddrType:\n \"\"\"The address this socket is connected to.\"\"\"\n from anyio._core._sockets import convert_ipv6_sockaddr\n return convert_ipv6_sockaddr(self.raw_socket.getpeername())\n","sub_path":"src/anyio/abc/sockets.py","file_name":"sockets.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"23955002","text":"import logging\nimport redis\n\nfrom src.models import SkippedTransaction, Block\nfrom src.utils import helpers, db_session\nfrom src.utils.config import shared_config\nfrom src.utils.redis_cache import get_json_cached_key, set_json_cached_key\n\nREDIS_URL = shared_config[\"redis\"][\"url\"]\nREDIS = redis.Redis.from_url(url=REDIS_URL)\n\nINDEXING_ERROR_KEY = \"indexing:error\"\nlogger = logging.getLogger(__name__)\n\n# returns the recorded skipped transactions in the db during indexing\n# filters by blocknumber, blockhash, or transaction hash if they are not null\ndef get_skipped_transactions(blocknumber, blockhash, txhash):\n db = db_session.get_db_read_replica()\n with db.scoped_session() as session:\n skipped_transactions_query = session.query(SkippedTransaction)\n if blocknumber is not None:\n skipped_transactions_query = skipped_transactions_query.filter(\n SkippedTransaction.blocknumber == blocknumber\n )\n if blockhash is not None:\n skipped_transactions_query = skipped_transactions_query.filter(\n SkippedTransaction.blockhash == blockhash\n )\n if txhash is not None:\n skipped_transactions_query = skipped_transactions_query.filter(\n SkippedTransaction.txhash == txhash\n )\n skipped_transactions_results = skipped_transactions_query.all()\n skipped_transactions_list = list(\n map(helpers.model_to_dictionary, skipped_transactions_results)\n )\n return skipped_transactions_list\n\n\ndef get_transaction_status(blocknumber, blockhash, txhash):\n \"\"\"Gets the indexing transaction status: 'PASSED', 'FAILED', or 'NOT_FOUND'\n given a blocknumber, blockhash, and transaction\n first checks whether there is an indexing error in reduis\n and whether the entry matches the given params\n otherwise checks the skipped_transactions in the database\n \"\"\"\n indexing_error = get_indexing_error(REDIS)\n\n if indexing_error:\n blocknumber_match = (\n \"blocknumber\" in indexing_error\n and indexing_error[\"blocknumber\"] == blocknumber\n )\n blockhash_match = (\n \"blockhash\" in indexing_error and indexing_error[\"blockhash\"] == blockhash\n )\n txhash_match = \"txhash\" in indexing_error and indexing_error[\"txhash\"] == txhash\n if blocknumber_match and blockhash_match and txhash_match:\n return \"FAILED\"\n\n db = db_session.get_db_read_replica()\n with db.scoped_session() as session:\n skipped_transactions_results = (\n session.query(SkippedTransaction)\n .filter(\n SkippedTransaction.blocknumber == blocknumber,\n SkippedTransaction.blockhash == blockhash,\n SkippedTransaction.txhash == txhash,\n )\n .all()\n )\n if len(skipped_transactions_results) > 1:\n raise Exception(\n \"Expected no more than 1 row for skipped indexing transaction with \\\n blocknumber={}, blockhash={}, txhash={}\".format(\n blocknumber, blockhash, txhash\n )\n )\n if len(skipped_transactions_results) == 1:\n return \"FAILED\"\n\n block_transaction_results = (\n session.query(Block)\n .filter(Block.number == blocknumber, Block.blockhash == blockhash)\n .all()\n )\n if len(block_transaction_results) > 1:\n raise Exception(\n \"Expected no more than 1 row for blocknumber={}, blockhash={}\".format(\n blocknumber, blockhash\n )\n )\n if len(block_transaction_results) == 1:\n return \"PASSED\"\n\n return \"NOT_FOUND\"\n\n\ndef get_indexing_error(redis_instance):\n indexing_error = get_json_cached_key(redis_instance, INDEXING_ERROR_KEY)\n return indexing_error\n\n\ndef set_indexing_error(\n redis_instance, blocknumber, blockhash, txhash, message, has_consensus=False\n):\n indexing_error = get_json_cached_key(redis_instance, INDEXING_ERROR_KEY)\n\n if indexing_error is None or (\n indexing_error[\"blocknumber\"] != blocknumber\n or indexing_error[\"blockhash\"] != blockhash\n or indexing_error[\"txhash\"] != txhash\n ):\n indexing_error = {\n \"count\": 1,\n \"blocknumber\": blocknumber,\n \"blockhash\": blockhash,\n \"txhash\": txhash,\n \"message\": message,\n \"has_consensus\": has_consensus,\n }\n set_json_cached_key(redis_instance, INDEXING_ERROR_KEY, indexing_error)\n else:\n indexing_error[\"count\"] += 1\n indexing_error[\"has_consensus\"] = has_consensus\n set_json_cached_key(redis_instance, INDEXING_ERROR_KEY, indexing_error)\n\n\ndef clear_indexing_error(redis_instance):\n redis_instance.delete(INDEXING_ERROR_KEY)\n","sub_path":"discovery-provider/src/queries/get_skipped_transactions.py","file_name":"get_skipped_transactions.py","file_ext":"py","file_size_in_byte":4896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"582524654","text":"# File: Grid.py\n\n# Description:\n\n# Student Name: Logan Hashmi\n\n# Student UT EID: Sah4334\n\n# Partner Name:\n\n# Partner UT EID:\n\n# Course Name: CS 303E\n\n# Unique Number: 51850\n\n# Date Created:\n\n# Date Last Modified:\n\ndef main():\n # open the file\n in_file = open(\"./grid.txt\", \"r\")\n\n # read the dimension of the grid\n dim = in_file.readline()\n dim = dim.strip()\n dim = int(dim)\n\n # create an empty grid\n grid = []\n\n # populate that grid\n for i in range(dim):\n line = in_file.readline()\n line = line.strip()\n row = line.split()\n for j in range(dim):\n row[j] = int(row[j])\n grid.append(row)\n\n # read each row in blocks of four\n row_prod = 1\n for row in grid:\n for i in range(dim - 3):\n prodrow=1\n for j in range(i, i + 4):\n prodrow = prodrow * row[j]\n if prodrow > row_prod:\n row_prod = prodrow\n\n # read each column in blocks of four\n col_prod = 1\n for j in range(dim):\n for i in range(dim - 3):\n prodcol = 1\n for k in range(i, i + 4):\n prodcol = prodcol*(grid[k][j])\n if prodcol>col_prod:\n col_prod=prodcol\n\n # go along all diagonals L to R in blocks of 4\n diag_prod = 1\n for i in range(dim - 3):\n for j in range(dim - 3):\n proddiag = 1\n for k in range(4):\n proddiag = proddiag*grid[i + k][j + k]\n if proddiag>diag_prod:\n diag_prod=proddiag\n\n #go along all diagonals R to L in blocks of 4\n right_diag_prod=1\n for i in range(dim-3):\n for j in range(dim-1,3,-1):\n prod_right=1\n for k in range(4):\n prod_right=prod_right*grid[i+k][j-k]\n if prod_right>right_diag_prod:\n right_diag_prod=prod_right\n\n #list of products\n lyst_prod=[]\n lyst_prod.append(row_prod)\n lyst_prod.append(col_prod)\n lyst_prod.append(diag_prod)\n lyst_prod.append(right_diag_prod)\n lyst_prod.sort()\n print(\"The greatest product is \"+str(lyst_prod[-1])+\".\")\n\n in_file.close()\n\nmain()\n","sub_path":"Grid.py","file_name":"Grid.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"514130710","text":"import os\nimport MakeLookupTxt\n\ndef make_val(annotation_path, write_file, lookup):\n ## 해당 OS에 맞게 정규화를 한다.\n annotation_path = os.path.normcase(annotation_path);\n\n if( not os.path.exists(annotation_path) ):\n return;\n\n save_str = ''\n\n with open(annotation_path, 'r') as rf:\n while True:\n line = rf.readline()\n if not line: break\n split_str = line.split(\"\\t\")\n\n filename = os.path.join(\"val/images/\", split_str[0])\n filename = os.path.normcase(filename);\n\n ctype = split_str[1]\n itype = lookup[ctype]\n\n save_str += '{}\\t{}\\n'.format(filename, itype)\n print(line)\n\n with open(write_file, 'a') as wf:\n wf.write(save_str)\n\nlookup = MakeLookupTxt.make_lookup(\n \"E:/Project/TinyImageNet/Data/tiny-imagenet-200/train\",\n \"E:/Project/TinyImageNet/Data/lookup.txt\"\n)\n\nmake_val(\n \"E:/Project/TinyImageNet/Data/tiny-imagenet-200/val/val_annotations.txt\",\n \"E:/Project/TinyImageNet/Data/val.txt\",\n lookup\n)\n","sub_path":"MakeValTxt.py","file_name":"MakeValTxt.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"38808432","text":"import sys\nsys.path.append('../util')\n\nfrom utils import Utils\n\n\nclass DebugUtils(object):\n @staticmethod\n def debug(game):\n DebugUtils.debug_1(game)\n # DebugUtils.debug_2(game)\n\n @staticmethod\n def debug_1(game):\n for p in game.players:\n print('player ' + p.get_name())\n for piece in p.get_pieces():\n if Utils.is_hand_piece(piece):\n print('\\tERROR {0:}\\'s {1:} {2:}'.format(piece.get_owner_name(), piece.get_name(), 'HAND'))\n else:\n print('\\t{0:}\\'s {1:} {2:} {3:}'.format(piece.get_owner_name(), piece.get_name(), piece.x, piece.y))\n for piece in p.get_hand():\n if Utils.is_hand_piece(piece):\n print('\\t{0:}\\'s {1:} {2:}'.format(piece.get_owner_name(), piece.get_name(), 'HAND'))\n else:\n print('\\tERROR {0:}\\'s {1:} {2:} {3:}'.format(piece.get_owner_name(), piece.get_name(), piece.x, piece.y))\n\n @staticmethod\n def debug_2(game):\n cells = [[0, 0], [1, 0], [2, 0],\n [0, 1], [1, 1], [2, 1],\n [0, 2], [1, 2], [2, 2],\n [0, 3], [1, 3], [2, 3]]\n for p in game.players:\n for piece in p.get_pieces():\n for c in cells:\n result = game.board.can_move_piece_to(game.board, piece, c[0], c[1])\n if result:\n print('player {0: }\\'s {1: } can move to ({2: }, {3: })'.format(piece.owner_name, piece.get_name(), c[0], c[1]))\n else:\n print('player {0: }\\'s {1: } cannot move to ({2: }, {3: })'.format(piece.owner_name, piece.get_name(), c[0], c[1]))\n\n for piece in game.players[0].get_pieces():\n print('player 0\\'s {0: } can move to {1: }'.format(piece.get_name(),\n piece.where_it_can_move_to))\n","sub_path":"impl/python3/game/debug_utils.py","file_name":"debug_utils.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"437242373","text":"def retournerMax(a,b):\n if a > b:\n return a\n return b\n\nprint(retournerMax(3,2))\nprint(retournerMax(4,9))\n\ndef sommeEntiers(m,n):\n k = 0\n cpt = m\n for i in range(0,(n-m)+1):\n k = k+m+i\n return k\n\nprint(sommeEntiers(5,10))\n","sub_path":"BTS-SIO/algorithme/1ère année/TP5-Fonctions/Algorithmes/exercice2.py","file_name":"exercice2.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"51644821","text":"import json\nimport requests\n\nclass YTstats:\n def __init__(self, api_key, channel_id):\n self.api_key = api_key\n self.channel_id = channel_id\n self.channel_statistics = None\n self.video_data = None\n\n\n # For youtube channel statistics\n def get_channel_statistics(self):\n \"\"\"Extract the channel statistics\"\"\"\n url = f'https://youtube.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics&id={self.channel_id}&key={self.api_key}'\n \n json_url = requests.get(url)\n data = json.loads(json_url.text)\n complete_channel_data=[]\n channel_data= data['items'][0]['snippet']\n \n complete_channel_data.append(channel_data)\n stats_data = data['items'][0]['statistics']\n complete_channel_data.append(stats_data)\n \n return complete_channel_data\n\n\n # For geting ids of all the videos available on the channel\n def get_channel_video_data(self):\n channel_videos= self._get_channel_videos(limit=6)\n List_of_all_video_ids= channel_videos\n url_for_stats= f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id=' \n initial=0\n for i in List_of_all_video_ids:\n if initial==0:\n url_for_stats= url_for_stats+i\n initial +=1\n url_for_stats= url_for_stats+'%2C'+i\n url_for_stats= url_for_stats + f'&key={self.api_key}'\n\n\n json_url= requests.get(url_for_stats)\n data= json.loads(json_url.text)\n first_data= data['items']\n list_of_data= []\n for i in first_data:\n temp_list= []\n temp_list.clear()\n snippet= i['snippet']\n temp_list.append(snippet)\n stats= i['statistics']\n temp_list.append(stats)\n list_of_data.append(temp_list)\n \n return list_of_data\n \n \n \n\n\n def _get_channel_videos(self, limit):\n url= f'https://www.googleapis.com/youtube/v3/search?key={self.api_key}&channelId={self.channel_id}&part=id&order=date'\n if limit is not None and isinstance(limit, int):\n url += '&maxResults=' + str(limit)\n \n vid= self._get_channel_videos_per_page(url)\n return vid\n \n \n\n\n def _get_channel_videos_per_page(self, url):\n json_url= requests.get(url)\n data= json.loads(json_url.text)\n video_raw_data= data['items']\n videos_id= []\n for i in video_raw_data:\n if i['id']['kind']== 'youtube#video':\n videos_id.append(i['id']['videoId'])\n return videos_id\n\n\n ","sub_path":"user/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"607336448","text":"def conv(n):\n a=n%100\n b=n%1000\n c=n%1000000\n d=n%1000000000\n if n==0:\n return 'zero'\n elif n<=9:\n unità=['uno','due','tre','quattro','cinque','sei','sette','otto','nove']\n return unità[n-1]\n elif n<=19:\n dieci=['dieci','undici','dodici','tredici','quattordici','quindici','sedici','diciassette','diciotto','diciannove']\n n=n%(10)\n return dieci[n]\n elif n<=99:\n decine=['venti','trenta','quaranta','cinquanta','sessanta','settanta','ottanta','novanta']\n t=n%10\n letter=decine[int(n/10)-2]\n if t==0:\n return letter\n if t==1 or t==8:\n letter=letter[ :-1]\n return letter+conv(n%10)\n elif n<=199:\n if (a)==0:\n return 'cento'\n if 80<=(a)<=89:\n return 'cent'+conv(a)\n else:\n return 'cento'+conv(a)\n elif n<=999:\n m=int(n/100)\n k=(a)+100\n if k==100:\n return conv(m)+'cento'\n else:\n return conv(m)+conv(k)\n elif n<=1999:\n if (b)==0:\n return 'mille'\n else:\n return 'mille'+conv(b)\n elif n<=999999:\n if (b)==0:\n return conv(int(n/1000))+'mila'\n else:\n return conv(int(n/1000))+'mila'+conv(b)\n elif n<=1999999:\n if (c)==0:\n return 'unmilione'\n else:\n return 'unmilione'+conv(c)\n elif n<=999999999:\n if (c)==0:\n return conv(int(n/1000000))+'milioni'\n else:\n return conv(int(n/1000000))+'milioni'+conv(c)\n elif n<=1999999999:\n if (d)==0:\n return 'unmiliardo'\n else:\n return 'unmiliardo'+conv(d)\n elif n<1000000000000:\n if (d)==0:\n return conv(int(n/1000000000))+'miliardi'\n else:\n return conv(int(n/1000000000))+'miliardi'+conv(d)\n","sub_path":"students/1813693/homework01/program02.py","file_name":"program02.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"522224539","text":"import json\nimport argparse\nfrom pathlib import Path\n\nimport numpy as np\nfrom sklearn import metrics\n\nfrom py_src.utils import read_all_predictions\nfrom py_src.utils import read_labels\nfrom py_src.utils import linear_combination\n\nJSON_SPECS_FILEPATH = '../specs.json'\nKEY_PRED_FILES = 'pred_files'\nKEY_LABELS = 'labels_file'\n\n\ndef _combine_predict(weights, all_predictions, y_true):\n predictions = linear_combination(weights, all_predictions)\n y_pred = np.argmax(predictions, axis=-1)\n \n acc = metrics.accuracy_score(y_true, y_pred)\n mf1 = metrics.f1_score(y_true, y_pred, average='macro')\n return acc, mf1\n\n\ndef uniform_combination(y_true, all_predictions):\n n_candidates = len(all_predictions)\n\n return _combine_predict(\n weights=np.ones(n_candidates) / n_candidates,\n all_predictions=all_predictions,\n y_true=y_true\n )\n\n\ndef random_combination(y_true, all_predictions):\n n_candidates = len(all_predictions)\n \n random_weights = np.random.random(n_candidates)\n random_weights /= random_weights.sum().item()\n return _combine_predict(\n weights=random_weights,\n all_predictions=all_predictions,\n y_true=y_true\n )\n\n\ndef final_combination(y_true, all_predictions, all_predictions_filepaths):\n \n def get_model_name(filepath):\n basename = Path(filepath).stem\n basename = basename[:basename.find('=')]\n return basename\n \n def get_epoch(filepath):\n dot_index = filepath.rfind('.')\n equals_index = filepath.find('=')\n \n return int(filepath[equals_index+1:dot_index])\n\n def split_by_names(filepaths):\n common = []\n cache = [filepaths[0]]\n previous = get_model_name(filepaths[0])\n\n for filepath in filepaths[1:]:\n cur_base = get_model_name(filepath)\n if cur_base != previous:\n previous = cur_base\n common.append(cache)\n cache = []\n cache.append(filepath)\n\n common.append(cache)\n return common\n \n # Initially there is a list of candidate filepaths. Split these paths\n # into smaller lists, each containing paths to each candidate checkpoint\n training_paths = split_by_names(all_predictions_filepaths)\n \n # For each candidate get only their corresponding epoch number\n training_paths_epochs = [\n [get_epoch(filepath) for filepath in path]\n for path in training_paths\n ]\n \n # Figure out what is the index of the last checkpoint (presumably\n # the best model)\n indices = [np.argmax(epochs) for epochs in training_paths_epochs]\n \n # Now it is possible to combine these guys\n return uniform_combination(\n y_true,\n [all_predictions[index] for index in indices]\n )\n\n\ndef _print_stats(name, acc, mf1):\n print(name)\n print('\\t Accuracy: {:4.4}'.format(acc))\n print('\\t Macro-F1: {:4.4}'.format(mf1))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(usage='Computes diferent ensemble baselines. Run with -h for help')\n parser.add_argument('model_name', help='Dataset used to train the model. Format: [dataset_model]. '+\n 'datasets=(dsC|dsD); model=(softmax|crf). Ex: dsC_softmax', type=str)\n\n args = parser.parse_args()\n model_name = args.model_name\n dataset_split = 'tst'\n\n all_specs = json.load(Path(JSON_SPECS_FILEPATH).open('r'))\n all_predictions_filepaths = all_specs[model_name][dataset_split][KEY_PRED_FILES]\n labels_filepath = all_specs[model_name][dataset_split][KEY_LABELS]\n\n print(f'Model name : {model_name}')\n print(f'Dataset split : {dataset_split}')\n print(f'Labels filepath : {labels_filepath}')\n\n all_predictions_filepaths = ['../' + filepath for filepath in all_predictions_filepaths]\n labels_filepath = '../' + labels_filepath\n n_samples, n_classes, all_predictions = read_all_predictions(all_predictions_filepaths)\n l_samples, l_classes, y_true = read_labels(labels_filepath)\n\n # Sanity check\n if l_samples != n_samples or l_classes != n_classes:\n print(f'n_samples = {n_samples}')\n print(f'n_classes = {n_classes}')\n print(f'l_samples = {l_samples}')\n print(f'l_classes = {l_classes}')\n raise RuntimeError('[ERROR] Amount of labels differs from the amount of predictions')\n\n acc, mf1 = uniform_combination(y_true, all_predictions)\n _print_stats('Uniform combination', acc, mf1)\n\n acc, mf1 = random_combination(y_true, all_predictions)\n _print_stats('Random combination', acc, mf1)\n \n acc, mf1 = final_combination(y_true, all_predictions, all_predictions_filepaths)\n _print_stats('Best candidates combination', acc, mf1)\n","sub_path":"experiments/metaheuristics/baselines.py","file_name":"baselines.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"288006045","text":"import turtle\n\nx1, y1 = eval(input(\"输入坐标1:\"))\nx2, y2 = eval(input(\"输入坐标2:\"))\n\njuli = ((x1-x2)**2+(y1-y2)**2)**0.5\n\nprint(x1,y1)\nprint(x2,y2)\nprint(juli)\n\nturtle.penup()\nturtle.goto(x1, y1)\nturtle.pendown()\nturtle.write(str(x1)+\",\"+str(y1))\nturtle.goto(x2, y2)\nturtle.write(str(x2)+\",\"+str(y2))\n\nturtle.penup()\nturtle.goto((x1+x2)/2,(y1+y2)/2)\nturtle.write(\"相距\"+str(juli))\n\nturtle.done()\n","sub_path":"尹成/p62_计算距离.py","file_name":"p62_计算距离.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"529685018","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Calculate possible kmers given k and sequence\ndef kmers_possible(k, sequence):\n l = len(sequence)\n result = 0\n \n # if 4 ** k is larger than the length of the sequence\n # the possible kmers cannot be 4 ** K\n if 4 ** k > l:\n result = l - k + 1\n elif 4 ** k <= l:\n result = 4 ** k\n return result\n\n# Calculate observed kmers\ndef kmers_observed(k, sequence):\n word_lists = []\n l = len(sequence)\n for m in range(l- k + 1):\n word = ''\n # combine the followiing k letters to generate a kmer \n for n in range(k):\n word = word + sequence[m+n]\n \n # save kmers in a list\n if word not in word_lists:\n word_lists.append(word)\n else:\n continue\n return len(word_lists)\n\n# create the dataframe\ndef create_dataframe(l, sequence):\n observed_kmers_lists = []\n possible_kmers_lists = []\n k_lists = []\n \n for k in range(1,l+1):\n observed_kmers = kmers_observed(k, sequence)\n possible_kmers = kmers_possible(k, sequence)\n observed_kmers_lists.append(observed_kmers)\n possible_kmers_lists.append(possible_kmers)\n k_lists.append(k)\n \n df = pd.DataFrame({\n 'k':k_lists,\n 'Observed kmers':observed_kmers_lists,\n 'Possible kmers':possible_kmers_lists,\n })\n \n \n df.set_index('k', inplace=True)\n \n \n return df\n\n# draw the graph\ndef graph(df):\n x = df.index\n y1 = df[\"Observed kmers\"]\n y2 = df[\"Possible kmers\"]\n plt.figure(figsize = (10,7))\n plt.plot(x,y1,'ro',label = 'Observed kmers', alpha = 0.6, markersize = 10)\n plt.plot(x,y2,'b^',label = 'Possible kmers', alpha = 0.6, markersize = 10)\n plt.xlabel('k')\n plt.ylabel('kmers')\n plt.legend()\n plt.show()\n\n# calculate the linguistic complexity\ndef complexity(df):\n sum_o = df[\"Observed kmers\"].sum()\n sum_p = df[\"Possible kmers\"].sum()\n return sum_o/sum_p\n\n# main function\nif __name__ == \"__main__\":\n sequence = 'ATTTGGATT'\n df = create_dataframe(9, sequence)\n print(\"========================================================================\")\n print(\"This is the dataframe\")\n print(\"========================================================================\")\n print(df)\n print(\"========================================================================\")\n print(\"The linguistic complexity is\", complexity(df))\n print(\"========================================================================\")\n graph(df)\n\n\n\n\n\n","sub_path":"kmers.py","file_name":"kmers.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"162451117","text":"import nltk\nimport math\nclass BM25:\n def __init__(self, k1=1.5, b=0.75):\n self.b = b\n self.k1 = k1\n\n def fit(self, corpus):\n \"\"\"\n Fit the various statistics that are required to calculate BM25 ranking\n score using the corpus given.\n\n Parameters\n ----------\n corpus : list[list[str]]\n Each element in the list represents a document, and each document\n is a list of the terms.\n\n Returns\n -------\n self\n \"\"\"\n tf = []\n df = {}\n idf = {}\n doc_len = []\n corpus_size = 0\n for document in corpus:\n corpus_size += 1\n doc_len.append(len(document))\n\n # compute tf (term frequency) per document\n frequencies = {}\n for term in document:\n term_count = frequencies.get(term, 0) + 1\n frequencies[term] = term_count\n\n tf.append(frequencies)\n\n # compute df (document frequency) per term\n for term, _ in frequencies.items():\n df_count = df.get(term, 0) + 1\n df[term] = df_count\n\n for term, freq in df.items():\n idf[term] = math.log(1 + (corpus_size - freq + 0.5) / (freq + 0.5))\n\n self.tf_ = tf\n self.df_ = df\n self.idf_ = idf\n self.doc_len_ = doc_len\n self.corpus_ = corpus\n self.corpus_size_ = corpus_size\n self.avg_doc_len_ = sum(doc_len) / corpus_size\n return self\n\n def search(self, query):\n scores = [self._score(query, index) for index in range(self.corpus_size_)]\n return scores\n\n def _score(self, query, index):\n score = 0.0\n\n doc_len = self.doc_len_[index]\n frequencies = self.tf_[index]\n for term in query:\n if term not in frequencies:\n continue\n\n freq = frequencies[term]\n numerator = self.idf_[term] * freq * (self.k1 + 1)\n denominator = freq + self.k1 * (1 - self.b + self.b * doc_len / self.avg_doc_len_)\n score += (numerator / denominator)\n\n return score","sub_path":"task/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"39480567","text":"import networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\n# ================ Initialisation des Graph =================\r\nG = nx.karate_club_graph()\r\n######################################\r\n# G=nx.davis_southern_women_graph()\r\n######################################\r\n# G=nx.dodecahedral_graph()\r\n######################################\r\n# G = nx.Graph()\r\n# G.add_edges_from([(\"A\", \"D\"), (\"A\", \"I\"), (\"A\", \"C\"), (\"A\", \"E\"), (\"A\", \"F\"), (\"A\", \"H\"),\r\n# (\"B\", \"I\"), (\"B\", \"H\"), (\"B\", \"G\"), (\"B\", \"F\"), (\"B\", \"E\"), (\"B\", \"D\"), (\"B\", \"L\"),\r\n# (\"C\", \"J\"), (\"C\", \"K\")])\r\n######################################\r\nG = nx.read_gml('football.gml')\r\n\r\n# ===========================================================\r\n\r\n####### Betweenness Centrality #######\r\nbetween = {}\r\nN = G.number_of_nodes()\r\n\r\nbetween = {}\r\ndef betweenness():\r\n for v in G:\r\n # print(v)\r\n segma_st = 0\r\n segma_st_v = 0\r\n help = []\r\n for s in G:\r\n for t in G:\r\n if (t, s) in help:\r\n continue\r\n help.append((s, t))\r\n sp = nx.all_shortest_paths(G, source=s, target=t)\r\n if v == s or v == t:\r\n continue\r\n elif s == t:\r\n segma_st = segma_st + 1\r\n continue\r\n else:\r\n for p in sp:\r\n segma_st = segma_st + 1\r\n # print(p)\r\n if v in p:\r\n segma_st_v = segma_st_v + 1\r\n # print(p)\r\n\r\n # print('segma_st_v: %s' % (segma_st_v))\r\n # print('segma_st: %s' % (segma_st))\r\n if segma_st != 0:\r\n between[v] = segma_st_v / segma_st\r\n\r\n\r\nbetweenness()\r\n# print(between)\r\n# print(nx.betweenness_centrality(G))\r\nmaxBetween = max(between.values())\r\n\r\n######################################\r\n\r\n##======== Affichage du réseau =======================\r\ndictR = between\r\nmaxDictR = maxBetween\r\n###### LAbels ####################\r\nlabels = {}# print(labels)\r\n\r\ni = 0\r\nfor key, value in dictR.items():\r\n labels[i] = str(key) + \"\\n\" + str(float(\"{0:.2f}\".format(value)))\r\n i = i + 1\r\n######################################\r\n\r\n########## Positions To int ##########\r\npos = nx.spring_layout(G)\r\nposI = {}\r\ni = 0\r\nfor key, value in pos.items():\r\n posI[i] = value\r\n i = i + 1\r\n# print(pos)\r\n# print(posI)\r\n######################################\r\nnx.draw_networkx_nodes(G, pos,\r\n node_color='r',\r\n node_size=[(i / maxDictR) * 2000 for i in list(dictR.values())],\r\n alpha=0.9)\r\nnx.draw_networkx_edges(G, pos, width=1.0, alpha=0.8)\r\nnx.draw_networkx_labels(G, posI, labels, font_size=8)\r\n# nx.draw_networkx(G)\r\nplt.axis('off')\r\nplt.show()\r\n# ===================================================","sub_path":"betweenness_centrality.py","file_name":"betweenness_centrality.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"89535540","text":"from os import path, getcwd\n###############\nDEBUG = False # \nPORT = 5000 #\n###############\nSECRET_KEY = 'secretkeydonthackplease' # key to secret sessions. keep it a complete secret!\nUPLOAD_FOLDER = path.join(getcwd(), 'data') # ./data as default. Folder with loaded files. You can enter your path\nZIP_FOLDER = path.join(getcwd(), 'temp_data') # ./temp_data as default. Folder with zipped files. You can enter your path\nLOG_FOLDER = path.join(getcwd(), 'logs') # ./logs as default. Folder with logs. You can enter your path\nCONFIG_PATH = path.join(getcwd(), 'settings.json') # path to json config file\nTELEGRAM_PATH = path.join(getcwd(), 'telegram_users.json') # path to telegram json database\nDB_NAME = 'gorbin' # name of Mongo database\nUSERS_COL_NAME = 'users' # name of the users collection \nFILES_COL_NAME = 'files' # name of the files collection\nMONGO_ADDRESS = 'mongodb://localhost:27017/' # MongoDB address\nBOT_TOKEN = None #Telegram bot token\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"441151372","text":"import math\nimport vincenty\nimport time\nimport haversine\nearth_mean_r = 6371.009\n\ndef big_circle_distance(cord1, cord2):\n cord1 = (math.radians(cord1[0]), math.radians(cord1[1]))\n cord2 = (math.radians(cord2[0]), math.radians(cord2[1]))\n dlat = cord1[0] - cord2[0]\n dlong = cord1[1] - cord2[1]\n d = 2 * math.asin(\n math.sqrt(pow(math.sin(dlat/2), 2) +\n math.cos(cord1[0])*math.cos(cord2[0]) *\n pow(math.sin((dlong)/2), 2))\n ) * earth_mean_r\n return d\n\ndef vincenty_distance(cord1, cord2):\n return vincenty.vincenty(cord1, cord2)\n\ndef haversine_distance(cord1, cord2):\n return haversine.haversine(cord1, cord2)\n\ncord1 = (59.353412, 17.979406)\ncord2 = (59.353850, 18.032621)\n\nprint(\"big_circle_distance %f\" % (big_circle_distance(cord1, cord2)*1000))\nprint(\"vincenty_distance %f\" % (vincenty_distance(cord1, cord2)*1000))\nprint(\"haversine_distance %f\" % (haversine_distance(cord1, cord2)*1000))\n\ndef timeit(func, args, iterations=10000):\n time1 = time.time()\n for i in range(0, iterations):\n func(*args)\n time2 = time.time()\n print('%s function took %0.3f ms' % (func.__name__, (time2-time1)*1000.0))\n\ntimeit(big_circle_distance, [cord1, cord2])\ntimeit(vincenty_distance, [cord1, cord2])\ntimeit(haversine_distance, [cord1, cord2])\n\ndef circle_to_box(point, radius, comp=True):\n ne_rad = math.radians(315)\n sw_rad = math.radians(135)\n pointne = None\n pointsw = None\n d_rad = (math.hypot(radius, radius)/1000)/earth_mean_r\n point_rad = convert_point(point, math.radians)\n def calc_comp(point, d, tc):\n # Thanks to: http://williams.best.vwh.net/avform.htm#LL\n lat = math.asin(math.sin(point[0])*math.cos(d)+math.cos(point[0])*math.sin(d)*math.cos(tc))\n dlon = math.atan2(\n math.sin(tc)*math.sin(d)*math.cos(point[0]),\n math.cos(d)-math.sin(point[0])*math.sin(lat)\n )\n lon = math.fmod(point[1]-dlon+math.pi, 2*math.pi)-math.pi\n return (lat, lon)\n def calc_simple(point, d, tc):\n # Thanks to: http://williams.best.vwh.net/avform.htm#LL\n lat = math.asin(math.sin(point[0])*math.cos(d)+math.cos(point[0])*math.sin(d)*math.cos(tc))\n if math.cos(lat) == 0:\n lon = point[1]\n else:\n lon = math.fmod(point[1]-math.asin(math.sin(tc)*math.sin(d)/math.cos(lat))+math.pi, 2*math.pi)-math.pi\n return (lat, lon)\n\n if comp:\n pointne = calc_comp(point_rad, d_rad, ne_rad)\n pointsw = calc_comp(point_rad, d_rad, sw_rad)\n else:\n pointne = calc_simple(point_rad, d_rad, ne_rad)\n pointsw = calc_simple(point_rad, d_rad, sw_rad)\n return (convert_point(pointne, math.degrees), convert_point(pointsw, math.degrees))\n\ndef convert_point(point, to):\n return to(point[0]), to(point[1])\n\nbox = circle_to_box(cord1, 1000)\nprint('circle_to_box_complex: %s: %s' % box)\ntimeit(circle_to_box, [cord1, 1000])\n\nbox = circle_to_box(cord1, 1000, comp=False)\nprint('circle_to_box_simple: %s: %s' % box)\ntimeit(circle_to_box, [cord1, 1000, False])\n","sub_path":"geotest.py","file_name":"geotest.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"336825664","text":"from flask import Flask,request,jsonify,abort\nimport get_faces\nimport Face_Detection\nimport json\nimport remove_face\nimport multiprocessing\n\n\napp = Flask(__name__)\n\nkeys=\"123\"\ncpu=4\n\n\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\n\n\n@app.route('/add', methods=[\"POST\"])\ndef add():\n j=json.loads(request.get_data())\n base = j['base']\n key = j['key']\n name = j['name']\n id =j['id']\n #print( j )\n if(key==keys):\n #s = multiprocessing.Process(target=get_faces.save_sql, args=(base,name,id))\n s= get_faces.save_sql(base,name,id)\n #s.start()\n if s==1:\n t = {\n 'code': 1,\n 'text': \"录入成功\"\n }\n else:\n t = {\n 'code': 0,\n 'text': \"没有找到人脸或者找到多张人脸\"\n }\n else:\n t = {\n 'code': 0,\n 'text':\"秘钥错误\"\n }\n\n return jsonify(t)\n\n\n@app.route('/find', methods=[\"POST\"])\ndef find():\n j = json.loads(request.get_data())\n base = j['base']\n key = j['key']\n if (key == keys):\n s =Face_Detection.Detection(base)\n #s = multiprocessing.Process(target=Face_Detection.Detection, args=(base,))\n #s.start()\n #print(s)\n r={\"face\":s}\n #print(r)\n r.setdefault('code',1)\n r.setdefault('text', \"成功比对\")\n else:\n r = {\n 'code': 0,\n 'text':\"秘钥错误\"\n }\n return jsonify(r)\n\n@app.route('/del', methods=[\"POST\"])\ndef delete():\n j = json.loads(request.get_data())\n key = j['key']\n name = j['name']\n id =j['id']\n if (key == keys):\n s= remove_face.remove(name,id)\n if s==1:\n t = {\n 'code': 1,\n 'text': \"删除成功\"\n }\n else:\n t = {\n 'code': 0,\n 'text': \"没有找到该用户\"\n }\n else:\n t = {\n 'code': 0,\n 'text':\"秘钥错误\"\n }\n return jsonify(t)\n\n\nif __name__ == '__main__':\n #app.run()\n app.run(processes=cpu,threaded=False)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"336880538","text":"par = []\nimpar = []\ntodos = list()\nmai = men = 0\nfor c in range(0, 7):\n n = int(input('Enter a number: '))\n if n % 2 == 0:\n par.append(n)\n else:\n impar.append(n)\ntodos.append(par[:])\ntodos.append(impar[:])\nprint(f'Even: {sorted(todos[0])}')\nprint(f'Odd: {sorted(todos[1])}')\n\n\n\n\n\n\n\n","sub_path":"exercicosPython/exercises/ex001_114/ex085separate.py","file_name":"ex085separate.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"57501282","text":"from django.contrib.auth.models import AnonymousUser\nfrom django.contrib.auth import get_user_model\n\n\nclass AuthenticationMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n auth = request.headers.get('Authorization')\n if auth is not None:\n prefix = 'Bearer'\n parts = auth.split(' ')\n\n if len(parts) != 2 or parts[0] != prefix:\n raise Exception(\"Improperly formed token\")\n\n # request.user = get_user_model().objects.get(id=1)\n else:\n request.user = AnonymousUser()\n return self.get_response(request)\n","sub_path":"authentication/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"371203832","text":"\"\"\"\nQuesta classe si occupa di effettuare le domande quando è stato scelto l'utilizzo in viaggio.\nRichiama la classe di Machine learning una volta settati tutti i parametri necessari.\n\"\"\"\n\nfrom tkinter import *\nfrom PIL import ImageTk, Image\n\n\nclass Race:\n\n def RaceQuestion(self, frame):\n ColorBttn = \"#BADEC0\"\n ColorBttnTxtree = \"#455a64\"\n ColorBttnTxT = \"#ff8f00\"\n\n frame.grid(row=0, column=0, columnspan=5, rowspan=5)\n\n canvasN = Canvas(frame, width=1230, height=660)\n imageN = ImageTk.PhotoImage(Image.open(\"img/DecisionCarRace.png\"))\n canvasN.create_image(0, 0, anchor=NW, image=imageN)\n canvasN.grid(row=0, column=0, columnspan=5, rowspan=5)\n\n def Tree():\n from img.TreePng import ShowTree\n ShowTree(frame, \"RACE\")\n\n def PrintResult(value, q2, q3, q4, q5, q6):\n def db():\n from Dataset import Database\n Database.DatabaseConnection(value, \"RACE\", q2, q3, q4, q5, q6)\n\n def Home():\n from DecisionML import Decision\n Decision(frame)\n\n l1 = Label(frame, text=\"Ti consiglio di acquistare\", background=\"#c8e6c9\", foreground=\"#43a047\",\n font=(\"Helvetica\", 50))\n b3 = Button(frame, text=\"Home\", width=15, background=ColorBttn,\n command=Home,\n font=('Courrier', '15'),\n foreground=ColorBttnTxtree)\n l3 = Label(frame, text=value, background='#c8e6c9', foreground=\"#e57373\",\n font=(\"Helvetica\", 70))\n b1 = Button(frame, text=\"Visualizza Albero\", width=15, background=ColorBttn,\n command=Tree,\n font=('Courrier', '15'),\n foreground=ColorBttnTxtree)\n b2 = Button(frame, text=\"Caratteristiche\", width=15, background=ColorBttn,\n command=db,\n font=('Courrier', '15'),\n foreground=ColorBttnTxtree)\n\n l1.grid(row=0, column=4)\n b3.grid(row=4, column=4)\n l3.grid(row=1, column=4)\n b1.grid(row=2, column=4)\n b2.grid(row=3, column=4)\n\n def CallMachineLearnng(q1, q2, q3, q4, q5, q6):\n from Prediction import DecisionTreeAll\n predizioneTrip = DecisionTreeAll.DecisionML.Decison(\"self\", q1, q2, q3, q4, q5, q6)\n PrintResult(predizioneTrip, q2, q3, q4, q5, q6)\n\n def Question1_6(q1, q2, q3, q4, q5):\n enterprice = StringVar(value=\"euro\")\n\n def setPrice():\n ChoiceQ1_6 = enterprice.get()\n destryAll()\n CallMachineLearnng(q1, q2, q3, q4, q5, ChoiceQ1_6)\n\n l1 = Label(frame, text=\"Quale prezzo preferiresti?\", background=\"#c8e6c9\", foreground=\"#43a047\",\n font=(\"Helvetica\", 50))\n insertPrice = Entry(frame, textvariable=enterprice, background=\"#DFF0E0\", foreground=ColorBttnTxtree,\n font=(\"Helvetica\", 30), border = 0)\n l1.grid(row=0, column=4)\n insertPrice.grid(row=1, column=4)\n b3 = Button(frame, text=\"Inserisci\", width=15, background=ColorBttn,\n command=setPrice,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b3.grid(row=2, column=4)\n\n def destryAll():\n l1.destroy()\n insertPrice.destroy()\n b3.destroy()\n\n def Question1_5(q1, q2, q3, q4):\n def setBenz():\n ChoiceQ1_5 = \"BENZ\"\n destryAll()\n Question1_6(q1, q2, q3, q4, ChoiceQ1_5)\n\n def setDis():\n ChoiceQ1_5 = \"DIS\"\n destryAll()\n Question1_6(q1, q2, q3, q4, ChoiceQ1_5)\n\n def setNotCarb():\n ChoiceQ1_5 = \"NOTCARB\"\n destryAll()\n Question1_6(q1, q2, q3, q4, ChoiceQ1_5)\n\n l1 = Label(frame, text=\"Quale tipo di carburante\", background=\"#c8e6c9\", foreground=\"#43a047\",\n font=(\"Helvetica\", 60))\n l2 = Label(frame, text=\"preferisci?\", background='#c8e6c9', foreground=\"#43a047\",\n font=(\"Helvetica\", 50))\n\n l1.grid(row=0, column=4)\n l2.grid(row=1, column=4)\n b1 = Button(frame, text=\"Benzina\", width=15, background=ColorBttn,\n command=setBenz,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b2 = Button(frame, text=\"Diesel\", width=15, background=ColorBttn,\n command=setDis,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b3 = Button(frame, text=\"Salta\", width=15, background=ColorBttn,\n command=setNotCarb,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b1.grid(row=2, column=4)\n b2.grid(row=3, column=4)\n b3.grid(row=4, column=4)\n\n def destryAll():\n l1.destroy()\n l2.destroy()\n b1.destroy()\n b2.destroy()\n b3.destroy()\n\n def Question1_4(q1, q2, q3):\n def setAnt():\n ChoiceQ1_4 = \"ANT\"\n destryAll()\n Question1_5(q1, q2, q3, ChoiceQ1_4)\n\n def setPost():\n ChoiceQ1_4 = \"POST\"\n destryAll()\n Question1_5(q1, q2, q3, ChoiceQ1_4)\n\n def setNot():\n ChoiceQ1_4 = \"NOT\"\n destryAll()\n Question1_5(q1, q2, q3, ChoiceQ1_4)\n\n l1 = Label(frame, text=\"Quale tipo di trazione\", background=\"#c8e6c9\", foreground=\"#43a047\",\n font=(\"Helvetica\", 60))\n l2 = Label(frame, text=\"preferisci?\", background='#c8e6c9', foreground=\"#43a047\",\n font=(\"Helvetica\", 50))\n\n l1.grid(row=0, column=4)\n l2.grid(row=1, column=4)\n b1 = Button(frame, text=\"Anteriore\", width=15, background=ColorBttn,\n command=setAnt,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b2 = Button(frame, text=\"Posteriore\", width=15, background=ColorBttn,\n command=setPost,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b3 = Button(frame, text=\"Salta\", width=15, background=ColorBttn,\n command=setNot,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b1.grid(row=2, column=4)\n b2.grid(row=3, column=4)\n b3.grid(row=4, column=4)\n\n def destryAll():\n l1.destroy()\n l2.destroy()\n b1.destroy()\n b2.destroy()\n b3.destroy()\n\n def Question1_3(q1, q2):\n def setYes():\n ChoiceQ1_3 = True\n destryAll()\n Question1_4(q1, q2, ChoiceQ1_3)\n\n def setNo():\n ChoiceQ1_3 = False\n destryAll()\n Question1_4(q1, q2, ChoiceQ1_3)\n\n l1 = Label(frame, text=\"Preferisci un auto di\", background=\"#c8e6c9\", foreground=\"#43a047\",\n font=(\"Helvetica\", 60))\n l2 = Label(frame, text=\"ridotte dimensioni?\", background='#c8e6c9', foreground=\"#43a047\",\n font=(\"Helvetica\", 50))\n\n l1.grid(row=0, column=4)\n l2.grid(row=1, column=4)\n b1 = Button(frame, text=\"Si\", width=15, background=ColorBttn,\n command=setYes,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b2 = Button(frame, text=\"No\", width=15, background=ColorBttn,\n command=setNo,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b1.grid(row=2, column=4)\n b2.grid(row=3, column=4)\n\n def destryAll():\n l1.destroy()\n l2.destroy()\n b1.destroy()\n b2.destroy()\n\n def Question1_2(q1):\n def setThree():\n ChoiceQ1_2 = \"Three\"\n destryAll()\n Question1_3(q1, ChoiceQ1_2)\n\n def setFive():\n ChoiceQ1_2 = \"Five\"\n destryAll()\n Question1_3(q1, ChoiceQ1_2)\n\n l1 = Label(frame, text=\"Quante porte preferisci?\", background=\"#c8e6c9\", foreground=\"#43a047\",\n font=(\"Helvetica\", 60))\n l1.grid(row=0, column=4)\n b1 = Button(frame, text=\"Tre\", width=15, background=ColorBttn,\n command=setThree,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b2 = Button(frame, text=\"Cinque\", width=15, background=ColorBttn,\n command=setFive,\n font=('Courrier', '20'),\n foreground=ColorBttnTxT)\n\n b1.grid(row=2, column=4)\n b2.grid(row=3, column=4)\n\n def destryAll():\n l1.destroy()\n b1.destroy()\n b2.destroy()\n\n Question1_2(\"trip\")\n mainloop()\n\n def __init__(self, frame):\n frame.grid_forget()\n Race.RaceQuestion(self, frame)\n","sub_path":"Gui_Ques/All.py","file_name":"All.py","file_ext":"py","file_size_in_byte":9769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"431431856","text":"from __future__ import annotations\nfrom abc import ABC, abstractmethod\nimport mailparser\nfrom email.parser import Parser\nfrom email import message_from_string\n\nclass EmailParser(ABC):\n\n def __init__(self):\n self.to = \"\"\n self.from_ = \"\"\n self.date = \"\"\n self.subject = \"\"\n self.message_id = \"\"\n super().__init__()\n\n @abstractmethod\n def parse_from_string(self, message):\n pass\n\n\nclass PythonEmailParser(EmailParser):\n\n def parse_from_string(self, email_message):\n parser = Parser()\n msg = parser.parsestr(email_message)\n print(msg)\n self.to = msg['to']\n self.from_ = msg['from']\n self.date = msg['date']\n self.subject = msg['subject']\n self.message_id = msg['message-id']\n\n\nclass MailParserEmailParser(EmailParser):\n \n def __init__(self):\n super().__init__()\n self.mailparser = None\n\n def parse_from_string(self, message):\n self.mailparser = mailparser.parse_from_string(message)\n if self.mailparser.to:\n self.to = self.mailparser.to\n if self.mailparser.from_:\n self.from_ = self.mailparser.from_\n if self.mailparser.date_raw:\n self.date = self.mailparser.date_raw.replace('[','').replace(']','').replace('\"','')\n if self.mailparser.subject:\n self.subject = self.mailparser.subject\n if self.mailparser.message_id:\n self.message_id = self.mailparser.message_id\n \nclass EmailParseStrategy(object):\n\n def __init__(self, parser: EmailParser):\n self.mailparser = parser\n\n @property\n def emailParser(self) -> EmailParser:\n return self.mailparser\n\n @emailParser.setter\n def setParser(self, parser: EmailParser):\n self.mailparser = parser\n\n def parse_email_from_string(self, message):\n return self.mailparser.parse_from_string(message)\n","sub_path":"email_api/parsers/email_parser.py","file_name":"email_parser.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"28834814","text":"import uuid\nfrom datetime import datetime\n\nimport models\n\ntime = \"%Y-%m-%dT%H:%M:%S\"\n\n\nclass BaseModel:\n\n def __init__(self, **kwargs):\n \"\"\"This method instantiates an object\"\"\"\n self.id = str(uuid.uuid4())\n self.created_at = datetime.utcnow()\n self.updated_at = self.created_at\n\n if kwargs:\n for key, value in kwargs.items():\n if key == 'created_at' or key == 'updated_at':\n value = datetime.strptime(value, time)\n\n if key != \"__class__\":\n setattr(self, key, value)\n\n def __str__(self):\n \"\"\"String representation of the BaseModel class\"\"\"\n return \"[{:s}] ({:s}) {}\".format(self.__class__.__name__, self.id,\n self.__dict__)\n\n def save(self, dest=\"objects\"):\n \"\"\"updates the attribute 'updated_at' with the current datetime\"\"\"\n self.updated_at = datetime.utcnow()\n models.storage.new(self, dest)\n models.storage.save(dest)\n\n def to_dict(self):\n \"\"\"Returns a dictionary containing all keys/values of the instance.\"\"\"\n new_dict = self.__dict__.copy()\n new_dict[\"created_at\"] = new_dict[\"created_at\"].strftime(time)\n new_dict[\"updated_at\"] = new_dict[\"updated_at\"].strftime(time)\n new_dict[\"__class__\"] = self.__class__.__name__\n new_dict.pop(\"_sa_instance_state\", None)\n return new_dict\n\n def delete(self, dest='objects'):\n \"\"\"delete the current instance from the storage\"\"\"\n models.storage.delete(self, dest)\n","sub_path":"models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"142415259","text":"from backend.services import services\nfrom urllib.parse import urlparse\n\ndef parse_url(url):\n '''\n takes a validated url pointing to an item on\n a supported streaming service and returns a \n query to be used with other streaming services\n\n Parameters:\n url (str): the url to be parsed\n \n Returns:\n query (Query): the query object to be used\n with other streaming services\n '''\n\n hygienic_url = urlparse(url)\n loc = hygienic_url.netloc\n for service in services.keys():\n if (loc in services[service].NETLOCS):\n return services[service].parse_link(url)","sub_path":"heroku-code/backend/parse_url.py","file_name":"parse_url.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"279122631","text":"# -*- coding: utf-8 -*-\r\n'''\r\n The Unofficial KissAnime Plugin, aka UKAP - a plugin for Kodi\r\n Copyright (C) 2016 dat1guy\r\n\r\n This file is part of UKAP.\r\n\r\n UKAP is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n UKAP is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with UKAP. If not, see .\r\n'''\r\n\r\n\r\nfrom resources.lib.common.helpers import helper\r\nfrom resources.lib.common import constants\r\nfrom resources.lib.list_types.media_container_list import MediaContainerList\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\nclass BookmarkList(MediaContainerList):\r\n ''' PUBLIC FUNCTIONS '''\r\n def parse(self):\r\n helper.start('BookmarkList.parse')\r\n if self.soup == None:\r\n return\r\n\r\n MediaContainerList.parse(self)\r\n self.bookmark_dict = {}\r\n table = self.soup.find('table', class_='listing')\r\n remove_bookmark_links = table.find_all('a', class_='aRemove')\r\n for link in remove_bookmark_links:\r\n self.bookmark_dict[link['mname']] = link['mid']\r\n\r\n helper.end('BookmarkList.parse')\r\n\r\n ''' OVERRIDDEN PROTECTED FUNCTIONS '''\r\n def _get_contextmenu_items(self, url, name, metadata, media_type):\r\n items = MediaContainerList._get_contextmenu_items(self, url, name, metadata, media_type)\r\n remove_id = self.bookmark_dict[name]\r\n query = self._construct_query(remove_id, 'removeBookmark', metadata, name, media_type)\r\n cm_item = constants.runplugin % helper.build_plugin_url(query)\r\n items.insert(1, ('Remove bookmark', cm_item))\r\n return items","sub_path":"resources/lib/list_types/bookmarklist.py","file_name":"bookmarklist.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"408623670","text":"import pandas as pd \nimport numpy as np \nimport sys\n\nimport dash\nfrom dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom pandas_datareader import data as web\nfrom datetime import datetime as dt\nimport plotly.graph_objs as go\n\n\ndf = pd.read_csv('GS_all_GSIDs_Company_names.csv')\ndf.drop(['Unnamed: 0'],axis = 1,inplace = True)\n\ncompany_groups = df.groupby(['company_name']).groups#['userid'].value_counts()\nkey1 = 'Apple Inc'\ndate = df.iloc[company_groups[key1]]['date']\n\ndf['year'] = pd.DatetimeIndex(df['date']).year\ncompany_2017_growthscores = df.groupby(['year','company_name'])['growthScore'].mean()\ncg = company_2017_growthscores[2017]. sort_values(ascending = False)[:5]\ncgg = pd.DataFrame(cg)\ncgg['company_name'] = cgg.index\ncgg = cgg[['company_name','growthScore']]\ncgg = cgg.round(3)\ncompany_2017_multiplescore = df.groupby(['year','company_name'])['multipleScore'].mean()\ncm = company_2017_multiplescore[2017]. sort_values(ascending = True)[:5]\ncmm = pd.DataFrame(cm)\ncmm['company_name'] = cmm.index\ncmm = cmm[['company_name','multipleScore']]\ncmm = cmm.round(3)\ncompany_2017_financialreturnscore = df.groupby(['year','company_name'])['financialReturnsScore'].mean()\ncf = company_2017_financialreturnscore[2017]. sort_values(ascending = False)[:5]\ncff = pd.DataFrame(cf)\ncff['company_name'] = cff.index\ncff = cff[['company_name','financialReturnsScore']]\ncff = cff.round(3)\n\n\napp = dash.Dash()\ncolors = {\n 'background': '#111111',\n 'text': 'Teal'\n}\n\ndef generate_table(dataframe, max_rows=5):\n return html.Table(\n # Header\n [html.Tr([html.Th(col) for col in dataframe.columns])] +\n\n # Body\n [html.Tr([\n html.Td(dataframe.iloc[i][col]) for col in dataframe.columns\n ]) for i in range(min(len(dataframe), max_rows))]\n )\n\n\napp.layout = html.Div([\n \n dcc.Tabs(id=\"tabs\", children=[\n dcc.Tab(label='Explore', children=[\n html.Div([\n html.H1('Examine Stock',style={\n 'textAlign': 'center',\n 'color': colors['text']\n }),\n dcc.Dropdown(\n id='my-dropdown',\n options=[{'label': i, 'value': i} for i in list(df['company_name'].drop_duplicates())],\n value='Carnival Corp'\n ),\n dcc.Graph(id='my-graph1',\n figure={\n 'layout': {\n 'height': 600\n }\n }),\n ])\n ]),\n dcc.Tab(label='Analyze', children=[\n html.Div([\n html.Div([\n html.H1('Compare Stocks',style={\n 'textAlign': 'center',\n 'color': colors['text'],\n 'font' : 'Helvetica Light'\n }),\n dcc.Dropdown(\n id='company_1',\n options=[{'label': i, 'value': i} for i in list(df['company_name'].drop_duplicates())],\n value='Carnival Corp'\n ),\n dcc.Dropdown(\n id='company_2',\n options=[{'label': i, 'value': i} for i in list(df['company_name'].drop_duplicates())],\n value='Tesla Inc',\n ),\n dcc.Dropdown(\n id='company_3',\n options=[{'label': i, 'value': i} for i in list(df['company_name'].drop_duplicates())],\n value='Apple Inc',\n ),\n dcc.Dropdown(\n id='company_4',\n options=[{'label': i, 'value': i} for i in list(df['company_name'].drop_duplicates())],\n value='Target Corp',\n ),\n dcc.RadioItems(\n id='my_button',\n options = [{'label': 'Integrated Score', 'value': 'integratedScore'},\n {'label': 'Growth Score', 'value': 'growthScore'},\n {'label': 'Multiple Score', 'value': 'multipleScore'},\n {'label': 'Financial Returns Score', 'value': 'financialReturnsScore'}],\n labelStyle={'display': 'inline-block', 'font' : 'Helvetica Light'},\n value = 'integratedScore'\n ),\n ]),\n dcc.Graph(id='my-graph2',\n figure={\n 'layout': {\n 'height': 600\n }\n }),\n ])\n ]),\n dcc.Tab(label='Our Picks', children=[\n html.Div([\n html.Div([\n html.H1('Recommended Stocks',style={\n 'textAlign': 'center',\n 'color': colors['text'],\n 'font' : 'Times New Roman'\n }),\n\n \n html.H2('High Growth',style={\n 'textAlign': 'Center',\n 'color': colors['text'],\n 'font' : 'Times New Roman'\n }),\n\n generate_table(cgg),\n \n html.P(\"The first category focuses on investments that have high upside in the near future,\\\n but also come with a substantial amount of risk. We placed more importance on growth and overlooked \\\n the multiple factor when developing our algorithm to choose the set of investments that could have\\\n rapid progress in the short term.\"\n ,style={\n 'textAlign': 'Center',\n 'font' : 'Times New Roman'\n }\n ),\n \n html.P(cg.index.values + \" \" + \" . \" + \" \"\n ,style={\n 'textAlign': 'Center',\n 'font' : 'Times New Roman'\n }),\n\n html.H2('Great Value',style={\n 'textAlign': 'Center',\n 'color': colors['text'],\n 'font' : 'Times New Roman'\n }),\n \n generate_table(cmm),\n\n html.P(\"These stocks are diamonds in the rough. They are not valued at the price they deserve\",\n style={\n 'textAlign': 'Center',\n 'font' : 'Times New Roman'\n }),\n html.P(cm.index.values + \" \" + \" . \" + \" \",\n style={\n 'textAlign': 'Center',\n 'font' : 'Times New Roman'\n }),\n\n\n html.H2('Consistent Returns',style={\n 'textAlign': 'Center',\n 'color': colors['text'],\n 'font' : 'Times New Roman'\n }),\n\n generate_table(cff),\n\n html.P(\"These stocks are reliable blue chips. You can expect them to keep paying dividends. Pensioners or people making a living off of capital gains should take note of these stocks\",\n style={\n 'textAlign': 'Center',\n 'font' : 'Times New Roman'\n }),\n html.P(cf.index.values + \" \" + \" . \" + \" \"\n ,style={\n 'textAlign': 'Center',\n 'font' : 'Times New Roman'\n })\n\n\n ],className='container', style={'maxWidth': '1000px'}),\n ],className='container', style={'maxWidth': '1000px'})\n ], style={'maxWidth': '1500px','font': 'Times New Roman'})\n \n ], style={'maxWidth': '1500px','font': 'Times New Roman'})\n \n ], style={'maxWidth': '1500px','font': 'Times New Roman'})\n\n@app.callback(Output('my-graph1', 'figure'), [Input('my-dropdown', 'value')])\ndef update_graph(selected_dropdown_value):\n \n trace0 = go.Scatter(\n x = df.iloc[company_groups[key1]]['date'],\n y = df.iloc[company_groups[selected_dropdown_value]]['growthScore'],\n mode = 'lines',\n name = 'growthScore'\n )\n trace1 = go.Scatter(\n x = df.iloc[company_groups[key1]]['date'],\n y = df.iloc[company_groups[selected_dropdown_value]]['multipleScore'],\n mode = 'lines',\n name = 'multipleScore'\n )\n trace2 = go.Scatter(\n x = df.iloc[company_groups[key1]]['date'],\n y = df.iloc[company_groups[selected_dropdown_value]]['financialReturnsScore'],\n mode = 'lines',\n name = 'financialReturnsScore'\n )\n trace3 = go.Scatter(\n x = df.iloc[company_groups[key1]]['date'],\n y = df.iloc[company_groups[selected_dropdown_value]]['integratedScore'],\n mode = 'lines',\n name = 'integratedScore'\n )\n\n data = [trace0, trace1, trace2, trace3]\n\n\n return {\n 'data': data\n }\n\n\n@app.callback(dash.dependencies.Output('my-graph2', 'figure'),\n [dash.dependencies.Input('company_1', 'value'),\n dash.dependencies.Input('company_2', 'value'),\n dash.dependencies.Input('company_3', 'value'),\n dash.dependencies.Input('company_4', 'value'),\n dash.dependencies.Input('my_button', 'value')])\ndef update_graph2(company_1_name, company_2_name,\n company_3_name, company_4_name,\n my_button_value):\n \n trace0 = go.Scatter(\n x = df.iloc[company_groups[key1]]['date'],\n y = df.iloc[company_groups[company_1_name]][my_button_value],\n mode = 'lines',\n name = company_1_name\n )\n trace1 = go.Scatter(\n x = df.iloc[company_groups[key1]]['date'],\n y = df.iloc[company_groups[company_2_name]][my_button_value],\n mode = 'lines',\n name = company_2_name\n )\n trace2 = go.Scatter(\n x = df.iloc[company_groups[key1]]['date'],\n y = df.iloc[company_groups[company_3_name]][my_button_value],\n mode = 'lines',\n name = company_3_name\n )\n trace3 = go.Scatter(\n x = df.iloc[company_groups[key1]]['date'],\n y = df.iloc[company_groups[company_4_name]][my_button_value],\n mode = 'lines',\n name = company_4_name\n )\n\n data = [trace0, trace1, trace2, trace3]\n\n\n return {\n 'data': data\n }\n\nif __name__ == '__main__':\n app.run_server()\n","sub_path":"Marquee_Analysis_FrontEnd.py","file_name":"Marquee_Analysis_FrontEnd.py","file_ext":"py","file_size_in_byte":12060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"186037379","text":"from mate.vm.constants import ReflectiveOp\n\nclass MOPDispatcher(object):\n\n\tSemantics_IDX = 0\n\tLayout_IDX = 1\n\tMessage_IDX = 2\n\n\t@staticmethod\n\tdef lookup_invokable(universe, reflective_op, enviroment):\n\n\t\tmetaclass = MOPDispatcher.meta_class_for_operation(reflective_op, enviroment)\n\t\tif not metaclass:\n\t\t\treturn None\n\n\t\tselector = MOPDispatcher.selector_for_operation(universe, reflective_op)\n\t\tif not selector:\n\t\t\treturn None\n\n\t\treturn metaclass.get_class(universe).lookup_invokable(selector)\n\n\t@staticmethod\n\tdef selector_for_operation(universe, reflective_op):\n\n\t\tselectors = {\n\t\t\tReflectiveOp.MessageLookup: \"find:since:\",\n\t\t\tReflectiveOp.MessageActivation: \"activate:withArguments:withSemantics:\",\n\n\t\t\tReflectiveOp.ExecutorReadField: \"read:\",\n\t\t\tReflectiveOp.ExecutorWriteField: \"write:value:\",\n\n\t\t\tReflectiveOp.ExecutorReturn: \"return:\",\n\n\t\t\tReflectiveOp.ExecutorLocalArg: \"readLocalArgument:inFrame:\",\n\n\t\t\tReflectiveOp.ExecutorReadLocal: \"readLocal:inFrame:\",\n\t\t\tReflectiveOp.ExecutorWriteLocal: \"writeLocal:inFrame:value:\",\n\n\t\t\tReflectiveOp.LayoutReadField: \"read:\",\n\t\t\tReflectiveOp.LayoutWriteField: \"write:value:\",\n\t\t}\n\n\t\treturn universe.symbol_for(selectors[reflective_op])\n\n\t@staticmethod\n\tdef meta_class_for_operation(reflective_op, enviroment):\n\n\t\tfield_idx = None\n\t\tif reflective_op <= ReflectiveOp.ExecutorReturn:\n\t\t\tfield_idx = MOPDispatcher.Semantics_IDX\n\t\telif reflective_op <= ReflectiveOp.MessageActivation:\n\t\t\tfield_idx = MOPDispatcher.Message_IDX\n\t\telif reflective_op <= ReflectiveOp.LayoutWriteField:\n\t\t\tfield_idx = MOPDispatcher.Layout_IDX\n\t\telse:\n\t\t\traise ValueError(\"reflective op unknown\")\n\n\t\treturn enviroment.get_field(field_idx)\n","sub_path":"src/mate/interpreter/mop.py","file_name":"mop.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"227175725","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 10 18:21:30 2016\n\n@author: owen\n\"\"\"\n\n# Given an input string , reverse the string word by word. \n\n# Example:\n\n# Input: [\"t\",\"h\",\"e\",\" \",\"s\",\"k\",\"y\",\" \",\"i\",\"s\",\" \",\"b\",\"l\",\"u\",\"e\"]\n# Output: [\"b\",\"l\",\"u\",\"e\",\" \",\"i\",\"s\",\" \",\"s\",\"k\",\"y\",\" \",\"t\",\"h\",\"e\"]\n\n# Note: \n\n# A word is defined as a sequence of non-space characters.\n# The input string does not contain leading or trailing spaces.\n# The words are always separated by a single space.\n\n\nclass Solution(object):\n def reverseWords(self, s):\n \"\"\"\n :type str: List[str]\n :rtype: void Do not return anything, modify str in-place instead.\n \"\"\"\n def reverse_word(s, start, end):\n while start < end:\n s[start], s[end] = s[end], s[start]\n start, end = start + 1, end - 1\n \n n = len(s)\n reverse_word(s, 0, n - 1)\n l = 0\n for i in range(n + 1):\n if i == n or s[i] == ' ':\n reverse_word(s, l, i - 1)\n l = i + 1\n # return s\n\nclass Solution(object):\n def reverseWords(self, s):\n \"\"\"\n :type str: List[str]\n :rtype: void Do not return anything, modify str in-place instead.\n \"\"\"\n s.reverse() # 和第一题一样\n n = len(s)\n curr = 0 # curr insert position, before curr is well-placed chars\n i = 0\n while i < n:\n if s[i] != ' ':\n if curr != 0:\n s[curr] = ' '\n curr += 1 # a new word come in, add a space\n j = i\n while j < n and s[j] != ' ':\n j += 1\n s[curr:curr+j-i] = s[i:j][::-1]\n curr += j - i\n i = j\n else:\n i += 1\n\n \nif __name__==\"__main__\":\n print(Solution().reverseWords([]))\n print(Solution().reverseWords([' ',' ','a','s','d',' ','f','g','h','j',' ','k','l']))\n ","sub_path":"186. Reverse Words in a String II.py","file_name":"186. Reverse Words in a String II.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"97834367","text":"import random\nfrom models import my_SSD\nfrom utils.prior_box_creator import PriorBoxCreator\nfrom utils.prior_box_manager import PriorBoxManager\nfrom utils.box_visualizer import BoxVisualizer\nfrom utils.XML_parser import XMLParser\nfrom utils.utils import flatten_prior_boxes\n\n# parameters\nroot_prefix = '../datasets/VOCdevkit/VOC2007/'\nimage_prefix = root_prefix + 'JPEGImages/'\nground_data_prefix = root_prefix + 'Annotations/'\nmodel = my_SSD(num_classes=21)\nimage_shape = model.input_shape[1:]\nbackground_id = 0\n\nground_truth_manager = XMLParser(ground_data_prefix, background_id)\nground_truth_data = ground_truth_manager.get_data()\nVOC2007_decoder = ground_truth_manager.arg_to_class\n\nbox_creator = PriorBoxCreator(model)\nprior_boxes = box_creator.create_boxes()\nvis = BoxVisualizer(image_prefix, image_shape[0:2], VOC2007_decoder)\nprior_boxes = flatten_prior_boxes(prior_boxes)\n\nselected_key = random.choice(list(ground_truth_data.keys()))\nselected_data = ground_truth_data[selected_key]\nselected_box_coordinates = selected_data[:, 0:4]\n\nprior_box_manager = PriorBoxManager(prior_boxes, background_id,box_scale_factors=[.1,.1,.2,.2])\nencoded_boxes = prior_box_manager.assign_boxes(selected_data)\npositive_mask = encoded_boxes[:, 4 + background_id] != 1\n\nvis.draw_normalized_box(encoded_boxes[positive_mask], selected_key)\ndecoded_boxes = prior_box_manager.decode_boxes(encoded_boxes)\nvis.draw_normalized_box(decoded_boxes[positive_mask], selected_key)\nvis.draw_normalized_box(prior_boxes[positive_mask], selected_key)\n","sub_path":"src/old_code/tests/assigner_test.py","file_name":"assigner_test.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"568423560","text":"# *****************************************************************\n#\n# Licensed Materials - Property of IBM\n#\n# (C) Copyright IBM Corp. 2020. All Rights Reserved.\n#\n# US Government Users Restricted Rights - Use, duplication or\n# disclosure restricted by GSA ADP Schedule Contract with IBM Corp.\n#\n# *****************************************************************\n\nimport sys\nimport os\nimport pathlib\ntest_dir = pathlib.Path(__file__).parent.absolute()\nsys.path.append(os.path.join(test_dir, '..', 'open-ce'))\n\nimport build_tree\nimport utils\nimport helpers\n\nclass TestBuildTree(build_tree.BuildTree):\n __test__ = False\n def __init__(self, #pylint: disable=super-init-not-called\n env_config_files,\n python_versions,\n build_types,\n mpi_types,\n repository_folder=\"./\",\n git_location=utils.DEFAULT_GIT_LOCATION,\n git_tag_for_env=\"master\",\n conda_build_config=utils.DEFAULT_CONDA_BUILD_CONFIG):\n self._env_config_files = env_config_files\n self._repository_folder = repository_folder\n self._git_location = git_location\n self._git_tag_for_env = git_tag_for_env\n self._conda_build_config = conda_build_config\n\ndef test_create_recipes(mocker):\n '''\n Tests that `_create_recipes` correctly builds the recipe and extracts all\n of the dependencies from the conda_build render result.\n '''\n dirTracker = helpers.DirTracker()\n mocker.patch(\n 'os.getcwd',\n return_value=\"/test/starting_dir\"\n )\n render_result=helpers.make_render_result(\"horovod\", ['build_req1', 'build_req2 1.2'],\n ['run_req1 1.3'],\n ['host_req1 1.0', 'host_req2'],\n ['test_req1'])\n mocker.patch(\n 'conda_build.api.render',\n return_value=render_result\n )\n mocker.patch(\n 'os.chdir',\n side_effect=(lambda x: dirTracker.validate_chdir(x, expected_dirs=[\"/test/my_repo\", # First the working directory should be changed to the arg.\n \"/test/starting_dir\"])) # And then changed back to the starting directory.\n )\n\n create_recipes_result = build_tree._create_recipes(\"/test/my_repo\", None, \"master\", {'python' : '3.6', 'build_type' : 'cuda', 'mpi_type' : 'openmpi'}, [])\n assert create_recipes_result[0].packages == {'horovod'}\n for dep in {'build_req1', 'build_req2 1.2'}:\n assert dep in create_recipes_result[0].build_dependencies\n for dep in {'run_req1 1.3'}:\n assert dep in create_recipes_result[0].run_dependencies\n for dep in {'host_req1 1.0', 'host_req2'}:\n assert dep in create_recipes_result[0].host_dependencies\n for dep in {'test_req1'}:\n assert dep in create_recipes_result[0].test_dependencies\n\ndef test_clone_repo(mocker):\n '''\n Simple positive test for `_clone_repo`.\n '''\n git_location = utils.DEFAULT_GIT_LOCATION\n\n mock_build_tree = TestBuildTree([], \"3.6\", \"cpu\", \"openmpi\")\n\n mocker.patch(\n 'os.system',\n return_value=0,\n side_effect=(lambda x: helpers.validate_cli(x, expect=[\"git clone\",\n \"-b master\",\n \"--single-branch\",\n git_location + \"/my_repo.git\",\n \"/test/my_repo\"]))\n )\n\n assert mock_build_tree._clone_repo(git_location + \"/my_repo.git\", \"/test/my_repo\", None, \"master\") == 0\n\ndef test_clone_repo_failure(mocker, capsys):\n '''\n Simple negative test for `_clone_repo`.\n '''\n mock_build_tree = TestBuildTree([], \"3.6\", \"cpu\", \"openmpi\")\n\n mocker.patch(\n 'os.system',\n side_effect=(lambda x: helpers.validate_cli(x, expect=[\"git clone\"], retval=1))\n )\n\n assert mock_build_tree._clone_repo(\"https://bad_url\", \"/test/my_repo\", None, \"master\") == 1\n captured = capsys.readouterr()\n assert \"Unable to clone repository\" in captured.out\n\nsample_build_commands = [build_tree.BuildCommand(\"recipe1\",\n \"repo1\",\n [\"package1a\", \"package1b\"],\n python=\"2.6\",\n build_type=\"cuda\",\n mpi_type=\"openmpi\",\n build_command_dependencies=[1,2]),\n build_tree.BuildCommand(\"recipe2\",\n \"repo2\",\n [\"package2a\"],\n python=\"2.6\",\n build_type=\"cpu\",\n mpi_type=\"openmpi\",\n build_command_dependencies=[]),\n build_tree.BuildCommand(\"recipe3\",\n \"repo3\",\n [\"package3a\", \"package3b\"],\n build_command_dependencies=[1])]\n\ndef test_get_dependency_names():\n '''\n Tests that the dependency names can be retrieved for each item in a BuildTree\n '''\n mock_build_tree = TestBuildTree([], \"3.6\", \"cpu\", \"openmpi\")\n mock_build_tree.build_commands = sample_build_commands\n\n output = \"\"\n for build_command in mock_build_tree:\n output += ' '.join([mock_build_tree[dep].name() for dep in build_command.build_command_dependencies]) + \"\\n\"\n\n expected_output = \"\\nrecipe2-py2-6-cpu-openmpi\\nrecipe2-py2-6-cpu-openmpi recipe3\\n\"\n\n assert output == expected_output\n\ndef test_build_tree_len():\n '''\n Tests that the __len__ function works for BuildTree\n '''\n mock_build_tree = TestBuildTree([], \"3.6\", \"cpu\", \"openmpi\")\n mock_build_tree.build_commands = sample_build_commands\n\n assert len(mock_build_tree) == 3\n","sub_path":"tests/build_tree_test.py","file_name":"build_tree_test.py","file_ext":"py","file_size_in_byte":6182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"652107462","text":"import numpy as np\nimport re\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.stem.porter import PorterStemmer\nimport wordninja\nfrom nltk.corpus import words\nfrom paths import *\nimport itertools\nimport csv\n\n\n\ndict0 = {} # this dictionnary contains the spelling correction collected from 2 dictionnaries found on the internet.\nslang = {} # slang dictionnary contains the slang words we will transform them to their original form ,i.e 4u = for you \n\n\ndef create_csv_submission(ids, y_pred, name):\n \"\"\"\n Creates an output file in csv format for submission to kaggle\n Arguments: ids (event ids associated with each prediction)\n y_pred (predicted class labels)\n name (string name of .csv output file to be created)\n \"\"\"\n with open(name, 'w') as csvfile:\n fieldnames = ['Id', 'Prediction']\n writer = csv.DictWriter(csvfile, delimiter=\",\", fieldnames=fieldnames)\n writer.writeheader()\n for r1, r2 in zip(ids, y_pred):\n writer.writerow({'Id':int(r1),'Prediction':int(r2)})\n\ndef dict_read(dict_path , dict0) :\n '''\n Creates a dictionnary from a text file\n '''\n dict1 = open(dict_path, 'rb')\n for word in dict1:\n word = word.decode('utf8')\n word = word.split()\n dict0[word[0]] = word[1]\n dict1.close()\n return dict0\n\ndict0 = dict_read(DICT_PATH + 'dict1.txt', dict0)\ndict0 = dict_read(DICT_PATH + 'dict2.txt', dict0) # correct words spelling dictionnary\nslang = dict_read(DICT_PATH + 'slang_words.txt',slang) # slang words and their original forms\n\ndef remove_url_user_mention(text):\n # Remove URLs\n text = re.sub(r\"\",\"\",str(text))\n # Remove user's name\n text = re.sub(r\"\",\"\",str(text))\n # Remove mentions\n text = re.sub(\"@[^\\s]*\", \"\", str(text))\n return text.strip()\n\n## Build positive and negative sentiment lexicon\n#Source : https://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html\npositiveWords = set(open(POS_NEG_WORDS_PATH + \"positive-words.txt\", encoding = \"ISO-8859-1\").read().split())\nnegativeWords = set(open(POS_NEG_WORDS_PATH + \"negative-words.txt\", encoding = \"ISO-8859-1\").read().split())\n\ndef emphasize_sentiment_words(text):\n '''\n This method adds the word positive/negative if the word processed is in the positive/negative dictionnary\n '''\n new_text = []\n for w in text.split():\n if w in positiveWords:\n new_text.append('positive ' + w)\n elif w in negativeWords:\n new_text.append('negative ' + w)\n else:\n new_text.append(w)\n return (\" \".join(new_text)).strip()\n\n\ndef remove_one_letter_words(text):\n '''\n this method removes words with length less than two characters except for numbers\n '''\n return \" \".join([w for w in text.split() if len(w) >1 or not w.isalpha()])\n\ndef remove_number(text):\n '''\n this method removes numbers from the tweets \n '''\n text = re.sub(\"\\d+\", \"\", text)\n return text\n\ndef separate_hashtag(text):\n '''\n This method removes # from hashtags and if it's composed of more than one word \n it will split it into different words using ninja library\n example: #nevergiveup ---> never give up\n '''\n separated = [] #ninja list\n text = re.sub(r\"#\", \" #\", text)\n new_text = []\n for w in text.split():\n if w.startswith(\"#\"):\n w = re.sub(r'#(\\S+)', r' \\1 ', w)\n separated = wordninja.split(w)\n w = (\" \".join(separated)).strip()\n new_text.append(w)\n else: new_text.append(w)\n return (\" \".join(new_text)).strip()\n\ndef correct_words_from_dictionnary(text , dic):\n '''\n This method corrects words in the tweet using the slang/spelling dictionnaries aleready created\n '''\n text = text.split()\n for i in range(len(text)):\n if text[i] in dic.keys():\n text[i] = dic[text[i]]\n text = ' '.join(text)\n return text\n\npunc_tokenizer = RegexpTokenizer(r'\\w+') # tokenizer that removes punctuation \ndef remove_punctuation(text):\n '''\n This method removes punctuation from the tweet\n '''\n return \" \".join(punc_tokenizer.tokenize(text))\n\n\ndef remove_repetition(text):\n \"This method removes letter repetitions from the tweet\" \n \"tttthank youuu --> tthank youu\"\n \" then these words will be checked with spelling dictionnary \"\n new_text=[]\n text=text.lower()\n text=text.split()\n for word in text:\n word = re.sub(r'(.)\\1+', r'\\1\\1', word)\n new_text.append(word)\n text = ' '.join(new_text) \n return text\n \ndef replace_haha(text):\n \"hahaha --> positive \"\n \" this method will replace all forms of hahaha ( laughs) including those which have mistakes like hahajaha with the word positive\"\n new_text=[]\n text=text.lower()\n text=text.split()\n haha= 'haha'\n pos = 'positive'\n for word in text:\n if haha in word :\n new_text.append(pos)\n else :\n new_text.append(word)\n \n text = ' '.join(new_text) \n return text \n\ndef emoji_translation(text):\n # Smile emojis= :), : ), :-), =) , (= , (:, ( :, (-:, :')\n text = re.sub(r'(:\\s?\\)|:-\\)|\\=\\)|\\(\\=|\\(\\s?:|\\(-:|:\\'\\))', ' positive ', text)\n # Laugh emojis= :D, : D, :-D, xD, x-D, XD, X-D , xd\n text = re.sub(r'(:\\s?D|:-D|x-?D|X-?D|xd)', ' positive ', text)\n # Love emojis= <3, :*\n text = re.sub(r'(<3|:\\*)', ' positive ', text)\n # Wink emojis= ;-), ;), ;-D, ;D, (;, (-; , :p\n text = re.sub(r'(;-?\\)|;-?D|\\(-?;|:p)', ' positive ', text)\n # Sad emojis= :-(, : (, :(, ):, ) : ,)-:\n text = re.sub(r'(:-\\(|:\\s?\\(|\\)\\s?:|\\)-:)', ' negative ', text)\n # Cry emojis= :,(, :'(, :\"(\n text = re.sub(r'(:,\\(|:\\'\\(|:\"\\()', ' negative ', text)\n return text\n\ndef apostrophe(text):\n '''\n This methode transforms words with apostrophes at the end into two words\n '''\n # Apostrophe lookup\n text = re.sub(r\"i\\'m\", \"i am \", text) # i'm --> i am\n text = re.sub(r\"I\\'m\", \"i am \", text) # I'm --> I am\n text = re.sub(r\"it\\'s\",\"it is\",str(text)) #it's --> it is\n text = re.sub(r\"he\\'s\",\"he is\",str(text)) #he's --> he is\n text = re.sub(r\"she\\'s\",\"she is\",str(text)) #she's --> she is\n text = re.sub(r\"we\\'re\",\"we are\",str(text)) #we're --> we are\n text = re.sub(r\"they\\'re\",\"they are\",str(text)) #they're --> they are\n \n text = re.sub(r\"there\\'s\",\"there is\",str(text)) #there's --> there is\n text = re.sub(r\"that\\'s\",\"that is\",str(text)) #that's --> that is\n \n text = re.sub(r\"i\\'d\",\"i would\",str(text)) #i'd --> i would\n text = re.sub(r\"he\\'d\",\"he would\",str(text)) #he'd --> he would\n text = re.sub(r\"it\\'d\",\"it would\",str(text)) #it'd --> it would\n text = re.sub(r\"she\\'d\",\"she would\",str(text)) #she'd --> she would\n text = re.sub(r\"we\\'d\",\"we would\",str(text)) #we'd --> we would\n text = re.sub(r\"they\\'d\",\"they would\",str(text)) #they'd --> they would\n \n text = re.sub(r\"i\\'ll\",\"i will\",str(text)) #i'll --> i will\n text = re.sub(r\"he\\'ll\",\"he will\",str(text)) #he'll --> he will\n text = re.sub(r\"it\\'ll\",\"it will\",str(text)) #it'll --> it will\n text = re.sub(r\"she\\'ll\",\"she will\",str(text)) #she'll --> she will\n text = re.sub(r\"we\\'ll\",\"we will\",str(text)) #we'll --> we will\n text = re.sub(r\"they\\'ll\",\"they will\",str(text)) #they'll --> they will\n \n text = re.sub(r\"don\\'t\",\"do not\",str(text)) #don't --> do not \n text = re.sub(r\"can\\'t\", \"can not\", text) #can't --> can not\n text = re.sub(r\"cannot\", \"can not \", text) #cannot --> can not\n text = re.sub(r\"could\\'t\", \"could not\", text) #could't --> could not\n text = re.sub(r\"should\\'t\", \"should not\", text) #should't --> should not\n text = re.sub(r\"haven\\'t\", \"have not\", text) #haven't --> have not\n text = re.sub(r\"didn\\'t\", \"did not\", text) #didn't --> did not \n \n text = re.sub(r\"what\\'s\", \"what is\", text) #what's --> what is\n text = re.sub(r\"where\\'s\", \"where is\", text) #where's --> where is\n text = re.sub(r\"when\\'s\", \"when is\", text) #when's --> when is\n text = re.sub(r\"why\\'s\", \"why is\", text) #why's --> why is \n \n \n \n return text\n\n# Loading stopwords list from NLTK\nstoplist = set(stopwords.words(\"english\"))\nnegative_stopwords = ['no', 'not', 'nor', 'only', 'against', 'up', 'down', 'couldn', 'didn', 'doesn', 'hadn', 'hasn', 'haven', 'isn', 'ain', 'aren', 'mightn', 'mustn', 'needn', 'shouldn', 'wasn', 'weren', 'wouldn']\n## Remove negation stopwords ( they have a negative sentiment )\nfor w in negative_stopwords:\n stoplist.remove(w)\n\ndef remove_stopwords(text):\n '''\n This method removes stop words from the tweet\n '''\n new_text = text.split()\n for word in new_text:\n if word in stoplist:\n new_text.remove(word)\n return ' '.join(new_text)\n\n# Lemmatization\nlemmatizer = WordNetLemmatizer()\ndef lemmatizing(text):\n '''\n lemmatize words: dances, dancing ,danced --> dance\n '''\n words = text.split()\n lemmatized = list()\n for word in words:\n try:\n lemmatized.append(lemmatizer.lemmatize(word).lower()) #check problem doesnt work correctly\n except Exception:\n lemmatized.append(word)\n return \" \".join(lemmatized)\n\n# Stemming\nstemmer = PorterStemmer()\ndef stemming(text):\n '''\n stemm words: Car, cars --> car\n '''\n x = [stemmer.stem(t) for t in text.split()]\n return \" \".join(x)\n\ndef load_cleaned_data_and_test(positive_data_file, negative_data_file, test_data_file, HASHTAG = True, EMPHASIZE = True, PUNC=True, NUMBER =True, SMALL_WORDS = True , \\\n SLANG =True, APOSTROPHE = True, EMOJI = True, REPITITION = True, SPELLING = True, \\\n STOPWORDS = True, LEMMATIZE = True, STEMMING = True):\n \n # Load data from files\n positive_tweets = list(open(positive_data_file, \"r\", encoding='utf-8').readlines())\n positive_tweets = [s.strip() for s in positive_tweets]\n negative_tweets = list(open(negative_data_file, \"r\", encoding='utf-8').readlines())\n negative_tweets = [s.strip() for s in negative_tweets]\n test_data = list(open(test_data_file, \"r\", encoding='utf-8').readlines())\n test_data = [s.strip() for s in test_data]\n \n # Split by words\n print(\"Starting Data processing\")\n x = positive_tweets + negative_tweets\n \n # remove urls , user name and mentions\n print(\"Processing urls , user names and mentions\")\n positive_tweets = [remove_url_user_mention(sentence) for sentence in positive_tweets]\n negative_tweets = [remove_url_user_mention(sentence) for sentence in negative_tweets]\n test_data = [remove_url_user_mention(sentence) for sentence in test_data]\n \n if EMOJI:\n print(\"Processing emojis\")\n positive_tweets = [emoji_translation(sentence) for sentence in positive_tweets]\n negative_tweets = [emoji_translation(sentence) for sentence in negative_tweets]\n test_data = [emoji_translation(sentence) for sentence in test_data]\n \n \n if REPITITION:\n print(\"Processing repetition\")\n positive_tweets = [remove_repetition(sentence) for sentence in positive_tweets]\n negative_tweets = [remove_repetition(sentence) for sentence in negative_tweets]\n test_data = [remove_repetition(sentence) for sentence in test_data] \n print(\"Processing haha..s\")\n positive_tweets = [replace_haha(sentence) for sentence in positive_tweets]\n negative_tweets = [replace_haha(sentence) for sentence in negative_tweets]\n test_data = [replace_haha(sentence) for sentence in test_data]\n \n if SLANG:\n print(\"Processing slang words\")\n positive_tweets = [correct_words_from_dictionnary(sentence, slang ) for sentence in positive_tweets]\n negative_tweets = [correct_words_from_dictionnary(sentence, slang ) for sentence in negative_tweets]\n test_data = [correct_words_from_dictionnary(sentence,slang ) for sentence in test_data]\n \n if SPELLING:\n print(\"Processing spelling mistakes\")\n positive_tweets = [correct_words_from_dictionnary(sentence, dict0 ) for sentence in positive_tweets]\n negative_tweets = [correct_words_from_dictionnary(sentence, dict0 ) for sentence in negative_tweets]\n test_data = [correct_words_from_dictionnary(sentence, dict0 ) for sentence in test_data]\n \n \n \n if HASHTAG:\n print(\"processing hashtags\")\n positive_tweets = [separate_hashtag(sentence) for sentence in positive_tweets]\n negative_tweets = [separate_hashtag(sentence) for sentence in negative_tweets]\n test_data = [separate_hashtag(sentence) for sentence in test_data] \n \n if STOPWORDS:\n print(\"Processing stop words\")\n positive_tweets = [remove_stopwords(sentence) for sentence in positive_tweets]\n negative_tweets = [remove_stopwords(sentence) for sentence in negative_tweets]\n test_data = [remove_stopwords(sentence) for sentence in test_data] \n \n if APOSTROPHE:\n print(\"Processing apostrophes\")\n positive_tweets = [apostrophe(sentence) for sentence in positive_tweets]\n negative_tweets = [apostrophe(sentence) for sentence in negative_tweets]\n test_data = [apostrophe(sentence) for sentence in test_data] \n \n if EMPHASIZE:\n print(\"Processing emphasize sentiment words\")\n positive_tweets = [emphasize_sentiment_words(sentence) for sentence in positive_tweets]\n negative_tweets = [emphasize_sentiment_words(sentence) for sentence in negative_tweets]\n test_data = [emphasize_sentiment_words(sentence) for sentence in test_data]\n\n if PUNC:\n print(\"Processing punctuation\")\n positive_tweets = [remove_punctuation(sentence) for sentence in positive_tweets]\n negative_tweets = [remove_punctuation(sentence) for sentence in negative_tweets]\n test_data = [remove_punctuation(sentence) for sentence in test_data]\n \n if NUMBER:\n print(\"Processing numbers\")\n positive_tweets = [remove_number(sentence) for sentence in positive_tweets]\n negative_tweets = [remove_number(sentence) for sentence in negative_tweets]\n test_data = [remove_number(sentence) for sentence in test_data]\n \n if SMALL_WORDS:\n print(\"Processing small words\")\n positive_tweets = [remove_one_letter_words(sentence) for sentence in positive_tweets]\n negative_tweets = [remove_one_letter_words(sentence) for sentence in negative_tweets]\n test_data = [remove_one_letter_words(sentence) for sentence in test_data] \n \n\n if SPELLING:\n print(\"Processing spelling mistakes a second time\")\n positive_tweets = [correct_words_from_dictionnary(sentence, dict0 ) for sentence in positive_tweets]\n negative_tweets = [correct_words_from_dictionnary(sentence, dict0 ) for sentence in negative_tweets]\n test_data = [correct_words_from_dictionnary(sentence, dict0 ) for sentence in test_data]\n \n if LEMMATIZE:\n print(\"Processing Lemmatizing\")\n positive_tweets = [lemmatizing(sentence) for sentence in positive_tweets]\n negative_tweets = [lemmatizing(sentence) for sentence in negative_tweets]\n test_data = [lemmatizing(sentence) for sentence in test_data]\n \n if STEMMING:\n print(\"Processing Stemming\")\n positive_tweets = [stemming(sentence) for sentence in positive_tweets]\n negative_tweets = [stemming(sentence) for sentence in negative_tweets]\n test_data = [stemming(sentence) for sentence in test_data]\n print(\"Returning Positive X data , Negative X data and test data\")\n return [positive_tweets, negative_tweets, test_data]\n\n \n \n \n \n \n \n \n \n \n \n","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":15832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"302931564","text":"# -*- encoding: utf-8 -*-\nfrom flask import Flask, request, Response\nimport json\nimport torch\nimport numpy as np\nimport gpt_gen\nimport gpt_gen_thread\nimport sys\nfrom datetime import datetime\nimport time\nimport logging\nfrom Config import config_predict\n\npath_source = sys.argv[1]\npath_target = sys.argv[2]\nif len(sys.argv)>3:\n path_config = sys.argv[3].split(',')\n doPredict = [int(t) for t in sys.argv[4].split(',')]\n gpus = sys.argv[5].split(',')\n ConfigPredict = config_predict(model_config=path_config,doPredict=doPredict,gpus = gpus)\n print('use input configs:%s'%'\\n'.join(path_config))\n print('gpus=%s'%','.join(ConfigPredict.gpus))\nelse:\n print('use default configs')\n ConfigPredict = config_predict()\nwith open(path_source,'r') as f:\n Data = f.read().strip().split('\\n')\nbatchGenerating=ConfigPredict.batchGenerating\npath_configs = ConfigPredict.model_configs\nnum0 = ConfigPredict.predict_nums\ntags = ConfigPredict.tags\nrmHFW = ConfigPredict.rmHFW\nmaxNext = ConfigPredict.maxNext_JLX\npath_next = ConfigPredict.path_JLX_next\npath_simi = ConfigPredict.path_JLX_simi\nmodel,tokenizer,config,device = [], [], [], []\nfor ii in range(len(path_configs)):\n if ConfigPredict.doPredict[ii]:\n m0,t0,c0,d0 = gpt_gen.getModel(path_config=path_configs[ii],gpu=ConfigPredict.gpus[ii])\n c0['repetition_penalty'] = ConfigPredict.repetition_penalty[ii]\n c0['temperature'] = ConfigPredict.temperature[ii]\n c0['length'] = ConfigPredict.length[ii]\n else:\n m0,t0,c0,d0 = '','','',''\n model.append(m0)\n tokenizer.append(t0)\n config.append(c0)\n device.append(d0)\nif ConfigPredict.doPredict[-1]:\n D_simi = json.load(open(path_simi,'r',encoding='utf-8'))\n D_next = json.load(open(path_next,'r',encoding='utf-8'))\n D_simi = {k:json.loads(D_simi[k]) for k in D_simi}\n D_next = {k:json.loads(D_next[k]) for k in D_next}\nelse:\n D_simi,D_next = [],[]\napp = 0\nquick = False\ndef write_excel(path_target,data,sheetname='Sheet1'):\n import xlwt\n # 创建一个workbook 设置编码\n workbook = xlwt.Workbook(encoding='utf-8')\n # 创建一个worksheet\n worksheet = workbook.add_sheet(sheetname)\n # 写入excel\n # 参数对应 行, 列, 值\n rows,cols = len(data),len(data[0])\n for i in range(rows):\n for j in range(cols):\n worksheet.write(i, j, label=str(data[i][j]))\n # 保存\n workbook.save(path_target)\ndef main():\n S = []\n T0 = time.time()\n for data in Data:\n if ConfigPredict.useThread:\n result = gpt_gen_thread.generating_thread(app, data, model, config, tokenizer, device, ConfigPredict,quick, num0,\n removeHighFreqWordss=rmHFW, batchGenerating=batchGenerating,tags=tags,\n D_simi=D_simi,D_next=D_next,maxNext=maxNext,maxChoice=10)\n else:\n result = []\n for ii in range(len(path_configs)):\n gpu = ConfigPredict.gpus[ii]\n torch.cuda.set_device(int(gpu))\n if ii==1:\n r0 = gpt_gen.generating_poem(app,data, model[ii], config[ii], tokenizer[ii],device[ii],quick,num0[ii],batchGenerating=batchGenerating,gpu=gpu)\n else:\n r0 = gpt_gen.generating(app,data, model[ii], config[ii], tokenizer[ii],device[ii],ConfigPredict,quick=quick,num=num0[ii],removeHighFreqWords=rmHFW[ii],batchGenerating=batchGenerating,gpu=gpu)\n r0 = [rr + tags[ii] for rr in r0]\n result.extend(r0)\n result_nnlm = gpt_gen.nnlm_modelpredict(D_simi,D_next,ConfigPredict,inputStr=data,maxNext=maxNext,maxChoice=10,num=num)\n result += [tmp+tags[-1] for tmp in result_nnlm]\n response = {'input':data,'result': result}\n S.append(response)\n T1 = time.time()\n T = T1 - T0\n with open(path_target, 'w') as f:\n json.dump(S, f, ensure_ascii=False, indent=4)\n A = []\n for i in range(len(S)):\n for j in range(len(S[i]['result'])):\n s = S[i]['result'][j]\n t = ''.join([s[len(s) - i - 1] for i in range(len(s))])\n idx0 = len(s) - t.find('(') - 1\n idx1 = len(s) - t.find(')') - 1\n tag = s[idx0:idx1 + 1]\n if j == 0:\n z = [S[i]['input'], S[i]['result'][j]]\n else:\n z = ['', S[i]['result'][j]]\n z.append(tag)\n A.append(z)\n path_target1 = path_target.replace('json', 'xls')\n write_excel(path_target1, A)\n print('used time %0.2f and QPS=%0.2f' % (T, len(Data) / T))\n# start flask app\nif __name__ == '__main__':\n main()\n","sub_path":"test_online/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"18925838","text":"from grid import Point, Direction\nfrom exceptions import *\n\n\nclass Doll():\n def __init__(self, table):\n self.table = table\n self.position = None\n self.direction = None\n self.dirs = [\"NORTH\", \"EAST\", \"SOUTH\", \"WEST\"]\n self.arrow = {\n \"NORTH\": Direction(0, 1),\n \"EAST\": Direction(1, 0),\n \"SOUTH\": Direction(0, -1),\n \"WEST\": Direction(-1, 0),\n }\n\n def place(self, params):\n position = Point(int(params[0]),int(params[1]))\n if self.table.contains(position):\n self.position = position\n if params[2] in self.dirs:\n self.direction = params[2]\n else:\n raise NotValidCommand('Command Not in Proper Format: \"%s\"' % params[2])\n else:\n raise BoundException('Given Position Not on Table')\n\n def move(self):\n if not self.position:\n raise PlaceNotExecuted('PLACE command is Not Executed Till Now')\n new_pos = self.position + (self.arrow[self.direction] * 1)\n if self.table.contains(new_pos):\n self.position = new_pos\n else:\n raise BoundException('Cannot Move the Doll Beyond Boundaries')\n\n def left(self):\n if self.position is None:\n raise PlaceNotExecuted('PLACE command is Not Executed Till Now')\n pos = self.dirs.index(self.direction)\n pos_new = (pos - 1) % len(self.dirs)\n new_dir = self.dirs[pos_new]\n self.direction = new_dir\n\n def right(self):\n if self.position is None:\n raise PlaceNotExecuted('PLACE command is Not Executed Till Now')\n pos = self.dirs.index(self.direction)\n pos_new = (pos + 1) % len(self.dirs)\n new_dir = self.dirs[pos_new]\n self.direction = new_dir\n\n def report(self):\n if self.position is None:\n raise PlaceNotExecuted('PLACE command is Not Executed Till Now')\n print(self.position.x,self.position.y,self.direction)","sub_path":"doll.py","file_name":"doll.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"265860067","text":"# -*- coding: utf-8 -*-\n\n#Copyright 2016-2017 Angel Ferran Pousa, DESY\n#\n#This file is part of VisualPIC.\n#\n#VisualPIC is free software: you can redistribute it and/or modify\n#it under the terms of the GNU General Public License as published by\n#the Free Software Foundation, either version 3 of the License, or\n#(at your option) any later version.\n#\n#VisualPIC 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 VisualPIC. If not, see .\n\n\nimport os\nfrom h5py import File as H5File\nimport numpy as np\n\nfrom VisualPIC.DataHandling.species import Species\nfrom VisualPIC.DataHandling.folderDataElements import FolderField, FolderRawDataSet\nfrom VisualPIC.DataHandling.rawDataTags import RawDataTags\n\n# Try to import opmd_viewer, for openPMD files\n# TODO: add try/except statements\nfrom opmd_viewer import OpenPMDTimeSeries\n\nclass FolderDataReader:\n \"\"\"Scans the simulation folder and creates all the necessary species, fields and rawDataSet objects\"\"\"\n def __init__(self, parentDataContainer):\n self._dataContainer = parentDataContainer\n self._dataLocation = \"\"\n self._loadDataFrom = {\"Osiris\": self.LoadOsirisData,\n \"HiPACE\": self.LoadHiPaceData,\n \"openPMD\": self.LoadOpenPMDData }\n\n def SetDataLocation(self, dataLocation):\n self._dataLocation = dataLocation\n\n def GetDataLocation(self):\n return self._dataLocation\n\n \"\"\"\n Data managing. Methods for adding the detected species, fields...\n \"\"\"\n def AddSpecies(self, species):\n addSpecies = True\n # the species will not be added if it already exists\n for avSpecies in self._dataContainer._availableSpecies:\n if avSpecies.GetName() == species.GetName():\n addSpecies = False\n if addSpecies:\n self._dataContainer._availableSpecies.append(species)\n\n def AddFieldToSpecies(self, speciesName, field):\n for species in self._dataContainer._availableSpecies:\n if species.GetName() == speciesName:\n species.AddAvailableField(field)\n\n def AddRawDataToSpecies(self, speciesName, dataSet):\n for species in self._dataContainer._availableSpecies:\n if species.GetName() == speciesName:\n species.AddRawDataSet(dataSet)\n\n def AddRawDataTagsToSpecies(self, speciesName, tags):\n for species in self._dataContainer._availableSpecies:\n if species.GetName() == speciesName:\n species.AddRawDataTags(tags)\n\n def AddDomainField(self,field):\n self._dataContainer._availableDomainFields.append(field)\n\n \"\"\"\n Main data loader. It will automatically call the specific loader for a particular simulation code\n \"\"\"\n def LoadData(self, simulationCode):\n self._loadDataFrom[simulationCode]()\n\n \"\"\"\n Specific data loaders\n \"\"\"\n # OSIRIS\n def LoadOsirisData(self):\n \"\"\"Osiris Loader\"\"\"\n keyFolderNames = [\"DENSITY\", \"FLD\", \"PHA\", \"RAW\" ]\n mainFolders = os.listdir(self._dataLocation)\n for folder in mainFolders:\n subDir = self._dataLocation + \"/\" + folder\n if folder == keyFolderNames[0]:\n speciesNames = os.listdir(subDir)\n for species in speciesNames:\n if os.path.isdir(os.path.join(subDir, species)):\n self.AddSpecies(Species(species))\n speciesFields = os.listdir(subDir + \"/\" + species)\n for field in speciesFields:\n if os.path.isdir(os.path.join(subDir + \"/\" + species, field)):\n fieldLocation = subDir + \"/\" + species + \"/\" + field\n fieldName = field\n timeSteps = self.GetTimeStepsInOsirisLocation(fieldLocation)\n if timeSteps.size != 0:\n self.AddFieldToSpecies(species, FolderField(\"Osiris\", fieldName, self.GiveStandardNameForOsirisQuantity(fieldName), fieldLocation, timeSteps, species))\n elif folder == keyFolderNames[1]:\n domainFields = os.listdir(subDir)\n for field in domainFields:\n if os.path.isdir(os.path.join(subDir, field)):\n fieldLocation = subDir + \"/\" + field\n fieldName = field\n timeSteps = self.GetTimeStepsInOsirisLocation(fieldLocation)\n if timeSteps.size != 0:\n self.AddDomainField(FolderField(\"Osiris\", fieldName, self.GiveStandardNameForOsirisQuantity(fieldName), fieldLocation, timeSteps))\n\n elif folder == keyFolderNames[3]:\n subDir = self._dataLocation + \"/\" + folder\n speciesNames = os.listdir(subDir)\n for species in speciesNames:\n if os.path.isdir(os.path.join(subDir, species)):\n self.AddSpecies(Species(species))\n dataSetLocation = subDir + \"/\" + species\n timeSteps = self.GetTimeStepsInOsirisLocation(dataSetLocation)\n if timeSteps.size != 0:\n file_path = dataSetLocation + \"/\" + \"RAW-\" + species + \"-\" + str(timeSteps[0]).zfill(6) + \".h5\"\n file_content = H5File(file_path, 'r')\n for dataSetName in list(file_content):\n if dataSetName == \"tag\":\n self.AddRawDataTagsToSpecies(species, RawDataTags(\"Osiris\", dataSetName, dataSetLocation, timeSteps, species, dataSetName))\n else:\n self.AddRawDataToSpecies(species, FolderRawDataSet(\"Osiris\", dataSetName, self.GiveStandardNameForOsirisQuantity(dataSetName), dataSetLocation, timeSteps, species, dataSetName))\n file_content.close()\n\n def GetTimeStepsInOsirisLocation(self, location):\n fileNamesList = os.listdir(location)\n # filter only .h5 files\n h5Files = list()\n for file in fileNamesList:\n if file.endswith(\".h5\"):\n h5Files.append(file)\n timeSteps = np.zeros(len(h5Files))\n i = 0\n for file in h5Files:\n timeStep = int(file[-9:-3])\n timeSteps[i] = timeStep\n i+=1\n timeSteps = timeSteps.astype(np.int64)\n timeSteps.sort()\n return timeSteps\n\n def GiveStandardNameForOsirisQuantity(self, osirisName):\n if \"e1\" in osirisName:\n return \"Ez\"\n elif \"e2\" in osirisName:\n return \"Ey\"\n elif \"e3\" in osirisName:\n return \"Ex\"\n elif \"b1\" in osirisName:\n return \"Bz\"\n elif \"b2\" in osirisName:\n return \"By\"\n elif \"b3\" in osirisName:\n return \"Bx\"\n elif \"charge\" in osirisName:\n return \"Charge density\"\n elif osirisName == \"x1\":\n return \"z\"\n elif osirisName == \"x2\":\n return \"y\"\n elif osirisName == \"x3\":\n return \"x\"\n elif osirisName == \"p1\":\n return \"Pz\"\n elif osirisName == \"p2\":\n return \"Py\"\n elif osirisName == \"p3\":\n return \"Px\"\n elif osirisName == \"q\":\n return \"Charge\"\n elif osirisName == \"ene\":\n return \"Energy\"\n else:\n return osirisName\n\n # HiPACE\n def LoadHiPaceData(self):\n \"\"\"HiPACE loader\"\"\"\n raise NotImplementedError\n \"\"\"\n HOW TO USE:\n\n This function has to scan the folder where the simulation data is stored.\n It will create a Species, FolderField, FolderRawDataSet or RawDataTags object for each\n species, field, raw (particle) data set and particle tags found in the folder.\n\n To add these data into the dataContainer the following functions have to be used:\n\n self.AddSpecies(..)\n self.AddFieldToSpecies(..)\n self.AddDomainField(..)\n self.AddRawDataToSpecies(..)\n self.AddRawDataTagsToSpecies(..)\n \"\"\"\n\n # openPMD\n def LoadOpenPMDData(self):\n \"\"\"OpenPMD Loader\"\"\"\n # Scan the folder using openPMD-viewer\n ts = OpenPMDTimeSeries( self._dataLocation, check_all_files=False )\n\n # Register the available fields\n if ts.avail_fields is not None:\n for field in ts.avail_fields:\n # Vector field\n if ts.fields_metadata[field]['type'] == 'vector':\n available_coord = ['x', 'y', 'z']\n # Register each coordinate of the vector\n for coord in available_coord:\n fieldName = field + '/' + coord\n standardName = self.GiveStandardNameForOpenPMDQuantity(fieldName)\n self.AddDomainField(\n FolderField( \"openPMD\", fieldName, standardName,\n self._dataLocation, ts.iterations ) )\n # Scalar field\n if ts.fields_metadata[field]['type'] == 'scalar':\n fieldName = field\n standardName = self.GiveStandardNameForOpenPMDQuantity(field)\n self.AddDomainField(\n FolderField( \"openPMD\", fieldName, standardName,\n self._dataLocation, ts.iterations ) )\n\n # Register the available species\n if ts.avail_species is not None:\n for species in ts.avail_species:\n self.AddSpecies(Species(species))\n for species_quantity in ts.avail_record_components[species]:\n if species_quantity == \"id\":\n self.AddRawDataTagsToSpecies( species,\n RawDataTags( \"openPMD\", species_quantity,\n self._dataLocation, ts.iterations,\n species, species_quantity) )\n else:\n self.AddRawDataToSpecies( species,\n FolderRawDataSet( \"openPMD\", species_quantity,\n self.GiveStandardNameForOpenPMDQuantity(species_quantity),\n self._dataLocation, ts.iterations,\n species, species_quantity) )\n\n def GetTimeStepsInOpenPMDLocation(self, location):\n ts = OpenPMDTimeSeries( location, check_all_files=False )\n return ts.iterations\n\n def GiveStandardNameForOpenPMDQuantity(self, openpmdName):\n if \"E/z\" in openpmdName:\n return \"Ez\"\n elif \"E/y\" in openpmdName:\n return \"Ey\"\n elif \"E/x\" in openpmdName:\n return \"Ex\"\n elif \"B/z\" in openpmdName:\n return \"Bz\"\n elif \"B/y\" in openpmdName:\n return \"By\"\n elif \"B/x\" in openpmdName:\n return \"Bx\"\n elif \"rho\" in openpmdName:\n return \"Charge density\"\n elif openpmdName == \"uz\":\n return \"Pz\"\n elif openpmdName == \"uy\":\n return \"Py\"\n elif openpmdName == \"ux\":\n return \"Px\"\n elif openpmdName == \"charge\":\n return \"Charge\"\n else:\n return openpmdName\n","sub_path":"VisualPIC/DataReading/folderDataReader.py","file_name":"folderDataReader.py","file_ext":"py","file_size_in_byte":11692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"480749063","text":"#!/usr/bin/python\n#\n# Parse ss.log textual output written by ss_log_thread() in nsperf.py.\n# Usage:\n# infile=foo/ss.log outdir=out/ ss_log_parser.py\n#\n# Author:\n# Neal Cardwell\n# Based on code by:\n# Kevin (Yudong) Yang\n# Soheil Hassas Yeganeh\n\nimport os\nimport socket\nimport sys\nimport time\n\nDEBUG = False # enable debugging output?\n\ndef debug(s):\n if DEBUG:\n print('DEBUG: %s' % s)\n\ndef median(nums):\n \"\"\"Return median of all numbers.\"\"\"\n\n if len(nums) == 0:\n return 0\n sorted_nums = sorted(nums)\n n = len(sorted_nums)\n m = n - 1\n return (sorted_nums[n/2] + sorted_nums[m/2]) / 2.0\n\ndef read_file():\n \"\"\"Read the ss.log file and parse into a dictionary.\"\"\"\n all_data = {} # data for all time: